Skip to content

Commit cf4c957

Browse files
authored
Merge pull request #5446 from modelcontextprotocol/v2/fix/5216-filesystem-search-exclude-patterns
fix(filesystem): read search_files excludePatterns like directory_tree
2 parents 775a985 + 435dc70 commit cf4c957

6 files changed

Lines changed: 234 additions & 35 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": patch
3+
---
4+
5+
`search_files` now reads `excludePatterns` the same way `directory_tree` does: a bare name such as `"node_modules"` excludes an entry of that name at any depth and the whole subtree below it, instead of only one directly under the searched path. Wildcard patterns keep their meaning, and an excluded directory is still never resolved or read. Thanks to @xubenqiang for the prototype fix.

‎src/filesystem/README.md‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -248,11 +248,14 @@ Files inside the allowed directories are also [resources](https://modelcontextpr
248248
- `pattern` (string): Glob matched, case-sensitively, against each entry's
249249
path relative to `path`: `*.ext` matches entries directly under `path`,
250250
`**/*.ext` or `**/name` matches at any depth
251-
- `excludePatterns` (string[]): Globs for entries to skip, matched like
252-
`pattern`, so a bare name skips only the top-level entry: use
253-
`**/node_modules` to skip that name at any depth. An excluded entry is
254-
skipped before it is resolved or read, so excluding a slow folder keeps
255-
the search out of it entirely.
251+
- `excludePatterns` (string[]): Entries to leave out, read the same way as
252+
`directory_tree`'s. A bare name such as `node_modules` excludes an entry
253+
of that name at any depth and everything below it; it matches whole
254+
names, so `node_modules_old` is kept. A pattern containing `*` is a glob
255+
matched against the path relative to `path` as written: `*.log` excludes
256+
only entries directly under `path`, `**/*.log` at any depth. An excluded
257+
entry is skipped before it is resolved or read, so excluding a slow
258+
folder keeps the search out of it entirely.
256259
- Glob-style pattern matching
257260
- Returns full paths to matches
258261
- Bounded: see [Slow and very large trees](#slow-and-very-large-trees)
@@ -265,10 +268,10 @@ Files inside the allowed directories are also [resources](https://modelcontextpr
265268
- Get recursive JSON tree structure of directory contents
266269
- Inputs:
267270
- `path` (string): Starting directory
268-
- `excludePatterns` (string[]): Globs for entries to leave out, with their
269-
contents, matched against each entry's path relative to `path`. A
270-
pattern with no `*` also matches that name at any depth, so
271-
`node_modules` leaves out every `node_modules` directory.
271+
- `excludePatterns` (string[]): Entries to leave out, read the same way as
272+
`search_files`'s: a bare name excludes that name at any depth and the
273+
subtree below it, and a pattern containing `*` is a glob matched against
274+
the path relative to `path` as written.
272275
- `depth` (positive integer, optional): How many levels to descend. `1`
273276
lists only the entries directly in `path`, `2` adds their children, and
274277
so on. Omitted, the whole tree is returned

‎src/filesystem/__tests__/input-descriptions.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
// This is the reference implementation other server authors copy, so the rule
55
// is pinned for every tool, existing or added later, and for nested
66
// properties (array items, object fields) as well as top-level ones. The
7-
// excludePatterns descriptions state matching rules that differ between
8-
// directory_tree and search_files, so those rules are pinned here as well.
7+
// excludePatterns descriptions state the matching rule directory_tree and
8+
// search_files share (#5216), so that rule is pinned here as well.
99

1010
import fs from "fs/promises";
1111
import path from "path";
@@ -116,10 +116,9 @@ describe("excludePatterns, as the descriptions state it (#3669)", () => {
116116
expect(text).toContain("keep.txt");
117117
});
118118

119-
it("search_files: a bare name skips only the top-level entry", async () => {
119+
it("search_files: a name with no '*' is skipped at any depth", async () => {
120120
expect(await search(["node_modules"])).toEqual([
121121
path.join(dir, "pkg", "keep.txt"),
122-
path.join(dir, "pkg", "node_modules", "deep.txt"),
123122
]);
124123
});
125124

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// search_files and directory_tree read `excludePatterns` the same way (#5216).
2+
// directory_tree matched a bare name such as "node_modules" at any depth and
3+
// pruned the subtree below it, while search_files matched every pattern only
4+
// against the path relative to the searched root, so the same argument left a
5+
// nested node_modules in one tool's result and not the other's. Both now go
6+
// through isExcludedPath. These tests drive both tools over one tree through a
7+
// real client, check that a nested excluded directory is still never realpath'd
8+
// or read (#4162), and pin the predicate's rules directly: whole-name matching,
9+
// and wildcard patterns matched as written.
10+
11+
import fs from "fs/promises";
12+
import path from "path";
13+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14+
import type { Client } from "@modelcontextprotocol/client";
15+
import {
16+
call,
17+
connect,
18+
makeTempDir,
19+
quietStderr,
20+
textOf,
21+
type Connected,
22+
} from "./helpers.js";
23+
import { isExcludedPath } from "../lib.js";
24+
25+
interface TreeEntry {
26+
name: string;
27+
type: "file" | "directory";
28+
children?: TreeEntry[];
29+
}
30+
31+
let dir: string;
32+
let conn: Connected;
33+
let client: Client;
34+
35+
// dir/
36+
// index.js
37+
// node_modules/dep.js
38+
// node_modules_old/keep.js
39+
// packages/app/main.js
40+
// packages/app/node_modules/nested.js
41+
// packages/app/debug.log
42+
// debug.log
43+
beforeEach(async () => {
44+
quietStderr();
45+
dir = await makeTempDir("mcp-fs-exclude-");
46+
const files = [
47+
"index.js",
48+
"debug.log",
49+
"node_modules/dep.js",
50+
"node_modules_old/keep.js",
51+
"packages/app/main.js",
52+
"packages/app/debug.log",
53+
"packages/app/node_modules/nested.js",
54+
];
55+
for (const file of files) {
56+
await fs.mkdir(path.dirname(path.join(dir, file)), { recursive: true });
57+
await fs.writeFile(path.join(dir, file), "");
58+
}
59+
conn = await connect([dir]);
60+
client = conn.client;
61+
});
62+
63+
afterEach(async () => {
64+
vi.restoreAllMocks();
65+
await conn.close();
66+
await fs.rm(dir, { recursive: true, force: true });
67+
});
68+
69+
/** The search_files result as paths relative to `dir`, sorted. */
70+
async function search(
71+
pattern: string,
72+
excludePatterns: string[],
73+
): Promise<string[]> {
74+
const result = await call(client, "search_files", {
75+
path: dir,
76+
pattern,
77+
excludePatterns,
78+
});
79+
expect(result.isError).toBeFalsy();
80+
return textOf(result)
81+
.split("\n")
82+
.map((line) => path.relative(dir, line))
83+
.sort();
84+
}
85+
86+
/** Every file path in a directory_tree result, relative to `dir`, sorted. */
87+
async function treeFiles(excludePatterns: string[]): Promise<string[]> {
88+
const result = await call(client, "directory_tree", {
89+
path: dir,
90+
excludePatterns,
91+
});
92+
expect(result.isError).toBeFalsy();
93+
const files: string[] = [];
94+
const walk = (entries: TreeEntry[], prefix: string) => {
95+
for (const entry of entries) {
96+
const relative = path.join(prefix, entry.name);
97+
if (entry.type === "file") files.push(relative);
98+
walk(entry.children ?? [], relative);
99+
}
100+
};
101+
walk(JSON.parse(textOf(result)) as TreeEntry[], "");
102+
return files.sort();
103+
}
104+
105+
describe("search_files excludePatterns (#5216)", () => {
106+
it("excludes a bare name at any depth, not only at the searched root", async () => {
107+
expect(await search("**/*.js", ["node_modules"])).toEqual(
108+
["index.js", "node_modules_old/keep.js", "packages/app/main.js"].map(
109+
(p) => path.join(...p.split("/")),
110+
),
111+
);
112+
});
113+
114+
it("returns the same files directory_tree lists for the same excludePatterns", async () => {
115+
for (const excludePatterns of [
116+
["node_modules"],
117+
["app"],
118+
["*.log"],
119+
["**/*.log", "node_modules"],
120+
]) {
121+
expect(await search("**/*.*", excludePatterns)).toEqual(
122+
await treeFiles(excludePatterns),
123+
);
124+
}
125+
});
126+
127+
it("never realpaths or reads a nested excluded directory (#4162)", async () => {
128+
const realpath = vi.spyOn(fs, "realpath");
129+
const readdir = vi.spyOn(fs, "readdir");
130+
await search("**/*.js", ["node_modules"]);
131+
const nested = path.join(dir, "packages", "app", "node_modules");
132+
const touched = [...realpath.mock.calls, ...readdir.mock.calls].map(
133+
([target]) => target.toString(),
134+
);
135+
expect(touched.filter((target) => target.startsWith(nested))).toEqual([]);
136+
});
137+
138+
it("keeps matching a wildcard pattern against the relative path as written", async () => {
139+
// "*.log" has a wildcard, so it is not expanded to any depth: it excludes
140+
// the root's debug.log only, in both tools.
141+
const expected = ["packages/app/debug.log"].map((p) =>
142+
path.join(...p.split("/")),
143+
);
144+
expect(await search("**/*.log", ["*.log"])).toEqual(expected);
145+
expect(
146+
(await treeFiles(["*.log"])).filter((file) => file.endsWith(".log")),
147+
).toEqual(expected);
148+
});
149+
});
150+
151+
describe("isExcludedPath", () => {
152+
const p = (posix: string) => path.join(...posix.split("/"));
153+
154+
it("matches a bare name at the root, at any depth, and below it", () => {
155+
expect(isExcludedPath("node_modules", ["node_modules"])).toBe(true);
156+
expect(isExcludedPath(p("a/b/node_modules"), ["node_modules"])).toBe(true);
157+
expect(isExcludedPath(p("a/node_modules/x/y.js"), ["node_modules"])).toBe(
158+
true,
159+
);
160+
});
161+
162+
it("matches whole names, never a prefix", () => {
163+
expect(isExcludedPath("node_modules_old", ["node_modules"])).toBe(false);
164+
expect(isExcludedPath(p("a/node_modules_old/x.js"), ["node_modules"])).toBe(
165+
false,
166+
);
167+
});
168+
169+
it("matches a wildcard pattern only as written", () => {
170+
expect(isExcludedPath("debug.log", ["*.log"])).toBe(true);
171+
expect(isExcludedPath(p("a/debug.log"), ["*.log"])).toBe(false);
172+
expect(isExcludedPath(p("a/debug.log"), ["**/*.log"])).toBe(true);
173+
});
174+
175+
it("excludes nothing for an empty list", () => {
176+
expect(isExcludedPath("anything", [])).toBe(false);
177+
});
178+
});

‎src/filesystem/lib.ts‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1183,6 +1183,33 @@ export async function headFile(
11831183
}
11841184
}
11851185

1186+
// Whether an entry is excluded by an `excludePatterns` list, given its path
1187+
// relative to the root of the walk. `directory_tree` and `search_files` take the
1188+
// same argument, so they share this one predicate and read it the same way
1189+
// (#5216). A pattern containing `*` is a glob matched against the relative path
1190+
// as written. A bare name also matches an entry of that name at any depth
1191+
// (`**/<name>`) and everything below it (`**/<name>/**`), so `["node_modules"]`
1192+
// prunes every `node_modules` directory, not only one at the root. Names are
1193+
// matched whole: `node_modules` does not exclude `node_modules_old`.
1194+
//
1195+
// Callers check it before validating an entry, so an excluded subtree is never
1196+
// realpath'd or read (#4162).
1197+
export function isExcludedPath(
1198+
relativePath: string,
1199+
excludePatterns: readonly string[],
1200+
): boolean {
1201+
return excludePatterns.some((pattern) => {
1202+
if (pattern.includes("*")) {
1203+
return minimatch(relativePath, pattern, { dot: true });
1204+
}
1205+
return (
1206+
minimatch(relativePath, pattern, { dot: true }) ||
1207+
minimatch(relativePath, `**/${pattern}`, { dot: true }) ||
1208+
minimatch(relativePath, `**/${pattern}/**`, { dot: true })
1209+
);
1210+
});
1211+
}
1212+
11861213
export async function searchFilesWithValidation(
11871214
rootPath: string,
11881215
pattern: string,
@@ -1216,10 +1243,7 @@ export async function searchFilesWithValidation(
12161243
// excluded subtree is never realpath'd or read (#4162): excluding a slow
12171244
// provider folder keeps the walk from touching it at all.
12181245
const relativePath = path.relative(rootPath, fullPath);
1219-
const shouldExclude = excludePatterns.some((excludePattern) =>
1220-
minimatch(relativePath, excludePattern, { dot: true }),
1221-
);
1222-
if (shouldExclude) continue;
1246+
if (isExcludedPath(relativePath, excludePatterns)) continue;
12231247

12241248
visit();
12251249

‎src/filesystem/server.ts‎

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import { createReadStream } from "fs";
1111
import path from "path";
1212
import { pathToFileURL } from "url";
1313
import { z } from "zod";
14-
import { minimatch } from "minimatch";
1514
import { getValidRootDirectories } from "./roots-utils.js";
1615
import {
1716
confineRootsToDirectories,
@@ -28,6 +27,7 @@ import {
2827
moveFile,
2928
copyFile,
3029
searchFilesWithValidation,
30+
isExcludedPath,
3131
applyFileEdits,
3232
tailFile,
3333
headFile,
@@ -156,8 +156,9 @@ const DirectoryTreeArgsSchema = z.object({
156156
.optional()
157157
.default([])
158158
.describe(
159-
"Glob patterns for entries to leave out, with their contents, matched against each entry's path relative to path. " +
160-
"A pattern with no '*' also matches that name at any depth, so 'node_modules' leaves out every node_modules directory.",
159+
"Patterns for entries to leave out, with their contents, matched against each entry's path relative to path. " +
160+
"A pattern with no '*' matches that name at any depth ('node_modules' leaves out every node_modules directory); " +
161+
"a pattern with '*' is a glob matched as written.",
161162
),
162163
depth: z
163164
.number()
@@ -197,8 +198,9 @@ const SearchFilesArgsSchema = z.object({
197198
.optional()
198199
.default([])
199200
.describe(
200-
"Glob patterns for entries to skip, matched like pattern; a skipped directory is not searched. " +
201-
"Use '**/node_modules' to skip that name at any depth.",
201+
"Patterns for entries to leave out, with their contents, matched against each entry's path relative to path. " +
202+
"A pattern with no '*' matches that name at any depth ('node_modules' leaves out every node_modules directory); " +
203+
"a pattern with '*' is a glob matched as written.",
202204
),
203205
});
204206

@@ -866,19 +868,7 @@ export function createServer(
866868
rootPath,
867869
path.join(currentPath, entry.name),
868870
);
869-
const shouldExclude = excludePatterns.some((pattern) => {
870-
if (pattern.includes("*")) {
871-
return minimatch(relativePath, pattern, { dot: true });
872-
}
873-
// For files: match exact name or as part of path
874-
// For directories: match as directory path
875-
return (
876-
minimatch(relativePath, pattern, { dot: true }) ||
877-
minimatch(relativePath, `**/${pattern}`, { dot: true }) ||
878-
minimatch(relativePath, `**/${pattern}/**`, { dot: true })
879-
);
880-
});
881-
if (shouldExclude) continue;
871+
if (isExcludedPath(relativePath, excludePatterns)) continue;
882872
// Counted after the exclude check, so excluded subtrees cost
883873
// nothing; the cap and the readdir timeout keep one call from
884874
// walking an unbounded or stalled tree (#4162).

0 commit comments

Comments
 (0)