Skip to main content
Glama
safurrier

MCP Filesystem Server

head_file

Read the first N lines from a text file to preview content, check file structure, or verify data without opening the entire file.

Instructions

Read the first N lines of a text file.

Args:
    path: Path to the file
    lines: Number of lines to read (default: 10)
    encoding: Text encoding (default: utf-8)
    ctx: MCP context

Returns:
    First N lines of the file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
linesNo
encodingNoutf-8

Implementation Reference

  • Core implementation of head_file in FileOperations class: validates path, opens file, reads first N lines using async readline, joins and returns them.
    async def head_file(
        self, path: Union[str, Path], lines: int = 10, encoding: str = "utf-8"
    ) -> str:
        """Read the first N lines of a text file.
    
        Args:
            path: Path to the file
            lines: Number of lines to read (default: 10)
            encoding: Text encoding (default: utf-8)
    
        Returns:
            First N lines of the file
    
        Raises:
            ValueError: If path is outside allowed directories
            FileNotFoundError: If file does not exist
        """
        abs_path, allowed = await self.validator.validate_path(path)
        if not allowed:
            raise ValueError(f"Path outside allowed directories: {path}")
    
        try:
            result = []
            async with await anyio.open_file(abs_path, "r", encoding=encoding) as f:
                for _ in range(lines):
                    try:
                        line = await f.readline()
                        if not line:
                            break
                        result.append(line.rstrip("\n"))
                    except UnicodeDecodeError:
                        raise ValueError(f"Cannot decode file as {encoding}: {path}")
    
            return "\n".join(result)
    
        except FileNotFoundError:
            raise FileNotFoundError(f"File not found: {path}")
        except PermissionError:
            raise ValueError(f"Permission denied: {path}")
  • Registers the head_file MCP tool with @mcp.tool() decorator. Thin wrapper that retrieves components and delegates to operations.head_file, handling exceptions.
    @mcp.tool()
    async def head_file(
        path: str,
        ctx: Context,
        lines: int = 10,
        encoding: str = "utf-8",
    ) -> str:
        """Read the first N lines of a text file.
    
        Args:
            path: Path to the file
            lines: Number of lines to read (default: 10)
            encoding: Text encoding (default: utf-8)
            ctx: MCP context
    
        Returns:
            First N lines of the file
        """
        try:
            components = get_components()
            content = await components["operations"].head_file(path, lines, encoding)
            return content
        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/safurrier/mcp-filesystem'

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