Skip to content

Commit dfe9187

Browse files
cliffhallclaude
andcommitted
fix(filesystem): retry a failed realpath once before losing a root
The directories resolved once and kept (command-line directories at startup, and each client Root) now go through realpathWithRetry, which retries fs.promises.realpath once after 100 ms. On Windows the first native realpath right after subst maps a drive can throw before the mapping is visible (#5185); one failure dropped a Root, and cost a command-line directory its resolved spelling, so every request on the drive was refused as a symlink escape. Both sides still resolve through the same native fs.promises.realpath, and validatePath is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 66e3dec commit dfe9187

7 files changed

Lines changed: 116 additions & 5 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+
A Root or command-line directory whose `realpath` fails once is now retried after a short delay instead of being lost for the life of the process. On Windows the first native `realpath` right after `subst` maps a drive can fail before the mapping is visible; a Root was dropped as inaccessible, and a command-line directory lost its resolved spelling, so every request on the drive was refused.

‎src/filesystem/__tests__/path-utils.test.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import { describe, it, expect, afterEach } from "vitest";
1+
import { describe, it, expect, afterEach, vi } from "vitest";
2+
import { promises as fsp } from "fs";
23
import {
34
normalizePath,
45
normalizePathFormat,
56
expandHome,
67
convertToWindowsPath,
8+
realpathWithRetry,
79
} from "../path-utils.js";
810

911
describe("Path Utilities", () => {
@@ -421,3 +423,34 @@ describe("Path Utilities", () => {
421423
});
422424
});
423425
});
426+
427+
// #5185: the directories resolved once and kept get one retry.
428+
describe("realpathWithRetry", () => {
429+
afterEach(() => {
430+
vi.restoreAllMocks();
431+
});
432+
433+
it("returns the first call's result without retrying", async () => {
434+
const realpath = vi.spyOn(fsp, "realpath").mockResolvedValue("/real");
435+
expect(await realpathWithRetry("/given", 0)).toBe("/real");
436+
expect(realpath).toHaveBeenCalledTimes(1);
437+
});
438+
439+
it("retries once after a failure and returns the retry's result", async () => {
440+
const realpath = vi
441+
.spyOn(fsp, "realpath")
442+
.mockRejectedValueOnce(new Error("ENOENT"))
443+
.mockResolvedValueOnce("/real");
444+
expect(await realpathWithRetry("/given", 0)).toBe("/real");
445+
expect(realpath).toHaveBeenCalledTimes(2);
446+
});
447+
448+
it("rejects with the retry's error when both calls fail", async () => {
449+
const realpath = vi
450+
.spyOn(fsp, "realpath")
451+
.mockRejectedValueOnce(new Error("first"))
452+
.mockRejectedValueOnce(new Error("second"));
453+
await expect(realpathWithRetry("/given", 0)).rejects.toThrow("second");
454+
expect(realpath).toHaveBeenCalledTimes(2);
455+
});
456+
});

‎src/filesystem/__tests__/roots-utils.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,33 @@ describe("getValidRootDirectories", () => {
9494
);
9595
});
9696

