Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

read_file

Read file content or specific lines from a file, with optional JSON parsing, for secure file system operations through the Terminal Controller MCP server.

Instructions

Read content from a file with optional row selection

Args:
    path: Path to the file
    start_row: Starting row to read from (0-based, optional)
    end_row: Ending row to read to (0-based, inclusive, optional)
    as_json: If True, attempt to parse file content as JSON (optional)

Returns:
    File content or selected lines, optionally parsed as JSON

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
start_rowNo
end_rowNo
as_jsonNo

Implementation Reference

  • The handler function for the 'read_file' MCP tool. It reads the content of a specified file, supports optional line range selection (start_row, end_row), and can parse the content as JSON if requested. Includes safety checks for file existence, type, size, and permissions.
    @mcp.tool()
    async def read_file(path: str, start_row: int = None, end_row: int = None, as_json: bool = False) -> str:
        """
        Read content from a file with optional row selection
        
        Args:
            path: Path to the file
            start_row: Starting row to read from (0-based, optional)
            end_row: Ending row to read to (0-based, inclusive, optional)
            as_json: If True, attempt to parse file content as JSON (optional)
        
        Returns:
            File content or selected lines, optionally parsed as JSON
        """
        try:
            if not os.path.exists(path):
                return f"Error: File '{path}' does not exist."
                
            if not os.path.isfile(path):
                return f"Error: '{path}' is not a file."
            
            # Check file size before reading to prevent memory issues
            file_size = os.path.getsize(path)
            if file_size > 10 * 1024 * 1024:  # 10 MB limit
                return f"Warning: File is very large ({file_size/1024/1024:.2f} MB). Consider using row selection."
                
            with open(path, 'r', encoding='utf-8', errors='replace') as file:
                lines = file.readlines()
                
            # If row selection is specified
            if start_row is not None:
                if start_row < 0:
                    return "Error: start_row must be non-negative."
                    
                # If only start_row is specified, read just that single row
                if end_row is None:
                    if start_row >= len(lines):
                        return f"Error: start_row {start_row} is out of range (file has {len(lines)} lines)."
                    content = f"Line {start_row}: {lines[start_row]}"
                else:
                    # Both start_row and end_row are specified
                    if end_row < start_row:
                        return "Error: end_row must be greater than or equal to start_row."
                        
                    if end_row >= len(lines):
                        end_row = len(lines) - 1
                        
                    selected_lines = lines[start_row:end_row+1]
                    content = ""
                    for i, line in enumerate(selected_lines):
                        content += f"Line {start_row + i}: {line}" if not line.endswith('\n') else f"Line {start_row + i}: {line}"
            else:
                # If no row selection, return the entire file
                content = "".join(lines)
            
            # If as_json is True, try to parse the content as JSON
            if as_json:
                try:
                    import json
                    # If we're showing line numbers, we cannot parse as JSON
                    if start_row is not None:
                        return "Error: Cannot parse as JSON when displaying line numbers. Use as_json without row selection."
                    
                    # Try to parse the content as JSON
                    parsed_json = json.loads(content)
                    # Return pretty-printed JSON for better readability
                    return json.dumps(parsed_json, indent=4, sort_keys=False, ensure_ascii=False)
                except json.JSONDecodeError as e:
                    return f"Error: File content is not valid JSON. {str(e)}\n\nRaw content:\n{content}"
            
            return content
                
        except PermissionError:
            return f"Error: No permission to read file '{path}'."
        except Exception as e:
            return f"Error reading file: {str(e)}"
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions the core action (reading file content) and optional parsing as JSON, it lacks critical details: whether it requires specific file permissions, handles errors (e.g., missing files), supports encoding or format specifications, or has performance implications like size limits. For a file I/O tool with zero annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded: the first sentence states the core purpose, followed by a structured 'Args' and 'Returns' section that efficiently documents parameters and output. Every sentence earns its place with no redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (file reading with row selection and JSON parsing), no annotations, and no output schema, the description is partially complete. It covers parameters well but lacks behavioral context (e.g., error handling, file size limits) and output details beyond a high-level statement. This is adequate for basic use but leaves gaps for robust agent operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds substantial meaning beyond the input schema, which has 0% description coverage. It explains each parameter's purpose: 'path' as the file path, 'start_row' and 'end_row' for 0-based row selection (with 'end_row' being inclusive), and 'as_json' for JSON parsing. This compensates well for the schema's lack of descriptions, though it doesn't cover edge cases like negative indices or file format constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Read content from a file with optional row selection.' This specifies the verb ('read'), resource ('file'), and scope ('with optional row selection'). However, it doesn't explicitly differentiate from sibling tools like 'get_command_history' or 'list_directory' that might also involve reading operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'list_directory' (for listing files), 'get_command_history' (for command logs), and 'update_file_content' (for modifying files), there's no indication of when this read operation is appropriate versus other read-like or file-related tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/GongRzhe/terminal-controller-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server