Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

List Directory with Sizes

list_directory_with_sizes
Read-only

List files and directories with sizes to analyze storage usage and identify large items in a specified path. Results show [FILE] and [DIR] prefixes for clear distinction.

Instructions

Get a detailed listing of all files and directories in a specified path, including sizes. Results clearly distinguish between files and directories with [FILE] and [DIR] prefixes. This tool is useful for understanding directory structure and finding specific files within a directory. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
sortByNoSort entries by name or sizename

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes

Implementation Reference

  • The handler function for the 'list_directory_with_sizes' tool. It reads the directory, gets stats for each entry including size, sorts by name or size, formats the output with file/dir prefixes and sizes, and includes a summary of totals.
    async (args: z.infer<typeof ListDirectoryWithSizesArgsSchema>) => {
      const validPath = await validatePath(args.path);
      const entries = await fs.readdir(validPath, { withFileTypes: true });
    
      // Get detailed information for each entry
      const detailedEntries = await Promise.all(
        entries.map(async (entry) => {
          const entryPath = path.join(validPath, entry.name);
          try {
            const stats = await fs.stat(entryPath);
            return {
              name: entry.name,
              isDirectory: entry.isDirectory(),
              size: stats.size,
              mtime: stats.mtime
            };
          } catch (error) {
            return {
              name: entry.name,
              isDirectory: entry.isDirectory(),
              size: 0,
              mtime: new Date(0)
            };
          }
        })
      );
    
      // Sort entries based on sortBy parameter
      const sortedEntries = [...detailedEntries].sort((a, b) => {
        if (args.sortBy === 'size') {
          return b.size - a.size; // Descending by size
        }
        // Default sort by name
        return a.name.localeCompare(b.name);
      });
    
      // Format the output
      const formattedEntries = sortedEntries.map(entry =>
        `${entry.isDirectory ? "[DIR]" : "[FILE]"} ${entry.name.padEnd(30)} ${
          entry.isDirectory ? "" : formatSize(entry.size).padStart(10)
        }`
      );
    
      // Add summary
      const totalFiles = detailedEntries.filter(e => !e.isDirectory).length;
      const totalDirs = detailedEntries.filter(e => e.isDirectory).length;
      const totalSize = detailedEntries.reduce((sum, entry) => sum + (entry.isDirectory ? 0 : entry.size), 0);
    
      const summary = [
        "",
        `Total: ${totalFiles} files, ${totalDirs} directories`,
        `Combined size: ${formatSize(totalSize)}`
      ];
    
      const text = [...formattedEntries, ...summary].join("\n");
      const contentBlock = { type: "text" as const, text };
      return {
        content: [contentBlock],
        structuredContent: { content: text }
      };
    }
  • Zod schema defining the input arguments for the list_directory_with_sizes tool: path (required) and sortBy (optional, defaults to 'name'). Used for typing the handler function.
    const ListDirectoryWithSizesArgsSchema = z.object({
      path: z.string(),
      sortBy: z.enum(['name', 'size']).optional().default('name').describe('Sort entries by name or size'),
    });
  • Registration of the 'list_directory_with_sizes' tool using server.registerTool, including title, description, inputSchema (duplicated inline), outputSchema, annotations, and the inline handler function.
    server.registerTool(
      "list_directory_with_sizes",
      {
        title: "List Directory with Sizes",
        description:
          "Get a detailed listing of all files and directories in a specified path, including sizes. " +
          "Results clearly distinguish between files and directories with [FILE] and [DIR] " +
          "prefixes. This tool is useful for understanding directory structure and " +
          "finding specific files within a directory. Only works within allowed directories.",
        inputSchema: {
          path: z.string(),
          sortBy: z.enum(["name", "size"]).optional().default("name").describe("Sort entries by name or size")
        },
        outputSchema: { content: z.string() },
        annotations: { readOnlyHint: true }
      },
      async (args: z.infer<typeof ListDirectoryWithSizesArgsSchema>) => {
        const validPath = await validatePath(args.path);
        const entries = await fs.readdir(validPath, { withFileTypes: true });
    
        // Get detailed information for each entry
        const detailedEntries = await Promise.all(
          entries.map(async (entry) => {
            const entryPath = path.join(validPath, entry.name);
            try {
              const stats = await fs.stat(entryPath);
              return {
                name: entry.name,
                isDirectory: entry.isDirectory(),
                size: stats.size,
                mtime: stats.mtime
              };
            } catch (error) {
              return {
                name: entry.name,
                isDirectory: entry.isDirectory(),
                size: 0,
                mtime: new Date(0)
              };
            }
          })
        );
    
        // Sort entries based on sortBy parameter
        const sortedEntries = [...detailedEntries].sort((a, b) => {
          if (args.sortBy === 'size') {
            return b.size - a.size; // Descending by size
          }
          // Default sort by name
          return a.name.localeCompare(b.name);
        });
    
        // Format the output
        const formattedEntries = sortedEntries.map(entry =>
          `${entry.isDirectory ? "[DIR]" : "[FILE]"} ${entry.name.padEnd(30)} ${
            entry.isDirectory ? "" : formatSize(entry.size).padStart(10)
          }`
        );
    
        // Add summary
        const totalFiles = detailedEntries.filter(e => !e.isDirectory).length;
        const totalDirs = detailedEntries.filter(e => e.isDirectory).length;
        const totalSize = detailedEntries.reduce((sum, entry) => sum + (entry.isDirectory ? 0 : entry.size), 0);
    
        const summary = [
          "",
          `Total: ${totalFiles} files, ${totalDirs} directories`,
          `Combined size: ${formatSize(totalSize)}`
        ];
    
        const text = [...formattedEntries, ...summary].join("\n");
        const contentBlock = { type: "text" as const, text };
        return {
          content: [contentBlock],
          structuredContent: { content: text }
        };
      }
    );
Behavior4/5

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

Annotations provide readOnlyHint=true, but the description adds valuable behavioral context beyond that: it discloses output format details ([FILE]/[DIR] prefixes), the scope limitation ('Only works within allowed directories'), and that it provides sizes. This goes beyond what annotations alone provide, though it doesn't mention pagination or rate limits.

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 efficiently structured in three sentences: first states core functionality, second describes output format, third provides usage context and limitation. Every sentence adds value with zero wasted words, making it appropriately front-loaded and concise.

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

Completeness5/5

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

Given the tool's moderate complexity, the presence of annotations (readOnlyHint), an output schema (implied by context signals), and the description's coverage of key behavioral aspects, this description is complete enough. It explains what the tool does, output format, and limitations without needing to duplicate schema information.

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 50% schema description coverage (only 'sortBy' has a description), the description doesn't add any parameter-specific information beyond what's in the schema. It mentions 'specified path' which corresponds to the 'path' parameter but doesn't provide additional semantics like path format or constraints. The baseline 3 is appropriate given the partial schema coverage.

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 verb 'Get' and resource 'detailed listing of all files and directories in a specified path, including sizes', making the purpose specific. It distinguishes from sibling 'list_directory' by explicitly mentioning size inclusion and [FILE]/[DIR] prefixes, providing clear differentiation.

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

Usage Guidelines4/5

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

The description provides clear context with 'Only works within allowed directories' and implies usage for 'understanding directory structure and finding specific files', but doesn't explicitly state when to use this tool versus alternatives like 'directory_tree' or 'list_directory'. It offers some guidance but lacks explicit sibling comparisons.

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/modelcontextprotocol/filesystem'

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