list_directory
Retrieve detailed file and directory listings from a specified path, with options to filter by pattern, include hidden files, and choose output format.
Instructions
Get a detailed listing of files and directories in a path.
Args:
path: Path to the directory
include_hidden: Whether to include hidden files (starting with .)
pattern: Optional glob pattern to filter entries
format: Output format ('text' or 'json')
ctx: MCP context
Returns:
Formatted directory listing
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| include_hidden | No | ||
| pattern | No | ||
| format | No | text |
Implementation Reference
- mcp_filesystem/server.py:198-230 (handler)Primary MCP tool handler and registration for 'list_directory'. Handles parameters, delegates to FileOperations.list_directory() or list_directory_formatted() based on output format, and returns JSON or text listing.@mcp.tool() async def list_directory( path: str, ctx: Context, include_hidden: bool = False, pattern: Optional[str] = None, format: str = "text", ) -> str: """Get a detailed listing of files and directories in a path. Args: path: Path to the directory include_hidden: Whether to include hidden files (starting with .) pattern: Optional glob pattern to filter entries format: Output format ('text' or 'json') ctx: MCP context Returns: Formatted directory listing """ try: components = get_components() if format.lower() == "json": entries = await components["operations"].list_directory( path, include_hidden, pattern ) return json.dumps(entries, indent=2) else: return await components["operations"].list_directory_formatted( path, include_hidden, pattern ) except Exception as e: return f"Error listing directory: {str(e)}"
- mcp_filesystem/operations.py:268-320 (helper)Core helper function in FileOperations that performs the actual directory listing: validates path, iterates entries, filters by hidden/pattern, creates FileInfo, returns list of dicts.async def list_directory( self, path: Union[str, Path], include_hidden: bool = False, pattern: Optional[str] = None, ) -> List[Dict]: """List directory contents. Args: path: Path to the directory include_hidden: Whether to include hidden files (starting with .) pattern: Optional glob pattern to filter files Returns: List of file/directory information dictionaries Raises: ValueError: If path is outside allowed directories or not a directory PermissionError: If directory cannot be read """ abs_path, allowed = await self.validator.validate_path(path) if not allowed: raise ValueError(f"Path outside allowed directories: {path}") if not abs_path.is_dir(): raise ValueError(f"Not a directory: {path}") results = [] try: entries = await anyio.to_thread.run_sync(list, abs_path.iterdir()) for entry in entries: # Skip hidden files if not requested if not include_hidden and entry.name.startswith("."): continue # Apply pattern filter if specified if pattern and not entry.match(pattern): continue try: info = FileInfo(entry) results.append(info.to_dict()) except (PermissionError, FileNotFoundError): # Skip files we can't access pass return results except PermissionError as e: raise ValueError(f"Cannot read directory: {e}")
- mcp_filesystem/operations.py:321-353 (helper)Helper function that calls list_directory() and formats the output as a sorted, human-readable text listing with type, size, and modification time.async def list_directory_formatted( self, path: Union[str, Path], include_hidden: bool = False, pattern: Optional[str] = None, ) -> str: """List directory contents in a formatted string. Args: path: Path to the directory include_hidden: Whether to include hidden files pattern: Optional glob pattern to filter files Returns: Formatted string with directory contents """ entries = await self.list_directory(path, include_hidden, pattern) if not entries: return "Directory is empty" # Format the output result = [] for entry in sorted(entries, key=lambda x: (not x["is_directory"], x["name"])): prefix = "[DIR] " if entry["is_directory"] else "[FILE]" size = "" if entry["is_directory"] else f" ({entry['size']:,} bytes)" modified = datetime.fromisoformat(entry["modified"]).strftime( "%Y-%m-%d %H:%M:%S" ) result.append(f"{prefix} {entry['name']}{size} - {modified}") return "\n".join(result)