Skip to main content
Glama
owayo

MCP Source Tree Server

get_src_tree

Generate a JSON file tree from a directory's src folder while respecting .gitignore rules to visualize project structure.

Instructions

Generate a file tree for the specified directory, filtering files based on .gitignore. Traverses the filesystem and generates a JSON-formatted tree structure that preserves hierarchy.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
directoryYes

Implementation Reference

  • tree.py:132-145 (handler)
    The main tool handler function for 'get_src_tree', decorated with @mcp.tool(). Handles directory validation, gitignore parsing, tree building, and JSON serialization.
    @mcp.tool()
    async def get_src_tree(directory: str) -> str:
        """
        Generate a file tree for the specified directory, filtering files based on .gitignore.
        Traverses the filesystem and generates a JSON-formatted tree structure that preserves hierarchy.
        """
        if not os.path.exists(directory):
            return json.dumps({"error": "directory not found"}, indent=2)
    
        gitignore = read_gitignore(directory)
        tree = build_tree(directory, directory, gitignore)
    
        return json.dumps(tree, indent=2, ensure_ascii=False)
  • Core recursive helper that builds the hierarchical dictionary representation of the directory tree, applying ignore rules.
    def build_tree(
        path: str,
        base_path: str,
        gitignore: Optional[pathspec.PathSpec] = None,
        is_root: bool = True,
    ) -> Dict[str, Any]:
        """
        Build directory tree structure
    
        Args:
            path: Directory path to traverse
            base_path: Base directory path containing .gitignore
            gitignore: PathSpec object from .gitignore
            is_root: Whether this is the root directory
    
        Returns:
            Dictionary representing directory tree
        """
        # Check if path should be ignored
        if should_ignore(path, base_path, gitignore):
            return None
    
        name = os.path.abspath(path) if is_root else os.path.basename(path)
    
        if os.path.isfile(path):
            return {"name": name, "type": "file"}
    
        result = {"name": name, "type": "directory", "children": []}
    
        try:
            items = os.listdir(path)
            for item in sorted(items):
                item_path = os.path.join(path, item)
                child = build_tree(item_path, base_path, gitignore, is_root=False)
                if child:
                    result["children"].append(child)
        except PermissionError:
            pass
    
        return result
  • tree.py:41-71 (helper)
    Helper function to check if a file or directory should be ignored based on dot-prefix and .gitignore patterns.
    def should_ignore(
        path: str, base_path: str, gitignore: Optional[pathspec.PathSpec] = None
    ) -> bool:
        """
        Determine if the specified path should be ignored
    
        Args:
            path: Path to check
            base_path: Base directory path containing .gitignore
            gitignore: PathSpec object from .gitignore
    
        Returns:
            True if path should be ignored
        """
        # Ignore directories starting with .
        if os.path.isdir(path) and os.path.basename(path).startswith("."):
            return True
    
        # Check if path matches .gitignore rules
        if gitignore:
            relative_path = os.path.relpath(path, base_path)
            # Add trailing slash for directories
            if os.path.isdir(path):
                relative_path = relative_path + os.sep
            # Normalize path (unify slashes)
            relative_path = relative_path.replace(os.sep, "/")
            if gitignore.match_file(relative_path):
                return True
    
        return False
  • tree.py:14-39 (helper)
    Helper that parses the .gitignore file into a PathSpec for matching ignore patterns.
    def read_gitignore(base_path: str) -> Optional[pathspec.PathSpec]:
        """
        Read .gitignore file and return a PathSpec object
    
        Args:
            base_path: Base directory path containing .gitignore
    
        Returns:
            PathSpec object, or None if .gitignore doesn't exist
        """
        gitignore_path = os.path.join(base_path, ".gitignore")
        if not os.path.exists(gitignore_path):
            return None
    
        with open(gitignore_path, "r") as f:
            # Remove empty lines and comments
            lines = [
                line.strip()
                for line in f.readlines()
                if line.strip() and not line.startswith("#")
            ]
            gitignore = pathspec.PathSpec.from_lines(
                pathspec.patterns.GitWildMatchPattern, lines
            )
        return gitignore
  • tree.py:11-12 (registration)
    Initialization of the FastMCP server instance which handles tool registration via decorators.
    mcp = FastMCP("src-tree")
Behavior2/5

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

No annotations are provided, so the description carries full burden. It discloses that the tool traverses filesystems, generates JSON output, and applies .gitignore filtering. However, it omits critical behavioral details like error handling, performance characteristics (e.g., recursion depth, large directory handling), authentication needs, or rate limits. For a filesystem tool with zero annotation coverage, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with three sentences that directly address functionality. It's front-loaded with the core purpose and avoids unnecessary elaboration. However, the second sentence could be more tightly integrated with the first for better flow, slightly affecting structure.

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 filesystem traversal and JSON generation, with no annotations and no output schema, the description is incomplete. It mentions the output format ('JSON-formatted tree structure') but doesn't describe the structure's schema, error cases, or edge behaviors (e.g., symbolic links, permissions). For a tool with rich potential outputs and zero structured documentation, this falls short.

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 0%, with one parameter ('directory') undocumented in the schema. The description adds context by specifying it's for 'the specified directory' and mentions .gitignore filtering, which implies the directory should be a valid path. However, it doesn't explain parameter format (e.g., absolute vs. relative paths) or constraints, leaving gaps in parameter understanding.

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 tool's purpose: 'Generate a file tree for the specified directory, filtering files based on .gitignore.' It specifies the verb ('generate'), resource ('file tree'), and key behavior (gitignore filtering). However, with no sibling tools mentioned, it cannot demonstrate differentiation from alternatives, preventing 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 explicit guidance on when to use this tool versus alternatives. It mentions the core functionality but lacks context about prerequisites, limitations, or comparison to other file operations. With no sibling tools, this gap is less critical but still represents a lack of usage 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/owayo/mcp-src-tree'

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