Read file content, supports specifying line number range Args: file_path: File path, relative to workspace start_line: Starting line number (1-based, optional) end_line: Ending line number (1-based, optional) Returns: JSON string of file content or erro
(
file_path: str, start_line: int = None, end_line: int = None
)
| 112 | |
| 113 | @mcp.tool() |
| 114 | async def read_file( |
| 115 | file_path: str, start_line: int = None, end_line: int = None |
| 116 | ) -> str: |
| 117 | """ |
| 118 | Read file content, supports specifying line number range |
| 119 | |
| 120 | Args: |
| 121 | file_path: File path, relative to workspace |
| 122 | start_line: Starting line number (1-based, optional) |
| 123 | end_line: Ending line number (1-based, optional) |
| 124 | |
| 125 | Returns: |
| 126 | JSON string of file content or error message |
| 127 | """ |
| 128 | try: |
| 129 | full_path = validate_path(file_path) |
| 130 | |
| 131 | if not full_path.exists(): |
| 132 | result = {"status": "error", "message": f"File does not exist: {file_path}"} |
| 133 | log_operation( |
| 134 | "read_file_error", {"file_path": file_path, "error": "file_not_found"} |
| 135 | ) |
| 136 | return json.dumps(result, ensure_ascii=False, indent=2) |
| 137 | |
| 138 | with open(full_path, "r", encoding="utf-8") as f: |
| 139 | lines = f.readlines() |
| 140 | |
| 141 | # 处理行号范围 |
| 142 | if start_line is not None or end_line is not None: |
| 143 | start_idx = (start_line - 1) if start_line else 0 |
| 144 | end_idx = end_line if end_line else len(lines) |
| 145 | lines = lines[start_idx:end_idx] |
| 146 | |
| 147 | content = "".join(lines) |
| 148 | |
| 149 | result = { |
| 150 | "status": "success", |
| 151 | "content": content, |
| 152 | "file_path": file_path, |
| 153 | "total_lines": len(lines), |
| 154 | "size_bytes": len(content.encode("utf-8")), |
| 155 | } |
| 156 | |
| 157 | log_operation( |
| 158 | "read_file", |
| 159 | { |
| 160 | "file_path": file_path, |
| 161 | "start_line": start_line, |
| 162 | "end_line": end_line, |
| 163 | "lines_read": len(lines), |
| 164 | }, |
| 165 | ) |
| 166 | |
| 167 | return json.dumps(result, ensure_ascii=False, indent=2) |
| 168 | |
| 169 | except Exception as e: |
| 170 | result = { |
| 171 | "status": "error", |
nothing calls this directly
no test coverage detected