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)}"
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool reads files, implying a read-only operation, but doesn't mention error handling (e.g., for missing files or encoding issues), performance characteristics, or security constraints. The description adds basic context but lacks depth for behavioral transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured with a clear purpose statement followed by organized sections for arguments and returns. Every sentence adds value without redundancy, and it's front-loaded with the core functionality. The formatting enhances readability while maintaining brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (3 parameters, no annotations, no output schema), the description is mostly complete. It covers purpose, parameters, and returns adequately, but lacks details on error cases or behavioral nuances. For a read operation with simple inputs, this is sufficient though not exhaustive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, so the description must fully compensate. It clearly explains all three parameters: 'path' (file location), 'lines' (number of lines with default), and 'encoding' (text encoding with default). This adds essential meaning beyond the bare schema, making parameter purposes and defaults explicit and understandable.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Read the first N lines') and resource ('of a text file'), which directly explains what the tool does. It distinguishes from siblings like 'read_file' (reads entire file) and 'tail_file' (reads last lines), making the purpose unambiguous and well-defined.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for reading initial portions of files, but doesn't explicitly state when to use this tool versus alternatives like 'read_file' (for full content) or 'tail_file' (for end of file). No guidance on prerequisites or exclusions is provided, leaving usage context somewhat inferred rather than clearly articulated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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