read_file
Access and retrieve the content of any file within size limits using the MCP Python Interpreter. Specify the file path and optional size cap to safely read and return the data.
Instructions
Read the content of any file, with size limits for safety.
Args:
file_path: Path to the file (relative to working directory or absolute)
max_size_kb: Maximum file size to read in KB (default: 1024)
Returns:
str: File content or an error message
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| file_path | Yes | ||
| max_size_kb | No |
Implementation Reference
- mcp_python_interpreter/server.py:722-764 (handler)The main handler function for the 'read_file' MCP tool, decorated with @mcp.tool(). It reads file contents safely, checks permissions and size limits, handles encoding errors, and formats output appropriately for source files or binary.@mcp.tool() def read_file(file_path: str, max_size_kb: int = 1024) -> str: """ Read the content of any file, with size limits for safety. Args: file_path: Path to the file max_size_kb: Maximum file size to read in KB """ path = Path(file_path) if path.is_absolute(): if not is_path_allowed(path): return f"Access denied: Can only read files in working directory: {WORKING_DIR}" else: path = WORKING_DIR / path try: if not path.exists(): return f"Error: File '{file_path}' not found" file_size_kb = path.stat().st_size / 1024 if file_size_kb > max_size_kb: return f"Error: File size ({file_size_kb:.2f} KB) exceeds maximum ({max_size_kb} KB)" try: with open(path, 'r', encoding='utf-8') as f: content = f.read() source_extensions = ['.py', '.js', '.html', '.css', '.json', '.xml', '.md', '.txt', '.sh', '.bat', '.ps1'] if path.suffix.lower() in source_extensions: file_type = path.suffix[1:] if path.suffix else 'plain' return f"File: {file_path}\n\n```{file_type}\n{content}\n```" return f"File: {file_path}\n\n{content}" except UnicodeDecodeError: with open(path, 'rb') as f: content = f.read() hex_content = content.hex() return f"Binary file: {file_path}\nSize: {len(content)} bytes\nHex (first 1024 chars):\n{hex_content[:1024]}" except Exception as e: return f"Error reading file: {str(e)}"