read_file
Retrieve file contents from the filesystem by specifying a file path and optional encoding. This tool reads complete file data for processing or analysis within the MCP Filesystem Server environment.
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 |
|---|---|---|---|
| path | Yes | ||
| encoding | No | utf-8 |
Implementation Reference
- mcp_filesystem/server.py:94-111 (handler)MCP tool registration and handler for 'read_file'. This is the entry point that gets called by the MCP client, performs error handling, and delegates to the core FileOperations.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 logic in FileOperations class. Performs path validation using PathValidator and reads the file content asynchronously using anyio.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}")