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,

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