Skip to content

Commit ea2997b

Browse files
cliffhallclaude
andcommitted
feat(filesystem): add a --read-only mode that serves only read tools
With --read-only the server registers only the tools annotated readOnlyHint: true. Every other tool is removed before any client connects, so it is absent from tools/list and cannot be called, on both protocol eras. Keying on the annotation fails closed: a new write tool is withheld with no change to the mode. `--` ends the options. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit ea2997b

6 files changed

Lines changed: 302 additions & 5 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 `--read-only` command-line flag. With it the server registers only the tools annotated `readOnlyHint: true`, so `write_file`, `edit_file`, `create_directory` and `move_file` are not listed and cannot be called, on both protocol eras and whether the directories come from the command line or a client's Roots. `--` now ends the options, so a directory named like an option can still be given after it.

‎src/filesystem/README.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,18 @@ mcp-server-filesystem /path/to/dir1 /path/to/dir2
2626

2727
This is the only method that works on every protocol version, so it is the one to use.
2828

29+
### Read-only Mode
30+
Add `--read-only` to serve only the tools that cannot change the filesystem:
31+
```bash
32+
mcp-server-filesystem --read-only /path/to/dir1 /path/to/dir2
33+
```
34+
35+
The server then registers only the tools annotated `readOnlyHint: true` (see [Tool annotations](#tool-annotations-mcp-hints)): `read_text_file`, `read_media_file`, `read_multiple_files`, `list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`, `get_file_info`, `list_allowed_directories` and the deprecated `read_file`. Every write tool (`write_file`, `edit_file`, `create_directory`, `move_file`) is left out, so a client never lists it and a call to it fails as an unknown tool. The server enforces this, whatever the client is configured to allow, and it works the same with `npx` as with Docker. It applies on both protocol eras, and to directories that come from a client's Roots.
36+
37+
The flag may appear anywhere among the arguments. `--` ends the options, so a directory literally named `--read-only` can be given after it.
38+
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. With Docker, a bind mount's `ro` flag also makes a single directory read-only at the operating-system level.
40+
2941
### Method 2: MCP Roots (Deprecated, 2025-era clients only)
3042
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.
3143

Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
// Read-only mode (#632, #1160): `--read-only` on the command line, or
2+
// `readOnly` in createServer's options, serves only the tools whose
3+
// annotations declare `readOnlyHint: true`. The write tools are not merely
4+
// refused at call time but absent, so a client never lists them. These tests
5+
// pin the exact read-only tool set on both protocol eras, prove a write tool
6+
// cannot be called and leaves the disk untouched, and drive the flag through
7+
// main() so the command-line wiring is covered too.
8+
9+
import fs from "fs/promises";
10+
import path from "path";
11+
import { PassThrough } from "node:stream";
12+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13+
import {
14+
Client,
15+
InMemoryTransport,
16+
type CallToolResult,
17+
} from "@modelcontextprotocol/client";
18+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
19+
import { main, parseArgs } from "../index.js";
20+
import { createServer } from "../server.js";
21+
import { makeTempDir, quietStderr } from "./helpers.js";
22+
23+
// Every tool that cannot change the filesystem. A tool added to the server
24+
// must be added here if it is read-only; a write tool is withheld without any
25+
// change, which is the point of keying the mode on the annotation.
26+
const READ_ONLY_TOOLS = [
27+
"directory_tree",
28+
"get_file_info",
29+
"list_allowed_directories",
30+
"list_directory",
31+
"list_directory_with_sizes",
32+
"read_file",
33+
"read_media_file",
34+
"read_multiple_files",
35+
"read_text_file",
36+
"search_files",
37+
];
38+
39+
let dir: string;
40+
let stderr: ReturnType<typeof quietStderr>;
41+
let closers: Array<() => Promise<void>>;
42+
43+
beforeEach(async () => {
44+
stderr = quietStderr();
45+
dir = await makeTempDir("mcp-fs-read-only-");
46+
await fs.writeFile(path.join(dir, "note.txt"), "original");
47+
closers = [];
48+
});
49+
50+
afterEach(async () => {
51+
for (const close of closers.reverse()) await close();
52+
vi.restoreAllMocks();
53+
await fs.rm(dir, { recursive: true, force: true });
54+
});
55+
56+
/** A client connected to a server for `dir`, negotiating per `mode`. */
57+
async function connect(
58+
readOnly: boolean,
59+
mode: "auto" | "legacy",
60+
): Promise<Client> {
61+
const [clientTransport, serverTransport] =
62+
InMemoryTransport.createLinkedPair();
63+
const handle = serveStdio(
64+
({ era }) => createServer([dir], { era, readOnly }),
65+
{ transport: serverTransport },
66+
);
67+
const client = new Client(
68+
{ name: "fs-read-only-test", version: "0.0.0" },
69+
{ versionNegotiation: { mode } },
70+
);
71+
await client.connect(clientTransport);
72+
closers.push(
73+
() => handle.close(),
74+
() => client.close(),
75+
);
76+
return client;
77+
}
78+
79+
describe.each([
80+
["2026-07-28", "auto"],
81+
["2025-11-25", "legacy"],
82+
] as const)("read-only mode on %s", (_label, mode) => {
83+
it("lists only the read-only tools, each annotated readOnlyHint: true", async () => {
84+
const client = await connect(true, mode);
85+
const { tools } = await client.listTools();
86+
expect(tools.map((tool) => tool.name).sort()).toEqual(READ_ONLY_TOOLS);
87+
for (const tool of tools) {
88+
expect(tool.annotations?.readOnlyHint).toBe(true);
89+
}
90+
});
91+
92+
it("withholds exactly the tools not annotated read-only", async () => {
93+
const full = await connect(false, mode);
94+
const { tools } = await full.listTools();
95+
const writeTools = tools
96+
.filter((tool) => tool.annotations?.readOnlyHint !== true)
97+
.map((tool) => tool.name);
98+
expect(writeTools).toEqual(
99+
expect.arrayContaining([
100+
"write_file",
101+
"edit_file",
102+
"create_directory",
103+
"move_file",
104+
]),
105+
);
106+
const readOnly = await connect(true, mode);
107+
const listed = (await readOnly.listTools()).tools.map((t) => t.name);
108+
for (const name of writeTools) expect(listed).not.toContain(name);
109+
});
110+
111+
it("refuses a call to a write tool and leaves the file untouched", async () => {
112+
const client = await connect(true, mode);
113+
const target = path.join(dir, "note.txt");
114+
const result = (await client
115+
.callTool({
116+
name: "write_file",
117+
arguments: { path: target, content: "changed" },
118+
})
119+
.catch((error: unknown) => ({
120+
isError: true,
121+
content: [{ type: "text", text: String(error) }],
122+
}))) as CallToolResult;
123+
expect(result.isError).toBe(true);
124+
expect(JSON.stringify(result.content)).toMatch(/write_file/);
125+
expect(await fs.readFile(target, "utf8")).toBe("original");
126+
});
127+
128+
it("still serves the read tools", async () => {
129+
const client = await connect(true, mode);
130+
const result = (await client.callTool({
131+
name: "read_text_file",
132+
arguments: { path: path.join(dir, "note.txt") },
133+
})) as CallToolResult;
134+
expect(result.isError).toBeFalsy();
135+
expect(result.content).toEqual([{ type: "text", text: "original" }]);
136+
});
137+
});
138+
139+
describe("parseArgs", () => {
140+
it("takes every argument as a directory when no option is given", () => {
141+
expect(parseArgs(["/a", "/b"])).toEqual({
142+
directories: ["/a", "/b"],
143+
readOnly: false,
144+
});
145+
});
146+
147+
it("recognizes --read-only before, between or after the directories", () => {
148+
for (const args of [
149+
["--read-only", "/a", "/b"],
150+
["/a", "--read-only", "/b"],
151+
["/a", "/b", "--read-only"],
152+
]) {
153+
expect(parseArgs(args)).toEqual({
154+
directories: ["/a", "/b"],
155+
readOnly: true,
156+
});
157+
}
158+
});
159+
160+
it("treats everything after -- as a directory", () => {
161+
expect(parseArgs(["--read-only", "--", "--read-only", "/a"])).toEqual({
162+
directories: ["--read-only", "/a"],
163+
readOnly: true,
164+
});
165+
});
166+
});
167+
168+
describe("main() with --read-only", () => {
169+
it("serves only the read-only tools over stdio and says so on stderr", async () => {
170+
const stdin = new PassThrough();
171+
const stdout = new PassThrough();
172+
stdout.setEncoding("utf8");
173+
const handle = await main(["--read-only", dir], stdin, stdout);
174+
closers.push(() => handle.close());
175+
const line = new Promise<string>((resolve) => {
176+
let buffered = "";
177+
stdout.on("data", (chunk: string) => {
178+
buffered += chunk;
179+
const newline = buffered.indexOf("\n");
180+
if (newline !== -1) resolve(buffered.slice(0, newline));
181+
});
182+
});
183+
stdin.write(
184+
`${JSON.stringify({
185+
jsonrpc: "2.0",
186+
id: 1,
187+
method: "tools/list",
188+
params: {
189+
_meta: {
190+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
191+
"io.modelcontextprotocol/clientCapabilities": {},
192+
},
193+
},
194+
})}\n`,
195+
);
196+
const { result } = JSON.parse(await line) as {
197+
result: { tools: Array<{ name: string }> };
198+
};
199+
expect(result.tools.map((tool) => tool.name).sort()).toEqual(
200+
READ_ONLY_TOOLS,
201+
);
202+
expect(stderr).toHaveBeenCalledWith(
203+
"Read-only mode: only tools that cannot change the filesystem are served",
204+
);
205+
});
206+
207+
it("prints usage when --read-only is the only argument", async () => {
208+
const handle = await main(
209+
["--read-only"],
210+
new PassThrough(),
211+
new PassThrough(),
212+
);
213+
closers.push(() => handle.close());
214+
expect(stderr).toHaveBeenCalledWith(
215+
"Usage: mcp-server-filesystem [--read-only] [allowed-directory] [additional-directories...]",
216+
);
217+
});
218+
});

‎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 [allowed-directory] [additional-directories...]",
132+
"Usage: mcp-server-filesystem [--read-only] [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.",

‎src/filesystem/index.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
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 and serves
3+
// parses the command line (its options, such as --read-only, and the allowed
4+
// directories), resolves the allowed directories and serves
45
// createServer() on stdio through the SDK's serveStdio entry, which answers
56
// 2026-07-28 clients (server/discover, no handshake) and 2025-era clients
67
// (initialize, then Roots) from the same factory (#4852). Everything runs inside
@@ -84,6 +85,35 @@ export async function resolveAllowedDirectories(
8485
return accessibleDirectories;
8586
}
8687

88+
/** What the command line asks for: the directories, and the options. */
89+
export interface ParsedArgs {
90+
/** The allowed directories, as given (resolveAllowedDirectories resolves them). */
91+
directories: string[];
92+
/** `--read-only`: serve only the tools that cannot change anything (#632). */
93+
readOnly: boolean;
94+
}
95+
96+
/**
97+
* Split the command line into options and allowed directories. An option may
98+
* appear anywhere; `--` ends the options, so a directory whose name is an
99+
* option's can still be given after it. Any other argument is a directory, as
100+
* every argument was before options existed.
101+
*/
102+
export function parseArgs(args: string[]): ParsedArgs {
103+
const parsed: ParsedArgs = { directories: [], readOnly: false };
104+
let options = true;
105+
for (const arg of args) {
106+
if (options && arg === "--") {
107+
options = false;
108+
} else if (options && arg === "--read-only") {
109+
parsed.readOnly = true;
110+
} else {
111+
parsed.directories.push(arg);
112+
}
113+
}
114+
return parsed;
115+
}
116+
87117
/**
88118
* Serve the server over stdio with the allowed directories in `args`. The
89119
* first message the client sends picks the connection's protocol era, and the
@@ -95,9 +125,10 @@ export async function main(
95125
stdin: Readable = process.stdin,
96126
stdout: Writable = process.stdout,
97127
): Promise<StdioServerHandle> {
98-
if (args.length === 0) {
128+
const { directories, readOnly } = parseArgs(args);
129+
if (directories.length === 0) {
99130
console.error(
100-
"Usage: mcp-server-filesystem [allowed-directory] [additional-directories...]",
131+
"Usage: mcp-server-filesystem [--read-only] [allowed-directory] [additional-directories...]",
101132
);
102133
console.error("Note: Allowed directories can be provided via:");
103134
console.error(" 1. Command-line arguments (shown above)");
@@ -109,14 +140,15 @@ export async function main(
109140
);
110141
}
111142

112-
const allowedDirectories = await resolveAllowedDirectories(args);
143+
const allowedDirectories = await resolveAllowedDirectories(directories);
113144
// With no directories and a 2025-era client without Roots, the server
114145
// closes the connection after initialize (#4992); exit non-zero so the
115146
// failure shows.
116147
const handle = serveStdio(
117148
({ era }) =>
118149
createServer(allowedDirectories, {
119150
era,
151+
readOnly,
120152
onCannotOperate: () => process.exit(1),
121153
}),
122154
{
@@ -131,6 +163,11 @@ export async function main(
131163
},
132164
);
133165
console.error("Secure MCP Filesystem Server running on stdio");
166+
if (readOnly) {
167+
console.error(
168+
"Read-only mode: only tools that cannot change the filesystem are served",
169+
);
170+
}
134171
if (allowedDirectories.length === 0) {
135172
console.error(
136173
"Started without allowed directories - waiting for a 2025-era client to provide roots via MCP protocol",

‎src/filesystem/server.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,12 @@ export interface ServerOptions {
177177
* Roots (#4992). The stdio entry point exits the process from here.
178178
*/
179179
onCannotOperate?: (error: Error) => void;
180+
/**
181+
* Serve only the tools that cannot change the filesystem (#632, #1160):
182+
* every tool whose annotations do not declare `readOnlyHint: true` is left
183+
* out of the server, so clients never see it and cannot call it.
184+
*/
185+
readOnly?: boolean;
180186
}
181187

182188
/**
@@ -250,6 +256,25 @@ export function createServer(
250256
}
251257
return handler(...args);
252258
}) as never)) as typeof server.registerTool;
259+
// Read-only mode (#632, #1160) withholds every tool that does not declare
260+
// itself read-only. Keying on the annotation rather than on a list of write
261+
// tools fails closed: a new tool is withheld unless its registration says
262+
// `readOnlyHint: true`, the hint the repository already requires to be set
263+
// truthfully, so a new write tool needs no change here. A withheld tool is
264+
// registered and then removed, before any client connects, so it is absent
265+
// from tools/list and a call to it is answered as an unknown tool.
266+
if (options.readOnly) {
267+
const registerReadWrite = server.registerTool.bind(server);
268+
server.registerTool = ((
269+
name: string,
270+
config: Parameters<typeof registerReadWrite>[1],
271+
handler: Parameters<typeof registerReadWrite>[2],
272+
) => {
273+
const tool = registerReadWrite(name, config, handler);
274+
if (config.annotations?.readOnlyHint !== true) tool.remove();
275+
return tool;
276+
}) as typeof server.registerTool;
277+
}
253278

254279
// Tool registrations
255280

0 commit comments

Comments
 (0)