97+
// #5185: on Windows the first native realpath right after `subst` can
98+
// throw before the mapping is visible. A root is resolved once per roots
99+
// update, so one failure must not drop it.
100+
it("keeps a root whose realpath fails once and then succeeds (#5185)", async () => {
101+
const realpath = vi
102+
.spyOn(fsp, "realpath")
103+
.mockRejectedValueOnce(
104+
Object.assign(new Error("ENOENT"), { code: "ENOENT" }),
105+
);
106+
const result = await getValidRootDirectories([{ uri: testDir1 }]);
107+
expect(result).toEqual([testDir1]);
108+
expect(realpath).toHaveBeenCalledTimes(2);
109+
});
110+
111+
it("drops a root whose realpath fails twice, logging it (#5185)", async () => {
112+
const realpath = vi
113+
.spyOn(fsp, "realpath")
114+
.mockRejectedValueOnce(new Error("EIO"))
115+
.mockRejectedValueOnce(new Error("EIO"));
116+
const result = await getValidRootDirectories([{ uri: testDir1 }]);
117+
expect(result).toEqual([]);
118+
expect(realpath).toHaveBeenCalledTimes(2);
119+
expect(console.error).toHaveBeenCalledWith(
120+
`Skipping invalid path or inaccessible: ${testDir1}`,
121+
);
122+
});
123+
97124
it("drops a root whose stat fails after realpath succeeded, logging the error", async () => {
98125
vi.spyOn(fsp, "stat")
99126
.mockRejectedValueOnce(new Error("EACCES"))

‎src/filesystem/__tests__/stdio.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,20 @@ describe("startup", () => {
195195
expect(await resolveAllowedDirectories([link])).toEqual([link, target]);
196196
});
197197

198+
// #5185: a realpath that fails once (on Windows, the first native call
199+
// after `subst` maps a drive) is retried, so the resolved spelling, which
200+
// every request resolves to, is not lost for the life of the process.
201+
it("retries a realpath that fails once, keeping the resolved spelling (#5185)", async () => {
202+
const link = path.join(dir, "link");
203+
const target = path.join(dir, "target");
204+
await fs.mkdir(target);
205+
await fs.symlink(target, link);
206+
vi.spyOn(fs, "realpath").mockRejectedValueOnce(
207+
Object.assign(new Error("ENOENT"), { code: "ENOENT" }),
208+
);
209+
expect(await resolveAllowedDirectories([link])).toEqual([link, target]);
210+
});
211+
198212
it("expands ~ to the home directory", async () => {
199213
const home = await fs.realpath(os.homedir());
200214
const resolved = await resolveAllowedDirectories(["~"]);

‎src/filesystem/index.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
StdioServerTransport,
2020
type StdioServerHandle,
2121
} from "@modelcontextprotocol/server/stdio";
22-
import { normalizePath, expandHome } from "./path-utils.js";
22+
import { normalizePath, expandHome, realpathWithRetry } from "./path-utils.js";
2323
import { createServer } from "./server.js";
2424

2525
/**
@@ -43,7 +43,7 @@ export async function resolveAllowedDirectories(
4343
try {
4444
// Security: Resolve symlinks in allowed directories during startup
4545
// This ensures we know the real paths and can validate against them later
46-
const resolved = await fs.realpath(absolute);
46+
const resolved = await realpathWithRetry(absolute);
4747
const normalizedResolved = normalizePath(resolved);
4848
// Return both original and resolved paths if they differ
4949
// This allows matching against either /tmp or /private/tmp on macOS

‎src/filesystem/path-utils.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import { promises as fs } from "fs";
12
import path from "path";
23
import os from "os";
4+
import { setTimeout as delay } from "timers/promises";
35

46
/**
57
* Converts WSL or Unix-style Windows paths to Windows format
@@ -132,3 +134,33 @@ export function expandHome(filepath: string): string {
132134
}
133135
return filepath;
134136
}
137+
138+
/** How long realpathWithRetry waits before its one retry. */
139+
export const REALPATH_RETRY_DELAY_MS = 100;
140+
141+
/**
142+
* Resolves a path with fs.promises.realpath, retrying once after a short
143+
* delay if the first call fails.
144+
*
145+
* For the directories resolved once and kept (the command-line directories
146+
* at startup, and each client Root on a roots update), where a failure lasts
147+
* for the life of the process or the roots list. On Windows the first native
148+
* realpath right after `subst` maps a drive can throw before the mapping is
149+
* visible, and succeed a moment later (#5185). The retry goes through the
150+
* same fs.promises.realpath (the native implementation) that validatePath
151+
* resolves requests with, so both sides still agree on the spelling.
152+
* @param p The path to resolve
153+
* @param retryDelayMs How long to wait before the retry
154+
* @returns The resolved path; rejects with the second call's error
155+
*/
156+
export async function realpathWithRetry(
157+
p: string,
158+
retryDelayMs: number = REALPATH_RETRY_DELAY_MS,
159+
): Promise<string> {
160+
try {
161+
return await fs.realpath(p);
162+
} catch {
163+
await delay(retryDelayMs);
164+
return await fs.realpath(p);
165+
}
166+
}

‎src/filesystem/roots-utils.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { promises as fs, type Stats } from "fs";
22
import path from "path";
33
import os from "os";
4-
import { normalizePath } from "./path-utils.js";
4+
import { normalizePath, realpathWithRetry } from "./path-utils.js";
55
import type { Root } from "@modelcontextprotocol/server";
66
import { fileURLToPath } from "url";
77

@@ -20,7 +20,7 @@ async function parseRootUri(rootUri: string): Promise<string | null> {
2020
? path.join(os.homedir(), rawPath.slice(1))
2121
: rawPath;
2222
const absolutePath = path.resolve(expandedPath);
23-
const resolvedPath = await fs.realpath(absolutePath);
23+
const resolvedPath = await realpathWithRetry(absolutePath);
2424
return normalizePath(resolvedPath);
2525
} catch {
2626
return null; // Path doesn't exist or other error

0 commit comments

Comments
 (0)