Skip to content

Commit 1513547

Browse files
authored
Merge pull request #5317 from modelcontextprotocol/v2/fix/5183-filesystem-root-advertised-form
fix(filesystem): allow a client Root in its advertised form as well as its realpath
2 parents 858cfff + b7471ab commit 1513547

5 files changed

Lines changed: 189 additions & 14 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 client Root is now allowed in the form the client advertised it as well as in its resolved form, as command-line directories already were. A request that names a path through a symlinked Root's own spelling (for example `/tmp/...` for a Root of `file:///tmp/...` on macOS) is no longer refused, and `list_allowed_directories` lists both forms. Every request is still resolved and checked against the resolved directory, so a symlink inside a Root that points outside it stays refused.

‎src/filesystem/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ A client that connects with a 2025-era protocol version (the `initialize` handsh
3131

3232
Roots notified by Client to Server, completely replace any server-side Allowed directories when provided.
3333

34+
A Root reached through a symlink is allowed in both its advertised form and its resolved form, as a command-line directory is: a Root of `file:///tmp/project` on macOS allows `/tmp/project` and `/private/tmp/project`. Every requested path is still resolved and checked against the resolved directories, so a symlink inside a Root that points outside it is refused.
35+
3436
**Important**: If server starts without command-line arguments AND a 2025-era client doesn't support roots protocol, the server fails at initialization: it logs the reason to stderr, closes the connection and exits with status 1. A client that supports roots but provides none (or none that are valid) keeps the connection, with no allowed directories until it sends `roots/list_changed` with valid roots.
3537

3638
The 2026-07-28 protocol has no `initialize` handshake and no server-to-client `roots/list` request, so a 2026-07-28 client's roots are never asked for: the command-line directories are the whole allow-list. A server started with none answers every tool call on such a connection with an error saying so.
@@ -205,7 +207,7 @@ The server's directory access control follows this flow:
205207
- List all directories the server is allowed to access
206208
- No input required
207209
- Returns:
208-
- Directories that this server can read/write from
210+
- Directories that this server can read/write from. A directory reached through a symlink is listed twice, in the form it was given and in its resolved form
209211

210212
### Slow and very large trees
211213

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

Lines changed: 135 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,148 @@ describe("initial roots", () => {
8484
);
8585
});
8686

