head_file
Extract the first N lines from a text file to quickly preview content. Specify file path, line count, and encoding for efficient file analysis using MCP Filesystem Server.
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 |
|---|---|---|---|
| encoding | No | utf-8 | |
| lines | No | ||
| path | Yes |
Implementation Reference
- mcp_filesystem/operations.py:418-457 (handler)Core handler function in FileOperations class that implements the logic to read the first N lines of a specified file after validating the path.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)MCP tool registration using @mcp.tool() decorator. This is the entrypoint for the 'head_file' tool, which delegates to the operations.head_file implementation.@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)}"
- mcp_filesystem/advanced.py:310-314 (helper)Usage of head_file in batch_process_files method of AdvancedFileOperations class for batch processing.encoding = parameters.get("encoding", "utf-8") results[str_path] = await self.base_ops.head_file( path, lines, encoding )