DirectoryTreeTool.ts•1.85 kB
import { MCPTool } from "mcp-framework";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";
interface TreeEntry {
name: string;
type: 'file' | 'directory';
children?: TreeEntry[];
}
interface DirectoryTreeInput {
path: string;
}
class DirectoryTreeTool extends MCPTool<DirectoryTreeInput> {
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.";
schema = {
path: {
type: z.string(),
description: "Path to the directory to create a tree for",
},
};
private async buildTree(currentPath: string): Promise<TreeEntry[]> {
const entries = await fs.readdir(currentPath, { withFileTypes: true });
const result: TreeEntry[] = [];
for (const entry of entries) {
const entryData: TreeEntry = {
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file'
};
if (entry.isDirectory()) {
const subPath = path.join(currentPath, entry.name);
entryData.children = await this.buildTree(subPath);
}
result.push(entryData);
}
return result;
}
async execute(input: DirectoryTreeInput) {
try {
const treeData = await this.buildTree(input.path);
return JSON.stringify(treeData, null, 2);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to create directory tree: ${errorMessage}`);
}
}
}
export default DirectoryTreeTool;