Skip to content

Commit 3a2e1fd

Browse files
cliffhallclaude
andcommitted
feat(filesystem): add an optional depth to directory_tree
directory_tree takes an optional `depth` (a positive integer): 1 lists only the entries directly in the path, 2 adds their children, and so on. Directories at the last level are listed without a children array, and are not read, so a shallow view of a large tree costs neither the readdirs nor the bounded walk's entry budget (#4162). Omitted, the tree is the whole tree, as before. Closes #1077 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 3a2e1fd

4 files changed

Lines changed: 210 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-filesystem": minor
3+
---
4+
5+
Add an optional `depth` parameter to `directory_tree` that limits how many levels the tree descends; omitted, the whole tree is returned as before (#1077).

‎src/filesystem/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,20 @@ The server's directory access control follows this flow:
185185
- Inputs:
186186
- `path` (string): Starting directory
187187
- `excludePatterns` (string[]): Exclude any patterns. Glob formats are supported.
188+
- `depth` (positive integer, optional): How many levels to descend. `1`
189+
lists only the entries directly in `path`, `2` adds their children, and
190+
so on. Omitted, the whole tree is returned
188191
- Returns:
189192
- JSON array where each entry contains:
190193
- `name` (string): File/directory name
191194
- `type` ('file'|'directory'): Entry type
192195
- `children` (array): Present only for directories
193196
- Empty array for empty directories
194197
- Omitted for files
198+
- Omitted for directories at the last level when `depth` is set: they
199+
are not read, so whether they hold anything is not reported
200+
- A `depth` limit also keeps the walk out of deeper levels entirely, so
201+
entries below it do not count toward the 100,000-entry bound
195202
- Output is formatted with 2-space indentation for readability
196203
- Bounded: see [Slow and very large trees](#slow-and-very-large-trees)
197204

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Protocol-level tests for directory_tree's optional `depth` (#1077), driven
2+
// through a real Client over an in-memory transport. Omitted, the tree is the
3+
// whole tree, as before; set, the walk stops at that level, directories there
4+
// are listed without a children array, and nothing below them is read, so a
5+
// shallow view of a huge tree costs neither the readdirs nor the entry budget
6+
// of the bounded walk (#4162).
7+
8+
import fs from "fs/promises";
9+
import path from "path";
10+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11+
import type { Client } from "@modelcontextprotocol/client";
12+
import {
13+
call,
14+
connect,
15+
makeTempDir,
16+
quietStderr,
17+
textOf,
18+
type Connected,
19+
} from "./helpers.js";
20+
21+
interface TreeEntry {
22+
name: string;
23+
type: "file" | "directory";
24+
children?: TreeEntry[];
25+
}
26+
27+
/** Sort a tree by name at every level; readdir order is the OS's. */
28+
function sortTree(entries: TreeEntry[]): TreeEntry[] {
29+
return [...entries]
30+
.sort((a, b) => a.name.localeCompare(b.name))
31+
.map((entry) =>
32+
entry.children ? { ...entry, children: sortTree(entry.children) } : entry,
33+
);
34+
}
35+
36+
let dir: string;
37+
let conn: Connected;
38+
let client: Client;
39+
40+
// dir/
41+
// top.txt
42+
// empty/
43+
// a/
44+
// a.txt
45+
// b/
46+
// b.txt
47+
// c/
48+
// c.txt
49+
beforeEach(async () => {
50+
quietStderr();
51+
dir = await makeTempDir("mcp-fs-tree-depth-");
52+
await fs.mkdir(path.join(dir, "a", "b", "c"), { recursive: true });
53+
await fs.mkdir(path.join(dir, "empty"));
54+
await fs.writeFile(path.join(dir, "top.txt"), "");
55+
await fs.writeFile(path.join(dir, "a", "a.txt"), "");
56+
await fs.writeFile(path.join(dir, "a", "b", "b.txt"), "");
57+
await fs.writeFile(path.join(dir, "a", "b", "c", "c.txt"), "");
58+
conn = await connect([dir]);
59+
client = conn.client;
60+
});
61+
62+
afterEach(async () => {
63+
vi.restoreAllMocks();
64+
await conn.close();
65+
await fs.rm(dir, { recursive: true, force: true });
66+
});
67+
68+
async function tree(args: Record<string, unknown>): Promise<TreeEntry[]> {
69+
const result = await call(client, "directory_tree", { path: dir, ...args });
70+
expect(result.isError, textOf(result)).toBeFalsy();
71+
return sortTree(JSON.parse(textOf(result)) as TreeEntry[]);
72+
}
73+
74+
const FULL: TreeEntry[] = [
75+
{
76+
name: "a",
77+
type: "directory",
78+
children: [
79+
{ name: "a.txt", type: "file" },
80+
{
81+
name: "b",
82+
type: "directory",
83+
children: [
84+
{ name: "b.txt", type: "file" },
85+
{
86+
name: "c",
87+
type: "directory",
88+
children: [{ name: "c.txt", type: "file" }],
89+
},
90+
],
91+
},
92+
],
93+
},
94+
{ name: "empty", type: "directory", children: [] },
95+
{ name: "top.txt", type: "file" },
96+
];
97+
98+
describe("directory_tree depth", () => {
99+
it("returns the whole tree when depth is omitted", async () => {
100+
expect(await tree({})).toEqual(FULL);
101+
});
102+
103+
it("lists only the entries directly in path at depth 1, directories without children", async () => {
104+
expect(await tree({ depth: 1 })).toEqual([
105+
{ name: "a", type: "directory" },
106+
{ name: "empty", type: "directory" },
107+
{ name: "top.txt", type: "file" },
108+
]);
109+
});
110+
111+
it("descends one more level at depth 2", async () => {
112+
expect(await tree({ depth: 2 })).toEqual([
113+
{
114+
name: "a",
115+
type: "directory",
116+
children: [
117+
{ name: "a.txt", type: "file" },
118+
{ name: "b", type: "directory" },
119+
],
120+
},
121+
{ name: "empty", type: "directory", children: [] },
122+
{ name: "top.txt", type: "file" },
123+
]);
124+
});
125+
126+
it("returns the whole tree when depth reaches past its bottom", async () => {
127+
expect(await tree({ depth: 4 })).toEqual(FULL);
128+
expect(await tree({ depth: 100 })).toEqual(FULL);
129+
});
130+
131+
it("applies excludePatterns within the depth", async () => {
132+
expect(await tree({ depth: 2, excludePatterns: ["a.txt"] })).toEqual([
133+
{
134+
name: "a",
135+
type: "directory",
136+
children: [{ name: "b", type: "directory" }],
137+
},
138+
{ name: "empty", type: "directory", children: [] },
139+
{ name: "top.txt", type: "file" },
140+
]);
141+
});
142+
143+
it("never reads a directory below the depth", async () => {
144+
const readdir = vi.spyOn(fs, "readdir");
145+
await tree({ depth: 2 });
146+
const read = readdir.mock.calls.map(([target]) => String(target));
147+
expect(read).toContain(path.join(dir, "a"));
148+
expect(read).not.toContain(path.join(dir, "a", "b"));
149+
expect(read).not.toContain(path.join(dir, "a", "b", "c"));
150+
});
151+
152+
it.each([0, -1, 1.5, "2"])("rejects depth %j", async (depth) => {
153+
const result = await call(client, "directory_tree", { path: dir, depth });
154+
expect(result.isError).toBe(true);
155+
expect(textOf(result)).toMatch(
156+
/^Input validation error: Invalid arguments for tool directory_tree/,
157+
);
158+
});
159+
160+
it("advertises depth as an optional positive integer", async () => {
161+
const { tools } = await client.listTools();
162+
const schema = tools.find((t) => t.name === "directory_tree")
163+
?.inputSchema as {
164+
properties: Record<string, Record<string, unknown>>;
165+
required?: string[];
166+
};
167+
expect(schema.properties.depth).toMatchObject({
168+
type: "integer",
169+
exclusiveMinimum: 0,
170+
});
171+
expect(schema.properties.depth.description).toMatch(/^How many levels/);
172+
expect(schema.required).toEqual(["path"]);
173+
});
174+
});

‎src/filesystem/server.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,15 @@ const ListDirectoryWithSizesArgsSchema = z.object({
111111
const DirectoryTreeArgsSchema = z.object({
112112
path: z.string(),
113113
excludePatterns: z.array(z.string()).optional().default([]),
114+
depth: z
115+
.number()
116+
.int()
117+
.positive()
118+
.optional()
119+
.describe(
120+
"How many levels to descend: 1 lists only the entries directly in path. " +
121+
"Directories at the last level have no children array. Omit for the whole tree.",
122+
),
114123
});
115124

116125
const MoveFileArgsSchema = z.object({
@@ -638,7 +647,8 @@ export function createServer(
638647
description:
639648
"Get a recursive tree view of files and directories as a JSON structure. " +
640649
"Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
641-
"Files have no children array, while directories always have a children array (which may be empty). " +
650+
"Files have no children array, while directories always have a children array (which may be empty), " +
651+
"except at the last level when 'depth' limits the tree: those directories are not read and have no children array. " +
642652
"The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
643653
inputSchema: jsonSchema2020(DirectoryTreeArgsSchema.shape),
644654
outputSchema: jsonSchema2020({ content: z.string() }),
@@ -653,9 +663,13 @@ export function createServer(
653663
const rootPath = args.path;
654664
const visit = createEntryBudget("directory_tree", rootPath);
655665

666+
// `level` is the depth of currentPath's entries: 1 for those directly
667+
// in the requested path. A directory at the depth limit is listed but
668+
// not read, so its subtree costs no readdir and no entry budget (#1077).
656669
async function buildTree(
657670
currentPath: string,
658671
excludePatterns: string[] = [],
672+
level: number = 1,
659673
): Promise<TreeEntry[]> {
660674
const validPath = await validatePath(currentPath, allowedDirectories);
661675
const entries = await readdirWithTimeout(validPath);
@@ -689,9 +703,16 @@ export function createServer(
689703
type: entry.isDirectory() ? "directory" : "file",
690704
};
691705

692-
if (entry.isDirectory()) {
706+
if (
707+
entry.isDirectory() &&
708+
(args.depth === undefined || level < args.depth)
709+
) {
693710
const subPath = path.join(currentPath, entry.name);
694-
entryData.children = await buildTree(subPath, excludePatterns);
711+
entryData.children = await buildTree(
712+
subPath,
713+
excludePatterns,
714+
level + 1,
715+
);
695716
}
696717

697718
result.push(entryData);

0 commit comments

Comments
 (0)