// Roots handling as a client sees it (#4854): how the client's roots replace // the command-line directories after initialize, how roots/list_changed // updates them, and what happens when roots are invalid, fail or are not // offered. Driven by a real Client that answers the server's roots/list // requests over the in-memory transport. Guards the fixes for #3204 (tool // calls wait for the initial roots) and #4992 (no directories at all fails // visibly), and pins #3602's roots-replace-the-command-line behavior as the README documents it. import fs from "fs/promises"; import path from "path"; import { pathToFileURL } from "url"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Root } from "@modelcontextprotocol/server"; import { allowedDirectoriesOf, call, connect, makeTempDir, quietStderr, textOf, type Connected, } from "./helpers.js"; import { NO_ALLOWED_DIRECTORIES_ERROR } from "../server.js"; const ROOTS = { roots: { listChanged: true } }; let cliDir: string; let rootDir: string; let stderr: ReturnType; const open: Connected[] = []; async function connectTracked( ...args: Parameters ): Promise { const conn = await connect(...args); open.push(conn); return conn; } function rootOf(dir: string): Root { return { uri: pathToFileURL(dir).href, name: path.basename(dir) }; } beforeEach(async () => { stderr = quietStderr(); cliDir = await makeTempDir("mcp-fs-cli-"); rootDir = await makeTempDir("mcp-fs-root-"); }); afterEach(async () => { for (const conn of open.splice(0)) await conn.close(); vi.restoreAllMocks(); await fs.rm(cliDir, { recursive: true, force: true }); await fs.rm(rootDir, { recursive: true, force: true }); }); describe("initial roots", () => { // #3602: the client's roots replace the command-line directories rather // than being added to them, as the README documents. it("replace the command-line directories with the client's roots (#3602)", async () => { const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => [rootOf(rootDir)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); expect(stderr).toHaveBeenCalledWith( "Updated allowed directories from MCP roots: 1 valid directories", ); const result = await call(client, "list_directory", { path: cliDir }); expect(textOf(result)).toMatch(/^Access denied/); }); it("accept a pathToFileURL root with spaces and non-ASCII characters", async () => { const fancy = path.join(rootDir, "my café dir"); await fs.mkdir(fancy); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [{ uri: pathToFileURL(fancy).href }], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([fancy]), ); }); // #5183: a Root is allowed in its advertised spelling as well as its // realpath, as a command-line directory is, so a request that uses the // Root's own spelling is not refused. it("admit a symlinked root in both its advertised and its resolved form (#5183)", async () => { const link = path.join(cliDir, "link-to-root"); await fs.symlink(rootDir, link); await fs.writeFile(path.join(rootDir, "note.txt"), "inside the root"); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(link)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]), ); const viaLink = await call(client, "read_text_file", { path: path.join(link, "note.txt"), }); expect(textOf(viaLink)).toBe("inside the root"); const viaTarget = await call(client, "read_text_file", { path: path.join(rootDir, "note.txt"), }); expect(textOf(viaTarget)).toBe("inside the root"); }); // #5183: admitting the advertised spelling does not widen access. Every // request is still realpath'd and re-checked, so a symlink inside the Root // that points outside it is refused under either spelling. it("refuse a symlink inside a symlinked root that points outside it (#5183)", async () => { const link = path.join(cliDir, "link-to-root"); await fs.symlink(rootDir, link); const secret = path.join(cliDir, "secret.txt"); await fs.writeFile(secret, "outside the root"); await fs.symlink(secret, path.join(rootDir, "escape.txt")); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(link)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]), ); for (const dir of [link, rootDir]) { const result = await call(client, "read_text_file", { path: path.join(dir, "escape.txt"), }); expect(textOf(result)).toMatch(/^Access denied/); } }); // #5183: the advertised form names a symlink, which can be retargeted after // the Roots load. A new file or directory under it must still be refused // when the symlink now leads outside every allowed directory. it("refuse creating under a root alias retargeted outside the root (#5183)", async () => { const link = path.join(cliDir, "link-to-root"); await fs.symlink(rootDir, link); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(link)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]), ); const outside = path.join(cliDir, "outside"); await fs.mkdir(outside); await fs.rm(link); await fs.symlink(outside, link); const written = await call(client, "write_file", { path: path.join(link, "new.txt"), content: "x", }); expect(textOf(written)).toMatch(/^Access denied/); const created = await call(client, "create_directory", { path: path.join(link, "a", "b"), }); expect(textOf(created)).toMatch(/^Access denied/); expect(await fs.readdir(outside)).toEqual([]); }); // #5183: the advertised form is kept as the client spelled it. Trimming // whitespace or quotes from it would name a different directory, here an // unrelated sibling, and allow it. POSIX only: Windows filenames cannot end // in a space. it.skipIf(process.platform === "win32")( "keep a root's advertised form verbatim, not trimmed to a sibling's name (#5183)", async () => { const link = path.join(cliDir, "alias "); await fs.symlink(rootDir, link); const sibling = path.join(cliDir, "alias"); await fs.mkdir(sibling); await fs.writeFile(path.join(sibling, "secret.txt"), "not in the root"); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(link)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]), ); const result = await call(client, "read_text_file", { path: path.join(sibling, "secret.txt"), }); expect(textOf(result)).toMatch(/^Access denied/); }, ); // #5183 as reported: on macOS /tmp is a symlink to /private/tmp, so a Root // of file:///tmp/... was allowed only as /private/tmp/... and a request // naming /tmp/... was refused. it.runIf(process.platform === "darwin")( "admit a macOS /tmp root under its /tmp spelling (#5183)", async () => { const tmpRoot = await fs.mkdtemp("/tmp/mcp-fs-5183-"); try { await fs.writeFile(path.join(tmpRoot, "note.txt"), "in /tmp"); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(tmpRoot)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([ tmpRoot, await fs.realpath(tmpRoot), ]), ); const result = await call(client, "read_text_file", { path: path.join(tmpRoot, "note.txt"), }); expect(textOf(result)).toBe("in /tmp"); } finally { await fs.rm(tmpRoot, { recursive: true, force: true }); } }, ); it("list a root once when it is advertised in both its forms (#5183)", async () => { const link = path.join(cliDir, "link-to-root"); await fs.symlink(rootDir, link); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => [rootOf(link), rootOf(rootDir)], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([link, rootDir]), ); }); it("drop invalid roots and keep the valid ones", async () => { await fs.writeFile(path.join(cliDir, "file.txt"), ""); const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => [ rootOf(path.join(cliDir, "missing")), rootOf(path.join(cliDir, "file.txt")), rootOf(rootDir), ], }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); expect(stderr).toHaveBeenCalledWith( `Skipping invalid path or inaccessible: ${pathToFileURL(path.join(cliDir, "missing")).href}`, ); expect(stderr).toHaveBeenCalledWith( `Skipping non-directory root: ${path.join(cliDir, "file.txt")}`, ); }); it("keep the command-line directories when no root is valid", async () => { const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => [rootOf(path.join(cliDir, "missing"))], }); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "No valid root directories provided by client", ), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); it("keep the command-line directories when the client returns an empty list", async () => { const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => [], }); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "No valid root directories provided by client", ), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); it("keep the command-line directories when roots/list fails", async () => { const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => { throw new Error("client has no roots today"); }, }); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Failed to request initial roots from client:", "client has no roots today", ), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); // #3204: a tool call that arrives while the initial roots/list is still // outstanding waits for it, and is checked against the client's roots // rather than the command-line directories (here, none). it("are awaited before tool calls are served (#3204)", async () => { await fs.writeFile(path.join(rootDir, "f.txt"), "from root"); let release: () => void = () => {}; const gate = new Promise((resolve) => { release = resolve; }); let asked = false; const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { asked = true; await gate; return [rootOf(rootDir)]; }, }); let settled = false; const early = call(client, "read_text_file", { path: path.join(rootDir, "f.txt"), }).finally(() => { settled = true; }); await vi.waitFor(() => expect(asked).toBe(true)); await new Promise((resolve) => setTimeout(resolve, 50)); expect(settled).toBe(false); release(); const result = await early; expect(result.isError).toBeFalsy(); expect(textOf(result)).toBe("from root"); expect(await allowedDirectoriesOf(client)).toEqual([rootDir]); }); it("are awaited by concurrent tool calls, which then all succeed (#3204)", async () => { await fs.writeFile(path.join(rootDir, "a.txt"), "a"); await fs.writeFile(path.join(rootDir, "b.txt"), "b"); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { await new Promise((resolve) => setTimeout(resolve, 20)); return [rootOf(rootDir)]; }, }); const results = await Promise.all([ call(client, "read_text_file", { path: path.join(rootDir, "a.txt") }), call(client, "read_text_file", { path: path.join(rootDir, "b.txt") }), call(client, "list_allowed_directories"), ]); expect(results.map(textOf)).toEqual([ "a", "b", `Allowed directories:\n${rootDir}`, ]); }); it("fall back to the command-line directories for waiting calls when roots/list fails (#3204)", async () => { await fs.writeFile(path.join(cliDir, "f.txt"), "from cli"); const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: async () => { await new Promise((resolve) => setTimeout(resolve, 20)); throw new Error("no roots"); }, }); const result = await call(client, "read_text_file", { path: path.join(cliDir, "f.txt"), }); expect(textOf(result)).toBe("from cli"); }); }); describe("roots/list_changed", () => { it("re-fetches the roots and replaces the allowed directories", async () => { let roots = [rootOf(rootDir)]; const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => roots, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); roots = [rootOf(cliDir), rootOf(rootDir)]; await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([cliDir, rootDir]), ); }); // #5094: once the client's roots are in force, an update that leaves no // valid root revokes access instead of keeping the previous directories. it("revokes access when the client withdraws its last root (#5094)", async () => { let roots = [rootOf(rootDir)]; const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => roots, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); roots = []; await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([]), ); expect(stderr).toHaveBeenCalledWith( "No valid root directories provided by client; access revoked until it exposes a root again", ); const result = await call(client, "list_directory", { path: rootDir }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch( /^Access denied - no allowed directories: the client exposes no valid roots/, ); // The command-line directories do not come back either. expect( textOf(await call(client, "list_directory", { path: cliDir })), ).toMatch(/^Access denied/); }); it("revokes access when every remaining root is invalid (#5094)", async () => { let roots = [rootOf(rootDir)]; const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => roots, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); roots = [rootOf(path.join(rootDir, "gone"))]; await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([]), ); }); it("restores access when the client exposes a root again (#5094)", async () => { let roots = [rootOf(rootDir)]; const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => roots, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); roots = []; await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([]), ); roots = [rootOf(rootDir)]; await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); }); it("keeps the command-line directories on an empty update before any root was in force", async () => { let roots: Root[] = []; const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: () => roots, }); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "No valid root directories provided by client", ), ); roots = []; await client.sendRootsListChanged(); await vi.waitFor(() => expect( stderr.mock.calls.filter( (c) => c[0] === "No valid root directories provided by client", ), ).toHaveLength(2), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); // #5097: the answers to overlapping refreshes can arrive out of order; only // the newest refresh's answer is applied, so a stale one cannot undo it. it("applies the newest of two overlapping updates when their answers arrive out of order (#5097)", async () => { let calls = 0; let releaseStale!: () => void; const staleHeld = new Promise((resolve) => (releaseStale = resolve)); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) return [rootOf(rootDir)]; // the initial load if (calls === 2) { await staleHeld; // the older update, answered last return [rootOf(rootDir)]; } return []; // the newer update withdraws the root }, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); await client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([]), ); releaseStale(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); expect(await allowedDirectoriesOf(client)).toEqual([]); }); it("discards the initial answer when an update overtakes it (#5097)", async () => { let calls = 0; let releaseInitial!: () => void; const initialHeld = new Promise( (resolve) => (releaseInitial = resolve), ); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) { await initialHeld; return [rootOf(rootDir)]; } return [rootOf(cliDir)]; }, }); await vi.waitFor(() => expect(calls).toBe(1)); await client.sendRootsListChanged(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Updated allowed directories from MCP roots: 1 valid directories", ), ); releaseInitial(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); // #5097: a call waiting for the initial roots must not be released by the // stale initial answer; it waits for the update that overtook it. it("holds waiting tool calls until the update that overtook the initial load applies (#5097)", async () => { let calls = 0; let releaseInitial!: () => void; let releaseUpdate!: () => void; const initialHeld = new Promise( (resolve) => (releaseInitial = resolve), ); const updateHeld = new Promise( (resolve) => (releaseUpdate = resolve), ); const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: async () => { calls += 1; await (calls === 1 ? initialHeld : updateHeld); return [rootOf(rootDir)]; }, }); await vi.waitFor(() => expect(calls).toBe(1)); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); releaseInitial(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); // Asked before the update has answered: it must not run against the // command-line directory in the meantime. let settled = false; const pending = call(client, "list_directory", { path: cliDir }).then( (result) => { settled = true; return result; }, ); await new Promise((resolve) => setTimeout(resolve, 50)); expect(settled).toBe(false); releaseUpdate(); expect(textOf(await pending)).toMatch(/^Access denied/); expect(await allowedDirectoriesOf(client)).toEqual([rootDir]); }); it("releases waiting tool calls when the update that overtook the initial load fails (#5097)", async () => { let calls = 0; let releaseInitial!: () => void; const initialHeld = new Promise( (resolve) => (releaseInitial = resolve), ); const { client } = await connectTracked([cliDir], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) { await initialHeld; return [rootOf(rootDir)]; } throw new Error("gone"); }, }); await vi.waitFor(() => expect(calls).toBe(1)); await client.sendRootsListChanged(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Failed to request roots from client:", "gone", ), ); // Asked while the initial roots/list is still unanswered: the failed update // releases waiting calls instead of leaving them blocked on it. expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); // Let the stale initial answer finish before teardown removes its roots. releaseInitial(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); }); // #5101: a call made while a runtime refresh is pending waits for it, so it // cannot reach a root the client has just withdrawn. it("holds tool calls while a runtime refresh is pending (#5101)", async () => { let calls = 0; let releaseUpdate!: () => void; const updateHeld = new Promise( (resolve) => (releaseUpdate = resolve), ); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) return [rootOf(rootDir)]; await updateHeld; // the withdrawal is answered slowly return []; }, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); let settled = false; const pending = call(client, "list_directory", { path: rootDir }).then( (result) => { settled = true; return result; }, ); await new Promise((resolve) => setTimeout(resolve, 50)); expect(settled).toBe(false); releaseUpdate(); expect(textOf(await pending)).toMatch( /^Access denied - no allowed directories/, ); }); it("releases a call queued behind a runtime refresh that fails (#5101)", async () => { await fs.writeFile(path.join(rootDir, "a.txt"), "a"); let calls = 0; let failUpdate!: () => void; const updateHeld = new Promise((resolve) => (failUpdate = resolve)); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) return [rootOf(rootDir)]; await updateHeld; throw new Error("gone"); }, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); // Queued while the refresh is still pending, before it fails. let settled = false; const pending = call(client, "list_directory", { path: rootDir }).then( (result) => { settled = true; return result; }, ); await new Promise((resolve) => setTimeout(resolve, 50)); expect(settled).toBe(false); failUpdate(); const result = await pending; expect(result.isError).toBeFalsy(); expect(textOf(result)).toBe("[FILE] a.txt"); expect(stderr).toHaveBeenCalledWith( "Failed to request roots from client:", expect.stringContaining("gone"), ); }); // A client may announce a newer change while answering an older refresh's // roots/list; the older refresh must not replace the newer one's barrier. it("keeps the newest barrier when a client's roots/list answer announces another change (#5101)", async () => { let calls = 0; let announce: () => Promise = async () => {}; let releaseNewest!: () => void; const newestHeld = new Promise( (resolve) => (releaseNewest = resolve), ); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) return [rootOf(rootDir)]; if (calls === 2) { // Discarded on purpose: the server handles the notification on its // own schedule, and the test waits for its roots/list instead. void announce(); return [rootOf(rootDir)]; } await newestHeld; // the newest change withdraws the root, slowly return []; }, }); announce = () => client.sendRootsListChanged(); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(3)); let settled = false; const pending = call(client, "list_directory", { path: rootDir }).then( (result) => { settled = true; return result; }, ); await new Promise((resolve) => setTimeout(resolve, 50)); expect(settled).toBe(false); releaseNewest(); expect(textOf(await pending)).toMatch( /^Access denied - no allowed directories/, ); }); // An update handled before the deferred initial roots/list runs must still // count as newer than the initial load (#5101). it("applies an update announced right after initialize over the initial roots (#5101)", async () => { let calls = 0; let releaseInitial!: () => void; const initialHeld = new Promise( (resolve) => (releaseInitial = resolve), ); const conn = connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) { await initialHeld; return [rootOf(rootDir)]; } return [rootOf(cliDir)]; }, }); const { client } = await conn; await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); releaseInitial(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); }); // A call waiting on an older refresh must not stay blocked on it once a newer // refresh has applied the client's current roots (#5101). it("wakes a call waiting on an older refresh once a newer one finishes (#5101)", async () => { await fs.writeFile(path.join(rootDir, "a.txt"), "a"); let calls = 0; let releaseOlder!: () => void; const olderHeld = new Promise((resolve) => (releaseOlder = resolve)); const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: async () => { calls += 1; if (calls === 1) return [rootOf(rootDir)]; if (calls === 2) { await olderHeld; // not answered until the end of the test return []; } return [rootOf(rootDir)]; }, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); await client.sendRootsListChanged(); await vi.waitFor(() => expect(calls).toBe(2)); const pending = call(client, "list_directory", { path: rootDir }); await new Promise((resolve) => setTimeout(resolve, 50)); await client.sendRootsListChanged(); expect(textOf(await pending)).toBe("[FILE] a.txt"); expect(calls).toBe(3); // Cleanup: the older answer arrives last and is discarded as stale. releaseOlder(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Discarded a stale roots/list answer: a newer roots update has started", ), ); expect(await allowedDirectoriesOf(client)).toEqual([rootDir]); }); it("logs and keeps the current directories when the re-fetch fails", async () => { let fail = false; const { client } = await connectTracked([], { capabilities: ROOTS, listRoots: () => { if (fail) throw new Error("gone"); return [rootOf(rootDir)]; }, }); await vi.waitFor(async () => expect(await allowedDirectoriesOf(client)).toEqual([rootDir]), ); fail = true; await client.sendRootsListChanged(); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( "Failed to request roots from client:", "gone", ), ); expect(await allowedDirectoriesOf(client)).toEqual([rootDir]); }); }); describe("a client without the roots capability", () => { it("keeps the command-line directories and says so", async () => { const { client } = await connectTracked([cliDir]); expect(await allowedDirectoriesOf(client)).toEqual([cliDir]); expect(stderr).toHaveBeenCalledWith( "Client does not support MCP Roots, using allowed directories set from server args:", [cliDir], ); }); // #4992: with no directories from either source nothing could ever be // allowed, so the server says why on stderr and closes the connection // rather than staying up and refusing every call. it("closes the connection with an error when no directories were given (#4992)", async () => { const { client } = await connectTracked([]); await vi.waitFor(() => expect(stderr).toHaveBeenCalledWith( `Error: ${NO_ALLOWED_DIRECTORIES_ERROR}`, ), ); await expect( call(client, "list_directory", { path: rootDir }), ).rejects.toThrow(/Connection closed|Not connected/); }); });