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

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")

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