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
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| lines | No | ||
| encoding | No | utf-8 |
Implementation Reference
- mcp_filesystem/operations.py:418-457 (handler)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}")
- mcp_filesystem/server.py:325-349 (registration)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)}"