Skip to main content
Glama
safurrier

MCP Filesystem Server

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
NameRequiredDescriptionDefault
pathYes
formatNohuman

Implementation Reference

  • 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 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)}"

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/safurrier/mcp-filesystem'

If you have feedback or need assistance with the MCP directory API, please join our Discord server