Skip to content

Commit 89d6642

Browse files
cliffhallclaude
andcommitted
feat: serve both protocol eras on stdio in filesystem, memory and sequentialthinking
Each server's main() now serves its factory through the SDK's serveStdio entry, so the first message a client sends picks the connection's era: a 2026-07-28 client opens with server/discover and carries its version, identity and capabilities in each request's _meta; a 2025-era client opens with initialize, as before. - filesystem: Roots is deprecated as of 2026-07-28 and unreachable there (no initialize, no server-to-client roots/list), so a modern connection uses the command-line directories only. A server started with none answers each modern tool call with an error saying so. 2025-era Roots handling is unchanged. The README now recommends command-line directories (#4844). - memory: on 2026-07-28 graph updates are handed to the listen router, which delivers them only to a subscriptions/listen stream naming the URI; on 2025-era connections they still wait for resources/subscribe. - sequentialthinking: one thought history per connection, on either era. main() reports transport errors on stderr; serveStdio owns the transport. Part of #4852 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent c32f931 commit 89d6642

12 files changed

Lines changed: 708 additions & 79 deletions

File tree

‎src/filesystem/README.md‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,29 @@ Published on npm as [`@modelcontextprotocol/server-filesystem`](https://www.npmj
1111
- Move files/directories
1212
- Search files
1313
- Get file metadata
14-
- Dynamic directory access control via [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots)
14+
- Directory access control from command-line arguments, with [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) as a deprecated, 2025-era convenience
15+
- Serves both protocol eras on stdio: 2026-07-28 clients (`server/discover`, no handshake) and 2025-era clients (`initialize`)
1516

1617
## Directory Access Control
1718

18-
The server uses a flexible directory access control system. Directories can be specified via command-line arguments or dynamically via [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots).
19+
The server may touch only its **allowed directories**. Pass them on the command line. A 2025-era client that supports [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) can also replace them at runtime, but Roots is [deprecated as of protocol version 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/deprecated) and a 2026-07-28 connection cannot use it.
1920

20-
### Method 1: Command-line Arguments
21+
### Method 1: Command-line Arguments (Recommended)
2122
Specify Allowed directories when starting the server:
2223
```bash
2324
mcp-server-filesystem /path/to/dir1 /path/to/dir2
2425
```
2526

26-
### Method 2: MCP Roots (Recommended)
27-
MCP clients that support [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) can dynamically update the Allowed directories.
27+
This is the only method that works on every protocol version, so it is the one to use.
28+
29+
### Method 2: MCP Roots (Deprecated, 2025-era clients only)
30+
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.
2831

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

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.
34+
**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.
3235

33-
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.
36+
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.
3437

3538
### How It Works
3639

@@ -40,11 +43,12 @@ The server's directory access control follows this flow:
4043
- Server starts with directories from command-line arguments (if provided)
4144
- If no arguments provided, server starts with empty allowed directories
4245

43-
2. **Client Connection & Initialization**
44-
- Client connects and sends `initialize` request with capabilities
45-
- Server checks if client supports roots protocol (`capabilities.roots`)
46+
2. **Client Connection**
47+
- The client's first message picks the protocol era of the connection
48+
- A **2026-07-28** client sends `server/discover` (or any request carrying the per-request `_meta` envelope): the server uses the command-line directories, and steps 3 and 4 do not apply
49+
- A **2025-era** client sends `initialize` with its capabilities, and the server checks whether it supports roots (`capabilities.roots`)
4650

47-
3. **Roots Protocol Handling** (if client supports roots)
51+
3. **Roots Protocol Handling** (2025-era clients that support roots)
4852
- **On initialization**: Server requests roots from client via `roots/list`
4953
- Client responds with its configured roots
5054
- Server replaces ALL allowed directories with client's roots
@@ -54,7 +58,7 @@ The server's directory access control follows this flow:
5458
- Tool calls that arrive while an update is being fetched wait for it, so none runs against a root the client has just withdrawn
5559
- Once the client's roots are in force, an update with no valid roots revokes access: every path is refused ("Access denied - no allowed directories") until the client exposes a root again. Before any root has been in force, such an update keeps the command-line directories
5660

57-
4. **Fallback Behavior** (if client doesn't support roots)
61+
4. **Fallback Behavior** (2025-era clients that don't support roots)
5862
- Server continues using command-line directories only
5963
- No dynamic updates possible
6064
- With no command-line directories either, the server logs an error, closes the connection and exits with status 1
@@ -64,7 +68,7 @@ The server's directory access control follows this flow:
6468
- Use `list_allowed_directories` tool to see current directories
6569
- Server requires at least ONE allowed directory to operate
6670

67-
**Note**: The server will only allow operations within directories specified either via `args` or via Roots.
71+
**Note**: The server will only allow operations within directories specified either via `args` or, for a 2025-era client, via Roots.
6872

6973

7074

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// Access control on both protocol eras (#4852). main() serves createServer()
2+
// through the SDK's serveStdio entry, so the first message a client sends
3+
// picks the connection's era. On 2025-11-25 a client that supports Roots
4+
// replaces the command-line directories after initialize, as before. On
5+
// 2026-07-28 there is no initialize and no server-to-client roots/list, and
6+
// Roots is deprecated, so the command-line directories are the whole
7+
// allow-list: a client's roots are never asked for and never widen it, and a
8+
// server started with none says so on every call.
9+
//
10+
// The SDK-client tests serve createServer() exactly as main() does, over an
11+
// in-memory transport; the raw tests drive main() itself over in-memory
12+
// stdio, so its era wiring is covered too.
13+
14+
import fs from "fs/promises";
15+
import path from "path";
16+
import { PassThrough } from "node:stream";
17+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
18+
import {
19+
Client,
20+
InMemoryTransport,
21+
type CallToolResult,
22+
} from "@modelcontextprotocol/client";
23+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
24+
import { main } from "../index.js";
25+
import {
26+
createServer,
27+
NO_ALLOWED_DIRECTORIES_MODERN_ERROR,
28+
} from "../server.js";
29+
import { makeTempDir, quietStderr } from "./helpers.js";
30+
31+
let allowed: string;
32+
let other: string;
33+
let closers: Array<() => Promise<void>>;
34+
35+
beforeEach(async () => {
36+
quietStderr();
37+
allowed = await fs.realpath(await makeTempDir("mcp-fs-era-allowed-"));
38+
other = await fs.realpath(await makeTempDir("mcp-fs-era-other-"));
39+
await fs.writeFile(path.join(other, "secret.txt"), "secret");
40+
closers = [];
41+
});
42+
43+
afterEach(async () => {
44+
for (const close of closers.reverse()) await close();
45+
vi.restoreAllMocks();
46+
await fs.rm(allowed, { recursive: true, force: true });
47+
await fs.rm(other, { recursive: true, force: true });
48+
});
49+
50+
/**
51+
* A client that supports Roots and offers `other` as its only root, connected
52+
* to a server for `directories` and negotiating per `mode`.
53+
*/
54+
async function connect(
55+
directories: string[],
56+
mode: "auto" | "legacy",
57+
): Promise<{ client: Client; rootsAsked: () => number }> {
58+
const [clientTransport, serverTransport] =
59+
InMemoryTransport.createLinkedPair();
60+
const handle = serveStdio(({ era }) => createServer(directories, { era }), {
61+
transport: serverTransport,
62+
});
63+
const client = new Client(
64+
{ name: "fs-era-test", version: "0.0.0" },
65+
{ capabilities: { roots: {} }, versionNegotiation: { mode } },
66+
);
67+
let asked = 0;
68+
client.setRequestHandler("roots/list", async () => {
69+
asked++;
70+
return { roots: [{ uri: `file://${other}`, name: "other" }] };
71+
});
72+
await client.connect(clientTransport);
73+
closers.push(
74+
() => handle.close(),
75+
() => client.close(),
76+
);
77+
return { client, rootsAsked: () => asked };
78+
}
79+
80+
async function listAllowed(client: Client): Promise<string> {
81+
const result = (await client.callTool({
82+
name: "list_allowed_directories",
83+
arguments: {},
84+
})) as CallToolResult;
85+
return (result.content[0] as { text: string }).text;
86+
}
87+
88+
describe("on 2026-07-28", () => {
89+
it("serves only the command-line directories, and never asks for roots", async () => {
90+
const { client, rootsAsked } = await connect([allowed], "auto");
91+
expect(client.getProtocolEra()).toBe("modern");
92+
expect(await listAllowed(client)).toBe(`Allowed directories:\n${allowed}`);
93+
const read = (await client.callTool({
94+
name: "read_text_file",
95+
arguments: { path: path.join(other, "secret.txt") },
96+
})) as CallToolResult;
97+
expect(read.isError).toBe(true);
98+
expect((read.content[0] as { text: string }).text).toContain(
99+
"Access denied",
100+
);
101+
expect(rootsAsked()).toBe(0);
102+
});
103+
104+
it("explains on every call that a server with no directories cannot operate", async () => {
105+
const { client } = await connect([], "auto");
106+
const result = (await client.callTool({
107+
name: "list_allowed_directories",
108+
arguments: {},
109+
})) as CallToolResult;
110+
expect(result).toMatchObject({
111+
isError: true,
112+
content: [{ type: "text", text: NO_ALLOWED_DIRECTORIES_MODERN_ERROR }],
113+
});
114+
});
115+
});
116+
117+
describe("on 2025-11-25", () => {
118+
it("still lets the client's roots replace the command-line directories", async () => {
119+
const { client, rootsAsked } = await connect([allowed], "legacy");
120+
expect(client.getProtocolEra()).toBe("legacy");
121+
await vi.waitFor(() => expect(rootsAsked()).toBe(1));
122+
expect(await listAllowed(client)).toBe(`Allowed directories:\n${other}`);
123+
});
124+
});
125+
126+
describe("main() over stdio", () => {
127+
const envelope = {
128+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
129+
"io.modelcontextprotocol/clientCapabilities": { roots: {} },
130+
};
131+
132+
/** Start main() and send one raw 2026-07-28 tools/call; resolve its result. */
133+
async function callOverStdio(args: string[]) {
134+
const stdin = new PassThrough();
135+
const stdout = new PassThrough();
136+
stdout.setEncoding("utf8");
137+
const handle = await main(args, stdin, stdout);
138+
closers.push(() => handle.close());
139+
const line = new Promise<string>((resolve) => {
140+
let buffered = "";
141+
stdout.on("data", (chunk: string) => {
142+
buffered += chunk;
143+
const newline = buffered.indexOf("\n");
144+
if (newline !== -1) resolve(buffered.slice(0, newline));
145+
});
146+
});
147+
stdin.write(
148+
`${JSON.stringify({
149+
jsonrpc: "2.0",
150+
id: 1,
151+
method: "tools/call",
152+
params: {
153+
_meta: envelope,
154+
name: "list_allowed_directories",
155+
arguments: {},
156+
},
157+
})}\n`,
158+
);
159+
return JSON.parse(await line) as {
160+
result: CallToolResult & { resultType: string };
161+
};
162+
}
163+
164+
it("answers a 2026-07-28 request with no initialize", async () => {
165+
const { result } = await callOverStdio([allowed]);
166+
expect(result.resultType).toBe("complete");
167+
expect(result.content).toEqual([
168+
{ type: "text", text: `Allowed directories:\n${allowed}` },
169+
]);
170+
});
171+
172+
it("reports a transport error on stderr", async () => {
173+
const stderr = quietStderr();
174+
const stdin = new PassThrough();
175+
const handle = await main([allowed], stdin, new PassThrough());
176+
closers.push(() => handle.close());
177+
const failure = new Error("stdin broke");
178+
stdin.emit("error", failure);
179+
expect(stderr).toHaveBeenCalledWith("Transport error:", failure);
180+
});
181+
182+
it("fails each 2026-07-28 call visibly when started with no directories", async () => {
183+
const { result } = await callOverStdio([]);
184+
expect(result.isError).toBe(true);
185+
expect(result.content).toEqual([
186+
{ type: "text", text: NO_ALLOWED_DIRECTORIES_MODERN_ERROR },
187+
]);
188+
});
189+
});

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import path from "path";
1111
import { PassThrough } from "node:stream";
1212
import { pathToFileURL } from "url";
1313
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14-
import type { McpServer } from "@modelcontextprotocol/server";
14+
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
1515
import { isEntryPoint, main, resolveAllowedDirectories } from "../index.js";
1616
import { makeTempDir, quietStderr } from "./helpers.js";
1717

@@ -28,7 +28,7 @@ class StdioSession {
2828
readonly stdout = new PassThrough();
2929
private buffered = "";
3030
private readonly responses = new Map<number, JsonRpcResponse>();
31-
server?: McpServer;
31+
server?: StdioServerHandle;
3232

3333
constructor() {
3434
this.stdout.setEncoding("utf8");
@@ -135,7 +135,7 @@ describe("startup", () => {
135135
"At least one directory must be provided by EITHER method for the server to operate.",
136136
);
137137
expect(stderr).toHaveBeenCalledWith(
138-
"Started without allowed directories - waiting for client to provide roots via MCP protocol",
138+
"Started without allowed directories - waiting for a 2025-era client to provide roots via MCP protocol",
139139
);
140140
});
141141

‎src/filesystem/index.ts‎

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
#!/usr/bin/env node
22
// The stdio entry point of the filesystem server (the package's bin). It
3-
// resolves the allowed directories named on the command line, builds the
4-
// server with createServer() and connects it to stdio. Everything runs inside
3+
// resolves the allowed directories named on the command line and serves
4+
// createServer() on stdio through the SDK's serveStdio entry, which answers
5+
// 2026-07-28 clients (server/discover, no handshake) and 2025-era clients
6+
// (initialize, then Roots) from the same factory (#4852). Everything runs inside
57
// main(), and main() runs only when this file is the process entry point, so
68
// importing the module (as the tests do) starts nothing (#4854). main() takes
79
// the argv and the stdio streams as parameters so the tests can drive the real
@@ -12,8 +14,11 @@ import { realpathSync } from "fs";
1214
import fs from "fs/promises";
1315
import path from "path";
1416
import { fileURLToPath } from "url";
15-
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
16-
import type { McpServer } from "@modelcontextprotocol/server";
17+
import {
18+
serveStdio,
19+
StdioServerTransport,
20+
type StdioServerHandle,
21+
} from "@modelcontextprotocol/server/stdio";
1722
import { normalizePath, expandHome } from "./path-utils.js";
1823
import { createServer } from "./server.js";
1924

@@ -80,42 +85,52 @@ export async function resolveAllowedDirectories(
8085
}
8186

8287
/**
83-
* Start the server over stdio with the allowed directories in `args`.
84-
* Resolves to the connected server once the transport is listening.
88+
* Serve the server over stdio with the allowed directories in `args`. The
89+
* first message the client sends picks the connection's protocol era, and the
90+
* factory builds the server for it. A transport error, including one that
91+
* stops the transport from starting, is reported on stderr.
8592
*/
8693
export async function main(
8794
args: string[] = process.argv.slice(2),
8895
stdin: Readable = process.stdin,
8996
stdout: Writable = process.stdout,
90-
): Promise<McpServer> {
97+
): Promise<StdioServerHandle> {
9198
if (args.length === 0) {
9299
console.error(
93100
"Usage: mcp-server-filesystem [allowed-directory] [additional-directories...]",
94101
);
95102
console.error("Note: Allowed directories can be provided via:");
96103
console.error(" 1. Command-line arguments (shown above)");
97-
console.error(" 2. MCP roots protocol (if client supports it)");
104+
console.error(
105+
" 2. MCP roots protocol (deprecated; 2025-era clients that support it)",
106+
);
98107
console.error(
99108
"At least one directory must be provided by EITHER method for the server to operate.",
100109
);
101110
}
102111

103112
const allowedDirectories = await resolveAllowedDirectories(args);
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-
});
109-
110-
const transport = new StdioServerTransport(stdin, stdout);
111-
await server.connect(transport);
113+
// With no directories and a 2025-era client without Roots, the server
114+
// closes the connection after initialize (#4992); exit non-zero so the
115+
// failure shows.
116+
const handle = serveStdio(
117+
({ era }) =>
118+
createServer(allowedDirectories, {
119+
era,
120+
onCannotOperate: () => process.exit(1),
121+
}),
122+
{
123+
transport: new StdioServerTransport(stdin, stdout),
124+
onerror: (error) => console.error("Transport error:", error),
125+
},
126+
);
112127
console.error("Secure MCP Filesystem Server running on stdio");
113128
if (allowedDirectories.length === 0) {
114129
console.error(
115-
"Started without allowed directories - waiting for client to provide roots via MCP protocol",
130+
"Started without allowed directories - waiting for a 2025-era client to provide roots via MCP protocol",
116131
);
117132
}
118-
return server;
133+
return handle;
119134
}
120135

121136
/**

0 commit comments

Comments
 (0)