Skip to main content
Glama
MrGNSS

Desktop Commander MCP

by MrGNSS

list_directory

View all files and folders in a specific directory path, with clear labels to distinguish between files [FILE] and directories [DIR].

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 that implements the 'list_directory' tool logic. It validates the input path for security restrictions, reads the directory entries, and returns formatted list distinguishing files [FILE] and directories [DIR].
    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 input schema for the 'list_directory' tool, validating a single 'path' parameter.
    export const ListDirectoryArgsSchema = z.object({
      path: z.string(),
    });
  • src/server.ts:157-162 (registration)
    Tool registration in the MCP server's ListTools handler, defining name, description, and input schema for 'list_directory'.
    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)
    Server-side dispatch handler for the 'list_directory' tool call, parsing args, invoking the handler, and formatting response.
    case "list_directory": {
      const parsed = ListDirectoryArgsSchema.parse(args);
      const entries = await listDirectory(parsed.path);
      return {
        content: [{ type: "text", text: entries.join('\n') }],
      };
    }
  • Security helper function used by listDirectory to validate paths are within allowed directories, handles symlinks and non-existent files.
    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}`);
            }
        }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.2/5.0
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.