Skip to content

Commit 3f173d6

Browse files
cliffhallclaude
andcommitted
feat(filesystem): expose files as resources through a file:// template
Files inside the allowed directories can now be read with resources/read through a `file://{+path}` resource template, returned as text or as a base64 blob with their MIME type. Reads go through the same validatePath, roots barrier and 2026-07-28 no-directories error as the tools, and the template has no list callback, so resources/list never enumerates the disk. The template lives in file-resources.ts and is registered from createServer() with one call. Closes #297 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 3f173d6

6 files changed

Lines changed: 535 additions & 1 deletion

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+
Expose files in the allowed directories as MCP resources through a `file://{+path}` resource template, so a client can read a file with `resources/read` (text or a base64 blob by MIME type), confined to the allowed directories exactly as the tools are. `resources/list` stays empty, so the server never enumerates the disk.

‎src/filesystem/README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,17 @@ The server's directory access control follows this flow:
7676

7777
## API
7878

79+
### Resources
80+
81+
Files inside the allowed directories are also [resources](https://modelcontextprotocol.io/specification/2026-07-28/server/resources), so a client application can read one with `resources/read` and decide itself what to do with it (attach it to the model's context, show it to the user), rather than relaying it through a tool result.
82+
83+
- **Resource template** `file://{+path}` (name `file`)
84+
- Read any file by its absolute `file://` URI, for example `file:///home/user/project/README.md`. A path with spaces or other reserved characters is percent-encoded, as in any `file://` URL.
85+
- Text files are returned as `text`, with a MIME type from the extension (`text/plain` for an unknown extension whose bytes are UTF-8). Images, audio, PDFs and other binary files are returned as a base64 `blob` with their MIME type (`application/octet-stream` when unknown).
86+
- Confined exactly as the tools are: a URI outside the allowed directories, or a symlink whose target is outside them, is refused with an `Access denied` error (`-32602`). A missing file is "resource not found" (`-32602` with the URI in the error data), and a directory is not a resource.
87+
- `resources/list` returns nothing: the server never enumerates the disk. Find files with `list_directory`, `directory_tree` or `search_files`, then read them by URI.
88+
- Results carry a cache hint of `ttlMs: 0`, `cacheScope: "private"` (2026-07-28), since a file can change at any time.
89+
7990
### Tools
8091

8192
- **read_text_file**
Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
// Files as resources (#297), driven through a real Client over an in-memory
2+
// transport: the file:// template is advertised, resources/list enumerates
3+
// nothing, a read returns text or a base64 blob by type, and a read is
4+
// confined exactly as the tools are (allowed directories only, no symlink out,
5+
// the roots barrier on 2025-11-25, the no-directories error on 2026-07-28).
6+
7+
import fs from "fs/promises";
8+
import path from "path";
9+
import { pathToFileURL } from "url";
10+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11+
import {
12+
Client,
13+
InMemoryTransport,
14+
ProtocolError,
15+
ResourceNotFoundError,
16+
} from "@modelcontextprotocol/client";
17+
import { McpServer } from "@modelcontextprotocol/server";
18+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
19+
import {
20+
createServer,
21+
NO_ALLOWED_DIRECTORIES_MODERN_ERROR,
22+
} from "../server.js";
23+
import {
24+
FILE_RESOURCE_TEMPLATE,
25+
fileResourceContents,
26+
registerFileResources,
27+
} from "../file-resources.js";
28+
import { connect, makeTempDir, quietStderr } from "./helpers.js";
29+
30+
let allowed: string;
31+
let other: string;
32+
let closers: Array<() => Promise<void>>;
33+
34+
const uriOf = (p: string) => pathToFileURL(p).href;
35+
36+
beforeEach(async () => {
37+
quietStderr();
38+
allowed = await makeTempDir("mcp-fs-res-allowed-");
39+
other = await makeTempDir("mcp-fs-res-other-");
40+
await fs.writeFile(path.join(other, "secret.txt"), "secret");
41+
closers = [];
42+
});
43+
44+
afterEach(async () => {
45+
for (const close of closers.reverse()) await close();
46+
vi.restoreAllMocks();
47+
await fs.rm(allowed, { recursive: true, force: true });
48+
await fs.rm(other, { recursive: true, force: true });
49+
});
50+
51+
async function connectTo(directories: string[]): Promise<Client> {
52+
const { client, close } = await connect(directories);
53+
closers.push(close);
54+
return client;
55+
}
56+
57+
/** The error a resources/read rejects with. */
58+
async function readError(client: Client, uri: string): Promise<ProtocolError> {
59+
const error = await client.readResource({ uri }).then(
60+
() => undefined,
61+
(e: unknown) => e,
62+
);
63+
expect(error).toBeInstanceOf(ProtocolError);
64+
return error as ProtocolError;
65+
}
66+
67+
describe("resource discovery", () => {
68+
it("advertises the file:// template and lists no resources", async () => {
69+
const client = await connectTo([allowed]);
70+
expect(client.getServerCapabilities()?.resources).toBeDefined();
71+
const { resourceTemplates } = await client.listResourceTemplates();
72+
expect(resourceTemplates).toEqual([
73+
expect.objectContaining({
74+
name: "file",
75+
uriTemplate: FILE_RESOURCE_TEMPLATE,
76+
}),
77+
]);
78+
const { resources } = await client.listResources();
79+
expect(resources).toEqual([]);
80+
});
81+
});
82+
83+
describe("resources/read", () => {
84+
it("returns a text file as text", async () => {
85+
const file = path.join(allowed, "notes.md");
86+
await fs.writeFile(file, "# héllo\n");
87+
const client = await connectTo([allowed]);
88+
const { contents } = await client.readResource({ uri: uriOf(file) });
89+
expect(contents).toEqual([
90+
{ uri: uriOf(file), mimeType: "text/markdown", text: "# héllo\n" },
91+
]);
92+
});
93+
94+
it("returns an image as a base64 blob with its MIME type", async () => {
95+
const file = path.join(allowed, "pixel.png");
96+
const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]);
97+
await fs.writeFile(file, bytes);
98+
const client = await connectTo([allowed]);
99+
const { contents } = await client.readResource({ uri: uriOf(file) });
100+
expect(contents).toEqual([
101+
{
102+
uri: uriOf(file),
103+
mimeType: "image/png",
104+
blob: bytes.toString("base64"),
105+
},
106+
]);
107+
});
108+
109+
it("decodes a percent-encoded path", async () => {
110+
const file = path.join(allowed, "with space.txt");
111+
await fs.writeFile(file, "spaced");
112+
const client = await connectTo([allowed]);
113+
const uri = uriOf(file);
114+
expect(uri).toContain("%20");
115+
const { contents } = await client.readResource({ uri });
116+
expect(contents[0]).toMatchObject({ text: "spaced" });
117+
});
118+
119+
it("rejects a file outside the allowed directories", async () => {
120+
const client = await connectTo([allowed]);
121+
const error = await readError(
122+
client,
123+
uriOf(path.join(other, "secret.txt")),
124+
);
125+
expect(error.code).toBe(-32602);
126+
expect(error.message).toContain("Access denied");
127+
});
128+
129+
it("rejects a dot-dot URI that climbs out of an allowed directory", async () => {
130+
const client = await connectTo([allowed]);
131+
const climbing = `${uriOf(allowed)}/../${path.basename(other)}/secret.txt`;
132+
const error = await readError(client, climbing);
133+
expect(error.message).toContain("Access denied");
134+
});
135+
136+
it("rejects a symlink whose target is outside the allowed directories", async () => {
137+
const link = path.join(allowed, "link.txt");
138+
await fs.symlink(path.join(other, "secret.txt"), link);
139+
const client = await connectTo([allowed]);
140+
const error = await readError(client, uriOf(link));
141+
expect(error.message).toContain("symlink target outside");
142+
});
143+
144+
it("reports a missing file as resource not found", async () => {
145+
const client = await connectTo([allowed]);
146+
const uri = uriOf(path.join(allowed, "missing.txt"));
147+
const error = await readError(client, uri);
148+
expect(error).toBeInstanceOf(ResourceNotFoundError);
149+
expect(error.data).toEqual({ uri });
150+
});
151+
152+
it("reports a directory as not a resource", async () => {
153+
await fs.mkdir(path.join(allowed, "sub"));
154+
const client = await connectTo([allowed]);
155+
const uri = uriOf(path.join(allowed, "sub"));
156+
const error = await readError(client, uri);
157+
expect(error).toBeInstanceOf(ResourceNotFoundError);
158+
expect(error.message).toContain("is a directory");
159+
});
160+
161+
it.skipIf(process.platform === "win32")(
162+
"rejects a file URI with a remote host",
163+
async () => {
164+
const client = await connectTo([allowed]);
165+
const error = await readError(client, "file://elsewhere/etc/passwd");
166+
expect(error.code).toBe(-32602);
167+
expect(error.message).toContain("Invalid file URI");
168+
},
169+
);
170+
171+
it("reports any other read failure as an internal error", async () => {
172+
const file = path.join(allowed, "locked.txt");
173+
await fs.writeFile(file, "x");
174+
const client = await connectTo([allowed]);
175+
vi.spyOn(fs, "readFile").mockRejectedValueOnce(
176+
Object.assign(new Error("permission denied"), { code: "EACCES" }),
177+
);
178+
const error = await readError(client, uriOf(file));
179+
expect(error.code).toBe(-32603);
180+
expect(error.message).toContain("permission denied");
181+
});
182+
});
183+
184+
describe("fileResourceContents", () => {
185+
const uri = "file:///x";
186+
187+
it("sniffs an unknown extension: UTF-8 is text/plain", () => {
188+
expect(
189+
fileResourceContents(uri, "/a/Makefile", Buffer.from("all:\n")),
190+
).toEqual({ uri, mimeType: "text/plain", text: "all:\n" });
191+
});
192+
193+
it("sniffs an unknown extension: NUL bytes are an octet-stream blob", () => {
194+
const bytes = Buffer.from([0x41, 0x00, 0x42]);
195+
expect(fileResourceContents(uri, "/a/data.bin", bytes)).toEqual({
196+
uri,
197+
mimeType: "application/octet-stream",
198+
blob: bytes.toString("base64"),
199+
});
200+
});
201+
202+
it("returns a textual type that is not valid UTF-8 as a blob of that type", () => {
203+
const bytes = Buffer.from([0xc3, 0x28]);
204+
expect(fileResourceContents(uri, "/a/broken.JSON", bytes)).toEqual({
205+
uri,
206+
mimeType: "application/json",
207+
blob: bytes.toString("base64"),
208+
});
209+
});
210+
});
211+
212+
describe("protocol eras", () => {
213+
async function connectEra(
214+
directories: string[],
215+
mode: "auto" | "legacy",
216+
listRoots?: () => Promise<{ uri: string }[]>,
217+
): Promise<Client> {
218+
const [clientTransport, serverTransport] =
219+
InMemoryTransport.createLinkedPair();
220+
const handle = serveStdio(({ era }) => createServer(directories, { era }), {
221+
transport: serverTransport,
222+
});
223+
const client = new Client(
224+
{ name: "fs-res-era-test", version: "0.0.0" },
225+
{
226+
capabilities: listRoots ? { roots: {} } : {},
227+
versionNegotiation: { mode },
228+
},
229+
);
230+
if (listRoots) {
231+
client.setRequestHandler("roots/list", async () => ({
232+
roots: await listRoots(),
233+
}));
234+
}
235+
await client.connect(clientTransport);
236+
closers.push(
237+
() => handle.close(),
238+
() => client.close(),
239+
);
240+
return client;
241+
}
242+
243+
it("reads a file on 2026-07-28", async () => {
244+
const file = path.join(allowed, "a.txt");
245+
await fs.writeFile(file, "modern");
246+
const client = await connectEra([allowed], "auto");
247+
expect(client.getProtocolEra()).toBe("modern");
248+
const { contents } = await client.readResource({ uri: uriOf(file) });
249+
expect(contents[0]).toMatchObject({ text: "modern" });
250+
});
251+
252+
it("explains on 2026-07-28 that a server with no directories cannot operate", async () => {
253+
const client = await connectEra([], "auto");
254+
const error = await readError(
255+
client,
256+
uriOf(path.join(other, "secret.txt")),
257+
);
258+
expect(error.message).toContain(NO_ALLOWED_DIRECTORIES_MODERN_ERROR);
259+
});
260+
261+
it("waits on 2025-11-25 for the client's roots before reading", async () => {
262+
let answer!: (roots: { uri: string }[]) => void;
263+
const roots = new Promise<{ uri: string }[]>((r) => (answer = r));
264+
const client = await connectEra([allowed], "legacy", () => roots);
265+
expect(client.getProtocolEra()).toBe("legacy");
266+
const read = client.readResource({
267+
uri: uriOf(path.join(other, "secret.txt")),
268+
});
269+
answer([{ uri: uriOf(other) }]);
270+
const { contents } = await read;
271+
expect(contents[0]).toMatchObject({ text: "secret" });
272+
});
273+
});
274+
275+
describe("registerFileResources", () => {
276+
it("waits again when the roots barrier is replaced while it waits", async () => {
277+
const file = path.join(allowed, "a.txt");
278+
await fs.writeFile(file, "after");
279+
const first = Promise.resolve();
280+
const second = Promise.resolve();
281+
const barriers = [first, second, second, second];
282+
const rootsSettled = vi.fn(() => barriers.shift() ?? second);
283+
const server = new McpServer({ name: "t", version: "0.0.0" });
284+
registerFileResources(server, {
285+
allowedDirectories: () => [allowed],
286+
rootsSettled,
287+
unavailableReason: () => undefined,
288+
});
289+
const client = new Client({ name: "t", version: "0.0.0" });
290+
const [ct, st] = InMemoryTransport.createLinkedPair();
291+
await Promise.all([server.connect(st), client.connect(ct)]);
292+
closers.push(
293+
() => server.close(),
294+
() => client.close(),
295+
);
296+
const { contents } = await client.readResource({ uri: uriOf(file) });
297+
expect(contents[0]).toMatchObject({ text: "after" });
298+
// first, then (replaced) second, then second again: settled.
299+
expect(rootsSettled).toHaveBeenCalledTimes(4);
300+
});
301+
});

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,10 @@ describe("server identity and tool list", () => {
8383
});
8484
});
8585

86-
it("advertises only the tools capability", () => {
86+
it("advertises the tools and resources capabilities", () => {
8787
expect(client.getServerCapabilities()).toEqual({
8888
tools: { listChanged: true },
89+
resources: { listChanged: true },
8990
});
9091
});
9192

0 commit comments

Comments
 (0)