Skip to content

Commit 170cf42

Browse files
authored
Merge pull request #5388 from modelcontextprotocol/v2/feat/1077-filesystem-directory-tree-depth
feat(filesystem): add an optional depth to directory_tree
2 parents 4a0db4f + 3a2e1fd commit 170cf42

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
@@ -218,13 +218,20 @@ The server's directory access control follows this flow:
218218
- Inputs:
219219
- `path` (string): Starting directory
220220
- `excludePatterns` (string[]): Exclude any patterns. Glob formats are supported.
221+
- `depth` (positive integer, optional): How many levels to descend. `1`
222+
lists only the entries directly in `path`, `2` adds their children, and
223+
so on. Omitted, the whole tree is returned
221224
- Returns:
222225
- JSON array where each entry contains:
223226
- `name` (string): File/directory name
224227
- `type` ('file'|'directory'): Entry type
225228
- `children` (array): Present only for directories
226229
- Empty array for empty directories
227230
- Omitted for files
231+
- Omitted for directories at the last level when `depth` is set: they
232+
are not read, so whether they hold anything is not reported
233+
- A `depth` limit also keeps the walk out of deeper levels entirely, so
234+
entries below it do not count toward the 100,000-entry bound
228235
- Output is formatted with 2-space indentation for readability
229236
- Bounded: see [Slow and very large trees](#slow-and-very-large-trees)
230237

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
@@ -126,6 +126,15 @@ const ListDirectoryWithSizesArgsSchema = z.object({
126126
const DirectoryTreeArgsSchema = z.object({
127127
path: z.string(),
128128
excludePatterns: z.array(z.string()).optional().default([]),
129+
depth: z
130+
.number()
131+
.int()
132+
.positive()
133+
.optional()
134+
.describe(
135+
"How many levels to descend: 1 lists only the entries directly in path. " +
136+
"Directories at the last level have no children array. Omit for the whole tree.",
137+
),
129138
});
130139

131140
const MoveFileArgsSchema = z.object({
@@ -745,7 +754,8 @@ export function createServer(
745754
description:
746755
"Get a recursive tree view of files and directories as a JSON structure. " +
747756
"Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
748-
"Files have no children array, while directories always have a children array (which may be empty). " +
757+
"Files have no children array, while directories always have a children array (which may be empty), " +
758+
"except at the last level when 'depth' limits the tree: those directories are not read and have no children array. " +
749759
"The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
750760
inputSchema: jsonSchema2020(DirectoryTreeArgsSchema.shape),
751761
outputSchema: jsonSchema2020({ content: z.string() }),
@@ -765,9 +775,13 @@ export function createServer(
765775
const rootPath = args.path;
766776
const visit = createEntryBudget("directory_tree", rootPath);
767777

778+
// `level` is the depth of currentPath's entries: 1 for those directly
779+
// in the requested path. A directory at the depth limit is listed but
780+
// not read, so its subtree costs no readdir and no entry budget (#1077).
768781
async function buildTree(
769782
currentPath: string,
770783
excludePatterns: string[] = [],
784+
level: number = 1,
771785
): Promise<TreeEntry[]> {
772786
const validPath = await validatePath(currentPath, allowedDirectories);
773787
const entries = await readdirWithTimeout(validPath);
@@ -801,9 +815,16 @@ export function createServer(
801815
type: entry.isDirectory() ? "directory" : "file",
802816
};
803817

804-
if (entry.isDirectory()) {
818+
if (
819+
entry.isDirectory() &&
820+
(args.depth === undefined || level < args.depth)
821+
) {
805822
const subPath = path.join(currentPath, entry.name);
806-
entryData.children = await buildTree(subPath, excludePatterns);
823+
entryData.children = await buildTree(
824+
subPath,
825+
excludePatterns,
826+
level + 1,
827+
);
807828
}
808829

809830
result.push(entryData);

0 commit comments

Comments
 (0)