Skip to content

Commit 2309e08

Browse files
cliffhallclaude
andcommitted
fix(filesystem): wait for initial roots; fail visibly with no directories
Tool calls now wait for the client's initial roots/list to settle before they run, so a call sent right after initialize is checked against the client's roots rather than refused with "Access denied" (#3204). With no command-line directories and a client without Roots support, the server no longer throws from oninitialized (an error the client never saw). It logs the reason, closes the connection, and the stdio entry point exits with status 1, as the README describes (#4992). The README now also says what happens when a Roots client provides no roots. The pinning tests assert the fixed behavior and lose their KNOWN BUG markers. Closes #3204 Closes #4992 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 571e2b3 commit 2309e08

7 files changed

Lines changed: 156 additions & 37 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+
Tool calls now wait for the client's initial roots before checking paths, so a call sent right after connecting is no longer refused with "Access denied" (#3204). A server started with no directories, connected to a client without Roots support, now fails visibly: it logs the reason, closes the connection and exits with status 1, instead of staying up and refusing every call (#4992).

‎src/filesystem/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ MCP clients that support [Roots](https://modelcontextprotocol.io/docs/learn/clie
2828

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

31-
**Important**: If server starts without command-line arguments AND client doesn't support roots protocol (or provides empty roots), the server will throw an error during initialization.
31+
**Important**: If server starts without command-line arguments AND 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.
3232

3333
This is the recommended method, as this enables runtime directory updates via `roots/list_changed` notifications without server restart, providing a more flexible and modern integration experience.
3434

@@ -48,12 +48,14 @@ The server's directory access control follows this flow:
4848
- **On initialization**: Server requests roots from client via `roots/list`
4949
- Client responds with its configured roots
5050
- Server replaces ALL allowed directories with client's roots
51+
- Tool calls that arrive before the initial roots are loaded wait for them, so they are checked against the client's roots
5152
- **On runtime updates**: Client can send `notifications/roots/list_changed`
5253
- Server requests updated roots and replaces allowed directories again
5354

5455
4. **Fallback Behavior** (if client doesn't support roots)
5556
- Server continues using command-line directories only
5657
- No dynamic updates possible
58+
- With no command-line directories either, the server logs an error, closes the connection and exits with status 1
5759

5860
5. **Access Control**
5961
- All filesystem operations are restricted to allowed directories

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,12 @@ describe("relative paths", () => {
153153
});
154154

155155
it("resolves against the process cwd when there are no allowed directories, and refuses it", async () => {
156-
const empty = await connect([]);
156+
// A Roots client that offers no roots: with no directories and no Roots
157+
// at all the server closes the connection instead (#4992).
158+
const empty = await connect([], {
159+
capabilities: { roots: {} },
160+
listRoots: () => [],
161+
});
157162
try {
158163
const result = await call(empty.client, "read_text_file", {
159164
path: "anything.txt",

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

Lines changed: 69 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
// the command-line directories after initialize, how roots/list_changed
33
// updates them, and what happens when roots are invalid, fail or are not
44
// offered. Driven by a real Client that answers the server's roots/list
5-
// requests over the in-memory transport. Pins #3204 as a known bug, and
6-
// #3602's roots-replace-the-command-line behavior as the README documents it.
5+
// requests over the in-memory transport. Guards the fixes for #3204 (tool
6+
// calls wait for the initial roots) and #4992 (no directories at all fails
7+
// visibly), and pins #3602's roots-replace-the-command-line behavior as the README documents it.
78

89
import fs from "fs/promises";
910
import path from "path";
@@ -19,6 +20,7 @@ import {
1920
textOf,
2021
type Connected,
2122
} from "./helpers.js";
23+
import { NO_ALLOWED_DIRECTORIES_ERROR } from "../server.js";
2224

2325
const ROOTS = { roots: { listChanged: true } };
2426

@@ -157,40 +159,77 @@ describe("initial roots", () => {
157159
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
158160
});
159161

160-
// KNOWN BUG #3204: pins current (wrong) behavior; the fix changes this assertion.
161-
// #3204: the server does not wait for the initial roots before serving
162-
// tool calls. A call that arrives while roots/list is outstanding is
163-
// checked against the command-line directories (here, none).
164-
it("are not awaited before tool calls are served (#3204)", async () => {
162+
// #3204: a tool call that arrives while the initial roots/list is still
163+
// outstanding waits for it, and is checked against the client's roots
164+
// rather than the command-line directories (here, none).
165+
it("are awaited before tool calls are served (#3204)", async () => {
165166
await fs.writeFile(path.join(rootDir, "f.txt"), "from root");
166167
let release: () => void = () => {};
167168
const gate = new Promise<void>((resolve) => {
168169
release = resolve;
169170
});
171+
let asked = false;
170172
const { client } = await connectTracked([], {
171173
capabilities: ROOTS,
172174
listRoots: async () => {
175+
asked = true;
173176
await gate;
174177
return [rootOf(rootDir)];
175178
},
176179
});
177180

178-
const early = await call(client, "read_text_file", {
181+
let settled = false;
182+
const early = call(client, "read_text_file", {
179183
path: path.join(rootDir, "f.txt"),
184+
}).finally(() => {
185+
settled = true;
180186
});
181-
expect(early.isError).toBe(true);
182-
expect(textOf(early)).toBe(
183-
`Access denied - path outside allowed directories: ${path.join(rootDir, "f.txt")} not in `,
184-
);
187+
await vi.waitFor(() => expect(asked).toBe(true));
188+
await new Promise((resolve) => setTimeout(resolve, 50));
189+
expect(settled).toBe(false);
185190

186191
release();
187-
await vi.waitFor(async () =>
188-
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]),
189-
);
190-
const late = await call(client, "read_text_file", {
191-
path: path.join(rootDir, "f.txt"),
192+
const result = await early;
193+
expect(result.isError).toBeFalsy();
194+
expect(textOf(result)).toBe("from root");
195+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]);
196+
});
197+
198+
it("are awaited by concurrent tool calls, which then all succeed (#3204)", async () => {
199+
await fs.writeFile(path.join(rootDir, "a.txt"), "a");
200+
await fs.writeFile(path.join(rootDir, "b.txt"), "b");
201+
const { client } = await connectTracked([], {
202+
capabilities: ROOTS,
203+
listRoots: async () => {
204+
await new Promise((resolve) => setTimeout(resolve, 20));
205+
return [rootOf(rootDir)];
206+
},
192207
});
193-
expect(textOf(late)).toBe("from root");
208+
const results = await Promise.all([
209+
call(client, "read_text_file", { path: path.join(rootDir, "a.txt") }),
210+
call(client, "read_text_file", { path: path.join(rootDir, "b.txt") }),
211+
call(client, "list_allowed_directories"),
212+
]);
213+
expect(results.map(textOf)).toEqual([
214+
"a",
215+
"b",
216+
`Allowed directories:\n${rootDir}`,
217+
]);
218+
});
219+
220+
it("fall back to the command-line directories for waiting calls when roots/list fails (#3204)", async () => {
221+
await fs.writeFile(path.join(cliDir, "f.txt"), "from cli");
222+
const { client } = await connectTracked([cliDir], {
223+
capabilities: ROOTS,
224+
listRoots: async () => {
225+
await new Promise((resolve) => setTimeout(resolve, 20));
226+
throw new Error("no roots");
227+
},
228+
});
229+
const result = await call(client, "read_text_file", {
230+
path: path.join(cliDir, "f.txt"),
231+
});
232+
expect(textOf(result)).toBe("from cli");
194233
});
195234
});
196235

@@ -247,15 +286,18 @@ describe("a client without the roots capability", () => {
247286
);
248287
});
249288

250-
// KNOWN BUG #4992: with no directories and no Roots, the initialization error the README promises is swallowed and the session stays up with nothing allowed; the fix changes this assertion.
251-
// With no directories from either source, oninitialized throws. The SDK
252-
// routes a notification handler's rejection to the server's onerror, which
253-
// the server leaves unset, so the error is invisible to the client: the
254-
// session stays up and every path is refused.
255-
it("stays connected with nothing allowed when no directories were given", async () => {
289+
// #4992: with no directories from either source nothing could ever be
290+
// allowed, so the server says why on stderr and closes the connection
291+
// rather than staying up and refusing every call.
292+
it("closes the connection with an error when no directories were given (#4992)", async () => {
256293
const { client } = await connectTracked([]);
257-
expect(await allowedDirectoriesOf(client)).toEqual([]);
258-
const result = await call(client, "list_directory", { path: rootDir });
259-
expect(textOf(result)).toMatch(/^Access denied/);
294+
await vi.waitFor(() =>
295+
expect(stderr).toHaveBeenCalledWith(
296+
`Error: ${NO_ALLOWED_DIRECTORIES_ERROR}`,
297+
),
298+
);
299+
await expect(
300+
call(client, "list_directory", { path: rootDir }),
301+
).rejects.toThrow(/Connection closed|Not connected/);
260302
});
261303
});

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,20 @@ describe("startup", () => {
139139
);
140140
});
141141

142+
// #4992: with no directories and a client without Roots, the server fails
143+
// at initialization as the README says: it logs why and exits 1.
144+
it("exits 1 after initialize when no directories were given and the client lacks Roots (#4992)", async () => {
145+
const exit = vi
146+
.spyOn(process, "exit")
147+
.mockImplementation((() => undefined) as never);
148+
await session.start([]);
149+
await session.initialize();
150+
await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(1));
151+
expect(stderrText()).toContain(
152+
"Error: Server cannot operate: No allowed directories available.",
153+
);
154+
});
155+
142156
it("skips a missing directory with a warning and keeps the rest", async () => {
143157
const missing = path.join(dir, "missing");
144158
const accessible = path.join(dir, "ok");

‎src/filesystem/index.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,11 @@ export async function main(
101101
}
102102

103103
const allowedDirectories = await resolveAllowedDirectories(args);
104-
const server = createServer(allowedDirectories);
104+
// With no directories and a client without Roots, the server closes the
105+
// connection after initialize (#4992); exit non-zero so the failure shows.
106+
const server = createServer(allowedDirectories, {
107+
onCannotOperate: () => process.exit(1),
108+
});
105109

106110
const transport = new StdioServerTransport(stdin, stdout);
107111
await server.connect(transport);

‎src/filesystem/server.ts‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -131,19 +131,56 @@ async function readFileAsBase64Stream(filePath: string): Promise<string> {
131131
});
132132
}
133133

134+
/**
135+
* Why the server cannot operate when it has no allowed directories from either
136+
* the command line or the client's Roots (#4992).
137+
*/
138+
export const NO_ALLOWED_DIRECTORIES_ERROR =
139+
"Server cannot operate: No allowed directories available. Server was started without command-line directories and client does not support MCP roots protocol. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.";
140+
141+
export interface ServerOptions {
142+
/**
143+
* Called after the server has closed the connection because it cannot
144+
* operate: no directories were given and the client does not support
145+
* Roots (#4992). The stdio entry point exits the process from here.
146+
*/
147+
onCannotOperate?: (error: Error) => void;
148+
}
149+
134150
/**
135151
* Build a filesystem server that may touch only `initialAllowedDirectories`
136152
* (already resolved and normalized by the caller) until the client's Roots
137153
* replace them.
138154
*/
139-
export function createServer(initialAllowedDirectories: string[]): McpServer {
155+
export function createServer(
156+
initialAllowedDirectories: string[],
157+
options: ServerOptions = {},
158+
): McpServer {
140159
let allowedDirectories = [...initialAllowedDirectories];
141160

142161
const server = new McpServer({
143162
name: "secure-filesystem-server",
144163
version: SERVER_VERSION,
145164
});
146165

166+
// Settles once the post-initialize setup (fetching the client's initial
167+
// roots) has finished, successfully or not; it never rejects. Every tool call
168+
// waits for it, so a call that arrives while the initial roots/list is still
169+
// outstanding is checked against the client's roots rather than against the
170+
// command-line directories (#3204). It is replaced in oninitialized, which
171+
// the SDK runs before any request sent after notifications/initialized.
172+
let initialization: Promise<void> = Promise.resolve();
173+
const registerTool = server.registerTool.bind(server);
174+
server.registerTool = ((
175+
name: string,
176+
config: Parameters<typeof registerTool>[1],
177+
handler: (...args: unknown[]) => unknown,
178+
) =>
179+
registerTool(name, config, (async (...args: unknown[]) => {
180+
await initialization;
181+
return handler(...args);
182+
}) as never)) as typeof server.registerTool;
183+
147184
// Tool registrations
148185

149186
// read_file (deprecated) and read_text_file
@@ -739,8 +776,13 @@ export function createServer(initialAllowedDirectories: string[]): McpServer {
739776
},
740777
);
741778

742-
// Handles post-initialization setup, specifically checking for and fetching MCP roots.
743-
server.server.oninitialized = async () => {
779+
// Handles post-initialization setup, specifically checking for and fetching
780+
// MCP roots. Tool calls wait for it (see `initialization` above).
781+
server.server.oninitialized = () => {
782+
initialization = initialize();
783+
};
784+
785+
async function initialize(): Promise<void> {
744786
const clientCapabilities = server.server.getClientCapabilities();
745787

746788
if (clientCapabilities?.roots) {
@@ -767,12 +809,17 @@ export function createServer(initialAllowedDirectories: string[]): McpServer {
767809
allowedDirectories,
768810
);
769811
} else {
770-
throw new Error(
771-
`Server cannot operate: No allowed directories available. Server was started without command-line directories and client either does not support MCP roots protocol or provided empty roots. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.`,
772-
);
812+
// Nothing could ever be allowed in this session, so fail visibly
813+
// rather than serve every call with "Access denied" (#4992): log the
814+
// reason and close the connection. Throwing here would only reach the
815+
// SDK's onerror, which the client never sees.
816+
const error = new Error(NO_ALLOWED_DIRECTORIES_ERROR);
817+
console.error(`Error: ${error.message}`);
818+
await server.close();
819+
options.onCannotOperate?.(error);
773820
}
774821
}
775-
};
822+
}
776823

777824
return server;
778825
}

0 commit comments

Comments
 (0)