Skip to main content
Glama

list_directory

Read-only

Lists files and directories in a specified path with clear [FILE] and [DIR] labels, supports recursive listing with depth control, and includes overflow protection for large directories.

Instructions

                    Get a detailed listing of all files and directories in a specified path.
                    
                    Use this instead of 'execute_command' with ls/dir commands.
                    Results distinguish between files and directories with [FILE] and [DIR] prefixes.
                    
                    Supports recursive listing with the 'depth' parameter (default: 2):
                    - depth=1: Only direct contents of the directory
                    - depth=2: Contents plus one level of subdirectories
                    - depth=3+: Multiple levels deep
                    
                    CONTEXT OVERFLOW PROTECTION:
                    - Top-level directory shows ALL items
                    - Nested directories are limited to 100 items maximum per directory
                    - When a nested directory has more than 100 items, you'll see a warning like:
                      [WARNING] node_modules: 500 items hidden (showing first 100 of 600 total)
                    - This prevents overwhelming the context with large directories like node_modules
                    
                    Results show full relative paths from the root directory being listed.
                    Example output with depth=2:
                    [DIR] src
                    [FILE] src/index.ts
                    [DIR] src/tools
                    [FILE] src/tools/filesystem.ts
                    
                    If a directory cannot be accessed, it will show [DENIED] instead.
                    Only works within allowed directories.
                    
                    IMPORTANT: Always use absolute paths for reliability. Paths are automatically normalized regardless of slash direction. Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.
                    This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
depthNo

Implementation Reference

  • The MCP tool handler function 'handleListDirectory' that validates input arguments using ListDirectoryArgsSchema, calls the listDirectory helper, measures execution time, joins results with newlines, and returns formatted ServerResult or error response.
    /**
     * Handle list_directory command
     */
    export async function handleListDirectory(args: unknown): Promise<ServerResult> {
        try {
            const startTime = Date.now();
            const parsed = ListDirectoryArgsSchema.parse(args);
            const entries = await listDirectory(parsed.path, parsed.depth);
            const duration = Date.now() - startTime;
    
            const resultText = entries.join('\n');
    
            return {
                content: [{ type: "text", text: resultText }],
            };
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            return createErrorResponse(errorMessage);
        }
    }
  • Zod input validation schema for the list_directory tool defining required 'path' (string) and optional 'depth' (number, default 2). Used in handler and tool registration.
    export const ListDirectoryArgsSchema = z.object({
      path: z.string(),
      depth: z.number().optional().default(2),
    });
  • src/server.ts:437-474 (registration)
    Tool registration in the MCP server's list_tools handler: defines name 'list_directory', detailed description of recursive listing with depth and protections, inputSchema from ListDirectoryArgsSchema, and read-only annotations.
    {
        name: "list_directory",
        description: `
                Get a detailed listing of all files and directories in a specified path.
                
                Use this instead of 'execute_command' with ls/dir commands.
                Results distinguish between files and directories with [FILE] and [DIR] prefixes.
                
                Supports recursive listing with the 'depth' parameter (default: 2):
                - depth=1: Only direct contents of the directory
                - depth=2: Contents plus one level of subdirectories
                - depth=3+: Multiple levels deep
                
                CONTEXT OVERFLOW PROTECTION:
                - Top-level directory shows ALL items
                - Nested directories are limited to 100 items maximum per directory
                - When a nested directory has more than 100 items, you'll see a warning like:
                  [WARNING] node_modules: 500 items hidden (showing first 100 of 600 total)
                - This prevents overwhelming the context with large directories like node_modules
                
                Results show full relative paths from the root directory being listed.
                Example output with depth=2:
                [DIR] src
                [FILE] src/index.ts
                [DIR] src/tools
                [FILE] src/tools/filesystem.ts
                
                If a directory cannot be accessed, it will show [DENIED] instead.
                Only works within allowed directories.
                
                ${PATH_GUIDANCE}
                ${CMD_PREFIX_DESCRIPTION}`,
        inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
        annotations: {
            title: "List Directory Contents",
            readOnlyHint: true,
        },
    },
  • Handler dispatch registration in MCP server's call_tool switch statement: maps 'list_directory' tool calls to handlers.handleListDirectory.
    case "list_directory":
        result = await handlers.handleListDirectory(args);
        break;
  • Core helper function implementing recursive directory listing up to specified depth. Validates paths, handles permissions ([DENIED]), limits nested directories to 100 items with warnings, formats output with [DIR]/[FILE] prefixes and relative paths.
    export async function listDirectory(dirPath: string, depth: number = 2): Promise<string[]> {
        const validPath = await validatePath(dirPath);
        const results: string[] = [];
    
        const MAX_NESTED_ITEMS = 100; // Maximum items to show per nested directory
    
        async function listRecursive(currentPath: string, currentDepth: number, relativePath: string = '', isTopLevel: boolean = true): Promise<void> {
            if (currentDepth <= 0) return;
    
            let entries;
            try {
                entries = await fs.readdir(currentPath, { withFileTypes: true });
            } catch (error) {
                // If we can't read this directory (permission denied), show as denied
                const displayPath = relativePath || path.basename(currentPath);
                results.push(`[DENIED] ${displayPath}`);
                return;
            }
    
            // Apply filtering for nested directories (not top level)
            const totalEntries = entries.length;
            let entriesToShow = entries;
            let filteredCount = 0;
    
            if (!isTopLevel && totalEntries > MAX_NESTED_ITEMS) {
                entriesToShow = entries.slice(0, MAX_NESTED_ITEMS);
                filteredCount = totalEntries - MAX_NESTED_ITEMS;
            }
    
            for (const entry of entriesToShow) {
                const fullPath = path.join(currentPath, entry.name);
                const displayPath = relativePath ? path.join(relativePath, entry.name) : entry.name;
    
                // Add this entry to results
                results.push(`${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${displayPath}`);
    
                // If it's a directory and we have depth remaining, recurse
                if (entry.isDirectory() && currentDepth > 1) {
                    try {
                        // Validate the path before recursing
                        await validatePath(fullPath);
                        await listRecursive(fullPath, currentDepth - 1, displayPath, false);
                    } catch (error) {
                        // If validation fails or we can't access it, it will be marked as denied
                        // when we try to read it in the recursive call
                        continue;
                    }
                }
            }
    
            // Add warning message if items were filtered
            if (filteredCount > 0) {
                const displayPath = relativePath || path.basename(currentPath);
                results.push(`[WARNING] ${displayPath}: ${filteredCount} items hidden (showing first ${MAX_NESTED_ITEMS} of ${totalEntries} total)`);
            }
        }
    
        await listRecursive(validPath, depth, '', true);
        return results;
    }
