Skip to main content
Glama

get_file_tree

Retrieve the file tree structure of a code project to understand its organization and contents, with options to filter using .gitignore rules and custom exclusions.

Instructions

Retrieves the file tree structure of the project.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathNoThe target directory path.
use_gitignoreNoWhether to use .gitignore rules.
ignore_gitNoWhether to ignore the .git directory.
custom_blacklistNoCustom blacklist items.

Implementation Reference

  • Main handler function that implements the core logic of the get_file_tree tool: path validation, file listing, tree building, rendering, and result formatting.
    async function handleRequest(parameters) {
        console.error('get_file_tree: Starting execution');
        const startTime = Date.now();
    
        const { path: targetPath, use_gitignore, ignore_git, custom_blacklist } = parameters;
        if (!targetPath) {
            throw new Error("Missing required parameter: 'path'.");
        }
    
        // Resolve to absolute path - assuming the input path might be relative to CWD
        const absolutePath = path.resolve(targetPath);
        console.error(`get_file_tree: Resolved path to ${absolutePath}`);
    
        // Validate path existence and type
        try {
            const stats = await fs.stat(absolutePath);
            if (!stats.isDirectory()) {
                throw new Error(`Path '${targetPath}' is not a directory.`);
            }
            console.error(`get_file_tree: Validated path exists and is a directory`);
        } catch (error) {
            if (error.code === 'ENOENT') {
                throw new Error(`Path '${targetPath}' not found.`);
            }
            // Rethrow other stat errors (like permission issues)
            throw new Error(`Error accessing path '${targetPath}': ${error.message}`);
        }
    
        // List files using the core lister and provided filter options
        console.error(`get_file_tree: Listing files in ${absolutePath}`);
        const fileList = await listFiles(absolutePath, {
            useGitignore: use_gitignore || false, // Pass through params correctly, default to false for speed
            ignoreGit: ignore_git || true,
            customBlacklist: custom_blacklist || []
        });
        console.error(`get_file_tree: Found ${fileList.length} files`);
    
        // Build and render the tree structure
        console.error(`get_file_tree: Building tree object`);
        const treeObject = buildTreeObject(fileList);
        const rootDirName = path.basename(absolutePath);
    
        // Render the tree starting from the root object, prefix indicates level
        console.error(`get_file_tree: Rendering tree`);
        const treeString = rootDirName + '/\n' + renderTree(treeObject);
    
        const executionTime = Date.now() - startTime;
        console.error(`get_file_tree: Execution completed in ${executionTime}ms`);
    
        return {
            file_tree: treeString // Return the result in the expected format
        };
    }
  • Registers the get_file_tree tool with the MCP server, including input schema validation using Zod and a wrapper that calls the handler with logging and result adaptation.
    if (getFileTreeHandler) {
        server.tool(
            'get_file_tree',
            'Retrieves the file tree structure of the project.',
            {
                path: z.string().optional().describe('The target directory path.'),
                use_gitignore: z.boolean().optional().describe('Whether to use .gitignore rules.'),
                ignore_git: z.boolean().optional().describe('Whether to ignore the .git directory.'),
                custom_blacklist: z.array(z.string()).optional().describe('Custom blacklist items.')
            },
            async (params) => {
                logInfo(`Executing get_file_tree tool with params: ${JSON.stringify(params)}`);
                try {
                    const startTime = Date.now();
                    const result = await getFileTreeHandler(params);
                    const executionTime = Date.now() - startTime;
                    logDebug(`get_file_tree completed in ${executionTime}ms`);
                    return adaptToolResult(result);
                } catch (error) {
                    logError('Error in get_file_tree tool:', error);
                    throw error;
                }
            }
        );
    }
  • Zod schema defining the input parameters for the get_file_tree tool.
    path: z.string().optional().describe('The target directory path.'),
    use_gitignore: z.boolean().optional().describe('Whether to use .gitignore rules.'),
    ignore_git: z.boolean().optional().describe('Whether to ignore the .git directory.'),
    custom_blacklist: z.array(z.string()).optional().describe('Custom blacklist items.')
  • Helper function to build a hierarchical tree object from a flat list of file paths, used in the handler.
    function buildTreeObject(filePaths) {
        const tree = {};
        // Sort paths alphabetically for consistent tree structure
        const sortedPaths = [...filePaths].sort((a, b) => a.localeCompare(b));
        sortedPaths.forEach(filePath => {
            // Normalize path separators just in case
            const parts = filePath.replace(/\\/g, '/').split('/');
            let currentLevel = tree;
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                if (!part) continue; // Skip empty parts potentially caused by leading/trailing slashes
                if (i === parts.length - 1) { // It's a file
                    if (!currentLevel._files) {
                        currentLevel._files = [];
                    }
                    // Avoid adding duplicates if path normalization leads to same entry
                    if (!currentLevel._files.includes(part)) {
                         currentLevel._files.push(part);
                    }
                } else { // It's a directory
                    if (!currentLevel[part]) {
                        currentLevel[part] = {}; // Create directory node if it doesn't exist
                    }
                    // Ensure we don't try to traverse into a file node mistakenly marked earlier
                    if (typeof currentLevel[part] === 'object' && currentLevel[part] !== null) {
                        currentLevel = currentLevel[part];
                    } else {
                        // Handle potential path conflict (e.g., 'a/b' file and 'a/b/c' directory)
                        // This basic builder assumes valid, non-conflicting paths from listFiles
                        console.warn(`Path conflict or unexpected structure processing: ${filePath}`);
                        break; // Stop processing this conflicting path
                    }
                }
            }
        });
        return tree;
    }
  • Helper function to render the tree object into an ASCII art string representation, used in the handler.
    function renderTree(node, prefix = '') {
        let result = '';
        // Get directory names, sort them
        const folders = Object.keys(node).filter(key => key !== '_files').sort((a, b) => a.localeCompare(b));
        // Get file names, sort them
        const files = node._files ? [...node._files].sort((a, b) => a.localeCompare(b)) : [];
        const totalItems = folders.length + files.length;
        let itemCount = 0;
        // Render folders first
        folders.forEach((folder) => {
            itemCount++;
            const isLast = itemCount === totalItems;
            const connector = isLast ? '└── ' : '├── ';
            const childPrefix = isLast ? '    ' : '│   '; // Connector for children
            result += prefix + connector + folder + '/\n';
            result += renderTree(node[folder], prefix + childPrefix); // Recurse into subdirectory
        });
        // Render files
        files.forEach((file) => {
             itemCount++;
            const isLast = itemCount === totalItems;
            const connector = isLast ? '└── ' : '├── ';
            result += prefix + connector + file + '\n';
        });
        return result;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states 'Retrieves' which implies a read-only operation, but doesn't cover critical aspects like whether it requires specific permissions, how it handles large directories, or what the output format looks like (e.g., tree structure details). This leaves significant gaps for a tool with 4 parameters.

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 a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded and wastes no space, making it highly concise and well-structured for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a file tree retrieval tool with 4 parameters and no output schema, the description is incomplete. It doesn't explain the return format (e.g., hierarchical structure), potential limitations (e.g., depth or size constraints), or how parameters interact (e.g., combining gitignore and custom blacklist). Without annotations, this leaves the agent under-informed for effective use.

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?

The input schema has 100% description coverage, so parameters like 'path', 'use_gitignore', 'ignore_git', and 'custom_blacklist' are well-documented in the schema. The description adds no additional parameter semantics beyond implying a 'project' context, which is minimal value. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Retrieves' and the resource 'file tree structure of the project', making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'analyze_code' or 'merge_content', which might also involve file operations, so it falls short of a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'analyze_code' or 'merge_content'. It lacks context about scenarios where retrieving a file tree is appropriate, such as for navigation or analysis, leaving the agent to infer usage without explicit direction.

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/yy1588133/code-merge-mcp'

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