Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

directory_tree

Generate a recursive JSON tree view of files and directories with name, type, and children arrays for structured filesystem navigation.

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. Validates input, recursively builds a tree structure of directories and files starting from the given path, sorts entries (dirs first), handles subdir access errors by setting empty children, and returns pretty-printed JSON.
    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 for validating the input arguments to 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 list of tools returned by ListToolsRequest, including name, description, and input schema.
    {
      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,
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 key behavioral traits: output format (JSON with 2-space indentation), structure (entries with name, type, children), and constraints (only within allowed directories). However, it lacks details on error handling, recursion depth limits, or performance implications 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 in three sentences: first states the core purpose, second details output structure, third adds critical constraint. Every sentence adds value with zero wasted words, and key information is front-loaded.

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 (recursive traversal), no annotations, and no output schema, the description does well by explaining output structure and constraints. However, it could better address potential issues like symbolic links, hidden files, or large directory performance to be fully complete.

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 fully documents the single 'path' parameter. The description adds no additional parameter semantics beyond what's in the schema, but doesn't need to compensate for gaps. This meets the baseline for high schema coverage.

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 ('Get a recursive tree view') and resource ('files and directories'), distinguishing it from siblings like 'list_directory' (flat listing) and 'get_file_info' (single file metadata). It precisely defines what the tool does beyond just the name.

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 for when to use this tool ('Only works within allowed directories') and implies usage for hierarchical views versus flat listings. However, it doesn't explicitly name alternatives (e.g., 'list_directory' for non-recursive) or state when not to use it, keeping it from a perfect score.

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/A-Niranjan/mcp-filesystem'

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