Skip to content

Commit 7d36dcc

Browse files
committed
fix(filesystem): add optional depth parameter to list_directory
Add optional depth parameter to list_directory tool to support recursive directory listing. Some LLMs generate a depth argument for directory listing which was previously rejected as an "additional property" error. Fixes: modelcontextprotocol#2703
1 parent f424458 commit 7d36dcc

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

‎src/filesystem/index.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ const CreateDirectoryArgsSchema = z.object({
132132

133133
const ListDirectoryArgsSchema = z.object({
134134
path: z.string(),
135+
depth: z.number().optional().describe("Recursive depth for directory listing (1 = one level deep)"),
135136
});
136137

137138
const ListDirectoryWithSizesArgsSchema = z.object({
@@ -433,8 +434,26 @@ server.registerTool(
433434
annotations: { readOnlyHint: true }
434435
},
435436
async (args: z.infer<typeof ListDirectoryArgsSchema>) => {
437+
438+
439+
async function listDirRecursive(dirPath, currentDepth, maxDepth) {
440+
const entries = await fs.readdir(dirPath, { withFileTypes: true });
441+
const results = [];
442+
443+
for (const entry of entries) {
444+
const fullPath = path.join(dirPath, entry.name);
445+
const prefix = currentDepth > 0 ? " ".repeat(currentDepth) : "";
446+
results.push(`${prefix}${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`);
447+
448+
if (entry.isDirectory() && (maxDepth === undefined || currentDepth < maxDepth)) {
449+
const subEntries = await listDirRecursive(fullPath, currentDepth + 1, maxDepth);
450+
results.push(...subEntries);
451+
}
452+
}
453+
return results;
454+
}
436455
const validPath = await validatePath(args.path);
437-
const entries = await fs.readdir(validPath, { withFileTypes: true });
456+
const entries = await listDirRecursive(validPath, 0, args.depth);
438457
const formatted = entries
439458
.map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`)
440459
.join("\n");

0 commit comments

Comments
 (0)