Skip to main content
Glama
Preston-Harrison

Filesystem MCP Server

directory_tree

Generate a plain text tree structure to visualize directory contents and hierarchy for navigation and organization purposes.

Instructions

Generate a plain text tree structure of a directory.

Args: path (str): Directory path to generate tree for (absolute or relative to allowed directories)

Returns: str: Plain text representation of directory tree, or error message if failed

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • main.py:319-377 (handler)
    The main handler function for the 'directory_tree' tool. It resolves the path, generates a visual tree structure using Unicode characters, respects .gitignore via _skip_ignored, handles recursion with depth limit, and counts directories/files. Includes input validation docstring serving as schema and @mcp.tool decorator for registration.
    @mcp.tool
    def directory_tree(path: str) -> str:
        """Generate a plain text tree structure of a directory.
    
        Args:
            path (str): Directory path to generate tree for (absolute or relative to allowed directories)
    
        Returns:
            str: Plain text representation of directory tree, or error message if failed
        """
        try:
            rp = _resolve(path)
            spec_cache: Dict[Path, Optional[pathspec.PathSpec]] = {}
            space =  '    '
            branch = '│   '
            tee =    '├── '
            last =   '└── '
    
            def tree(dir_path: Path, level: int=-1, limit_to_directories: bool=False, length_limit: int=500):
                """Given a directory Path object print a visual tree structure"""
                result = ""
                dir_path = Path(dir_path) # accept string coerceable to Path
                files = 0
                directories = 0
                def inner(dir_path: Path, prefix: str='', level=-1):
                    nonlocal files, directories
                    # print(dir_path, _skip_ignored(dir_path, rp, spec_cache), file=sys.stderr)
                    if _skip_ignored(dir_path, rp, spec_cache):
                        return
                    if not level: 
                        return # 0, stop iterating
                    if limit_to_directories:
                        contents = [d for d in dir_path.iterdir() if d.is_dir()]
                    else: 
                        contents = list(dir for dir in dir_path.iterdir() )
    
                    pointers = [tee] * (len(contents) - 1) + [last]
                    for pointer, path in zip(pointers, contents):
                        if path.is_dir():
                            yield prefix + pointer + path.name
                            directories += 1
                            extension = branch if pointer == tee else space 
                            yield from inner(path, prefix=prefix+extension, level=level-1)
                        elif not limit_to_directories:
                            yield prefix + pointer + path.name
                            files += 1
                result += dir_path.name + "\n"
                iterator = inner(dir_path, level=level)
                for line in islice(iterator, length_limit):
                    result += line + "\n"
                if next(iterator, None):
                    result += f'... length_limit, {length_limit}, reached, counted:\n'
                result += f'\n{directories} directories' + (f', {files} files' if files else '') + "\n"
                return result
    
            return tree(rp)
        except Exception as e:
            return _human_error(e, "enumerating directory")
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses that the tool generates a tree structure (behavior) and may return an error message on failure (error handling). However, it doesn't mention important behavioral traits like whether it follows symlinks, recursion depth limits, permission requirements, or performance characteristics for large directories.

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 with a clear purpose statement followed by Args and Returns sections. Every sentence earns its place: the first sentence states the core functionality, the Args section clarifies parameter usage, and the Returns section explains output behavior. No wasted words.

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?

Given the tool's moderate complexity (directory tree generation), no annotations, 0% schema coverage, but with an output schema present (returns string), the description is reasonably complete. It covers purpose, parameter semantics, and return behavior. The main gap is lack of detailed behavioral context about tree generation specifics, but the output schema reduces the need to explain return format.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds significant semantic value beyond the 0% schema coverage. While the schema only shows a 'path' parameter with type string, the description clarifies it can be 'absolute or relative to allowed directories', explaining path resolution context. Since there's only one parameter and the description provides meaningful context, this compensates well for the schema gap.

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 ('Generate a plain text tree structure') and resource ('of a directory'), using precise verb+resource phrasing. It distinguishes from sibling tools like list_directory (which likely shows file details) and list_allowed_directories (which shows accessible paths) by focusing on hierarchical tree visualization.

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 through the 'path' parameter description mentioning 'allowed directories', suggesting this tool is for visualizing directory structures within permitted paths. However, it doesn't explicitly state when to use this versus alternatives like list_directory or when not to use it (e.g., for non-directory paths).

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/Preston-Harrison/fs-mcp-py'

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