Skip to main content
Glama
gabrielmaialva33

MCP Filesystem Server

directory_tree

Generate a recursive JSON tree structure of files and directories, listing 'name', 'type' (file/directory), and 'children' for directories. Output is formatted for readability, providing clear visualization of accessible filesystem paths.

Instructions

Get a recursive tree view of files and directories as a JSON structure. Each entry includes 'name', 'type' (file/directory), and 'children' for directories. Files have no children array, while directories always have a children array (which may be empty). The output is formatted with 2-space indentation for readability. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath of the directory to create a tree view for

Implementation Reference

  • The main handler for the 'directory_tree' tool. Parses input arguments, recursively builds a tree structure of directories and files starting from the given path, sorts entries (directories first), handles subdirectories recursively, and returns a pretty-printed JSON representation of the tree.
    case 'directory_tree': {
      const parsed = DirectoryTreeArgsSchema.safeParse(a)
      if (!parsed.success) {
        throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, {
          errors: parsed.error.format(),
        })
      }
    
      async function buildTree(currentPath: string): Promise<TreeEntry[]> {
        const validPath = await validatePath(currentPath, config)
        const entries = await fs.readdir(validPath, { withFileTypes: true })
    
        // Sort directories first, then files, both alphabetically
        entries.sort((f, g) => {
          if (f.isDirectory() && !g.isDirectory()) return -1
          if (!f.isDirectory() && g.isDirectory()) return 1
          return f.name.localeCompare(g.name)
        })
    
        const result: TreeEntry[] = []
    
        for (const entry of entries) {
          const entryData: TreeEntry = {
            name: entry.name,
            type: entry.isDirectory() ? 'directory' : 'file',
          }
    
          if (entry.isDirectory()) {
            try {
              const subPath = path.join(currentPath, entry.name)
              entryData.children = await buildTree(subPath)
            } catch (error) {
              // If we can't access a subdirectory, represent it as empty
              entryData.children = []
            }
          }
    
          result.push(entryData)
        }
    
        return result
      }
    
      const treeData = await buildTree(parsed.data.path)
      await logger.debug(`Generated directory tree: ${parsed.data.path}`)
    
      endMetric()
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(treeData, null, 2),
          },
        ],
      }
    }
  • Zod schema defining the input for the 'directory_tree' tool, requiring a 'path' string.
    const DirectoryTreeArgsSchema = z.object({
      path: z.string().describe('Path of the directory to create a tree view for'),
    })
  • src/index.ts:288-295 (registration)
    Registration of the 'directory_tree' tool in the listTools response, including name, description, and inputSchema reference.
    {
      name: 'directory_tree',
      description:
        'Get a recursive tree view of files and directories as a JSON structure. ' +
        "Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
        'Files have no children array, while directories always have a children array (which may be empty). ' +
        'The output is formatted with 2-space indentation for readability. Only works within allowed directories.',
      inputSchema: zodToJsonSchema(DirectoryTreeArgsSchema) as ToolInput,
  • TypeScript interface defining the recursive TreeEntry structure used by the directory_tree handler.
    interface TreeEntry {
      name: string
      type: 'file' | 'directory'
      children?: TreeEntry[]
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden and does well by disclosing key behavioral traits: it's a read-only operation (implied by 'Get'), outputs JSON with specific structure, includes formatting details (2-space indentation), and has access restrictions (allowed directories). It doesn't mention error handling or performance implications, but covers the essential behavior adequately.

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 front-loaded with the core purpose, followed by output structure details and constraints. Each sentence adds value: first defines the operation, second explains the JSON structure, third clarifies formatting, and fourth states access limits. No wasted words or redundancy.

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?

For a single-parameter read tool with no annotations and no output schema, the description provides good completeness: it explains what the tool does, output format, structure details, and access restrictions. It could slightly improve by mentioning error cases (e.g., invalid path) or linking to list_allowed_directories more explicitly, but it's largely sufficient.

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 100%, so the schema already documents the 'path' parameter adequately. The description doesn't add any parameter-specific details beyond what's in the schema (e.g., path format examples or constraints), so it meets the baseline of 3 without compensating further.

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 verb 'Get' and resource 'recursive tree view of files and directories as a JSON structure', distinguishing it from siblings like list_directory (flat listing) or get_file_info (single file metadata). It specifies the recursive nature and JSON output format, making the purpose specific and differentiated.

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

Usage Guidelines4/5

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

The description provides clear context with 'Only works within allowed directories', which implicitly suggests using list_allowed_directories first. However, it doesn't explicitly name alternatives or state when not to use it (e.g., vs. list_directory for non-recursive listing), keeping it at a 4 rather than a 5.

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

Related 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/gabrielmaialva33/mcp-filesystem'

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