Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

Directory Tree

directory_tree
Read-only

Generate a recursive JSON tree structure of files and directories, showing names, types, and hierarchical relationships for organized file system visualization.

Instructions

Get a recursive tree view of files and directories as a JSON structure. Each entry includes 'name', 'type' (file/directory), and 'children' for directories. Files have no children array, while directories always have a children array (which may be empty). The output is formatted with 2-space indentation for readability. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
excludePatternsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes

Implementation Reference

  • The main handler function for the directory_tree tool. It recursively builds a JSON tree structure of directory contents using a buildTree helper, applies excludePatterns using minimatch for glob patterns, validates paths, and returns the tree as formatted JSON.
    async (args: z.infer<typeof DirectoryTreeArgsSchema>) => {
      interface TreeEntry {
        name: string;
        type: 'file' | 'directory';
        children?: TreeEntry[];
      }
      const rootPath = args.path;
    
      async function buildTree(currentPath: string, excludePatterns: string[] = []): Promise<TreeEntry[]> {
        const validPath = await validatePath(currentPath);
        const entries = await fs.readdir(validPath, { withFileTypes: true });
        const result: TreeEntry[] = [];
    
        for (const entry of entries) {
          const relativePath = path.relative(rootPath, path.join(currentPath, entry.name));
          const shouldExclude = excludePatterns.some(pattern => {
            if (pattern.includes('*')) {
              return minimatch(relativePath, pattern, { dot: true });
            }
            // For files: match exact name or as part of path
            // For directories: match as directory path
            return minimatch(relativePath, pattern, { dot: true }) ||
              minimatch(relativePath, `**/${pattern}`, { dot: true }) ||
              minimatch(relativePath, `**/${pattern}/**`, { dot: true });
          });
          if (shouldExclude)
            continue;
    
          const entryData: TreeEntry = {
            name: entry.name,
            type: entry.isDirectory() ? 'directory' : 'file'
          };
    
          if (entry.isDirectory()) {
            const subPath = path.join(currentPath, entry.name);
            entryData.children = await buildTree(subPath, excludePatterns);
          }
    
          result.push(entryData);
        }
    
        return result;
      }
    
      const treeData = await buildTree(rootPath, args.excludePatterns);
      const text = JSON.stringify(treeData, null, 2);
      const contentBlock = { type: "text" as const, text };
      return {
        content: [contentBlock],
        structuredContent: { content: text }
      };
    }
  • Zod schema defining the input arguments for directory_tree: path (string) and optional excludePatterns (array of strings).
    const DirectoryTreeArgsSchema = z.object({
      path: z.string(),
      excludePatterns: z.array(z.string()).optional().default([])
    });
  • Registers the directory_tree tool with the MCP server, specifying title, description, inputSchema (mirroring DirectoryTreeArgsSchema), outputSchema, and annotations.
    server.registerTool(
      "directory_tree",
      {
        title: "Directory Tree",
        description:
          "Get a recursive tree view of files and directories as a JSON structure. " +
          "Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
          "Files have no children array, while directories always have a children array (which may be empty). " +
          "The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
        inputSchema: {
          path: z.string(),
          excludePatterns: z.array(z.string()).optional().default([])
        },
        outputSchema: { content: z.string() },
        annotations: { readOnlyHint: true }
      },
Behavior4/5

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

The description adds valuable behavioral context beyond the readOnlyHint annotation. It specifies the recursive nature, output format details (JSON with 2-space indentation), structural rules (files have no children, directories always have children array), and the constraint about allowed directories. This provides important operational context that annotations alone don't cover.

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 perfectly front-loaded with the core purpose in the first sentence, followed by specific behavioral details. Every sentence adds value: the JSON structure details, formatting information, and operational constraint. No wasted words or redundant information.

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 has readOnlyHint annotation and an output schema exists, the description provides good coverage of behavioral aspects. It explains the recursive nature, output structure, and operational constraints. The main gap is lack of parameter documentation, but with only 2 parameters and an output schema handling return values, this is reasonably complete.

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 0% schema description coverage, the schema provides no parameter documentation. The description doesn't mention either parameter (path or excludePatterns), so it doesn't compensate for the schema gap. However, the tool has only 2 parameters (1 required), making the baseline reasonable despite the lack of parameter information in the description.

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 specific action ('Get a recursive tree view') and resource ('files and directories as a JSON structure'), distinguishing it from siblings like list_directory (flat listing) or get_file_info (single file metadata). It explicitly mentions the recursive nature and JSON output format, which differentiates it from similar tools.

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 about when to use this tool ('recursive tree view') and includes one exclusion ('Only works within allowed directories'), but doesn't explicitly mention when to choose alternatives like list_directory (for flat listings) or search_files (for pattern-based searches). The context is helpful but lacks explicit sibling tool 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