Skip to main content
Glama

get_directory_tree

Generate a JSON-structured tree view of files and directories within the workspace filesystem. Specify a root path to visualize project directory hierarchy, including details like 'name', 'type', and nested 'children'.

Instructions

Get a recursive tree view of files and directories within the workspace filesystem as a JSON structure. Each entry includes 'name', 'type' (file/directory), and 'children' (an array) for directories. Files have no 'children' array. The output is formatted JSON text. Useful for understanding the complete structure of a project directory.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesThe root path for the directory tree (relative to the workspace directory).

Implementation Reference

  • Handler for get_directory_tree tool: parses arguments using schema, validates path, builds directory tree recursively, and returns JSON string.
    case "get_directory_tree": {
        const parsed = DirectoryTreeArgsSchema.parse(args);
        const validPath = validateWorkspacePath(parsed.path);
        const treeData = await buildDirectoryTree(validPath);
        resultText = JSON.stringify(treeData, null, 2);
        break;
    }
  • Recursive helper function to build the directory tree structure as JSON-compatible TreeEntry objects.
    async function buildDirectoryTree(currentPath: string): Promise<TreeEntry[]> {
        const entries = await fs.readdir(currentPath, {withFileTypes: true});
        const result: TreeEntry[] = [];
    
        for (const entry of entries) {
            const entryData: TreeEntry = {
                name: entry.name,
                type: entry.isDirectory() ? 'directory' : 'file'
            };
    
            if (entry.isDirectory()) {
                const subPath = path.join(currentPath, entry.name);
                 try {
                    const realPath = await fs.realpath(subPath);
                    if (realPath.startsWith(path.dirname(currentPath))) {
                        entryData.children = await buildDirectoryTree(subPath);
                    } else {
                         entryData.children = [];
                    }
                } catch (e) {
                     entryData.children = [];
                     console.error(`Skipping tree build in ${subPath}: ${(e as Error).message}`);
                }
            }
            result.push(entryData);
        }
        result.sort((a, b) => {
            if (a.type === 'directory' && b.type === 'file') return -1;
            if (a.type === 'file' && b.type === 'directory') return 1;
            return a.name.localeCompare(b.name);
        });
        return result;
    }
  • Zod schema for input arguments: requires a 'path' string.
    export const DirectoryTreeArgsSchema = z.object({
      path: z.string().describe("The root path for the directory tree (relative to the workspace directory)."),
    });
  • ToolDefinition object defining name, description, inputSchema, and buildPrompt for registration.
    export const directoryTreeTool: ToolDefinition = {
        name: "get_directory_tree", // Renamed slightly
        description:
          "Get a recursive tree view of files and directories within the workspace filesystem as a JSON structure. " +
          "Each entry includes 'name', 'type' (file/directory), and 'children' (an array) for directories. " +
          "Files have no 'children' array. The output is formatted JSON text. " +
          "Useful for understanding the complete structure of a project directory.",
        inputSchema: DirectoryTreeJsonSchema as any, // Cast as any if needed
    
        // Minimal buildPrompt as execution logic is separate
        buildPrompt: (args: any, modelId: string) => {
            const parsed = DirectoryTreeArgsSchema.safeParse(args);
            if (!parsed.success) {
                throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for get_directory_tree: ${parsed.error}`);
            }
            return {
                systemInstructionText: "",
                userQueryText: "",
                useWebSearch: false,
                enableFunctionCalling: false
            };
        },
        // No 'execute' function here
    };
  • Import and inclusion of directoryTreeTool in allTools array for server registration.
    import { directoryTreeTool } from "./directory_tree.js";
    import { moveFileTool } from "./move_file.js";
    import { searchFilesTool } from "./search_files.js";
    import { getFileInfoTool } from "./get_file_info.js";
    import { executeTerminalCommandTool } from "./execute_terminal_command.js"; // Renamed file and tool variable
    // Import the new combined tools
    import { saveGenerateProjectGuidelinesTool } from "./save_generate_project_guidelines.js";
    import { saveDocSnippetTool } from "./save_doc_snippet.js";
    import { saveTopicExplanationTool } from "./save_topic_explanation.js";
    // Removed old save_query_answer, added new specific ones
    import { saveAnswerQueryDirectTool } from "./save_answer_query_direct.js";
    import { saveAnswerQueryWebsearchTool } from "./save_answer_query_websearch.js";
    
    // Import new research-oriented tools
    import { codeAnalysisWithDocsTool } from "./code_analysis_with_docs.js";
    import { technicalComparisonTool } from "./technical_comparison.js";
    import { architecturePatternRecommendationTool } from "./architecture_pattern_recommendation.js";
    import { dependencyVulnerabilityScanTool } from "./dependency_vulnerability_scan.js";
    import { databaseSchemaAnalyzerTool } from "./database_schema_analyzer.js";
    import { securityBestPracticesAdvisorTool } from "./security_best_practices_advisor.js";
    import { testingStrategyGeneratorTool } from "./testing_strategy_generator.js";
    import { regulatoryComplianceAdvisorTool } from "./regulatory_compliance_advisor.js";
    import { microserviceDesignAssistantTool } from "./microservice_design_assistant.js";
    import { documentationGeneratorTool } from "./documentation_generator.js";
    
    
    export const allTools: ToolDefinition[] = [
        // Query & Generation Tools
        answerQueryWebsearchTool,
        answerQueryDirectTool,
        explainTopicWithDocsTool,
        getDocSnippetsTool,
        generateProjectGuidelinesTool,
        // Filesystem Tools
        readFileTool, // Handles single and multiple files now
        // readMultipleFilesTool, // Merged into readFileTool
        writeFileTool,
        editFileTool,
        // createDirectoryTool, // Removed
        listDirectoryTool,
        directoryTreeTool,
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the recursive nature, JSON output format, and structure of entries (name, type, children). However, it doesn't mention performance considerations (e.g., depth limits, large directories), error handling, or workspace boundaries.

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 efficiently structured in three sentences: first states the core functionality, second details the output structure, third provides usage context. Every sentence adds value with zero 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?

For a single-parameter read operation with no annotations and no output schema, the description provides good coverage of what the tool does and returns. It explains the output structure in detail, which compensates for the missing output schema. However, it could mention recursion depth limits or performance considerations for completeness.

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?

Schema description coverage is 100%, so the schema already documents the single 'path' parameter. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., path format examples, default behavior). Baseline 3 is appropriate when schema does the heavy lifting.

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'), resource ('files and directories within the workspace filesystem'), and output format ('JSON structure'). It distinguishes from siblings like 'list_directory_contents' by specifying the recursive, hierarchical nature and JSON output format.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context ('useful for understanding the complete structure of a project directory') but doesn't explicitly state when to use this tool versus alternatives like 'list_directory_contents' or 'search_filesystem'. No exclusions or prerequisites are mentioned.

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

Related 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/shariqriazz/vertex-ai-mcp-server'

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