read_file
Extract and return the full contents of a file from the MCP Filesystem Server. Specify the file path and optional encoding (default: utf-8) to retrieve data as a string.
Instructions
Read the complete contents of a file.
Args:
path: Path to the file
encoding: File encoding (default: utf-8)
ctx: MCP context
Returns:
File contents as a string
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| encoding | No | utf-8 | |
| path | Yes |
Implementation Reference
- mcp_filesystem/server.py:94-111 (registration)MCP tool registration for 'read_file' using @mcp.tool() decorator. Thin wrapper handler that retrieves shared FileOperations instance and delegates to its read_file method.@mcp.tool() async def read_file(path: str, ctx: Context, encoding: str = "utf-8") -> str: """Read the complete contents of a file. Args: path: Path to the file encoding: File encoding (default: utf-8) ctx: MCP context Returns: File contents as a string """ try: components = get_components() return await components["operations"].read_file(path, encoding) except Exception as e: return f"Error reading file: {str(e)}"
- mcp_filesystem/operations.py:115-140 (handler)Core implementation of file reading in FileOperations class. Performs path validation using PathValidator, reads file content with specified encoding using pathlib, handles errors appropriately.async def read_file(self, path: Union[str, Path], encoding: str = "utf-8") -> str: """Read a text file. Args: path: Path to the file encoding: Text encoding (default: utf-8) Returns: File contents as string Raises: ValueError: If path is outside allowed directories FileNotFoundError: If file does not exist PermissionError: If file cannot be read """ abs_path, allowed = await self.validator.validate_path(path) if not allowed: raise ValueError(f"Path outside allowed directories: {path}") try: return await anyio.to_thread.run_sync( partial(abs_path.read_text, encoding=encoding) ) except UnicodeDecodeError: raise ValueError(f"Cannot decode file as {encoding}: {path}")
- mcp_filesystem/server.py:95-105 (schema)Tool schema defined by function signature (path: str, encoding: str='utf-8') and docstring describing inputs/outputs for automatic MCP schema generation.async def read_file(path: str, ctx: Context, encoding: str = "utf-8") -> str: """Read the complete contents of a file. Args: path: Path to the file encoding: File encoding (default: utf-8) ctx: MCP context Returns: File contents as a string """
- mcp_filesystem/server.py:48-82 (helper)Helper function that initializes and caches the FileOperations instance (containing read_file handler) along with validator, used by all tool handlers.def get_components() -> Dict[str, Any]: """Initialize and return shared components. Returns cached components if already initialized. Returns: Dictionary with initialized components """ # Return cached components if available if _components_cache: return _components_cache # Initialize components allowed_dirs_typed: List[Union[str, Path]] = get_allowed_dirs() validator = PathValidator(allowed_dirs_typed) operations = FileOperations(validator) advanced = AdvancedFileOperations(validator, operations) grep = GrepTools(validator) # Store in cache _components = { "validator": validator, "operations": operations, "advanced": advanced, "grep": grep, "allowed_dirs": validator.get_allowed_dirs(), } # Update cache _components_cache.update(_components) logger.info( f"Initialized filesystem components with allowed directories: {validator.get_allowed_dirs()}" )