Skip to main content
Glama
safurrier

MCP Filesystem Server

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
NameRequiredDescriptionDefault
encodingNoutf-8
pathYes

Implementation Reference

  • 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)}"
  • 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}")
  • 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 """
  • 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()}" )

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/safurrier/mcp-filesystem'

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