87-
it("resolve a symlinked root to its target", async () => {
87+
// #5183: a Root is allowed in its advertised spelling as well as its
88+
// realpath, as a command-line directory is, so a request that uses the
89+
// Root's own spelling is not refused.
90+
it("admit a symlinked root in both its advertised and its resolved form (#5183)", async () => {
8891
const link = path.join(cliDir, "link-to-root");
8992
await fs.symlink(rootDir, link);
93+
await fs.writeFile(path.join(rootDir, "note.txt"), "inside the root");
9094
const { client } = await connectTracked([], {
9195
capabilities: ROOTS,
9296
listRoots: () => [rootOf(link)],
9397
});
9498
await vi.waitFor(async () =>
95-
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]),
99+
expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]),
100+
);
101+
const viaLink = await call(client, "read_text_file", {
102+
path: path.join(link, "note.txt"),
103+
});
104+
expect(textOf(viaLink)).toBe("inside the root");
105+
const viaTarget = await call(client, "read_text_file", {
106+
path: path.join(rootDir, "note.txt"),
107+
});
108+
expect(textOf(viaTarget)).toBe("inside the root");
109+
});
110+
111+
// #5183: admitting the advertised spelling does not widen access. Every
112+
// request is still realpath'd and re-checked, so a symlink inside the Root
113+
// that points outside it is refused under either spelling.
114+
it("refuse a symlink inside a symlinked root that points outside it (#5183)", async () => {
115+
const link = path.join(cliDir, "link-to-root");
116+
await fs.symlink(rootDir, link);
117+
const secret = path.join(cliDir, "secret.txt");
118+
await fs.writeFile(secret, "outside the root");
119+
await fs.symlink(secret, path.join(rootDir, "escape.txt"));
120+
const { client } = await connectTracked([], {
121+
capabilities: ROOTS,
122+
listRoots: () => [rootOf(link)],
123+
});
124+
await vi.waitFor(async () =>
125+
expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]),
126+
);
127+
for (const dir of [link, rootDir]) {
128+
const result = await call(client, "read_text_file", {
129+
path: path.join(dir, "escape.txt"),
130+
});
131+
expect(textOf(result)).toMatch(/^Access denied/);
132+
}
133+
});
134+
135+
// #5183: the advertised form names a symlink, which can be retargeted after
136+
// the Roots load. A new file or directory under it must still be refused
137+
// when the symlink now leads outside every allowed directory.
138+
it("refuse creating under a root alias retargeted outside the root (#5183)", async () => {
139+
const link = path.join(cliDir, "link-to-root");
140+
await fs.symlink(rootDir, link);
141+
const { client } = await connectTracked([], {
142+
capabilities: ROOTS,
143+
listRoots: () => [rootOf(link)],
144+
});
145+
await vi.waitFor(async () =>
146+
expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]),
147+
);
148+
const outside = path.join(cliDir, "outside");
149+
await fs.mkdir(outside);
150+
await fs.rm(link);
151+
await fs.symlink(outside, link);
152+
153+
const written = await call(client, "write_file", {
154+
path: path.join(link, "new.txt"),
155+
content: "x",
156+
});
157+
expect(textOf(written)).toMatch(/^Access denied/);
158+
const created = await call(client, "create_directory", {
159+
path: path.join(link, "a", "b"),
160+
});
161+
expect(textOf(created)).toMatch(/^Access denied/);
162+
expect(await fs.readdir(outside)).toEqual([]);
163+
});
164+
165+
// #5183: the advertised form is kept as the client spelled it. Trimming
166+
// whitespace or quotes from it would name a different directory, here an
167+
// unrelated sibling, and allow it. POSIX only: Windows filenames cannot end
168+
// in a space.
169+
it.skipIf(process.platform === "win32")(
170+
"keep a root's advertised form verbatim, not trimmed to a sibling's name (#5183)",
171+
async () => {
172+
const link = path.join(cliDir, "alias ");
173+
await fs.symlink(rootDir, link);
174+
const sibling = path.join(cliDir, "alias");
175+
await fs.mkdir(sibling);
176+
await fs.writeFile(path.join(sibling, "secret.txt"), "not in the root");
177+
const { client } = await connectTracked([], {
178+
capabilities: ROOTS,
179+
listRoots: () => [rootOf(link)],
180+
});
181+
await vi.waitFor(async () =>
182+
expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]),
183+
);
184+
const result = await call(client, "read_text_file", {
185+
path: path.join(sibling, "secret.txt"),
186+
});
187+
expect(textOf(result)).toMatch(/^Access denied/);
188+
},
189+
);
190+
191+
// #5183 as reported: on macOS /tmp is a symlink to /private/tmp, so a Root
192+
// of file:///tmp/... was allowed only as /private/tmp/... and a request
193+
// naming /tmp/... was refused.
194+
it.runIf(process.platform === "darwin")(
195+
"admit a macOS /tmp root under its /tmp spelling (#5183)",
196+
async () => {
197+
const tmpRoot = await fs.mkdtemp("/tmp/mcp-fs-5183-");
198+
try {
199+
await fs.writeFile(path.join(tmpRoot, "note.txt"), "in /tmp");
200+
const { client } = await connectTracked([], {
201+
capabilities: ROOTS,
202+
listRoots: () => [rootOf(tmpRoot)],
203+
});
204+
await vi.waitFor(async () =>
205+
expect(await allowedDirectoriesOf(client)).toEqual([
206+
tmpRoot,
207+
await fs.realpath(tmpRoot),
208+
]),
209+
);
210+
const result = await call(client, "read_text_file", {
211+
path: path.join(tmpRoot, "note.txt"),
212+
});
213+
expect(textOf(result)).toBe("in /tmp");
214+
} finally {
215+
await fs.rm(tmpRoot, { recursive: true, force: true });
216+
}
217+
},
218+
);
219+
220+
it("list a root once when it is advertised in both its forms (#5183)", async () => {
221+
const link = path.join(cliDir, "link-to-root");
222+
await fs.symlink(rootDir, link);
223+
const { client } = await connectTracked([], {
224+
capabilities: ROOTS,
225+
listRoots: () => [rootOf(link), rootOf(rootDir)],
226+
});
227+
await vi.waitFor(async () =>
228+
expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]),
96229
);
97230
});
98231

‎src/filesystem/lib.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,19 @@ async function resolveUnicodeEquivalentPath(
376376
}
377377

