calculate_directory_size
Calculate the total size of a directory including all subdirectories and files. Specify output format for human-readable, bytes, or JSON results.
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 |
|---|---|---|---|
| path | Yes | ||
| format | No | human |
Implementation Reference
- mcp_filesystem/advanced.py:330-379 (handler)Core implementation of directory size calculation: validates path, recursively scans directory and subdirectories, sums file sizes while skipping inaccessible entries and respecting path validation.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
- mcp_filesystem/server.py:469-512 (registration)MCP tool registration with @mcp.tool() decorator. Wrapper that calls the core handler in AdvancedFileOperations, handles different output formats (human, bytes, json), and error handling.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)}"