Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

directory_tree

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

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 }
      },

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