// Characterization suite for every filesystem tool, driven through an SDK // Client over an in-memory transport (#4854). It pins what the server does // today, quirks included. It was written on SDK 1.x so the SDK v2 migration // (#4856) could show what changed on the wire. A test that pins a known bug says so, with // the issue number, so the fix has a test to change. import fs from "fs/promises"; import fsSync from "fs"; import path from "path"; import { fileURLToPath } from "url"; import { createRequire } from "node:module"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { allowedDirectoriesOf, call, connect, makeTempDir, quietStderr, textOf, type Connected, } from "./helpers.js"; const packageJson = createRequire(import.meta.url)("../package.json") as { version: string; }; const TOOL_NAMES = [ "read_file", "read_text_file", "read_media_file", "read_multiple_files", "write_file", "append_file", "edit_file", "create_directory", "list_directory", "list_directory_with_sizes", "directory_tree", "move_file", "copy_file", "search_files", "get_file_info", "list_allowed_directories", ]; interface TreeEntry { name: string; type: "file" | "directory"; children?: TreeEntry[]; } /** Sort a directory_tree result by name at every level; readdir order is the OS's. */ function sortTree(entries: TreeEntry[]): TreeEntry[] { return [...entries] .sort((a, b) => a.name.localeCompare(b.name)) .map((entry) => entry.children ? { ...entry, children: sortTree(entry.children) } : entry, ); } let dir: string; let conn: Connected; let client: Client; beforeEach(async () => { // The server logs its roots decision to stderr on every connect. quietStderr(); dir = await makeTempDir("mcp-fs-tools-"); conn = await connect([dir]); client = conn.client; }); afterEach(async () => { vi.restoreAllMocks(); await conn.close(); await fs.rm(dir, { recursive: true, force: true }); }); describe("server identity and tool list", () => { it("reports its name and the package.json version (#360, fixed by #4472)", () => { expect(client.getServerVersion()).toEqual({ name: "secure-filesystem-server", version: packageJson.version, }); }); it("advertises the tools and resources capabilities", () => { expect(client.getServerCapabilities()).toEqual({ tools: { listChanged: true }, resources: { listChanged: true }, }); }); it("lists the tools in registration order", async () => { const { tools } = await client.listTools(); expect(tools.map((t) => t.name)).toEqual(TOOL_NAMES); }); // #3402: every tool sets all four hints explicitly, the read-only ones // included (idempotent, never destructive), so a client never falls back // to the spec's defaults (destructive, not idempotent, open world). it("pins each tool's title and annotations (#3402)", async () => { const { tools } = await client.listTools(); const table = Object.fromEntries( tools.map((t) => [t.name, { title: t.title, ...t.annotations }]), ); const readOnly = { readOnlyHint: true, idempotentHint: true, destructiveHint: false, openWorldHint: false, }; expect(table).toEqual({ read_file: { title: "Read File (Deprecated)", ...readOnly }, read_text_file: { title: "Read Text File", ...readOnly }, read_media_file: { title: "Read Media File", ...readOnly }, read_multiple_files: { title: "Read Multiple Files", ...readOnly }, write_file: { title: "Write File", readOnlyHint: false, idempotentHint: true, destructiveHint: true, openWorldHint: false, }, append_file: { title: "Append File", readOnlyHint: false, idempotentHint: false, destructiveHint: false, openWorldHint: false, }, edit_file: { title: "Edit File", readOnlyHint: false, idempotentHint: false, destructiveHint: true, openWorldHint: false, }, create_directory: { title: "Create Directory", readOnlyHint: false, idempotentHint: true, destructiveHint: false, openWorldHint: false, }, list_directory: { title: "List Directory", ...readOnly }, list_directory_with_sizes: { title: "List Directory with Sizes", ...readOnly, }, directory_tree: { title: "Directory Tree", ...readOnly }, move_file: { title: "Move File", readOnlyHint: false, idempotentHint: false, destructiveHint: true, openWorldHint: false, }, copy_file: { title: "Copy File", readOnlyHint: false, idempotentHint: true, destructiveHint: false, openWorldHint: false, }, search_files: { title: "Search Files", ...readOnly }, get_file_info: { title: "Get File Info", ...readOnly }, list_allowed_directories: { title: "List Allowed Directories", ...readOnly, }, }); }); // #4841: the SDK 1.x tools/list handler stamped draft-07 on every schema it // rendered, which validators that accept only JSON Schema 2020-12 reject. The // server declares 2020-12 instead, as SDK v2 now does by default. it("declares the 2020-12 $schema on every input and output schema (#4841)", async () => { const { tools } = await client.listTools(); expect(tools).toHaveLength(TOOL_NAMES.length); for (const tool of tools) { expect(tool.inputSchema.$schema).toBe( "https://json-schema.org/draft/2020-12/schema", ); expect(tool.outputSchema?.$schema).toBe( "https://json-schema.org/draft/2020-12/schema", ); } }); // #4841: the schemas are still rendered with zod's draft-07 rules, so the // 2020-12 label holds only while they use no keyword whose meaning differs // between the two dialects: array-form (tuple) items, additionalItems, and // definitions rather than $defs. it("advertises no draft-07-only keyword under the 2020-12 label (#4841)", async () => { const { tools } = await client.listTools(); const draft07Only: string[] = []; const walk = (node: unknown, at: string): void => { if (Array.isArray(node)) { node.forEach((item, i) => walk(item, `${at}[${i}]`)); return; } if (node === null || typeof node !== "object") return; for (const [key, value] of Object.entries(node)) { if ( (key === "items" && Array.isArray(value)) || key === "additionalItems" || key === "definitions" ) { draft07Only.push(`${at}.${key}`); } walk(value, `${at}.${key}`); } }; for (const tool of tools) { walk(tool.inputSchema, `${tool.name}.inputSchema`); walk(tool.outputSchema, `${tool.name}.outputSchema`); } expect(draft07Only).toEqual([]); }); it("pins the input schemas a client is shown", async () => { const { tools } = await client.listTools(); const byName = Object.fromEntries(tools.map((t) => [t.name, t])); const strip = (schema: Record) => { const { $schema: _dialect, ...rest } = schema; return rest; }; expect(strip(byName.read_text_file.inputSchema)).toEqual({ type: "object", properties: { path: { type: "string", description: "The file to read as text. Absolute, or relative to an allowed directory; it must resolve inside the allowed directories.", }, tail: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "If provided, returns only the last N lines of the file", }, head: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "If provided, returns only the first N lines of the file", }, }, required: ["path"], }); // The deprecated alias advertises read_text_file's schema, not a copy. expect(byName.read_file.inputSchema).toEqual( byName.read_text_file.inputSchema, ); expect(strip(byName.edit_file.inputSchema)).toEqual({ type: "object", properties: { path: { type: "string", description: "The text file to edit. Absolute, or relative to an allowed directory; it must resolve inside the allowed directories.", }, edits: { type: "array", description: "The replacements to make, applied in order, each to the result of the ones before it. " + "If any one has no match, none is written.", items: { type: "object", properties: { oldText: { type: "string", description: "Text to search for - must match exactly", }, newText: { type: "string", description: "Text to replace with", }, }, required: ["oldText", "newText"], }, }, dryRun: { type: "boolean", default: false, description: "Preview changes using git-style diff format", }, }, required: ["path", "edits"], }); expect(strip(byName.list_allowed_directories.inputSchema)).toEqual({ type: "object", properties: {}, }); expect(strip(byName.write_file.outputSchema!)).toEqual({ type: "object", properties: { content: { type: "string" } }, required: ["content"], additionalProperties: false, }); }); it("advertises read_media_file's union outputSchema with every arm (#4029)", async () => { const { tools } = await client.listTools(); const tool = tools.find((t) => t.name === "read_media_file"); const schema = JSON.stringify(tool?.outputSchema); expect(schema).toMatch(/"image"/); expect(schema).toMatch(/"audio"/); expect(schema).toMatch(/"resource"/); }); it("returns every non-media tool's structuredContent as { content: string } mirroring the text block (#3110, #3106, #3093)", async () => { await fs.writeFile(path.join(dir, "a.txt"), "alpha"); const calls: Array<[string, Record]> = [ ["read_file", { path: path.join(dir, "a.txt") }], ["read_text_file", { path: path.join(dir, "a.txt") }], ["read_multiple_files", { paths: [path.join(dir, "a.txt")] }], ["write_file", { path: path.join(dir, "b.txt"), content: "beta" }], [ "edit_file", { path: path.join(dir, "b.txt"), edits: [{ oldText: "beta", newText: "gamma" }], }, ], ["create_directory", { path: path.join(dir, "sub") }], ["list_directory", { path: dir }], ["list_directory_with_sizes", { path: dir }], ["directory_tree", { path: dir }], [ "move_file", { source: path.join(dir, "b.txt"), destination: path.join(dir, "c.txt"), }, ], ["search_files", { path: dir, pattern: "*.txt" }], ["get_file_info", { path: path.join(dir, "a.txt") }], ["list_allowed_directories", {}], ]; for (const [name, args] of calls) { const result = await call(client, name, args); expect(result.isError, name).toBeFalsy(); expect(result.structuredContent, name).toEqual({ content: textOf(result), }); } }); it("rejects an unknown tool with -32602", async () => { await expect(call(client, "no_such_tool")).rejects.toMatchObject({ code: -32602, message: "Tool no_such_tool not found", }); }); it("reports schema-invalid arguments as a tool error", async () => { const result = await call(client, "read_text_file", { path: 42 }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch( /^Input validation error: Invalid arguments for tool read_text_file/, ); }); }); describe("read_text_file and read_file", () => { let file: string; beforeEach(async () => { file = path.join(dir, "lines.txt"); await fs.writeFile(file, "one\ntwo\nthree\nfour\n"); }); it("returns the whole file", async () => { const result = await call(client, "read_text_file", { path: file }); expect(result).toEqual({ content: [{ type: "text", text: "one\ntwo\nthree\nfour\n" }], structuredContent: { content: "one\ntwo\nthree\nfour\n" }, }); }); it("read_file is a deprecated alias with the same result", async () => { const legacy = await call(client, "read_file", { path: file, head: 1 }); const current = await call(client, "read_text_file", { path: file, head: 1, }); expect(legacy).toEqual(current); }); it("returns the first N lines with head", async () => { const result = await call(client, "read_text_file", { path: file, head: 2, }); expect(textOf(result)).toBe("one\ntwo"); }); it("returns the last N lines with tail, not counting the trailing newline as a line (#5187)", async () => { const result = await call(client, "read_text_file", { path: file, tail: 2, }); expect(textOf(result)).toBe("three\nfour"); }); describe("head line endings (#5187)", () => { async function head(content: string, n: number): Promise { const target = path.join(dir, "head.txt"); await fs.writeFile(target, content); return textOf( await call(client, "read_text_file", { path: target, head: n }), ); } it("returns the first lines of an LF file unchanged", async () => { expect(await head("a\nb\nc\n", 2)).toBe("a\nb"); }); it("returns the first lines of a CRLF file without their \\r", async () => { expect(await head("a\r\nb\r\nc\r\n", 2)).toBe("a\nb"); }); it("returns a CRLF file with no final newline normalized to LF", async () => { expect(await head("a\r\nb\r\nc", 5)).toBe("a\nb\nc"); }); // headFile reads 1 KB chunks from the start. Here the first chunk ends // on the "\r" of a "\r\n" pair whose "\n" opens the second chunk. it("joins a CRLF pair split across a chunk boundary", async () => { const content = "C".repeat(1023) + "\r\nnext\r\n"; expect(await head(content, 2)).toBe("C".repeat(1023) + "\nnext"); }); }); describe("tail at the end of the file (#5187)", () => { async function tail(content: string, n: number): Promise { const target = path.join(dir, "tail.txt"); await fs.writeFile(target, content); return textOf( await call(client, "read_text_file", { path: target, tail: n }), ); } it("returns the last line of an LF file that ends with a newline", async () => { expect(await tail("a\nb\nc\n", 1)).toBe("c"); }); it("returns the last lines of a CRLF file that ends with a newline", async () => { expect(await tail("a\r\nb\r\nc\r\n", 2)).toBe("b\nc"); }); it("returns the last lines of a file with no final newline unchanged", async () => { expect(await tail("a\nb\nc", 2)).toBe("b\nc"); }); it("counts a blank last line as a line", async () => { expect(await tail("a\nb\n\n", 2)).toBe("b\n"); }); it("returns the whole file when tail exceeds its line count", async () => { expect(await tail("a\nb\n", 5)).toBe("a\nb"); }); // tailFile reads 1 KB chunks from the end. Here the last chunk holds both // remaining newlines but starts partway through the first wanted line, so // the read loop must not count the final newline as a line break it needs. it("reads back past a chunk boundary for the first wanted line (LF)", async () => { const content = "head\n" + "A".repeat(611) + "\n" + "B".repeat(511) + "\n"; expect(await tail(content, 2)).toBe( "A".repeat(611) + "\n" + "B".repeat(511), ); }); it("reads back past a chunk boundary for the first wanted line (CRLF)", async () => { const content = "head\r\n" + "A".repeat(611) + "\r\n" + "B".repeat(510) + "\r\n"; expect(await tail(content, 2)).toBe( "A".repeat(611) + "\n" + "B".repeat(510), ); }); it("joins a CRLF pair split across a chunk boundary", async () => { // The last 1024 bytes start with the "\n" of the "\r\n" after "x". const content = "x\r\n" + "C".repeat(1021) + "\r\n"; expect(await tail(content, 2)).toBe("x\n" + "C".repeat(1021)); }); }); describe("a zero count (#5184)", () => { it.each(["head", "tail"])("%s: 0 returns no lines", async (key) => { const result = await call(client, "read_text_file", { path: file, [key]: 0, }); expect(result.isError).toBeFalsy(); expect(result.structuredContent).toEqual({ content: "" }); }); it.each(["head", "tail"])( "%s: 0 still reports a missing file", async (key) => { const result = await call(client, "read_text_file", { path: path.join(dir, "missing.txt"), [key]: 0, }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^ENOENT: no such file or directory/); }, ); it("rejects head: 0 and tail: 0 together", async () => { const result = await call(client, "read_text_file", { path: file, head: 0, tail: 0, }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( "Cannot specify both head and tail parameters simultaneously", ); }); it.each([ ["head", -1], ["tail", -1], ["head", 1.5], ["tail", 1.5], ])("rejects %s: %s as invalid input", async (key, value) => { for (const tool of ["read_text_file", "read_file"]) { const result = await call(client, tool, { path: file, [key]: value, }); expect(result.isError, tool).toBe(true); expect(textOf(result), tool).toMatch(/Input validation error/); } }); }); it("rejects head and tail together", async () => { const result = await call(client, "read_text_file", { path: file, head: 1, tail: 1, }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( "Cannot specify both head and tail parameters simultaneously", ); }); it("reports a missing file as a tool error naming ENOENT", async () => { const result = await call(client, "read_text_file", { path: path.join(dir, "missing.txt"), }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^ENOENT: no such file or directory/); }); it("reads an empty file with tail as empty text", async () => { const empty = path.join(dir, "empty.txt"); await fs.writeFile(empty, ""); const result = await call(client, "read_text_file", { path: empty, tail: 3, }); expect(textOf(result)).toBe(""); }); }); describe("read_media_file", () => { const cases: Array<[string, string, "image" | "audio"]> = [ ["a.png", "image/png", "image"], ["a.jpg", "image/jpeg", "image"], ["a.JPEG", "image/jpeg", "image"], ["a.gif", "image/gif", "image"], ["a.webp", "image/webp", "image"], ["a.bmp", "image/bmp", "image"], ["a.svg", "image/svg+xml", "image"], ["a.mp3", "audio/mpeg", "audio"], ["a.wav", "audio/wav", "audio"], ["a.ogg", "audio/ogg", "audio"], ["a.flac", "audio/flac", "audio"], ]; it.each(cases)( "returns %s as a %s %s block, round-tripping the bytes", async (name, mimeType, type) => { const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff]); await fs.writeFile(path.join(dir, name), bytes); const result = await call(client, "read_media_file", { path: path.join(dir, name), }); const block = { type, data: bytes.toString("base64"), mimeType }; expect(result).toEqual({ content: [block], structuredContent: { content: [block] }, }); }, ); it("returns any other file as an embedded resource with a pathToFileURL uri, never a blob block (#4029)", async () => { const bytes = Buffer.from([0x00, 0x01, 0xfe, 0xff]); const file = path.join(dir, "my café.bin"); await fs.writeFile(file, bytes); const result = await call(client, "read_media_file", { path: file }); const [block] = result.content; expect(block.type).toBe("resource"); if (block.type !== "resource") return; expect(block.resource.mimeType).toBe("application/octet-stream"); expect(block.resource.uri).toMatch(/^file:\/\/.*%20.*(%C3%A9|%CC%81)/); expect(fileURLToPath(block.resource.uri)).toBe(file); expect("blob" in block.resource && block.resource.blob).toBe( bytes.toString("base64"), ); expect(result.structuredContent).toEqual({ content: result.content }); }); it("reports a read failure (a directory) as a tool error", async () => { await fs.mkdir(path.join(dir, "folder.png")); const result = await call(client, "read_media_file", { path: path.join(dir, "folder.png"), }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^EISDIR/); }); }); describe("read_multiple_files", () => { it("joins each file's content with its path, and reports per-file failures inline", async () => { const a = path.join(dir, "a.txt"); const b = path.join(dir, "b.txt"); const missing = path.join(dir, "missing.txt"); await fs.writeFile(a, "alpha"); await fs.writeFile(b, "beta"); const result = await call(client, "read_multiple_files", { paths: [a, missing, b, "/etc/hostname"], }); expect(result.isError).toBeFalsy(); const text = textOf(result); const parts = text.split("\n---\n"); expect(parts).toHaveLength(4); expect(parts[0]).toBe(`${a}:\nalpha\n`); expect(parts[1]).toMatch( new RegExp( `^${missing.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}: Error - ENOENT`, ), ); expect(parts[2]).toBe(`${b}:\nbeta\n`); expect(parts[3]).toBe( `/etc/hostname: Error - Access denied - path outside allowed directories: ${path.resolve("/etc/hostname")} not in ${dir}`, ); }); it("reports a non-Error read failure by its string form", async () => { const a = path.join(dir, "a.txt"); await fs.writeFile(a, "alpha"); // The read goes through the descriptor the anchored open returned. vi.spyOn(fsSync, "readFile").mockImplementationOnce((( _fd: number, callback: (error: unknown) => void, ) => callback("disk on fire")) as typeof fsSync.readFile); const result = await call(client, "read_multiple_files", { paths: [a] }); expect(textOf(result)).toBe(`${a}: Error - disk on fire`); }); it("rejects an empty paths array at input validation", async () => { const result = await call(client, "read_multiple_files", { paths: [] }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/Input validation error/); }); }); describe("write_file", () => { it("creates a new file", async () => { const file = path.join(dir, "new.txt"); const result = await call(client, "write_file", { path: file, content: "hello", }); expect(result).toEqual({ content: [{ type: "text", text: `Successfully wrote to ${file}` }], structuredContent: { content: `Successfully wrote to ${file}` }, }); expect(await fs.readFile(file, "utf-8")).toBe("hello"); }); it("echoes the requested path, not the resolved one, in its message", async () => { const result = await call(client, "write_file", { path: "relative.txt", content: "x", }); expect(textOf(result)).toBe("Successfully wrote to relative.txt"); expect(await fs.readFile(path.join(dir, "relative.txt"), "utf-8")).toBe( "x", ); }); // #4512: an overwrite writes through the existing file rather than renaming // a temp file over it, so the file keeps its inode, its creation time and // its permission bits. it("keeps the inode, birthtime and permission bits on overwrite (#4512)", async () => { const file = path.join(dir, "existing.txt"); await fs.writeFile(file, "old"); await fs.chmod(file, 0o640); const before = await fs.stat(file); await call(client, "write_file", { path: file, content: "new" }); const after = await fs.stat(file); expect(await fs.readFile(file, "utf-8")).toBe("new"); expect(after.ino).toBe(before.ino); expect(after.birthtimeMs).toBe(before.birthtimeMs); // Windows has no POSIX mode bits: a writable file always reports 666. expect(after.mode & 0o777).toBe( process.platform === "win32" ? 0o666 : 0o640, ); }); it("keeps a hard link on overwrite (#4512)", async () => { const file = path.join(dir, "linked.txt"); const hardLink = path.join(dir, "hardlink.txt"); await fs.writeFile(file, "shared"); await fs.link(file, hardLink); await call(client, "write_file", { path: file, content: "changed" }); expect(await fs.readFile(hardLink, "utf-8")).toBe("changed"); }); // Writing in place opens the existing file for writing, so a read-only file // is refused rather than replaced; the old rename only got past the mode // bits because it rewrote the directory entry instead of the file. Root // ignores mode bits, so the refusal cannot be observed there. it.skipIf(process.getuid?.() === 0)( "refuses to overwrite a read-only file and leaves it unchanged", async () => { const file = path.join(dir, "readonly.txt"); await fs.writeFile(file, "keep me"); await fs.chmod(file, 0o444); try { const result = await call(client, "write_file", { path: file, content: "replaced", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/EACCES|EPERM/); expect(await fs.readFile(file, "utf-8")).toBe("keep me"); } finally { await fs.chmod(file, 0o644); } }, ); it("truncates the old content when the new content is shorter", async () => { const file = path.join(dir, "existing.txt"); await fs.writeFile(file, "a much longer original"); await call(client, "write_file", { path: file, content: "short" }); expect(await fs.readFile(file, "utf-8")).toBe("short"); }); it("writes through a symlink inside the allowed directory to its target", async () => { const target = path.join(dir, "target.txt"); const link = path.join(dir, "link.txt"); await fs.writeFile(target, "before"); await fs.symlink(target, link); await call(client, "write_file", { path: link, content: "after" }); expect(await fs.readFile(target, "utf-8")).toBe("after"); expect((await fs.lstat(link)).isSymbolicLink()).toBe(true); }); // #3199: on Windows a rename over a file another process holds open fails // with EPERM. An overwrite never renames, so such a rename failing does not // matter, and no temp file is left behind. The rename is mocked, so this runs // on every platform. it("overwrites without a rename, so a rename failing with EPERM does not matter (#3199)", async () => { const file = path.join(dir, "locked.txt"); await fs.writeFile(file, "original"); const rename = vi.spyOn(fs, "rename").mockRejectedValue( Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM", }), ); const result = await call(client, "write_file", { path: file, content: "replacement", }); expect(result.isError).toBeFalsy(); expect(await fs.readFile(file, "utf-8")).toBe("replacement"); expect(await fs.readdir(dir)).toEqual(["locked.txt"]); expect(rename).not.toHaveBeenCalled(); }); // The TOCTOU window: validation resolved the path to a regular file, then // something swapped what is at the path before the write opened it. The swap // is staged inside the server's own lstat call, so it lands in that window. describe("a path swapped after validation", () => { const swapAfterLstat = (swap: () => Promise) => { const realLstat = fs.lstat.bind(fs); vi.spyOn(fs, "lstat").mockImplementationOnce(async (p, opts) => { const stats = await realLstat(p, opts); await swap(); return stats; }); }; it.skipIf(process.platform === "win32")( "refuses to write through a symlink swapped in", async () => { const file = path.join(dir, "victim.txt"); const outside = await makeTempDir("mcp-fs-outside-"); const secret = path.join(outside, "secret.txt"); await fs.writeFile(file, "original"); await fs.writeFile(secret, "SECRET"); try { swapAfterLstat(async () => { await fs.unlink(file); await fs.symlink(secret, file); }); const result = await call(client, "write_file", { path: file, content: "pwned", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^ELOOP/); expect(await fs.readFile(secret, "utf-8")).toBe("SECRET"); } finally { await fs.rm(outside, { recursive: true, force: true }); } }, ); it("refuses to write to a different file swapped in", async () => { const file = path.join(dir, "victim.txt"); const other = path.join(dir, "other.txt"); await fs.writeFile(file, "original"); await fs.writeFile(other, "other"); swapAfterLstat(() => fs.rename(other, file)); const result = await call(client, "write_file", { path: file, content: "replacement", }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Refusing to write: ${file} was replaced while it was being opened`, ); expect(await fs.readFile(file, "utf-8")).toBe("other"); }); }); it("refuses to overwrite a directory", async () => { const sub = path.join(dir, "sub"); await fs.mkdir(sub); const result = await call(client, "write_file", { path: sub, content: "x", }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Refusing to write: not a regular file: ${sub}`, ); }); it("reports a create failure other than EEXIST as is", async () => { vi.spyOn(fsSync, "openSync").mockImplementationOnce(() => { throw Object.assign(new Error("EIO: i/o error"), { code: "EIO" }); }); const result = await call(client, "write_file", { path: path.join(dir, "new.txt"), content: "x", }); expect(textOf(result)).toBe("EIO: i/o error"); }); it("reports a missing parent directory (#5432)", async () => { const result = await call(client, "write_file", { path: path.join(dir, "no", "such", "file.txt"), content: "x", }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Parent directory does not exist: ${path.join(dir, "no", "such")}`, ); }); }); describe("edit_file", () => { let file: string; beforeEach(async () => { file = path.join(dir, "code.ts"); await fs.writeFile( file, "function greet() {\n console.log('hi');\n return 1;\n}\n", ); }); it("applies an exact edit and returns a fenced unified diff", async () => { const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return 2;" }], }); expect(textOf(result)).toBe( "```diff\n" + `Index: ${file}\n` + "===================================================================\n" + `--- ${file}\toriginal\n` + `+++ ${file}\tmodified\n` + "@@ -1,4 +1,4 @@\n" + " function greet() {\n" + " console.log('hi');\n" + "- return 1;\n" + "+ return 2;\n" + " }\n" + "```\n\n", ); expect(await fs.readFile(file, "utf-8")).toContain("return 2;"); }); it("leaves the file alone on a dry run", async () => { const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return 2;" }], dryRun: true, }); expect(textOf(result)).toContain("+ return 2;"); expect(await fs.readFile(file, "utf-8")).toContain("return 1;"); }); it("applies several edits in order, each against the previous result", async () => { await call(client, "edit_file", { path: file, edits: [ { oldText: "return 1;", newText: "return 2;" }, { oldText: "return 2;", newText: "return 3;" }, ], }); expect(await fs.readFile(file, "utf-8")).toContain("return 3;"); }); it("replaces only the first occurrence of an exact match", async () => { await fs.writeFile(file, "x\nx\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "x", newText: "y" }], }); expect(await fs.readFile(file, "utf-8")).toBe("y\nx\n"); }); it("inserts $ patterns in newText literally", async () => { await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return '$&$1$$';" }], }); expect(await fs.readFile(file, "utf-8")).toContain("return '$&$1$$';"); }); it("reports an edit with no match, quoting its oldText", async () => { const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "return 9;", newText: "x" }], }); expect(result.isError).toBe(true); // #2034: the error also quotes the closest lines of the file. expect(textOf(result)).toMatch( /^Could not find exact match for edit 1 of 1\. [^]*\n\noldText:\nreturn 9;\n\nClosest text in the file \(lines 1-4 of 4\):\n[^]*3: {3}return 1;\n/, ); }); it("widens the diff fence when the diff itself contains backticks", async () => { await fs.writeFile(file, "a\n"); const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "a", newText: "````" }], }); const text = textOf(result); expect(text.startsWith("`````diff\n")).toBe(true); expect(text.endsWith("`````\n\n")).toBe(true); }); // #4991: an edit keeps the file's line endings, whatever oldText and // newText use. it("keeps a CRLF file's line endings", async () => { await fs.writeFile(file, "a\r\nb\r\n"); await call(client, "edit_file", { path: file, edits: [ { oldText: "a\r\n", newText: "c\r\n" }, { oldText: "b\n", newText: "d\ne\n" }, ], }); expect(await fs.readFile(file, "utf-8")).toBe("c\r\nd\r\ne\r\n"); }); it("keeps an LF file's line endings when newText uses CRLF", async () => { await fs.writeFile(file, "a\nb\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "a", newText: "c\r\nd" }], }); expect(await fs.readFile(file, "utf-8")).toBe("c\nd\nb\n"); }); // #2034: when there is no exact substring, the matcher compares line by line // with leading and trailing whitespace trimmed, and reindents the // replacement (#4990): each replacement line takes the indentation of the // file line it replaces, shifted by its indent relative to the matching // oldText line. describe("whitespace-tolerant matcher (#2034)", () => { it("matches lines whose indentation differs from oldText", async () => { await call(client, "edit_file", { path: file, edits: [ { oldText: "console.log('hi');\nreturn 1;", newText: "console.log('bye');\nreturn 0;", }, ], }); // Every line takes the indentation of the file line it replaces. expect(await fs.readFile(file, "utf-8")).toBe( "function greet() {\n console.log('bye');\n return 0;\n}\n", ); }); it("keeps relative indentation when both old and new lines are indented", async () => { await fs.writeFile(file, " if (a) {\n b();\n }\n"); await call(client, "edit_file", { path: file, edits: [ { oldText: "if (a) {\n b();\n}", newText: "if (a) {\n c();\n }", }, ], }); // Line 2: the file's 8, plus new indent 6 - old indent 2 = 4 more. // Line 3: the file's 4, plus new indent 2 - old indent 0 = 2 more. expect(await fs.readFile(file, "utf-8")).toBe( " if (a) {\n c();\n }\n", ); }); it("dedents a tab-indented file by levels when the edit indents with spaces", async () => { await fs.writeFile(file, "\tif (a) {\n\t\tb();\n\t}\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: " b();", newText: " c();" }], }); // The edit dedents b() by one 2-space level; in the file that is one // tab, not two characters (which would strip both tabs). expect(await fs.readFile(file, "utf-8")).toBe( "\tif (a) {\n\tc();\n\t}\n", ); }); it("indents a tab-indented file by levels when the edit indents with spaces", async () => { await fs.writeFile(file, "\tif (a) {\n\t\tb();\n\t}\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "if (a) {\n b();", newText: "if (a) {\n c();" }], }); expect(await fs.readFile(file, "utf-8")).toBe( "\tif (a) {\n\t\t\tc();\n\t}\n", ); }); it("indents a space-indented file by levels when the edit indents with tabs", async () => { await fs.writeFile(file, " if (a) {\n b();\n }\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "if (a) {\n\tb();", newText: "if (a) {\n\t\tc();" }], }); expect(await fs.readFile(file, "utf-8")).toBe( " if (a) {\n c();\n }\n", ); }); it("keeps the file's indentation when oldText indents with a different width", async () => { await fs.writeFile(file, " if (a) {\n b();\n }\n"); await call(client, "edit_file", { path: file, edits: [ { oldText: "if (a) {\n b();\n}", newText: "if (a) {\n c();\n}", }, ], }); expect(await fs.readFile(file, "utf-8")).toBe( " if (a) {\n c();\n }\n", ); }); it("dedents relative to the file line it replaces", async () => { await fs.writeFile(file, " x\n y\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "x\n y", newText: "x\n z" }], }); // Line 2: the file's 6, minus old indent 4 - new indent 1 = 3. expect(await fs.readFile(file, "utf-8")).toBe(" x\n z\n"); }); it("clamps a dedent at no indentation", async () => { await fs.writeFile(file, "x\n y\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "x\n y", newText: "x\nz" }], }); expect(await fs.readFile(file, "utf-8")).toBe("x\nz\n"); }); it("indents replacement lines beyond oldText's length relative to its last line", async () => { await fs.writeFile(file, " a\nb\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "a ", newText: "a\n added" }], }); expect(await fs.readFile(file, "utf-8")).toBe(" a\n added\nb\n"); }); it("keeps a blank replacement line as given", async () => { await fs.writeFile(file, " a\n b\n"); await call(client, "edit_file", { path: file, edits: [{ oldText: "a\nb", newText: "a\n\nb" }], }); expect(await fs.readFile(file, "utf-8")).toBe(" a\n\n b\n"); }); it("reports no match when a line differs beyond whitespace", async () => { const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "console.log('hi');\nreturn 2;", newText: "x" }], }); expect(result.isError).toBe(true); }); }); it("keeps the inode, birthtime and permission bits on edit (#4512)", async () => { await fs.chmod(file, 0o600); const before = await fs.stat(file); await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return 2;" }], }); const after = await fs.stat(file); expect(await fs.readFile(file, "utf-8")).toContain("return 2;"); expect(after.ino).toBe(before.ino); expect(after.birthtimeMs).toBe(before.birthtimeMs); // Windows has no POSIX mode bits: a writable file always reports 666. expect(after.mode & 0o777).toBe( process.platform === "win32" ? 0o666 : 0o600, ); }); it("keeps a hard link on edit (#4512)", async () => { const hardLink = path.join(dir, "hardlink.ts"); await fs.link(file, hardLink); await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return 2;" }], }); expect(await fs.readFile(hardLink, "utf-8")).toContain("return 2;"); }); it("edits without a rename, so a rename failing with EPERM does not matter (#3199)", async () => { const rename = vi .spyOn(fs, "rename") .mockRejectedValue(new Error("EPERM rename")); const result = await call(client, "edit_file", { path: file, edits: [{ oldText: "return 1;", newText: "return 2;" }], }); expect(result.isError).toBeFalsy(); expect(await fs.readFile(file, "utf-8")).toContain("return 2;"); expect(await fs.readdir(dir)).toEqual(["code.ts"]); expect(rename).not.toHaveBeenCalled(); }); }); describe("create_directory", () => { it("creates nested directories in one call (#4629)", async () => { const target = path.join(dir, "a", "b", "c"); const result = await call(client, "create_directory", { path: target }); expect(textOf(result)).toBe(`Successfully created directory ${target}`); expect((await fs.stat(target)).isDirectory()).toBe(true); }); it("succeeds on an existing directory", async () => { const result = await call(client, "create_directory", { path: dir }); expect(result.isError).toBeFalsy(); }); it("reports an existing file in the way", async () => { await fs.writeFile(path.join(dir, "file"), ""); const result = await call(client, "create_directory", { path: path.join(dir, "file"), }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^EEXIST/); }); }); describe("list_directory", () => { it("lists entries with [DIR] and [FILE] prefixes", async () => { await fs.mkdir(path.join(dir, "sub")); await fs.writeFile(path.join(dir, "f.txt"), ""); const result = await call(client, "list_directory", { path: dir }); expect(textOf(result).split("\n").sort()).toEqual([ "[DIR] sub", "[FILE] f.txt", ]); }); it("returns empty text for an empty directory", async () => { const result = await call(client, "list_directory", { path: dir }); expect(textOf(result)).toBe(""); }); it("reports a file path as ENOTDIR", async () => { await fs.writeFile(path.join(dir, "f.txt"), ""); const result = await call(client, "list_directory", { path: path.join(dir, "f.txt"), }); expect(textOf(result)).toMatch(/^ENOTDIR/); }); }); describe("list_directory_with_sizes", () => { beforeEach(async () => { await fs.writeFile(path.join(dir, "b.txt"), "x".repeat(2048)); await fs.writeFile(path.join(dir, "a.txt"), "xy"); await fs.mkdir(path.join(dir, "c")); }); it("sorts by name by default and appends a summary", async () => { const result = await call(client, "list_directory_with_sizes", { path: dir, }); expect(textOf(result)).toBe( [ `[FILE] ${"a.txt".padEnd(30)} ${"2 B".padStart(10)}`, `[FILE] ${"b.txt".padEnd(30)} ${"2.00 KB".padStart(10)}`, `[DIR] ${"c".padEnd(30)} `, "", "Total: 2 files, 1 directories", "Combined size: 2.00 KB", ].join("\n"), ); }); it("sorts by size, largest first, when asked", async () => { const result = await call(client, "list_directory_with_sizes", { path: dir, sortBy: "size", }); // Directories sort by their own stat size, which the listing does not // show and which varies by file system, so only the files are compared. const files = textOf(result) .split("\n") .filter((line) => line.startsWith("[FILE]")) .map((line) => line.split(/\s+/)[1]); expect(files).toEqual(["b.txt", "a.txt"]); }); it("lists an entry it cannot stat (a dangling symlink) as unknown size, left out of the total (#5190)", async () => { await fs.symlink(path.join(dir, "gone"), path.join(dir, "dangling")); const result = await call(client, "list_directory_with_sizes", { path: dir, }); expect(textOf(result)).toContain( `[FILE] ${"dangling".padEnd(30)} ${"unknown".padStart(10)}`, ); expect(textOf(result)).not.toContain(" 0 B"); expect(textOf(result)).toContain("Total: 3 files, 1 directories"); expect(textOf(result)).toContain( "Combined size: 2.00 KB (excludes 1 file of unknown size)", ); }); it("sorts entries of unknown size last when sorting by size (#5190)", async () => { await fs.symlink(path.join(dir, "gone"), path.join(dir, "dangling")); await fs.symlink(path.join(dir, "gone2"), path.join(dir, "dangling2")); await fs.writeFile(path.join(dir, "empty.txt"), ""); const result = await call(client, "list_directory_with_sizes", { path: dir, sortBy: "size", }); const files = textOf(result) .split("\n") .filter((line) => line.startsWith("[FILE]")) .map((line) => line.split(/\s+/)[1]); expect(files.slice(0, 3)).toEqual(["b.txt", "a.txt", "empty.txt"]); expect(files.slice(3).sort()).toEqual(["dangling", "dangling2"]); expect(textOf(result)).toContain( "Combined size: 2.00 KB (excludes 2 files of unknown size)", ); }); it("does not report the size of a symlink target outside the allowed directories", async () => { const outside = await makeTempDir("mcp-fs-tools-outside-"); try { await fs.writeFile(path.join(outside, "secret.bin"), "x".repeat(1536)); await fs.symlink( path.join(outside, "secret.bin"), path.join(dir, "link-out"), ); const result = await call(client, "list_directory_with_sizes", { path: dir, }); expect(textOf(result)).toContain( `[FILE] ${"link-out".padEnd(30)} ${"unknown".padStart(10)}`, ); expect(textOf(result)).not.toContain("1.50 KB"); expect(textOf(result)).toContain( "Combined size: 2.00 KB (excludes 1 file of unknown size)", ); } finally { await fs.rm(outside, { recursive: true, force: true }); } }); it("reports the size of a symlink target inside the allowed directories", async () => { await fs.symlink(path.join(dir, "b.txt"), path.join(dir, "link-in")); const result = await call(client, "list_directory_with_sizes", { path: dir, }); expect(textOf(result)).toContain( `[FILE] ${"link-in".padEnd(30)} ${"2.00 KB".padStart(10)}`, ); }); it("summarizes an empty directory", async () => { const empty = path.join(dir, "c"); const result = await call(client, "list_directory_with_sizes", { path: empty, }); expect(textOf(result)).toBe( "\nTotal: 0 files, 0 directories\nCombined size: 0 B", ); }); }); describe("directory_tree", () => { beforeEach(async () => { await fs.mkdir(path.join(dir, "src")); await fs.mkdir(path.join(dir, "node_modules")); await fs.mkdir(path.join(dir, ".git")); await fs.mkdir(path.join(dir, "nested", "node_modules"), { recursive: true, }); await fs.writeFile(path.join(dir, ".env"), ""); await fs.writeFile(path.join(dir, ".env.local"), ""); await fs.writeFile(path.join(dir, "src", "index.js"), ""); await fs.writeFile(path.join(dir, "package.json"), "{}"); await fs.writeFile(path.join(dir, "node_modules", "m.js"), ""); await fs.writeFile(path.join(dir, "nested", "node_modules", "d.js"), ""); }); async function tree( excludePatterns?: string[], root: string = dir, ): Promise { const result = await call(client, "directory_tree", { path: root, ...(excludePatterns ? { excludePatterns } : {}), }); return sortTree(JSON.parse(textOf(result)) as TreeEntry[]); } it("returns the whole tree as 2-space-indented JSON; directories always carry children", async () => { const result = await call(client, "directory_tree", { path: path.join(dir, "src"), }); expect(textOf(result)).toBe( '[\n {\n "name": "index.js",\n "type": "file"\n }\n]', ); expect(await tree()).toEqual([ { name: ".env", type: "file" }, { name: ".env.local", type: "file" }, { name: ".git", type: "directory", children: [] }, { name: "nested", type: "directory", children: [ { name: "node_modules", type: "directory", children: [{ name: "d.js", type: "file" }], }, ], }, { name: "node_modules", type: "directory", children: [{ name: "m.js", type: "file" }], }, { name: "package.json", type: "file" }, { name: "src", type: "directory", children: [{ name: "index.js", type: "file" }], }, ]); }); it("excludes a bare name at any depth, and not its prefix matches", async () => { const names = (await tree(["node_modules", ".env"])).map((e) => e.name); expect(names).toEqual([ ".env.local", ".git", "nested", "package.json", "src", ]); const nested = (await tree(["node_modules"])).find( (e) => e.name === "nested", ); expect(nested?.children).toEqual([]); }); it("matches a glob pattern against the relative path only", async () => { const names = (await tree(["*.env"])).map((e) => e.name); expect(names).not.toContain(".env"); expect(names).toContain(".env.local"); const deep = await tree(["*.js"]); // "*.js" does not cross a separator, so nested files stay. expect(deep.find((e) => e.name === "src")?.children).toEqual([ { name: "index.js", type: "file" }, ]); }); it("lists a symlinked directory as a file and does not descend into it", async () => { await fs.symlink(path.join(dir, "src"), path.join(dir, "srclink")); const entry = (await tree()).find((e) => e.name === "srclink"); expect(entry).toEqual({ name: "srclink", type: "file" }); }); it("refuses a root outside the allowed directories", async () => { const result = await call(client, "directory_tree", { path: "/" }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); }); }); describe("move_file", () => { it("moves a file and reports the requested paths", async () => { const source = path.join(dir, "a.txt"); const destination = path.join(dir, "b.txt"); await fs.writeFile(source, "a"); const result = await call(client, "move_file", { source, destination }); expect(textOf(result)).toBe( `Successfully moved ${source} to ${destination}`, ); expect(await fs.readFile(destination, "utf-8")).toBe("a"); await expect(fs.stat(source)).rejects.toThrow(); }); it("moves a directory", async () => { await fs.mkdir(path.join(dir, "d1")); await fs.writeFile(path.join(dir, "d1", "f"), "x"); await call(client, "move_file", { source: path.join(dir, "d1"), destination: path.join(dir, "d2"), }); expect(await fs.readFile(path.join(dir, "d2", "f"), "utf-8")).toBe("x"); }); it("refuses to overwrite an existing destination", async () => { await fs.writeFile(path.join(dir, "a.txt"), "a"); await fs.writeFile(path.join(dir, "b.txt"), "b"); const result = await call(client, "move_file", { source: path.join(dir, "a.txt"), destination: path.join(dir, "b.txt"), }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Destination already exists: ${path.join(dir, "b.txt")}`, ); expect(await fs.readFile(path.join(dir, "b.txt"), "utf-8")).toBe("b"); }); it("refuses a destination outside the allowed directories", async () => { await fs.writeFile(path.join(dir, "a.txt"), "a"); const result = await call(client, "move_file", { source: path.join(dir, "a.txt"), destination: "/tmp-outside-allowed/a.txt", }); expect(textOf(result)).toMatch(/^Access denied/); }); it("reports a missing source as ENOENT", async () => { const result = await call(client, "move_file", { source: path.join(dir, "missing"), destination: path.join(dir, "b"), }); expect(textOf(result)).toMatch(/^ENOENT/); }); // #5188: rename cannot cross a device boundary. A second mount cannot be // staged in a test, so the rename is made to fail as it would across one. describe("across filesystems (rename fails with EXDEV)", () => { const crossDevice = () => vi.spyOn(fsSync, "renameSync").mockImplementation(() => { throw Object.assign( new Error("EXDEV: cross-device link not permitted"), { code: "EXDEV", }, ); }); it("moves a file by copying it and removing the source", async () => { const source = path.join(dir, "a.txt"); const destination = path.join(dir, "sub", "b.txt"); await fs.mkdir(path.join(dir, "sub")); await fs.writeFile(source, "across"); const rename = crossDevice(); const result = await call(client, "move_file", { source, destination }); expect(rename).toHaveBeenCalled(); expect(result.isError).toBeFalsy(); expect(textOf(result)).toBe( `Successfully moved ${source} to ${destination}`, ); expect(await fs.readFile(destination, "utf-8")).toBe("across"); await expect(fs.stat(source)).rejects.toThrow(); }); it("refuses a directory with a clear error, and leaves it in place", async () => { const source = path.join(dir, "d1"); await fs.mkdir(source); await fs.writeFile(path.join(source, "f"), "x"); crossDevice(); const result = await call(client, "move_file", { source, destination: path.join(dir, "d2"), }); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Cannot move a directory across filesystems: ${source}. ` + "Create the directory at the destination and move its files one at a time.", ); expect(await fs.readFile(path.join(source, "f"), "utf-8")).toBe("x"); await expect(fs.stat(path.join(dir, "d2"))).rejects.toThrow(); }); it("leaves no partial destination when the copy fails", async () => { const source = path.join(dir, "a.txt"); await fs.writeFile(source, "keep"); crossDevice(); vi.spyOn(fsSync, "read").mockImplementationOnce(((...args: unknown[]) => { (args[args.length - 1] as (error: Error) => void)( Object.assign(new Error("EIO: i/o error, read"), { code: "EIO" }), ); }) as typeof fsSync.read); const result = await call(client, "move_file", { source, destination: path.join(dir, "b.txt"), }); expect(textOf(result)).toBe("EIO: i/o error, read"); expect(await fs.readdir(dir)).toEqual(["a.txt"]); expect(await fs.readFile(source, "utf-8")).toBe("keep"); }); }); it("reports a destination lstat failure other than ENOENT as is", async () => { await fs.writeFile(path.join(dir, "a.txt"), "a"); vi.spyOn(fs, "lstat").mockRejectedValueOnce(new Error("EACCES lstat")); const result = await call(client, "move_file", { source: path.join(dir, "a.txt"), destination: path.join(dir, "b.txt"), }); expect(textOf(result)).toBe("EACCES lstat"); }); }); // The TOCTOU window one level up: validation resolved every directory on the // path to a real one inside the allowed directory, then something replaced one // of them with a symlink to a directory outside it before the operation ran. // The kernel follows that symlink at use, so the operation would land outside. // The swap is staged right after validation's realpath of the given path, so // it lands in that window. describe.skipIf(process.platform === "win32")( "a directory on the path swapped for a symlink after validation", () => { let outside: string; let flip: string; let flipReal: string; beforeEach(async () => { outside = await makeTempDir("mcp-fs-outside-"); flip = path.join(dir, "flip"); flipReal = path.join(dir, "flip-real"); await fs.mkdir(flip); }); afterEach(async () => { await fs.rm(outside, { recursive: true, force: true }); }); // flip → a symlink to `outside`, keeping the real directory aside, and // back again. Synchronous, so it can run inside a synchronous call. const swapOut = () => { fsSync.renameSync(flip, flipReal); fsSync.symlinkSync(outside, flip); }; const swapBack = () => { fsSync.unlinkSync(flip); fsSync.renameSync(flipReal, flip); }; /** Swap `flip` out once validation has realpath'd `target`. */ const swapAfterRealpath = (target: string) => { const realRealpath = fs.realpath.bind(fs); let swapped = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); if (!swapped && p === target) { swapped = true; swapOut(); } return resolved; }); }; /** * Swap `flip` back the moment the operation reaches for it again: after * the process enters it, or before anything re-resolves it by path. A * racer that toggles the swap needs only "swapped at use, restored at * the check". */ const swapBackAtUse = () => { let restored = false; const realChdir = process.chdir.bind(process); vi.spyOn(process, "chdir").mockImplementation((directory) => { realChdir(directory); if (!restored && directory === flip) { restored = true; swapBack(); } }); const realRealpath = fs.realpath; const spy = vi.mocked(fs.realpath); const swapAt = spy.getMockImplementation() ?? realRealpath; spy.mockImplementation(async (p, opts) => { if (!restored && p === flip && fsSync.existsSync(flipReal)) { restored = true; swapBack(); } return swapAt(p, opts); }); }; it("write_file refuses to create a file through it", async () => { swapAfterRealpath(flip); const result = await call(client, "write_file", { path: path.join(flip, "created.txt"), content: "pwned", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readdir(outside)).toEqual([]); }); it("write_file refuses to create a file through it, swapped back before the check", async () => { swapAfterRealpath(flip); swapBackAtUse(); const result = await call(client, "write_file", { path: path.join(flip, "created.txt"), content: "pwned", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readdir(outside)).toEqual([]); }); it("write_file refuses to overwrite a file through it", async () => { const victim = path.join(flip, "victim.txt"); await fs.writeFile(victim, "original"); await fs.writeFile(path.join(outside, "victim.txt"), "SECRET"); swapAfterRealpath(victim); const result = await call(client, "write_file", { path: victim, content: "pwned", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe( "SECRET", ); }); it.each(["write_file", "edit_file"])( "%s refuses to overwrite a file through it, swapped back before the check", async (tool) => { const victim = path.join(flip, "victim.txt"); await fs.writeFile(victim, "original"); await fs.writeFile(path.join(outside, "victim.txt"), "original"); swapAfterRealpath(victim); swapBackAtUse(); const result = await call( client, tool, tool === "write_file" ? { path: victim, content: "pwned" } : { path: victim, edits: [{ oldText: "original", newText: "pwned" }], }, ); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect( await fs.readFile(path.join(outside, "victim.txt"), "utf-8"), ).toBe("original"); }, ); it("edit_file refuses to write a file through it", async () => { const victim = path.join(flip, "victim.txt"); await fs.writeFile(victim, "original"); await fs.writeFile(path.join(outside, "victim.txt"), "original"); swapAfterRealpath(victim); const result = await call(client, "edit_file", { path: victim, edits: [{ oldText: "original", newText: "pwned" }], }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe( "original", ); }); it("create_directory refuses to create a directory through it", async () => { swapAfterRealpath(flip); const result = await call(client, "create_directory", { path: path.join(flip, "a", "b"), }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readdir(outside)).toEqual([]); }); it("move_file refuses to move a file through it", async () => { const source = path.join(dir, "sensitive.txt"); await fs.writeFile(source, "SECRET"); swapAfterRealpath(flip); const result = await call(client, "move_file", { source, destination: path.join(flip, "moved.txt"), }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readdir(outside)).toEqual([]); expect(await fs.readFile(source, "utf-8")).toBe("SECRET"); }); it("a write that entered the real directory stays in it when the path is swapped afterwards", async () => { // The directory is genuine when the process enters it and is checked, // and swapped only before the open: the open acts on the directory // entered, not on what the path now resolves to. const realOpenSync = fsSync.openSync.bind(fsSync); vi.spyOn(fsSync, "openSync").mockImplementationOnce( (file, flags, mode) => { swapOut(); return realOpenSync(file, flags, mode); }, ); const result = await call(client, "write_file", { path: path.join(flip, "created.txt"), content: "data", }); expect(result.isError).toBeFalsy(); expect(await fs.readdir(outside)).toEqual([]); expect( await fs.readFile(path.join(flipReal, "created.txt"), "utf-8"), ).toBe("data"); }); // A refused operation must not act on any path again: a second swap can // redirect anything that does. Here flip points at the in-tree `other`, // and `other` is swapped for a symlink to `outside` as soon as anything // looks at the entry the operation would have left in it. describe("a refusal acts on nothing outside", () => { let other: string; beforeEach(async () => { other = path.join(dir, "other"); await fs.mkdir(other); }); const redirectAfterLookingAt = (entry: string) => { fsSync.rmSync(flip, { recursive: true }); fsSync.symlinkSync(other, flip); const realLstat = fs.lstat.bind(fs); vi.spyOn(fs, "lstat").mockImplementation(async (p, opts) => { const stats = await realLstat(p, opts); if (p === entry) { fsSync.renameSync(other, `${other}-moved`); fsSync.symlinkSync(outside, other); } return stats; }); }; it("write_file deletes no file outside", async () => { await fs.writeFile(path.join(outside, "created.txt"), "USER DATA"); // Validated while flip is real; swapped once validation is done. const realRealpath = fs.realpath.bind(fs); let armed = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); if (!armed && p === flip) { armed = true; redirectAfterLookingAt(path.join(other, "created.txt")); } return resolved; }); const result = await call(client, "write_file", { path: path.join(flip, "created.txt"), content: "x", }); expect(result.isError).toBe(true); expect( await fs.readFile(path.join(outside, "created.txt"), "utf-8"), ).toBe("USER DATA"); }); it("create_directory removes no directory outside", async () => { // Round 1 removed what a refused mkdir -p had created with rmdir by // path; a second swap pointed that at empty directories outside. await fs.mkdir(path.join(outside, "a", "b"), { recursive: true }); const realRmdir = fs.rmdir.bind(fs); const rmdir = vi .spyOn(fs, "rmdir") .mockImplementation(async (p, opts) => { if (fsSync.lstatSync(flip).isSymbolicLink()) { fsSync.unlinkSync(flip); fsSync.symlinkSync(outside, flip); } return realRmdir(p, opts); }); const realRealpath = fs.realpath.bind(fs); let armed = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); if (!armed && p === flip) { armed = true; fsSync.rmSync(flip, { recursive: true }); fsSync.symlinkSync(other, flip); } return resolved; }); const result = await call(client, "create_directory", { path: path.join(flip, "a", "b"), }); expect(result.isError).toBe(true); expect(rmdir).not.toHaveBeenCalled(); expect( (await fs.stat(path.join(outside, "a", "b"))).isDirectory(), ).toBe(true); expect(await fs.readdir(other)).toEqual([]); }); it("move_file moves no file in from outside", async () => { const source = path.join(dir, "mine.txt"); await fs.writeFile(source, "MINE"); await fs.writeFile(path.join(outside, "moved.txt"), "OUTSIDE SECRET"); const realRealpath = fs.realpath.bind(fs); let armed = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); if (!armed && p === flip) { armed = true; redirectAfterLookingAt(path.join(other, "moved.txt")); } return resolved; }); const result = await call(client, "move_file", { source, destination: path.join(flip, "moved.txt"), }); expect(result.isError).toBe(true); expect( await fs.readFile(path.join(outside, "moved.txt"), "utf-8"), ).toBe("OUTSIDE SECRET"); expect(await fs.readFile(source, "utf-8")).toBe("MINE"); }); }); }, ); // A case-insensitive volume (the macOS default, and Windows) finds `Docs` when // asked for `docs`. The write operations compare where they really are with // the path validation returned, so validation must return the directory's // on-disk spelling, or every such request is refused. describe("a directory requested in another case", () => { let caseInsensitive: boolean; beforeEach(async () => { await fs.mkdir(path.join(dir, "Docs")); caseInsensitive = fsSync.existsSync(path.join(dir, "docs")); }); it("write_file creates a file in it", async ({ skip }) => { if (!caseInsensitive) skip(); const result = await call(client, "write_file", { path: path.join(dir, "docs", "new.txt"), content: "hello", }); expect(result.isError).toBeFalsy(); expect(await fs.readFile(path.join(dir, "Docs", "new.txt"), "utf-8")).toBe( "hello", ); }); it("create_directory creates a directory in it", async ({ skip }) => { if (!caseInsensitive) skip(); const result = await call(client, "create_directory", { path: path.join(dir, "docs", "sub"), }); expect(result.isError).toBeFalsy(); expect((await fs.stat(path.join(dir, "Docs", "sub"))).isDirectory()).toBe( true, ); }); it("move_file moves a file into it", async ({ skip }) => { if (!caseInsensitive) skip(); await fs.writeFile(path.join(dir, "Docs", "f.txt"), "f"); const result = await call(client, "move_file", { source: path.join(dir, "Docs", "f.txt"), destination: path.join(dir, "docs", "g.txt"), }); expect(result.isError).toBeFalsy(); expect(await fs.readFile(path.join(dir, "Docs", "g.txt"), "utf-8")).toBe( "f", ); }); }); // Every anchored write borrows the process's working directory; concurrent // requests must neither see one another's nor leave it changed. describe("concurrent writes", () => { it("land in their own directories and leave the working directory as it was", async () => { const before = process.cwd(); const targets = await Promise.all( Array.from({ length: 8 }, async (_, i) => { const sub = path.join(dir, `d${i}`); await fs.mkdir(sub); return path.join(sub, "f.txt"); }), ); const results = await Promise.all([ ...targets.map((target, i) => call(client, "write_file", { path: target, content: `content ${i}` }), ), ...targets.map((target) => call(client, "create_directory", { path: path.join(path.dirname(target), "x", "y"), }), ), ]); expect(results.every((result) => !result.isError)).toBe(true); for (const [i, target] of targets.entries()) { expect(await fs.readFile(target, "utf-8")).toBe(`content ${i}`); expect( ( await fs.stat(path.join(path.dirname(target), "x", "y")) ).isDirectory(), ).toBe(true); } expect(process.cwd()).toBe(before); }); }); // Names that differ only in Unicode normalization. On a filesystem that // compares names byte for byte (Linux), café in NFC and in NFD are two // directories, so the anchor must not fold one into the other; and a // directory whose on-disk name is NFD must still be writable. describe("directories whose names differ only in normalization", () => { const nfc = "caf\u00e9"; const nfd = "cafe\u0301"; it("write_file writes into a directory whose on-disk name is NFD", async () => { const root = path.join(dir, nfd); await fs.mkdir(path.join(root, "x"), { recursive: true }); const nfdConn = await connect([root]); try { const target = path.join(root, "x", "new.txt"); const result = await call(nfdConn.client, "write_file", { path: target, content: "hello", }); expect(result.isError).toBeFalsy(); expect(await fs.readFile(target, "utf-8")).toBe("hello"); } finally { await nfdConn.close(); } }); it("write_file refuses a directory swapped for a symlink to its NFD twin", async ({ skip, }) => { if (process.platform === "win32") skip(); const allowed = path.join(dir, nfc, "proj"); const twin = path.join(dir, nfd, "proj"); await fs.mkdir(path.join(allowed, "x"), { recursive: true }); await fs.mkdir(path.join(twin, "x"), { recursive: true }); // Only a filesystem that keeps both names can hold the twin (Linux). if ((await fs.readdir(dir)).length !== 2) skip(); const twinConn = await connect([allowed]); try { const x = path.join(allowed, "x"); const realRealpath = fs.realpath.bind(fs); let swapped = false; vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => { const resolved = await realRealpath(p, opts); if (!swapped && p === x) { swapped = true; fsSync.rmSync(x, { recursive: true }); fsSync.symlinkSync(path.join(twin, "x"), x); } return resolved; }); const result = await call(twinConn.client, "write_file", { path: path.join(x, "new.txt"), content: "pwned", }); expect(result.isError).toBe(true); expect(textOf(result)).toMatch(/^Access denied/); expect(await fs.readdir(path.join(twin, "x"))).toEqual([]); } finally { await twinConn.close(); } }); }); // An allowed directory spelled through the macOS Data-volume firmlink // (/System/Volumes/Data/private/...): realpath keeps that spelling while // getcwd reports /private/..., and the two name the same directory. describe("an allowed directory spelled through the Data-volume firmlink", () => { it("accepts writes, nested writes and nested directories", async ({ skip, }) => { const spelled = `/System/Volumes/Data${dir}`; if (process.platform !== "darwin" || !fsSync.existsSync(spelled)) skip(); await fs.mkdir(path.join(dir, "Sub")); const firmConn = await connect([spelled]); try { for (const [tool, args] of [ ["write_file", { path: path.join(spelled, "new.txt"), content: "a" }], [ "write_file", { path: path.join(spelled, "Sub", "x.txt"), content: "b" }, ], ["create_directory", { path: path.join(spelled, "d1", "d2") }], ] as const) { const result = await call(firmConn.client, tool, args); expect(result.isError, textOf(result)).toBeFalsy(); } expect(await fs.readFile(path.join(dir, "Sub", "x.txt"), "utf-8")).toBe( "b", ); expect((await fs.stat(path.join(dir, "d1", "d2"))).isDirectory()).toBe( true, ); } finally { await firmConn.close(); } }); }); describe("search_files", () => { beforeEach(async () => { await fs.mkdir(path.join(dir, "sub", "deeper"), { recursive: true }); await fs.writeFile(path.join(dir, "top.txt"), ""); await fs.writeFile(path.join(dir, "top.log"), ""); await fs.writeFile(path.join(dir, "sub", "mid.txt"), ""); await fs.writeFile(path.join(dir, "sub", "deeper", "low.txt"), ""); }); async function search(args: Record): Promise { const text = textOf( await call(client, "search_files", { path: dir, ...args }), ); return text.split("\n").sort(); } it("matches a bare glob against top-level entries only", async () => { expect(await search({ pattern: "*.txt" })).toEqual([ path.join(dir, "top.txt"), ]); }); it("recurses into subdirectories for a ** glob", async () => { expect(await search({ pattern: "**/*.txt" })).toEqual([ path.join(dir, "sub", "deeper", "low.txt"), path.join(dir, "sub", "mid.txt"), path.join(dir, "top.txt"), ]); }); it("matches directories as well as files", async () => { expect(await search({ pattern: "**/deeper" })).toEqual([ path.join(dir, "sub", "deeper"), ]); }); it("skips excluded paths and does not descend into them", async () => { expect( await search({ pattern: "**/*.txt", excludePatterns: ["sub"] }), ).toEqual([path.join(dir, "top.txt")]); }); it('says "No matches found" when nothing matches', async () => { const result = await call(client, "search_files", { path: dir, pattern: "*.none", }); expect(textOf(result)).toBe("No matches found"); }); it("silently skips a symlink that leaves the allowed directories", async () => { const outside = await makeTempDir("mcp-fs-outside-"); try { await fs.writeFile(path.join(outside, "secret.txt"), ""); await fs.symlink(outside, path.join(dir, "escape")); expect(await search({ pattern: "**/*" })).not.toContain( path.join(dir, "escape"), ); } finally { await fs.rm(outside, { recursive: true, force: true }); } }); }); describe("get_file_info", () => { it("reports a file's metadata as key: value lines", async () => { const file = path.join(dir, "f.txt"); await fs.writeFile(file, "12345"); await fs.chmod(file, 0o640); const lines = textOf( await call(client, "get_file_info", { path: file }), ).split("\n"); expect(lines.map((l) => l.split(":")[0])).toEqual([ "size", "created", "modified", "accessed", "isDirectory", "isFile", "permissions", "hardLinks", ]); expect(lines[0]).toBe("size: 5"); expect(lines[4]).toBe("isDirectory: false"); expect(lines[5]).toBe("isFile: true"); // Windows has no POSIX mode bits: a writable file always reports 666. expect(lines[6]).toBe( process.platform === "win32" ? "permissions: 666" : "permissions: 640", ); // Dates are rendered with Date#toString, in the server's local time zone. expect(lines[2]).toMatch(/^modified: \w{3} \w{3} \d{2} \d{4} /); }); it("reports a file's hard-link count (#5226)", async () => { const file = path.join(dir, "linked.txt"); await fs.writeFile(file, "shared"); const info = async () => textOf(await call(client, "get_file_info", { path: file })); expect(await info()).toContain("hardLinks: 1"); await fs.link(file, path.join(dir, "hardlink.txt")); expect(await info()).toContain("hardLinks: 2"); }); it("reports a directory", async () => { const text = textOf(await call(client, "get_file_info", { path: dir })); expect(text).toContain("isDirectory: true"); expect(text).toContain("isFile: false"); }); }); describe("list_allowed_directories", () => { it("lists the directories the server was built with", async () => { const result = await call(client, "list_allowed_directories"); expect(textOf(result)).toBe(`Allowed directories:\n${dir}`); }); }); describe("two servers in one process", () => { it("keep separate allow-lists (#4854)", async () => { const other = await makeTempDir("mcp-fs-other-"); const second = await connect([other]); try { await fs.writeFile(path.join(dir, "mine.txt"), "mine"); await fs.writeFile(path.join(other, "theirs.txt"), "theirs"); expect(await allowedDirectoriesOf(second.client)).toEqual([other]); expect(await allowedDirectoriesOf(client)).toEqual([dir]); const crossed = await call(second.client, "read_text_file", { path: path.join(dir, "mine.txt"), }); expect(textOf(crossed)).toMatch(/^Access denied/); const own = await call(second.client, "read_text_file", { path: path.join(other, "theirs.txt"), }); expect(textOf(own)).toBe("theirs"); } finally { await second.close(); await fs.rm(other, { recursive: true, force: true }); } }); });