378378
let currentPath = await realpathWithTimeout(allowedDirectory);
379+
// An allowed directory can be a symlink (the advertised form of a Root or a
380+
// command-line directory), retargeted since it was allowed, so its realpath
381+
// is checked like every component below it (#5183).
382+
if (
383+
!isPathWithinAllowedDirectories(
384+
normalizePathFormat(currentPath),
385+
allowedDirectories,
386+
)
387+
) {
388+
throw new Error(
389+
`Access denied - symlink target outside allowed directories: ${currentPath} not in ${allowedDirectories.join(", ")}`,
390+
);
391+
}
379392
const relativeParts = path
380393
.relative(allowedDirectory, absolutePath)
381394
.split(path.sep)

‎src/filesystem/roots-utils.ts‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,30 @@
11
import { promises as fs, type Stats } from "fs";
22
import path from "path";
33
import os from "os";
4-
import { normalizePath, realpathWithRetry } from "./path-utils.js";
4+
import {
5+
normalizePath,
6+
normalizePathFormat,
7+
realpathWithRetry,
8+
} from "./path-utils.js";
59
import type { Root } from "@modelcontextprotocol/server";
610
import { fileURLToPath } from "url";
711

12+
/** A root's two spellings: as the client advertised it, and its realpath. */
13+
interface RootPaths {
14+
advertised: string;
15+
resolved: string;
16+
}
17+
818
/**
9-
* Converts a root URI to a normalized directory path with basic security validation.
19+
* Converts a root URI to its normalized absolute path and its realpath.
20+
* Both are kept, as resolveAllowedDirectories in index.ts keeps both forms of
21+
* a command-line directory, so a request may use either spelling (#5183).
22+
* validatePath still realpaths every request, so access stays bounded by the
23+
* resolved directory.
1024
* @param rootUri - File URI (file://...) or plain directory path
11-
* @returns Promise resolving to validated path or null if invalid
25+
* @returns Promise resolving to both forms, or null if invalid
1226
*/
13-
async function parseRootUri(rootUri: string): Promise<string | null> {
27+
async function parseRootUri(rootUri: string): Promise<RootPaths | null> {
1428
try {
1529
const rawPath = rootUri.startsWith("file://")
1630
? fileURLToPath(rootUri)
@@ -21,7 +35,12 @@ async function parseRootUri(rootUri: string): Promise<string | null> {
2135
: rawPath;
2236
const absolutePath = path.resolve(expandedPath);
2337
const resolvedPath = await realpathWithRetry(absolutePath);
24-
return normalizePath(resolvedPath);
38+
return {
39+
// normalizePathFormat, not normalizePath: trimming whitespace or quotes
40+
// from the client's spelling would name a different directory.
41+
advertised: normalizePathFormat(absolutePath),
42+
resolved: normalizePath(resolvedPath),
43+
};
2544
} catch {
2645
return null; // Path doesn't exist or other error
2746
}
@@ -51,19 +70,20 @@ function formatDirectoryError(
5170
*
5271
* Converts root URI specifications (file:// URIs or plain paths) into normalized
5372
* directory paths, validating that each path exists and is a directory.
54-
* Includes symlink resolution for security.
73+
* Each root contributes its advertised form and, when it differs, its resolved
74+
* (realpath) form, deduplicated across roots.
5575
*
5676
* @param requestedRoots - Array of root specifications with URI and optional name
5777
* @returns Promise resolving to array of validated directory paths
5878
*/
5979
export async function getValidRootDirectories(
6080
requestedRoots: readonly Root[],
6181
): Promise<string[]> {
62-
const validatedDirectories: string[] = [];
82+
const validatedDirectories = new Set<string>();
6383

6484
for (const requestedRoot of requestedRoots) {
65-
const resolvedPath = await parseRootUri(requestedRoot.uri);
66-
if (!resolvedPath) {
85+
const rootPaths = await parseRootUri(requestedRoot.uri);
86+
if (!rootPaths) {
6787
console.error(
6888
formatDirectoryError(
6989
requestedRoot.uri,
@@ -74,10 +94,12 @@ export async function getValidRootDirectories(
7494
continue;
7595
}
7696

97+
const { advertised, resolved: resolvedPath } = rootPaths;
7798
try {
7899
const stats: Stats = await fs.stat(resolvedPath);
79100
if (stats.isDirectory()) {
80-
validatedDirectories.push(resolvedPath);
101+
validatedDirectories.add(advertised);
102+
validatedDirectories.add(resolvedPath);
81103
} else {
82104
console.error(
83105
formatDirectoryError(resolvedPath, undefined, "non-directory root"),
@@ -88,5 +110,5 @@ export async function getValidRootDirectories(
88110
}
89111
}
90112

91-
return validatedDirectories;
113+
return [...validatedDirectories];
92114
}

0 commit comments

Comments
 (0)