Skip to main content
Glama

get_disk_usage

Analyze disk space consumption for directories to identify storage usage patterns and optimize resource allocation.

Instructions

Get disk usage for a directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to directory
max_depthNoMax depth for breakdown

Implementation Reference

  • The implementation of get_disk_usage which calculates disk usage for a directory.
    async function getDiskUsageImpl(input: { path: string; max_depth?: number }): Promise<ToolResult> {
      try {
        const absolutePath = path.resolve(input.path);
        const maxDepth = input.max_depth ?? 1;
    
        const stats = await fs.stat(absolutePath);
    
        if (!stats.isDirectory()) {
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  path: absolutePath,
                  size: stats.size,
                  sizeFormatted: formatBytes(stats.size),
                  isFile: true,
                }),
              },
            ],
          };
        }
    
        // Calculate directory size
        const usage = await calculateDirSize(absolutePath, 0, maxDepth);
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  path: absolutePath,
                  totalSize: usage.totalSize,
                  totalSizeFormatted: formatBytes(usage.totalSize),
                  fileCount: usage.fileCount,
                  directoryCount: usage.directoryCount,
                  breakdown: usage.breakdown,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        const err = error as NodeJS.ErrnoException;
    
        if (err.code === 'ENOENT') {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'FILE_NOT_FOUND',
                  message: `Path not found: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        return {
          isError: true,
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                code: 'UNKNOWN_ERROR',
                message: `Error calculating disk usage: ${err.message}`,
              }),
            },
          ],
        };
      }
    }
  • Registration of get_disk_usage tool with the MCP server.
    // get_disk_usage tool
    server.tool(
      'get_disk_usage',
      'Get disk usage for a directory',
      {
        path: z.string().describe('Path to directory'),
        max_depth: z.number().optional().describe('Max depth for breakdown'),
      },
      async (args) => {
        return await getDiskUsageImpl(args);
      }
    );
  • Recursive helper function to calculate directory size.
    async function calculateDirSize(
      dirPath: string,
      currentDepth: number,
      maxDepth: number
    ): Promise<{
      totalSize: number;
      fileCount: number;
      directoryCount: number;
      breakdown: Array<{ name: string; size: number; sizeFormatted: string }>;
    }> {
      let totalSize = 0;
      let fileCount = 0;
      let directoryCount = 0;
      const breakdown: Array<{ name: string; size: number; sizeFormatted: string }> = [];
    
      try {
        const entries = await fs.readdir(dirPath, { withFileTypes: true });
    
        for (const entry of entries) {
          const entryPath = path.join(dirPath, entry.name);
    
          try {
            if (entry.isFile()) {
              const stats = await fs.stat(entryPath);
              totalSize += stats.size;
              fileCount++;
    
              if (currentDepth < maxDepth) {
                breakdown.push({
                  name: entry.name,
                  size: stats.size,
                  sizeFormatted: formatBytes(stats.size),
                });
              }
            } else if (entry.isDirectory()) {
              directoryCount++;
    
              const subResult = await calculateDirSize(entryPath, currentDepth + 1, maxDepth);
              totalSize += subResult.totalSize;
              fileCount += subResult.fileCount;
              directoryCount += subResult.directoryCount;
    
              if (currentDepth < maxDepth) {
                breakdown.push({
                  name: entry.name + '/',
                  size: subResult.totalSize,
                  sizeFormatted: formatBytes(subResult.totalSize),
                });
              }
            }
          } catch {
            // Skip entries we can't access
          }
        }
      } catch {
        // Ignore permission errors on directories
      }
    
      // Sort breakdown by size descending
      breakdown.sort((a, b) => b.size - a.size);
    
      return { totalSize, fileCount, directoryCount, breakdown };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but offers minimal information. It doesn't specify whether this is a read-only operation, what permissions are required, how it handles errors (e.g., invalid paths), or what format the disk usage information is returned in. The description only states what the tool does at the most basic level.

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

Conciseness5/5

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

The description is extremely concise at just five words, front-loading the essential information with zero wasted words. Every word earns its place by communicating the core functionality efficiently.

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

Completeness2/5

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

For a tool with no annotations, no output schema, and multiple sibling tools, the description is inadequate. It doesn't explain what information is returned (e.g., total size, breakdown by subdirectory), how errors are handled, or when to choose this over similar tools. The description provides only the most basic functional statement without necessary context.

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

Parameters3/5

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

With 100% schema description coverage, both parameters are already documented in the schema. The description doesn't add any additional meaning about the parameters beyond what's in the schema descriptions ('Path to directory' and 'Max depth for breakdown'), so it meets the baseline but doesn't provide extra value.

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

Purpose4/5

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

The description clearly states the verb ('Get') and resource ('disk usage for a directory'), making the purpose immediately understandable. However, it doesn't differentiate from potential siblings like 'file_stat' or 'read_directory' that might provide related file system information, preventing a perfect score.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'file_stat' (which might include size info) and 'read_directory' (which could list contents), there's no indication of when this specific disk usage tool is appropriate or what distinguishes it from other file operations.

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/mcp-tool-shop-org/mcp-file-forge'

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