Skip to main content
Glama

read_file

Read file contents safely with configurable size limits to prevent memory issues when accessing files in Python environments.

Instructions

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
max_size_kbNo

Implementation Reference

  • The @mcp.tool()-decorated function implementing the 'read_file' tool. It reads file contents with security checks (path allowance, size limits), handles text and binary files, and formats output with syntax highlighting for source files.
    @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)}"

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/yzfly/mcp-python-interpreter'

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