directory_tree
Create a plain text tree structure of any directory by specifying its path. This tool helps visualize directory hierarchies for easier navigation and management within secure filesystem operations.
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
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes |
Implementation Reference
- main.py:319-377 (handler)The handler function for the 'directory_tree' tool. It resolves the path, generates a visual tree structure using Unicode box-drawing characters, respects .gitignore files via _skip_ignored, limits output length, and counts files/directories. Decorated with @mcp.tool for automatic registration and schema inference from docstring.@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")