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)}"
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but lacks behavioral details. It mentions recursion but doesn't disclose performance implications for large directories, error handling for invalid paths, or whether it follows symlinks. The return format options are listed but not explained.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (Args, Returns) and front-loaded purpose. It's concise but could be slightly tighter by integrating the format options into the main sentence rather than a separate list.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 2 parameters, no annotations, and no output schema, the description covers the basics but lacks depth. It explains parameters adequately but doesn't detail return values beyond 'Directory size information', leaving ambiguity about output structure for different formats.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It clearly explains 'path' as 'Directory path' and 'format' with its three options, adding essential meaning beyond the bare schema. The 'ctx' parameter is mentioned but not explained, slightly reducing completeness.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('calculate the total size') and resource ('directory recursively'), distinguishing it from siblings like 'get_file_info' (single file) or 'list_directory' (listing contents). The verb 'calculate' with 'recursively' precisely defines the scope.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like 'get_file_info' (for single files) or 'find_large_files' (for identifying large items). The description only states what it does, not when it's appropriate compared to sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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