Skip to content

Commit c9fdf34

Browse files
authored
Merge pull request #5098 from modelcontextprotocol/v2/fix/5097-filesystem-roots-refresh-order
fix(filesystem): apply only the newest roots refresh's answer
2 parents 3e005bb + fc5e9c9 commit c9fdf34

3 files changed

Lines changed: 216 additions & 16 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+
Overlapping roots refreshes now take effect in the order they started: when a client sends `roots/list_changed` again before the previous `roots/list` answer arrived (or while the initial roots are still loading), an answer that arrives after a newer refresh has started is discarded instead of overwriting it, so a stale answer can no longer undo a newer update such as a revocation (#5097).

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

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,163 @@ describe("roots/list_changed", () => {
345345
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
346346
});
347347

348+
// #5097: the answers to overlapping refreshes can arrive out of order; only
349+
// the newest refresh's answer is applied, so a stale one cannot undo it.
350+
it("applies the newest of two overlapping updates when their answers arrive out of order (#5097)", async () => {
351+
let calls = 0;
352+
let releaseStale!: () => void;
353+
const staleHeld = new Promise<void>((resolve) => (releaseStale = resolve));
354+
const { client } = await connectTracked([], {
355+
capabilities: ROOTS,
356+
listRoots: async () => {
357+
calls += 1;
358+
if (calls === 1) return [rootOf(rootDir)]; // the initial load
359+
if (calls === 2) {
360+
await staleHeld; // the older update, answered last
361+
return [rootOf(rootDir)];
362+
}
363+
return []; // the newer update withdraws the root
364+
},
365+
});
366+
await vi.waitFor(async () =>
367+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]),
368+
);
369+
370+
await client.sendRootsListChanged();
371+
await vi.waitFor(() => expect(calls).toBe(2));
372+
await client.sendRootsListChanged();
373+
await vi.waitFor(async () =>
374+
expect(await allowedDirectoriesOf(client)).toEqual([]),
375+
);
376+
377+
releaseStale();
378+
await vi.waitFor(() =>
379+
expect(stderr).toHaveBeenCalledWith(
380+
"Discarded a stale roots/list answer: a newer roots update has started",
381+
),
382+
);
383+
expect(await allowedDirectoriesOf(client)).toEqual([]);
384+
});
385+
386+
it("discards the initial answer when an update overtakes it (#5097)", async () => {
387+
let calls = 0;
388+
let releaseInitial!: () => void;
389+
const initialHeld = new Promise<void>(
390+
(resolve) => (releaseInitial = resolve),
391+
);
392+
const { client } = await connectTracked([], {
393+
capabilities: ROOTS,
394+
listRoots: async () => {
395+
calls += 1;
396+
if (calls === 1) {
397+
await initialHeld;
398+
return [rootOf(rootDir)];
399+
}
400+
return [rootOf(cliDir)];
401+
},
402+
});
403+
await vi.waitFor(() => expect(calls).toBe(1));
404+
await client.sendRootsListChanged();
405+
await vi.waitFor(() =>
406+
expect(stderr).toHaveBeenCalledWith(
407+
"Updated allowed directories from MCP roots: 1 valid directories",
408+
),
409+
);
410+
411+
releaseInitial();
412+
await vi.waitFor(() =>
413+
expect(stderr).toHaveBeenCalledWith(
414+
"Discarded a stale roots/list answer: a newer roots update has started",
415+
),
416+
);
417+
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
418+
});
419+
420+
// #5097: a call waiting for the initial roots must not be released by the
421+
// stale initial answer; it waits for the update that overtook it.
422+
it("holds waiting tool calls until the update that overtook the initial load applies (#5097)", async () => {
423+
let calls = 0;
424+
let releaseInitial!: () => void;
425+
let releaseUpdate!: () => void;
426+
const initialHeld = new Promise<void>(
427+
(resolve) => (releaseInitial = resolve),
428+
);
429+
const updateHeld = new Promise<void>(
430+
(resolve) => (releaseUpdate = resolve),
431+
);
432+
const { client } = await connectTracked([cliDir], {
433+
capabilities: ROOTS,
434+
listRoots: async () => {
435+
calls += 1;
436+
await (calls === 1 ? initialHeld : updateHeld);
437+
return [rootOf(rootDir)];
438+
},
439+
});
440+
await vi.waitFor(() => expect(calls).toBe(1));
441+
await client.sendRootsListChanged();
442+
await vi.waitFor(() => expect(calls).toBe(2));
443+
444+
releaseInitial();
445+
await vi.waitFor(() =>
446+
expect(stderr).toHaveBeenCalledWith(
447+
"Discarded a stale roots/list answer: a newer roots update has started",
448+
),
449+
);
450+
// Asked before the update has answered: it must not run against the
451+
// command-line directory in the meantime.
452+
let settled = false;
453+
const pending = call(client, "list_directory", { path: cliDir }).then(
454+
(result) => {
455+
settled = true;
456+
return result;
457+
},
458+
);
459+
await new Promise((resolve) => setTimeout(resolve, 50));
460+
expect(settled).toBe(false);
461+
462+
releaseUpdate();
463+
expect(textOf(await pending)).toMatch(/^Access denied/);
464+
expect(await allowedDirectoriesOf(client)).toEqual([rootDir]);
465+
});
466+
467+
it("releases waiting tool calls when the update that overtook the initial load fails (#5097)", async () => {
468+
let calls = 0;
469+
let releaseInitial!: () => void;
470+
const initialHeld = new Promise<void>(
471+
(resolve) => (releaseInitial = resolve),
472+
);
473+
const { client } = await connectTracked([cliDir], {
474+
capabilities: ROOTS,
475+
listRoots: async () => {
476+
calls += 1;
477+
if (calls === 1) {
478+
await initialHeld;
479+
return [rootOf(rootDir)];
480+
}
481+
throw new Error("gone");
482+
},
483+
});
484+
await vi.waitFor(() => expect(calls).toBe(1));
485+
await client.sendRootsListChanged();
486+
await vi.waitFor(() =>
487+
expect(stderr).toHaveBeenCalledWith(
488+
"Failed to request roots from client:",
489+
"gone",
490+
),
491+
);
492+
493+
// Asked while the initial roots/list is still unanswered: the failed update
494+
// releases waiting calls instead of leaving them blocked on it.
495+
expect(await allowedDirectoriesOf(client)).toEqual([cliDir]);
496+
// Let the stale initial answer finish before teardown removes its roots.
497+
releaseInitial();
498+
await vi.waitFor(() =>
499+
expect(stderr).toHaveBeenCalledWith(
500+
"Discarded a stale roots/list answer: a newer roots update has started",
501+
),
502+
);
503+
});
504+
348505
it("logs and keeps the current directories when the re-fetch fails", async () => {
349506
let fail = false;
350507
const { client } = await connectTracked([], {

‎src/filesystem/server.ts‎

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,12 @@ export function createServer(
174174
// withdraws its roots withdraws the server's access too (#5094). Until then an
175175
// update with no valid roots keeps the command-line directories.
176176
let rootsInForce = false;
177+
// Each roots refresh (the initial load and every roots/list_changed) takes
178+
// the next generation before it asks for roots. The SDK runs notification
179+
// handlers without waiting for earlier ones, so answers can come back out of
180+
// order; one is applied only if no newer refresh has started since, so a
181+
// stale answer cannot undo a newer update, such as a revocation (#5097).
182+
let rootsGeneration = 0;
177183

178184
const server = new McpServer({
179185
name: "secure-filesystem-server",
@@ -187,14 +193,24 @@ export function createServer(
187193
// command-line directories (#3204). It is replaced in oninitialized, which
188194
// the SDK runs before any request sent after notifications/initialized.
189195
let initialization: Promise<void> = Promise.resolve();
196+
// True from the initial roots/list until a refresh's answer has been
197+
// applied or the newest refresh has failed. A roots/list_changed that
198+
// overtakes the initial load while this holds replaces `initialization`, so
199+
// waiting tool calls keep waiting for the refresh that will actually apply
200+
// rather than running against the command-line directories (#5097).
201+
let initialRootsPending = false;
190202
const registerTool = server.registerTool.bind(server);
191203
server.registerTool = ((
192204
name: string,
193205
config: Parameters<typeof registerTool>[1],
194206
handler: (...args: unknown[]) => unknown,
195207
) =>
196208
registerTool(name, config, (async (...args: unknown[]) => {
197-
await initialization;
209+
let awaited: Promise<void>;
210+
do {
211+
awaited = initialization;
212+
await awaited;
213+
} while (awaited !== initialization);
198214
return handler(...args);
199215
}) as never)) as typeof server.registerTool;
200216

@@ -760,9 +776,19 @@ export function createServer(
760776
},
761777
);
762778

763-
// Updates allowed directories based on MCP client roots
764-
async function updateAllowedDirectoriesFromRoots(requestedRoots: Root[]) {
779+
// Updates allowed directories based on MCP client roots, unless a newer
780+
// refresh started after this one's `generation` was taken (#5097).
781+
async function updateAllowedDirectoriesFromRoots(
782+
requestedRoots: Root[],
783+
generation: number,
784+
) {
765785
const validatedRootDirs = await getValidRootDirectories(requestedRoots);
786+
if (generation !== rootsGeneration) {
787+
console.error(
788+
"Discarded a stale roots/list answer: a newer roots update has started",
789+
);
790+
return;
791+
}
766792
if (validatedRootDirs.length > 0) {
767793
allowedDirectories = [...validatedRootDirs];
768794
rootsInForce = true;
@@ -783,19 +809,27 @@ export function createServer(
783809
server.server.setNotificationHandler(
784810
"notifications/roots/list_changed",
785811
async () => {
786-
try {
787-
// Request the updated roots list from the client
788-
const response = await server.server.listRoots();
789-
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
790-
if (response && "roots" in response) {
791-
await updateAllowedDirectoriesFromRoots(response.roots);
812+
const generation = ++rootsGeneration;
813+
const refresh = (async () => {
814+
try {
815+
// Request the updated roots list from the client
816+
const response = await server.server.listRoots();
817+
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the implicit else cannot run */
818+
if (response && "roots" in response) {
819+
await updateAllowedDirectoriesFromRoots(response.roots, generation);
820+
}
821+
} catch (error) {
822+
console.error(
823+
"Failed to request roots from client:",
824+
error instanceof Error ? error.message : String(error),
825+
);
826+
} finally {
827+
if (generation === rootsGeneration) initialRootsPending = false;
792828
}
793-
} catch (error) {
794-
console.error(
795-
"Failed to request roots from client:",
796-
error instanceof Error ? error.message : String(error),
797-
);
798-
}
829+
})();
830+
// Overtaking the initial load: tool calls wait for this refresh instead.
831+
if (initialRootsPending) initialization = refresh;
832+
await refresh;
799833
},
800834
);
801835

@@ -809,11 +843,13 @@ export function createServer(
809843
const clientCapabilities = server.server.getClientCapabilities();
810844

811845
if (clientCapabilities?.roots) {
846+
const generation = ++rootsGeneration;
847+
initialRootsPending = true;
812848
try {
813849
const response = await server.server.listRoots();
814850
/* v8 ignore else -- the SDK validates the roots/list result against ListRootsResultSchema, which requires roots, so the else cannot run */
815851
if (response && "roots" in response) {
816-
await updateAllowedDirectoriesFromRoots(response.roots);
852+
await updateAllowedDirectoriesFromRoots(response.roots, generation);
817853
} else {
818854
console.error(
819855
"Client returned no roots set, keeping current settings",
@@ -824,6 +860,8 @@ export function createServer(
824860
"Failed to request initial roots from client:",
825861
error instanceof Error ? error.message : String(error),
826862
);
863+
} finally {
864+
if (generation === rootsGeneration) initialRootsPending = false;
827865
}
828866
} else {
829867
if (allowedDirectories.length > 0) {

0 commit comments

Comments
 (0)