Skip to content

Commit 086e847

Browse files
authored
Merge pull request #5359 from modelcontextprotocol/v2/feat/632-filesystem-read-only
feat(filesystem): add a --read-only mode that serves only read tools
2 parents 76ff516 + be9d4b6 commit 086e847

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 every tool that writes (such as `write_file` and `edit_file`) is 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` in the [Tool annotations](#tool-annotations-mcp-hints) table, the ones that read and list. Every tool not annotated `readOnlyHint: true`, that is every tool that writes (such as `write_file` and `edit_file`), is left out, so a client never lists it and a call to it fails as an unknown tool. A tool added later follows the same rule through its annotation. 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. That separation holds only while the writable server keeps its command-line directories: a 2025-era client that supports Roots replaces them (see Method 2), so it could expose a protected directory to the writable server. Where that matters, make the protected directories read-only at the operating-system level as well, with file permissions or, with Docker, a bind mount's `ro` flag.
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
@@ -94,6 +95,35 @@ export async function resolveAllowedDirectories(
9495
return accessibleDirectories;
9596
}
9697

98+
/** What the command line asks for: the directories, and the options. */
99+
export interface ParsedArgs {
100+
/** The allowed directories, as given (resolveAllowedDirectories resolves them). */
101+
directories: string[];
102+
/** `--read-only`: serve only the tools that cannot change anything (#632). */
103+
readOnly: boolean;
104+
}
105+
106+
/**
107+
* Split the command line into options and allowed directories. An option may
108+
* appear anywhere; `--` ends the options, so a directory whose name is an
109+
* option's can still be given after it. Any other argument is a directory, as
110+
* every argument was before options existed.
111+
*/
112+
export function parseArgs(args: string[]): ParsedArgs {
113+
const parsed: ParsedArgs = { directories: [], readOnly: false };
114+
let options = true;
115+
for (const arg of args) {
116+
if (options && arg === "--") {
117+
options = false;
118+
} else if (options && arg === "--read-only") {
119+
parsed.readOnly = true;
120+
} else {
121+
parsed.directories.push(arg);
122+
}
123+
}
124+
return parsed;
125+
}
126+
97127
/**
98128
* Serve the server over stdio with the allowed directories in `args`. The
99129
* first message the client sends picks the connection's protocol era, and the
@@ -105,9 +135,10 @@ export async function main(
105135
stdin: Readable = process.stdin,
106136
stdout: Writable = process.stdout,
107137
): Promise<StdioServerHandle> {
108-
if (args.length === 0) {
138+
const { directories, readOnly } = parseArgs(args);
139+
if (directories.length === 0) {
109140
console.error(
110-
"Usage: mcp-server-filesystem [allowed-directory] [additional-directories...]",
141+
"Usage: mcp-server-filesystem [--read-only] [allowed-directory] [additional-directories...]",
111142
);
112143
console.error("Note: Allowed directories can be provided via:");
113144
console.error(" 1. Command-line arguments (shown above)");
@@ -119,14 +150,15 @@ export async function main(
119150
);
120151
}
121152

122-
const allowedDirectories = await resolveAllowedDirectories(args);
153+
const allowedDirectories = await resolveAllowedDirectories(directories);
123154
// With no directories and a 2025-era client without Roots, the server
124155
// closes the connection after initialize (#4992); exit non-zero so the
125156
// failure shows.
126157
const handle = serveStdio(
127158
({ era }) =>
128159
createServer(allowedDirectories, {
129160
era,
161+
readOnly,
130162
onCannotOperate: () => process.exit(1),
131163
}),
132164
{
@@ -141,6 +173,11 @@ export async function main(
141173
},
142174
);
143175
console.error("Secure MCP Filesystem Server running on stdio");
176+
if (readOnly) {
177+
console.error(
178+
"Read-only mode: only tools that cannot change the filesystem are served",
179+
);
180+
}
144181
if (allowedDirectories.length === 0) {
145182
console.error(
146183
"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
@@ -209,6 +209,12 @@ export interface ServerOptions {
209209
* Roots (#4992). The stdio entry point exits the process from here.
210210
*/
211211
onCannotOperate?: (error: Error) => void;
212+
/**
213+
* Serve only the tools that cannot change the filesystem (#632, #1160):
214+
* every tool whose annotations do not declare `readOnlyHint: true` is left
215+
* out of the server, so clients never see it and cannot call it.
216+
*/
217+
readOnly?: boolean;
212218
}
213219

214220
/**
@@ -282,6 +288,25 @@ export function createServer(
282288
}
283289
return handler(...args);
284290
}) as never)) as typeof server.registerTool;
291+
// Read-only mode (#632, #1160) withholds every tool that does not declare
292+
// itself read-only. Keying on the annotation rather than on a list of write
293+
// tools fails closed: a new tool is withheld unless its registration says
294+
// `readOnlyHint: true`, the hint the repository already requires to be set
295+
// truthfully, so a new write tool needs no change here. A withheld tool is
296+
// registered and then removed, before any client connects, so it is absent
297+
// from tools/list and a call to it is answered as an unknown tool.
298+
if (options.readOnly) {
299+
const registerReadWrite = server.registerTool.bind(server);
300+
server.registerTool = ((
301+
name: string,
302+
config: Parameters<typeof registerReadWrite>[1],
303+
handler: Parameters<typeof registerReadWrite>[2],
304+
) => {
305+
const tool = registerReadWrite(name, config, handler);
306+
if (config.annotations?.readOnlyHint !== true) tool.remove();
307+
return tool;
308+
}) as typeof server.registerTool;
309+
}
285310

286311
// Tool registrations
287312

0 commit comments

Comments
 (0)