read_text_file
Read UTF-8 text file contents with optional line range selection to extract specific sections from files within allowed directories.
Instructions
Read the contents of a UTF-8 text file, optionally within a line range.
Args: path (str): File path to read (absolute or relative to allowed directories) fromLine (int, optional): Starting line number (1-indexed, inclusive) toLine (int, optional): Ending line number (1-indexed, inclusive)
Returns: str: File contents as text, or error message if failed
Note: - Path must be within allowed directory roots - Only reads UTF-8 text files (binary files will return error) - If line range specified, returns only those lines - Line numbers are 1-indexed
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| fromLine | No | ||
| toLine | No |
Implementation Reference
- main.py:285-317 (handler)The handler function for the 'read_text_file' MCP tool. It resolves the file path using _resolve, checks if it's a text file with _is_text, reads the content, applies optional line range slicing, and returns the content or an error message.@mcp.tool def read_text_file( path: str, fromLine: int | None = None, toLine: int | None = None ) -> str: """Read the contents of a UTF-8 text file, optionally within a line range. Args: path (str): File path to read (absolute or relative to allowed directories) fromLine (int, optional): Starting line number (1-indexed, inclusive) toLine (int, optional): Ending line number (1-indexed, inclusive) Returns: str: File contents as text, or error message if failed Note: - Path must be within allowed directory roots - Only reads UTF-8 text files (binary files will return error) - If line range specified, returns only those lines - Line numbers are 1-indexed """ try: rp = _resolve(path) if not _is_text(rp): return f"Error reading file: '{rp}' is not a UTF-8 text file or is binary" lines = rp.read_text(encoding="utf-8").splitlines(keepends=False) if fromLine is None and toLine is None: return "\n".join(lines) start = (fromLine or 1) - 1 end = toLine or len(lines) return "\n".join(lines[start:end]) except Exception as e: return _human_error(e, "reading file")