Skip to main content
Glama

read_directory

List files and directories in a specified path with options for recursion, depth limits, hidden files, and pattern filtering to organize and access file system contents.

Instructions

List contents of a directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the directory
recursiveNoInclude subdirectories
max_depthNoMax recursion depth
include_hiddenNoInclude hidden files
patternNoGlob pattern filter

Implementation Reference

  • The core implementation of the read_directory tool logic.
    async function readDirectoryImpl(
      input: ReadDirectoryInput,
      currentDepth = 0
    ): Promise<ToolResult> {
      try {
        const absolutePath = path.resolve(input.path);
    
        // Check if directory exists
        const stats = await fs.stat(absolutePath);
    
        if (!stats.isDirectory()) {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'INVALID_PATH',
                  message: `Path is not a directory: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        // Check depth limit
        if (input.recursive && currentDepth >= input.max_depth) {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'DEPTH_EXCEEDED',
                  message: `Maximum recursion depth ${input.max_depth} exceeded`,
                }),
              },
            ],
          };
        }
    
        // Read directory entries
        const entries = await fs.readdir(absolutePath, { withFileTypes: true });
        const results: DirectoryEntry[] = [];
    
        for (const entry of entries) {
          // Skip hidden files if not requested
          if (!input.include_hidden && entry.name.startsWith('.')) {
            continue;
          }
    
          // Apply glob pattern filter if specified
          if (input.pattern) {
            // Simple glob matching (basic implementation)
            const regex = globToRegex(input.pattern);
            if (!regex.test(entry.name)) {
              continue;
            }
          }
    
          const entryPath = path.join(absolutePath, entry.name);
          const isFile = entry.isFile();
          const isDirectory = entry.isDirectory();
    
          const dirEntry: DirectoryEntry = {
            name: entry.name,
            path: entryPath,
            isFile,
            isDirectory,
          };
    
          // Get size for files
          if (isFile) {
            try {
              const entryStats = await fs.stat(entryPath);
              dirEntry.size = entryStats.size;
            } catch {
              // Ignore stat errors for individual files
            }
  • Tool registration for read_directory in the MCP server.
    // read_directory tool
    server.tool(
      'read_directory',
      'List contents of a directory',
      {
        path: z.string().describe('Path to the directory'),
        recursive: z.boolean().optional().describe('Include subdirectories'),
        max_depth: z.number().optional().describe('Max recursion depth'),
        include_hidden: z.boolean().optional().describe('Include hidden files'),
        pattern: z.string().optional().describe('Glob pattern filter'),
      },
      async (args) => {
        const input = ReadDirectoryInputSchema.parse(args);
        return await readDirectoryImpl(input);
      }
    );
  • Zod schema for validating the read_directory input.
    export const ReadDirectoryInputSchema = z.object({
      path: z.string().describe('Path to directory'),
      recursive: z.boolean().default(false).describe('Include subdirectories'),
      max_depth: z.number().default(5).describe('Max recursion depth'),
      include_hidden: z.boolean().default(false).describe('Include hidden files'),
      pattern: z.string().optional().describe('Glob pattern filter'),
    });
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. 'List contents of a directory' implies a read-only operation but doesn't specify permissions needed, whether it follows symlinks, error conditions (e.g., non-existent directory), or output format. For a tool with 5 parameters and no annotations, this minimal description leaves significant behavioral gaps unaddressed.

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 a single, efficient sentence that gets straight to the point: 'List contents of a directory.' There's no wasted words, no unnecessary elaboration, and the core purpose is immediately clear. This is an excellent example of conciseness.

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?

Given 5 parameters, no annotations, and no output schema, the description is insufficiently complete. A directory listing tool with filtering options (recursive, max_depth, include_hidden, pattern) needs more context about how these interact, what the output looks like, and error handling. The minimal description doesn't compensate for the lack of structured metadata.

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?

Schema description coverage is 100%, so all parameters are documented in the schema. The description adds no parameter-specific information beyond what's already in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in description, which applies here.

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 'List contents of a directory' clearly states the verb ('List') and resource ('contents of a directory'), making the purpose immediately understandable. It distinguishes from siblings like 'file_stat' or 'read_file' by focusing on directory listing rather than file operations. However, it doesn't explicitly differentiate from 'glob_search' which also lists files, so it's not a perfect 5.

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 'glob_search' (pattern-based file finding) and 'find_by_content' (content-based searching), there's no indication of when directory listing is preferred over these other listing/search tools. The description simply states what it does without contextual usage information.

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