Skip to content

Commit 135a925

Browse files
cliffhallclaude
andcommitted
fix(filesystem): name the subdirectories search_files could not read
search_files wrapped path validation, the match and the recursive descent in one try whose catch skipped the entry, so an I/O error such as EACCES from reading a subdirectory was discarded with the validation failures it was meant to skip, and the result came back short with no sign it was incomplete. Only validatePath is guarded now. A subdirectory whose readdir fails is skipped and reported through a new onUnreadable option, and the tool appends a note after the matches listing each unreadable directory with its error code. The starting directory failing, a timeout and the entry cap still end the request with an error. Closes #5189 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 135a925

5 files changed

Lines changed: 231 additions & 20 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` no longer drops a subdirectory it cannot read without saying so. It still returns the matches it found, and now follows them with a note that the search is incomplete, listing each unreadable directory and its error code. Paths outside the allowed directories are still skipped silently, and an unreadable starting directory is still an error.

‎src/filesystem/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ The server's directory access control follows this flow:
179179
- Glob-style pattern matching
180180
- Returns full paths to matches
181181
- Bounded: see [Slow and very large trees](#slow-and-very-large-trees)
182+
- A subdirectory that cannot be read (no permission, say) is skipped, and the
183+
result says so: after the matches, a note that the search is incomplete
184+
lists each unreadable directory with its error code. Paths outside the
185+
allowed directories are still skipped silently.
182186

183187
- **directory_tree**
184188
- Get recursive JSON tree structure of directory contents
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// search_files over a tree with a subdirectory it cannot read (#5189). The
2+
// walk used to swallow that readdir failure with the validation errors it
3+
// skips on purpose, so the result came back short with nothing to say so. Now
4+
// the walk skips the directory, keeps going, and the tool names it after the
5+
// matches. These tests make readdir fail for one directory by spying on the
6+
// fs/promises object the server shares with this file, which works on every
7+
// platform; one more test uses a real chmod 000 directory where POSIX
8+
// permissions apply.
9+
10+
import fs from "fs/promises";
11+
import type { PathLike } from "fs";
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 { searchFilesWithValidation } from "../lib.js";
24+
25+
const realReaddir = fs.readdir.bind(fs);
26+
27+
let dir: string;
28+
let conn: Connected;
29+
let client: Client;
30+
31+
beforeEach(async () => {
32+
quietStderr();
33+
dir = await makeTempDir("mcp-fs-unreadable-");
34+
await fs.mkdir(path.join(dir, "open"));
35+
await fs.mkdir(path.join(dir, "locked"));
36+
await fs.mkdir(path.join(dir, "sealed"));
37+
await fs.writeFile(path.join(dir, "open", "a.txt"), "");
38+
await fs.writeFile(path.join(dir, "locked", "hidden.txt"), "");
39+
await fs.writeFile(path.join(dir, "sealed", "also-hidden.txt"), "");
40+
conn = await connect([dir]);
41+
client = conn.client;
42+
});
43+
44+
afterEach(async () => {
45+
vi.restoreAllMocks();
46+
await conn.close();
47+
await fs.chmod(path.join(dir, "locked"), 0o755);
48+
await fs.rm(dir, { recursive: true, force: true });
49+
});
50+
51+
/** Make readdir reject with `error` for each directory in `failing`. */
52+
function failReaddir(failing: string[], error: Error): void {
53+
vi.spyOn(fs, "readdir").mockImplementation(((
54+
target: PathLike,
55+
...rest: unknown[]
56+
) =>
57+
failing.includes(target.toString())
58+
? Promise.reject(error)
59+
: (
60+
realReaddir as (
61+
target: PathLike,
62+
...rest: unknown[]
63+
) => Promise<unknown>
64+
)(target, ...rest)) as typeof fs.readdir);
65+
}
66+
67+
function eacces(): Error {
68+
return Object.assign(new Error("EACCES: permission denied"), {
69+
code: "EACCES",
70+
});
71+
}
72+
73+
describe("search_files with an unreadable subdirectory (#5189)", () => {
74+
it("returns the matches it found and names the directory it could not read", async () => {
75+
const locked = path.join(dir, "locked");
76+
failReaddir([locked], eacces());
77+
const result = await call(client, "search_files", {
78+
path: dir,
79+
pattern: "**/*.txt",
80+
});
81+
expect(result.isError).toBeFalsy();
82+
const text = textOf(result);
83+
expect(text.split("\n\n")).toEqual([
84+
expect.stringContaining(path.join(dir, "open", "a.txt")),
85+
"The search is incomplete: 1 directory could not be read, and any matches inside are missing:\n" +
86+
`${locked} (EACCES)`,
87+
]);
88+
expect(text).toContain(path.join(dir, "sealed", "also-hidden.txt"));
89+
expect(text).not.toContain(path.join(locked, "hidden.txt"));
90+
expect(result.structuredContent).toEqual({ content: text });
91+
});
92+
93+
it('says "No matches found" and lists every unreadable directory when nothing else matched', async () => {
94+
const locked = path.join(dir, "locked");
95+
const sealed = path.join(dir, "sealed");
96+
failReaddir([locked, sealed], eacces());
97+
const result = await call(client, "search_files", {
98+
path: dir,
99+
pattern: "**/*hidden*",
100+
});
101+
expect(result.isError).toBeFalsy();
102+
const [matches, note] = textOf(result).split("\n\n");
103+
expect(matches).toBe("No matches found");
104+
const [heading, ...listed] = note.split("\n");
105+
expect(heading).toBe(
106+
"The search is incomplete: 2 directories could not be read, and any matches inside are missing:",
107+
);
108+
expect(listed.sort()).toEqual([`${locked} (EACCES)`, `${sealed} (EACCES)`]);
109+
});
110+
111+
it("names the directory without a code when the error carries none", async () => {
112+
const locked = path.join(dir, "locked");
113+
failReaddir([locked], new Error("unreadable"));
114+
const result = await call(client, "search_files", {
115+
path: dir,
116+
pattern: "**/a.txt",
117+
});
118+
expect(textOf(result)).toBe(
119+
`${path.join(dir, "open", "a.txt")}\n\n` +
120+
"The search is incomplete: 1 directory could not be read, and any matches inside are missing:\n" +
121+
locked,
122+
);
123+
});
124+
125+
it("still fails the request when the starting directory cannot be read", async () => {
126+
failReaddir([dir], eacces());
127+
const result = await call(client, "search_files", {
128+
path: dir,
129+
pattern: "**/*.txt",
130+
});
131+
expect(result.isError).toBe(true);
132+
expect(textOf(result)).toContain("EACCES");
133+
});
134+
135+
it("reports nothing extra when every directory reads", async () => {
136+
const result = await call(client, "search_files", {
137+
path: dir,
138+
pattern: "**/a.txt",
139+
});
140+
expect(textOf(result)).toBe(path.join(dir, "open", "a.txt"));
141+
});
142+
143+
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
144+
"reports a real chmod 000 directory",
145+
async () => {
146+
const locked = path.join(dir, "locked");
147+
await fs.chmod(locked, 0o000);
148+
const result = await call(client, "search_files", {
149+
path: dir,
150+
pattern: "**/*.txt",
151+
});
152+
expect(result.isError).toBeFalsy();
153+
expect(textOf(result)).toContain(`\n${locked} (EACCES)`);
154+
expect(textOf(result)).toContain(path.join(dir, "open", "a.txt"));
155+
},
156+
);
157+
});
158+
159+
describe("searchFilesWithValidation without an onUnreadable callback", () => {
160+
it("skips the unreadable directory and returns the rest", async () => {
161+
const locked = path.join(dir, "locked");
162+
failReaddir([locked], eacces());
163+
const realDir = await fs.realpath(dir);
164+
const results = await searchFilesWithValidation(realDir, "**/a.txt", [
165+
realDir,
166+
]);
167+
expect(results).toEqual([path.join(realDir, "open", "a.txt")]);
168+
});
169+
});

‎src/filesystem/lib.ts‎

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ interface FileInfo {
2828

2929
export interface SearchOptions {
3030
excludePatterns?: string[];
31+
/**
32+
* Called for each subdirectory below the starting path that could not be
33+
* read (EACCES, say). The walk skips it and goes on, so the matches it
34+
* returns are partial; this is how the caller finds out (#5189).
35+
*/
36+
onUnreadable?: (directory: string, error: unknown) => void;
3137
}
3238

3339
export interface SearchResult {
@@ -930,12 +936,25 @@ export async function searchFilesWithValidation(
930936
allowedDirectories: readonly string[],
931937
options: SearchOptions = {},
932938
): Promise<string[]> {
933-
const { excludePatterns = [] } = options;
939+
const { excludePatterns = [], onUnreadable } = options;
934940
const results: string[] = [];
935941
const visit = createEntryBudget("search_files", rootPath);
936942

937943
async function search(currentPath: string) {
938-
const entries = await readdirWithTimeout(currentPath);
944+
let entries: Dirent[];
945+
try {
946+
entries = await readdirWithTimeout(currentPath);
947+
} catch (error) {
948+
// The starting path failing is the request failing, and a timeout ends
949+
// the whole search (see FsTimeoutError). A subdirectory that cannot be
950+
// read is skipped, but reported to the caller, so the result never reads
951+
// as complete when it is not (#5189).
952+
if (currentPath === rootPath || error instanceof FsTimeoutError) {
953+
throw error;
954+
}
955+
onUnreadable?.(currentPath, error);
956+
return;
957+
}
939958

940959
for (const entry of entries) {
941960
const fullPath = path.join(currentPath, entry.name);
@@ -951,29 +970,27 @@ export async function searchFilesWithValidation(
951970

952971
visit();
953972

973+
// Only validation is guarded: an entry refused by validatePath (outside
974+
// the allowed directories, a dangling link) is skipped silently. A
975+
// timeout still ends the whole search rather than returning partial
976+
// results as if they were complete.
954977
try {
955978
await validatePath(fullPath, allowedDirectories);
956-
957-
// Use glob matching for the search pattern
958-
if (minimatch(relativePath, pattern, { dot: true })) {
959-
results.push(fullPath);
960-
}
961-
962-
if (entry.isDirectory()) {
963-
await search(fullPath);
964-
}
965979
} catch (error) {
966-
// A timeout or the entry cap ends the whole search with its error
967-
// rather than returning partial results as if they were complete; any
968-
// other failure (an entry refused or unreadable) skips that entry.
969-
if (
970-
error instanceof FsTimeoutError ||
971-
error instanceof WalkLimitError
972-
) {
980+
if (error instanceof FsTimeoutError) {
973981
throw error;
974982
}
975983
continue;
976984
}
985+
986+
// Use glob matching for the search pattern
987+
if (minimatch(relativePath, pattern, { dot: true })) {
988+
results.push(fullPath);
989+
}
990+
991+
if (entry.isDirectory()) {
992+
await search(fullPath);
993+
}
977994
}
978995
}
979996

‎src/filesystem/server.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -763,13 +763,29 @@ export function createServer(
763763
},
764764
async (args: z.infer<typeof SearchFilesArgsSchema>) => {
765765
const validPath = await validatePath(args.path, allowedDirectories);
766+
// A subdirectory that cannot be read is skipped, and named after the
767+
// matches so the caller knows they are partial (#5189).
768+
const unreadable: string[] = [];
766769
const results = await searchFilesWithValidation(
767770
validPath,
768771
args.pattern,
769772
allowedDirectories,
770-
{ excludePatterns: args.excludePatterns },
773+
{
774+
excludePatterns: args.excludePatterns,
775+
onUnreadable: (directory, error) => {
776+
const code = (error as NodeJS.ErrnoException).code;
777+
unreadable.push(code ? `${directory} (${code})` : directory);
778+
},
779+
},
771780
);
772-
const text = results.length > 0 ? results.join("\n") : "No matches found";
781+
let text = results.length > 0 ? results.join("\n") : "No matches found";
782+
if (unreadable.length > 0) {
783+
text +=
784+
`\n\nThe search is incomplete: ${unreadable.length} ` +
785+
`${unreadable.length === 1 ? "directory" : "directories"} could not be read, ` +
786+
"and any matches inside are missing:\n" +
787+
unreadable.join("\n");
788+
}
773789
return {
774790
content: [{ type: "text" as const, text }],
775791
structuredContent: { content: text },

0 commit comments

Comments
 (0)