read_text_file
Read UTF-8 text file contents securely, optionally within a specified line range. Ensures access only within allowed directories and handles 1-indexed line numbers for precise extraction.
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 |
|---|---|---|---|
| fromLine | No | ||
| path | Yes | ||
| toLine | No |
Implementation Reference
- main.py:285-317 (handler)The @mcp.tool decorated handler function that implements the read_text_file tool logic, including path resolution, text file validation, optional line range extraction, and error handling.@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")