Skip to main content
Glama
StrawHatAI

Claude Desktop Commander MCP

by StrawHatAI

list_directory

View all files and directories in a specified path with clear [FILE] and [DIR] labels to distinguish content types within allowed directories.

Instructions

Get a detailed listing of all files and directories in a specified path. Results distinguish between files and directories with [FILE] and [DIR] prefixes. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes

Implementation Reference

  • The core handler function for the list_directory tool. It validates the path, reads directory entries using fs.readdir with file types, and formats each entry as [DIR] or [FILE] followed by the name.
    export async function listDirectory(dirPath: string): Promise<string[]> {
        const validPath = await validatePath(dirPath);
        const entries = await fs.readdir(validPath, { withFileTypes: true });
        return entries.map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`);
    }
  • Zod schema defining the input for list_directory: an object with a required 'path' string.
    export const ListDirectoryArgsSchema = z.object({
      path: z.string(),
    });
  • src/server.ts:156-163 (registration)
    Registration of the list_directory tool in the ListToolsRequestHandler, providing name, description, and input schema.
    {
      name: "list_directory",
      description:
        "Get a detailed listing of all files and directories in a specified path. " +
        "Results distinguish between files and directories with [FILE] and [DIR] prefixes. " +
        "Only works within allowed directories.",
      inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
    },
  • src/server.ts:294-300 (registration)
    Dispatch logic in CallToolRequestHandler: parses arguments using the schema and invokes the listDirectory handler, formatting the response.
    case "list_directory": {
      const parsed = ListDirectoryArgsSchema.parse(args);
      const entries = await listDirectory(parsed.path);
      return {
        content: [{ type: "text", text: entries.join('\n') }],
      };
    }
  • Shared helper function validatePath used by listDirectory (and other filesystem tools) to ensure paths are within allowed directories, handling symlinks and non-existent files securely.
    export async function validatePath(requestedPath: string): Promise<string> {
        const expandedPath = expandHome(requestedPath);
        const absolute = path.isAbsolute(expandedPath)
            ? path.resolve(expandedPath)
            : path.resolve(process.cwd(), expandedPath);
            
        const normalizedRequested = normalizePath(absolute);
    
        // Check if path is within allowed directories
        const isAllowed = allowedDirectories.some(dir => normalizedRequested.startsWith(normalizePath(dir)));
        if (!isAllowed) {
            throw new Error(`Access denied - path outside allowed directories: ${absolute}`);
        }
    
        // Handle symlinks by checking their real path
        try {
            const realPath = await fs.realpath(absolute);
            const normalizedReal = normalizePath(realPath);
            const isRealPathAllowed = allowedDirectories.some(dir => normalizedReal.startsWith(normalizePath(dir)));
            if (!isRealPathAllowed) {
                throw new Error("Access denied - symlink target outside allowed directories");
            }
            return realPath;
        } catch (error) {
            // For new files that don't exist yet, verify parent directory
            const parentDir = path.dirname(absolute);
            try {
                const realParentPath = await fs.realpath(parentDir);
                const normalizedParent = normalizePath(realParentPath);
                const isParentAllowed = allowedDirectories.some(dir => normalizedParent.startsWith(normalizePath(dir)));
                if (!isParentAllowed) {
                    throw new Error("Access denied - parent directory outside allowed directories");
                }
                return absolute;
            } catch {
                throw new Error(`Parent directory does not exist: ${parentDir}`);
            }
        }
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden and does well by disclosing key behavioral traits: it's a read operation (implied by 'Get'), distinguishes file types with prefixes, and has access restrictions ('Only works within allowed directories'). It lacks details on error handling or output format, but covers essential safety and scope aspects.

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 front-loaded with the core purpose in the first sentence, followed by additional details in two more sentences, each adding value without waste. It efficiently conveys necessary information in a compact form.

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

Completeness4/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 (listing files with access restrictions), no annotations, no output schema, and low schema coverage, the description is fairly complete by covering purpose, usage constraints, and behavioral traits. It could improve by detailing output structure or error cases, but it provides enough context for basic use.

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?

The input schema has 0% description coverage for the single parameter 'path,' but the description adds meaning by specifying it as 'a specified path' and implying it must be within allowed directories. This compensates partially, but without details on path format or examples, it meets the baseline for minimal parameter info.

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 with specific verbs ('Get a detailed listing') and resources ('files and directories in a specified path'), and distinguishes it from siblings by specifying it lists contents rather than creating, editing, or moving files. The mention of distinguishing between files and directories with prefixes adds further specificity.

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 for usage with 'Only works within allowed directories,' which implicitly suggests using list_allowed_directories first. However, it does not explicitly state when not to use this tool or name alternatives like search_files for filtered searches, leaving some guidance gaps.

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/StrawHatAI/claude-dev-tools'

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