calculate_directory_size
Determine the size of a directory and its contents by specifying the path and output format ('human', 'bytes', or 'json'). Built for MCP Filesystem Server to manage complex directory structures efficiently.
Instructions
Calculate the total size of a directory recursively.
Args:
path: Directory path
format: Output format ('human', 'bytes', or 'json')
ctx: MCP context
Returns:
Directory size information
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| format | No | human | |
| path | Yes |
Implementation Reference
- mcp_filesystem/server.py:468-513 (handler)MCP tool handler for 'calculate_directory_size'. This is the entry point registered with FastMCP that handles input parameters, delegates size calculation to the advanced component, and formats the output in human-readable, bytes, or JSON format.@mcp.tool() async def calculate_directory_size( path: str, ctx: Context, format: str = "human" ) -> str: """Calculate the total size of a directory recursively. Args: path: Directory path format: Output format ('human', 'bytes', or 'json') ctx: MCP context Returns: Directory size information """ try: components = get_components() size_bytes = await components["advanced"].calculate_directory_size(path) if format.lower() == "bytes": return str(size_bytes) if format.lower() == "json": return json.dumps( { "path": path, "size_bytes": size_bytes, "size_kb": round(size_bytes / 1024, 2), "size_mb": round(size_bytes / (1024 * 1024), 2), "size_gb": round(size_bytes / (1024 * 1024 * 1024), 2), }, indent=2, ) # Human readable format if size_bytes < 1024: return f"Directory size: {size_bytes} bytes" elif size_bytes < 1024 * 1024: return f"Directory size: {size_bytes / 1024:.2f} KB" elif size_bytes < 1024 * 1024 * 1024: return f"Directory size: {size_bytes / (1024 * 1024):.2f} MB" else: return f"Directory size: {size_bytes / (1024 * 1024 * 1024):.2f} GB" except Exception as e: return f"Error calculating directory size: {str(e)}"
- mcp_filesystem/advanced.py:330-379 (helper)Supporting method in AdvancedFileOperations class that performs the recursive directory size calculation, including path validation, file size summation, and handling of permissions and subdirectories.async def calculate_directory_size(self, path: Union[str, Path]) -> int: """Calculate the total size of a directory recursively. Args: path: Directory path Returns: Total size in bytes Raises: ValueError: If path is outside allowed directories """ 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}") total_size = 0 async def scan_dir(dir_path: Path) -> None: nonlocal total_size try: entries = await anyio.to_thread.run_sync(list, dir_path.iterdir()) for entry in entries: try: if entry.is_file(): total_size += entry.stat().st_size elif entry.is_dir(): # Check if this path is still allowed ( entry_abs, entry_allowed, ) = await self.validator.validate_path(entry) if entry_allowed: await scan_dir(entry) except (PermissionError, FileNotFoundError): # Skip entries we can't access pass except (PermissionError, FileNotFoundError): # Skip directories we can't access pass await scan_dir(abs_path) return total_size