Behavior4/5

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

The description adds significant behavioral context beyond the readOnlyHint annotation. It details output formatting ('[FILE]' and '[DIR] prefixes'), recursive listing behavior with depth parameter, context overflow protection with item limits, error handling ('[DENIED]' for inaccessible directories), and path normalization behavior. While annotations cover safety, the description enriches understanding of the tool's operational characteristics.

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 and front-loaded information. It efficiently covers purpose, usage guidelines, parameters, behavior, and examples. While comprehensive, some redundancy exists (e.g., path guidance appears in multiple places), and the final paragraph about command referencing could be more 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 complexity (recursive listing, overflow protection, path handling) and lack of output schema, the description provides complete context. It explains output format with examples, error conditions, limitations, and practical usage guidance. The description compensates for the missing output schema by detailing what the tool returns and how to interpret results.

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

Parameters5/5

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

With 0% schema description coverage, the description fully compensates by explaining both parameters. For 'path': 'Always use absolute paths for reliability... Paths are automatically normalized... Relative paths may fail...' For 'depth': 'Supports recursive listing with the 'depth' parameter (default: 2)' with specific examples of depth=1, 2, 3+. It provides essential usage guidance that the bare schema lacks.

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 tool's purpose: 'Get a detailed listing of all files and directories in a specified path.' It specifies the verb ('Get a detailed listing'), resource ('files and directories'), and distinguishes from sibling 'execute_command' with ls/dir commands. The description explicitly differentiates this tool from alternatives.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool: 'Use this instead of 'execute_command' with ls/dir commands.' It also includes important context about path requirements: 'Always use absolute paths for reliability' and 'Only works within allowed directories.' This gives clear when-to-use and when-not-to-use guidance.

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/wonderwhy-er/ClaudeComputerCommander'

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