Skip to content

Commit 99ba0c6

Browse files
cliffhallclaude
andcommitted
feat(filesystem): add --confine-roots to keep client Roots inside the command-line directories
With --confine-roots, a 2025-era client's Roots can narrow the command-line directories but never replace or widen them: a root inside one is allowed, a root containing one is narrowed to it, and a root outside all of them is ignored and logged, like an invalid root. It is opt-in, so deployments that rely on Roots replacing the command-line directories keep working; without command-line directories it does nothing and says so at startup. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 6017ed3 commit 99ba0c6

8 files changed

Lines changed: 405 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": minor
3+
---
4+
5+
Add a `--confine-roots` command-line flag. With it, a 2025-era client's Roots can narrow the command-line directories but never replace or widen them: a root inside a command-line directory is allowed, a root containing one is narrowed to it, and a root outside all of them is ignored and logged. Without the flag, Roots replace the command-line directories as before.

‎src/filesystem/README.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,27 @@ The server then registers only the tools annotated `readOnlyHint: true` in the [
3636

3737
The flag may appear anywhere among the arguments. `--` ends the options, so a directory literally named `--read-only` can be given after it.
3838

39-
Read-only mode covers every allowed directory. To make only some of them read-only, run two servers: one with `--read-only` for the directories to protect, and one without it for the rest. That separation holds only while the writable server keeps its command-line directories: a 2025-era client that supports Roots replaces them (see Method 2), so it could expose a protected directory to the writable server. Where that matters, make the protected directories read-only at the operating-system level as well, with file permissions or, with Docker, a bind mount's `ro` flag.
39+
Read-only mode covers every allowed directory. To make only some of them read-only, run two servers: one with `--read-only` for the directories to protect, and one without it for the rest. That separation holds only while the writable server keeps its command-line directories: a 2025-era client that supports Roots replaces them (see Method 2), so it could expose a protected directory to the writable server, unless that server is started with `--confine-roots` (see below). Where that matters, make the protected directories read-only at the operating-system level as well, with file permissions or, with Docker, a bind mount's `ro` flag.
4040

4141
### Method 2: MCP Roots (Deprecated, 2025-era clients only)
4242
A client that connects with a 2025-era protocol version (the `initialize` handshake) and supports [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) can dynamically update the Allowed directories.
4343

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

46+
#### Confining Roots to the command-line directories
47+
To keep a client's Roots inside the directories you gave on the command line, add `--confine-roots`:
48+
```bash
49+
mcp-server-filesystem --confine-roots /path/to/dir1 /path/to/dir2
50+
```
51+
52+
The client's Roots can then narrow the command-line directories but never replace or widen them. The server allows the overlap of the two:
53+
54+
- A root inside a command-line directory is allowed as given, so a client can narrow access to one project.
55+
- A root that contains a command-line directory (for example `/`) is narrowed to that directory.
56+
- A root outside every command-line directory is ignored and logged. If every root is ignored, the server treats the update as one with no valid roots: before any root has been in force the command-line directories stay; once one has, access is revoked until the client exposes a root inside them again.
57+
58+
This suits an operator who decides what may be shared (the command line) while letting a client say what it wants to work on (its Roots), and it keeps a client from discarding the command-line directories by advertising its working directory. Without command-line directories the flag has no effect, and the server warns at startup. Without the flag, Roots replace the command-line directories as described above.
59+
4660
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.
4761

4862
**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.
@@ -65,7 +79,7 @@ The server's directory access control follows this flow:
6579
3. **Roots Protocol Handling** (2025-era clients that support roots)
6680
- **On initialization**: Server requests roots from client via `roots/list`
6781
- Client responds with its configured roots
68-
- Server replaces ALL allowed directories with client's roots
82+
- Server replaces ALL allowed directories with client's roots (with `--confine-roots`, with their overlap with the command-line directories)
6983
- Tool calls that arrive before the initial roots are loaded wait for them, so they are checked against the client's roots
7084
- **On runtime updates**: Client can send `notifications/roots/list_changed`
7185
- Server requests updated roots and replaces allowed directories again
Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
// --confine-roots (#3133): a 2025-era client's Roots may narrow the operator's
2+
// command-line directories but never replace or widen them. The overlap rule
3+
// is pinned on confineRootsToDirectories directly; the protocol tests drive a
4+
// real Client that answers roots/list over the in-memory transport and assert
5+
// what the server then allows, logs and refuses, including the withdrawal and
6+
// symlink cases the unconfined flow already guards. The 2026-07-28 era never
7+
// asks for Roots, so there the flag changes nothing, which main() pins.
8+
9+
import fs from "fs/promises";
10+
import path from "path";
11+
import { PassThrough } from "node:stream";
12+
import { pathToFileURL } from "url";
13+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14+
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
15+
import type { Root } from "@modelcontextprotocol/server";
16+
import {
17+
confineRootsToDirectories,
18+
describeAllowedDirectories,
19+
} from "../allowed-directories.js";
20+
import { main, parseArgs } from "../index.js";
21+
import { createServer } from "../server.js";
22+
import {
23+
allowedDirectoriesOf,
24+
call,
25+
makeTempDir,
26+
quietStderr,
27+
textOf,
28+
} from "./helpers.js";
29+
30+
let base: string;
31+
let outside: string;
32+
let stderr: ReturnType<typeof quietStderr>;
33+
let closers: Array<() => Promise<void>>;
34+
35+
beforeEach(async () => {
36+
stderr = quietStderr();
37+
base = await makeTempDir("mcp-fs-confine-base-");
38+
outside = await makeTempDir("mcp-fs-confine-outside-");
39+
await fs.mkdir(path.join(base, "inner"));
40+
await fs.writeFile(path.join(base, "inner", "in.txt"), "inside");
41+
await fs.writeFile(path.join(base, "top.txt"), "top");
42+
await fs.writeFile(path.join(outside, "out.txt"), "outside");
43+
closers = [];
44+
});
45+
46+
afterEach(async () => {
47+
for (const close of closers.reverse()) await close();
48+
vi.restoreAllMocks();
49+
await fs.rm(base, { recursive: true, force: true });
50+
await fs.rm(outside, { recursive: true, force: true });
51+
});
52+
53+
function rootOf(dir: string): Root {
54+
return { uri: pathToFileURL(dir).href, name: path.basename(dir) };
55+
}
56+
57+
/**
58+
* A 2025-era client that supports Roots and answers roots/list with
59+
* `roots()`, connected to a server for `directories` with confinement on.
60+
*/
61+
async function connect(
62+
directories: string[],
63+
roots: () => Root[],
64+
confineRoots = true,
65+
): Promise<Client> {
66+
const server = createServer(directories, { confineRoots });
67+
const client = new Client(
68+
{ name: "fs-confine-test", version: "0.0.0" },
69+
{ capabilities: { roots: { listChanged: true } } },
70+
);
71+
client.setRequestHandler("roots/list", async () => ({ roots: roots() }));
72+
const [clientTransport, serverTransport] =
73+
InMemoryTransport.createLinkedPair();
74+
await Promise.all([
75+
server.connect(serverTransport),
76+
client.connect(clientTransport),
77+
]);
78+
closers.push(async () => {
79+
await client.close();
80+
await server.close();
81+
});
82+
return client;
83+
}
84+
85+
describe("confineRootsToDirectories", () => {
86+
it("keeps a root inside a command-line directory", () => {
87+
expect(confineRootsToDirectories(["/b/x"], ["/b"])).toEqual({
88+
confined: ["/b/x"],
89+
ignored: [],
90+
});
91+
});
92+
93+
it("narrows a root that contains command-line directories to them", () => {
94+
expect(confineRootsToDirectories(["/"], ["/b", "/c/d"])).toEqual({
95+
confined: ["/b", "/c/d"],
96+
ignored: [],
97+
});
98+
});
99+
100+
it("ignores a root that overlaps no command-line directory", () => {
101+
expect(confineRootsToDirectories(["/elsewhere", "/b"], ["/b"])).toEqual({
102+
confined: ["/b"],
103+
ignored: ["/elsewhere"],
104+
});
105+
});
106+
107+
it("does not treat a sibling with a common prefix as inside", () => {
108+
expect(confineRootsToDirectories(["/base-other"], ["/base"])).toEqual({
109+
confined: [],
110+
ignored: ["/base-other"],
111+
});
112+
});
113+
114+
it("lists each directory once", () => {
115+
expect(confineRootsToDirectories(["/b", "/", "/b"], ["/b"])).toEqual({
116+
confined: ["/b"],
117+
ignored: [],
118+
});
119+
});
120+
});
121+
122+
describe("with --confine-roots on 2025-11-25", () => {
123+
it("narrows the allowed directories to a root inside them", async () => {
124+
const inner = path.join(base, "inner");
125+
const client = await connect([base], () => [rootOf(inner)]);
126+
await vi.waitFor(async () =>
127+
expect(await allowedDirectoriesOf(client)).toEqual([inner]),
128+
);
129+
expect(stderr).toHaveBeenCalledWith(
130+
describeAllowedDirectories([inner], {
131+
from: "roots",
132+
replacedCommandLine: true,
133+
confined: true,
134+
}),
135+
);
136+
const top = await call(client, "read_text_file", {
137+
path: path.join(base, "top.txt"),
138+
});
139+
expect(textOf(top)).toMatch(/^Access denied/);
140+
});
141+
142+
it("ignores a root outside them and keeps the command-line directories", async () => {
143+
const client = await connect([base], () => [rootOf(outside)]);
144+
await vi.waitFor(() =>
145+
expect(stderr).toHaveBeenCalledWith(
146+
`Ignored client roots outside the command-line directories (--confine-roots): ${outside}`,
147+
),
148+
);
149+
expect(await allowedDirectoriesOf(client)).toEqual([base]);
150+
const out = await call(client, "read_text_file", {
151+
path: path.join(outside, "out.txt"),
152+
});
153+
expect(textOf(out)).toMatch(/^Access denied/);
154+
const top = await call(client, "read_text_file", {
155+
path: path.join(base, "top.txt"),
156+
});
157+
expect(textOf(top)).toBe("top");
158+
});
159+
160+
it("narrows a root that contains a command-line directory to that directory", async () => {
161+
const client = await connect([base], () => [
162+
rootOf(path.dirname(base)),
163+
rootOf(outside),
164+
]);
165+
await vi.waitFor(async () =>
166+
expect(await allowedDirectoriesOf(client)).toEqual([base]),
167+
);
168+
const out = await call(client, "read_text_file", {
169+
path: path.join(outside, "out.txt"),
170+
});
171+
expect(textOf(out)).toMatch(/^Access denied/);
172+
});
173+
174+
it("refuses a symlink inside the directories that points outside them", async () => {
175+
const link = path.join(base, "link");
176+
await fs.symlink(outside, link);
177+
const client = await connect([base], () => [rootOf(link)]);
178+
await vi.waitFor(() =>
179+
expect(stderr).toHaveBeenCalledWith(
180+
`Ignored client roots outside the command-line directories (--confine-roots): ${outside}`,
181+
),
182+
);
183+
const out = await call(client, "read_text_file", {
184+
path: path.join(link, "out.txt"),
185+
});
186+
expect(textOf(out)).toMatch(/^Access denied/);
187+
});
188+
189+
it("revokes access once roots were in force and every new root is outside", async () => {
190+
const inner = path.join(base, "inner");
191+
let roots = [rootOf(inner)];
192+
const client = await connect([base], () => roots);
193+
await vi.waitFor(async () =>
194+
expect(await allowedDirectoriesOf(client)).toEqual([inner]),
195+
);
196+
roots = [rootOf(outside)];
197+
await client.sendRootsListChanged();
198+
await vi.waitFor(async () =>
199+
expect(await allowedDirectoriesOf(client)).toEqual([]),
200+
);
201+
const out = await call(client, "read_text_file", {
202+
path: path.join(outside, "out.txt"),
203+
});
204+
expect(textOf(out)).toMatch(/^Access denied/);
205+
});
206+
207+
it("lets the roots set the directories when none were given on the command line", async () => {
208+
const client = await connect([], () => [rootOf(outside)]);
209+
await vi.waitFor(async () =>
210+
expect(await allowedDirectoriesOf(client)).toEqual([outside]),
211+
);
212+
});
213+
});
214+
215+
describe("without --confine-roots", () => {
216+
it("still lets a root outside the command-line directories replace them", async () => {
217+
const client = await connect([base], () => [rootOf(outside)], false);
218+
await vi.waitFor(async () =>
219+
expect(await allowedDirectoriesOf(client)).toEqual([outside]),
220+
);
221+
});
222+
});
223+
224+
describe("the command line", () => {
225+
it("parses --confine-roots anywhere before --", () => {
226+
expect(parseArgs(["/a", "--confine-roots"])).toEqual({
227+
directories: ["/a"],
228+
readOnly: false,
229+
confineRoots: true,
230+
});
231+
expect(parseArgs(["--", "--confine-roots"])).toEqual({
232+
directories: ["--confine-roots"],
233+
readOnly: false,
234+
confineRoots: false,
235+
});
236+
});
237+
238+
it("warns that --confine-roots does nothing without directories", async () => {
239+
const handle = await main(
240+
["--confine-roots"],
241+
new PassThrough(),
242+
new PassThrough(),
243+
);
244+
closers.push(() => handle.close());
245+
expect(stderr).toHaveBeenCalledWith(
246+
"Warning: --confine-roots has no effect without command-line directories; a client's Roots will set the allowed directories",
247+
);
248+
});
249+
250+
it("serves the command-line directories on 2026-07-28, as without the flag", async () => {
251+
const stdin = new PassThrough();
252+
const stdout = new PassThrough();
253+
stdout.setEncoding("utf8");
254+
const handle = await main(["--confine-roots", base], stdin, stdout);
255+
closers.push(() => handle.close());
256+
const line = new Promise<string>((resolve) => {
257+
let buffered = "";
258+
stdout.on("data", (chunk: string) => {
259+
buffered += chunk;
260+
const newline = buffered.indexOf("\n");
261+
if (newline !== -1) resolve(buffered.slice(0, newline));
262+
});
263+
});
264+
stdin.write(
265+
`${JSON.stringify({
266+
jsonrpc: "2.0",
267+
id: 1,
268+
method: "tools/call",
269+
params: {
270+
_meta: {
271+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
272+
"io.modelcontextprotocol/clientCapabilities": { roots: {} },
273+
},
274+
name: "list_allowed_directories",
275+
arguments: {},
276+
},
277+
})}\n`,
278+
);
279+
const { result } = JSON.parse(await line) as {
280+
result: { content: Array<{ text: string }> };
281+
};
282+
expect(result.content[0].text).toBe(`Allowed directories:\n${base}`);
283+
});
284+
});

‎src/filesystem/__tests__/read-only.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ describe("parseArgs", () => {
141141
expect(parseArgs(["/a", "/b"])).toEqual({
142142
directories: ["/a", "/b"],
143143
readOnly: false,
144+
confineRoots: false,
144145
});
145146
});
146147

@@ -153,6 +154,7 @@ describe("parseArgs", () => {
153154
expect(parseArgs(args)).toEqual({
154155
directories: ["/a", "/b"],
155156
readOnly: true,
157+
confineRoots: false,
156158
});
157159
}
158160
});
@@ -161,6 +163,7 @@ describe("parseArgs", () => {
161163
expect(parseArgs(["--read-only", "--", "--read-only", "/a"])).toEqual({
162164
directories: ["--read-only", "/a"],
163165
readOnly: true,
166+
confineRoots: false,
164167
});
165168
});
166169
});
@@ -212,7 +215,7 @@ describe("main() with --read-only", () => {
212215
);
213216
closers.push(() => handle.close());
214217
expect(stderr).toHaveBeenCalledWith(
215-
"Usage: mcp-server-filesystem [--read-only] [allowed-directory] [additional-directories...]",
218+
"Usage: mcp-server-filesystem [--read-only] [--confine-roots] [allowed-directory] [additional-directories...]",
216219
);
217220
});
218221
});

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ describe("startup", () => {
129129
it("prints usage, and waits for roots, when started with no directories", async () => {
130130
await session.start([]);
131131
expect(stderrText()).toContain(
132-
"Usage: mcp-server-filesystem [--read-only] [allowed-directory] [additional-directories...]",
132+
"Usage: mcp-server-filesystem [--read-only] [--confine-roots] [allowed-directory] [additional-directories...]",
133133
);
134134
expect(stderrText()).toContain(
135135
"At least one directory must be provided by EITHER method for the server to operate.",

0 commit comments

Comments
 (0)