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 };
    }

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