Skip to main content
Glama

directory_tree

Generate a recursive JSON tree structure of files and directories with depth control and exclusion patterns using glob syntax. Each entry includes name, type, and children arrays for directories. Ideal for visualizing and managing filesystem hierarchies.

Instructions

Get a recursive tree view of files and directories as a JSON structure. Supports depth limiting to control traversal depth and exclusion patterns using glob syntax. 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). Requires maxDepth parameter (default 2) to limit recursion. Use excludePatterns to filter out unwanted files/directories. The output is formatted with 2-space indentation for readability. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
excludePatternsNoGlob patterns for files/directories to exclude (e.g., "*.log", "node_modules").
maxDepthYesMaximum depth to traverse. Must be a positive integer. Handler default: 2.
pathYes

Implementation Reference

  • Core implementation of the directory_tree tool handler. Parses args, validates path, recursively builds directory tree structure with depth limit and exclude patterns, returns JSON tree.
    export async function handleDirectoryTree( args: unknown, allowedDirectories: string[], symlinksMap: Map<string, string>, noFollowSymlinks: boolean ) { const parsed = parseArgs(DirectoryTreeArgsSchema, args, 'directory_tree'); const { path: startPath, maxDepth, excludePatterns } = parsed; // maxDepth is mandatory (handler default: 2) const validatedStartPath = await validatePath(startPath, allowedDirectories, symlinksMap, noFollowSymlinks); async function buildTree( currentPath: string, basePath: string, currentDepth: number, maxDepth?: number, excludePatterns?: string[] ): Promise<TreeEntry[]> { // Depth check if (maxDepth !== undefined && currentDepth >= maxDepth) { return []; // Stop traversal if max depth is reached } const validPath = await validatePath(currentPath, allowedDirectories, symlinksMap, noFollowSymlinks); let entries; try { entries = await fs.readdir(validPath, { withFileTypes: true }); } catch (error) { // Handle cases where directory might not be readable console.error(`Error reading directory ${validPath}: ${error}`); return []; } const result: TreeEntry[] = []; for (const entry of entries) { const entryFullPath = path.join(currentPath, entry.name); const entryRelativePath = path.relative(basePath, entryFullPath); // Exclusion check using minimatch if (excludePatterns && excludePatterns.length > 0) { const shouldExclude = excludePatterns.some(pattern => minimatch(entryRelativePath, pattern, { dot: true, matchBase: true }) ); if (shouldExclude) { continue; // Skip this entry if it matches any exclude pattern } } const entryData: TreeEntry = { name: entry.name, type: entry.isDirectory() ? 'directory' : 'file' }; if (entry.isDirectory()) { // Recursive call with incremented depth entryData.children = await buildTree( entryFullPath, basePath, currentDepth + 1, maxDepth, excludePatterns ); } result.push(entryData); } return result; } // Initial call to buildTree with base parameters const treeData = await buildTree( validatedStartPath, validatedStartPath, 0, maxDepth, excludePatterns ); return { content: [{ type: "text", text: JSON.stringify(treeData, null, 2) }], }; }
  • TypeBox schema defining input parameters for directory_tree: path (required), maxDepth (integer >=1), excludePatterns (optional array of glob patterns).
    export const DirectoryTreeArgsSchema = Type.Object({ path: Type.String(), maxDepth: Type.Integer({ minimum: 1, description: 'Maximum depth to traverse. Must be a positive integer. Handler default: 2.' }), excludePatterns: Type.Optional( Type.Array(Type.String(), { default: [], description: 'Glob patterns for files/directories to exclude (e.g., "*.log", "node_modules").' }) ) }); export type DirectoryTreeArgs = Static<typeof DirectoryTreeArgsSchema>;
  • index.ts:210-211 (registration)
    Maps the 'directory_tree' tool name to the handleDirectoryTree function in the toolHandlers object, passing server context (allowedDirectories, symlinksMap, noFollowSymlinks). Used by server.addTool loop.
    directory_tree: (a: unknown) => handleDirectoryTree(a, allowedDirectories, symlinksMap, noFollowSymlinks),
  • index.ts:308-308 (registration)
    Registers 'directory_tree' tool metadata (name and description) in the allTools array, filtered by permissions, then added to MCP server.
    { name: "directory_tree", description: "Directory tree view" },

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/rawr-ai/mcp-filesystem'

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