Skip to content

Commit 65e68d3

Browse files
cliffhallclaude
andcommitted
feat(filesystem): add a copy_file tool
copy_file copies one regular file to a new location, so a model can duplicate a file without reading it into the conversation and writing it back. It is registered right after move_file and, like move_file, never overwrites: an existing destination fails it. It reuses the copy half of the cross-device move (modelcontextprotocol#5188): the source is opened relative to its pinned directory and must be a regular file, and the destination is created exclusively relative to its own, then takes the source's permissions and times. Directories are refused. The stdio tests no longer pin the tool count, so a new tool does not break them; server-tools.test.ts still pins the full list. Closes modelcontextprotocol#519 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 65e68d3

8 files changed

Lines changed: 440 additions & 10 deletions

File tree

‎.changeset/filesystem-copy-file.md‎

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 `copy_file` tool that copies one regular file to a new location, keeping its permissions and modification time, and never overwrites an existing destination (#519).

‎src/filesystem/README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,19 @@ The server's directory access control follows this flow:
168168
source is left in place. A directory cannot be moved across filesystems
169169
and fails with an error; move its files one at a time instead
170170

171+
- **copy_file**
172+
- Copy a file to a new location, without its content passing through the
173+
conversation
174+
- Inputs:
175+
- `source` (string): The file to copy
176+
- `destination` (string): Where to create the copy
177+
- Fails if destination exists: it never overwrites
178+
- Copies one regular file, with its permissions and modification time, into
179+
a newly created destination. A directory, or anything else that is not a
180+
regular file, is refused; create the directory and copy its files one at a
181+
time instead. If the copy fails, the partial destination is removed. The
182+
source is never changed
183+
171184
- **search_files**
172185
- Recursively search for files/directories that match or do not match patterns
173186
- Inputs:
@@ -263,6 +276,7 @@ The mapping for filesystem tools is:
263276
| `write_file` | `false` | `true` | `true` | Overwrites existing files |
264277
| `edit_file` | `false` | `false` | `true` | Re‑applying edits can fail or double‑apply |
265278
| `move_file` | `false` | `false` | `true` | Deletes source file |
279+
| `copy_file` | `false` | `true` | `false` | Never overwrites; a repeat fails, changing nothing |
266280

267281
> Note: `idempotentHint` and `destructiveHint` are meaningful only when `readOnlyHint` is `false`, as defined by the MCP spec. Every tool also sets `openWorldHint: false` — this server only accesses the local filesystem within its allowed directories, never an open or external world.
268282
Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
// Protocol-level tests for the copy_file tool (#519), driven through a real
2+
// Client over an in-memory transport. They pin the contract the README states:
3+
// one regular file is copied with its permissions and modification time, the
4+
// source is left as it was, an existing destination is never overwritten,
5+
// directories and anything else that is not a regular file are refused, and
6+
// both paths go through the allowed-directory checks.
7+
8+
import fs from "fs/promises";
9+
import fsSync from "fs";
10+
import path from "path";
11+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
12+
import type { Client } from "@modelcontextprotocol/client";
13+
import {
14+
call,
15+
connect,
16+
makeTempDir,
17+
quietStderr,
18+
textOf,
19+
type Connected,
20+
} from "./helpers.js";
21+
22+
let dir: string;
23+
let conn: Connected;
24+
let client: Client;
25+
26+
beforeEach(async () => {
27+
quietStderr();
28+
dir = await makeTempDir("mcp-fs-copy-");
29+
conn = await connect([dir]);
30+
client = conn.client;
31+
});
32+
33+
afterEach(async () => {
34+
vi.restoreAllMocks();
35+
await conn.close();
36+
await fs.rm(dir, { recursive: true, force: true });
37+
});
38+
39+
describe("copy_file", () => {
40+
it("is listed right after move_file, with truthful annotations", async () => {
41+
const { tools } = await client.listTools();
42+
const names = tools.map((t) => t.name);
43+
expect(names.indexOf("copy_file")).toBe(names.indexOf("move_file") + 1);
44+
const tool = tools.find((t) => t.name === "copy_file");
45+
expect(tool?.title).toBe("Copy File");
46+
expect(tool?.annotations).toEqual({
47+
readOnlyHint: false,
48+
idempotentHint: true,
49+
destructiveHint: false,
50+
openWorldHint: false,
51+
});
52+
});
53+
54+
it("copies a file, leaving the source as it was", async () => {
55+
const source = path.join(dir, "a.txt");
56+
const destination = path.join(dir, "b.txt");
57+
await fs.writeFile(source, "alpha\r\nbeta");
58+
const result = await call(client, "copy_file", { source, destination });
59+
expect(result.isError).toBeFalsy();
60+
expect(textOf(result)).toBe(
61+
`Successfully copied ${source} to ${destination}`,
62+
);
63+
expect(result.structuredContent).toEqual({ content: textOf(result) });
64+
expect(await fs.readFile(destination, "utf-8")).toBe("alpha\r\nbeta");
65+
expect(await fs.readFile(source, "utf-8")).toBe("alpha\r\nbeta");
66+
const [sourceStat, copyStat] = await Promise.all([
67+
fs.stat(source, { bigint: true }),
68+
fs.stat(destination, { bigint: true }),
69+
]);
70+
expect(copyStat.ino).not.toBe(sourceStat.ino);
71+
});
72+
73+
it("copies binary content byte for byte, into another directory", async () => {
74+
const bytes = Buffer.from(
75+
Array.from({ length: 200_000 }, (_, i) => (i * 7) % 256),
76+
);
77+
const source = path.join(dir, "blob.bin");
78+
await fs.mkdir(path.join(dir, "sub"));
79+
const destination = path.join(dir, "sub", "blob-copy.bin");
80+
await fs.writeFile(source, bytes);
81+
const result = await call(client, "copy_file", { source, destination });
82+
expect(result.isError).toBeFalsy();
83+
expect((await fs.readFile(destination)).equals(bytes)).toBe(true);
84+
});
85+
86+
it.skipIf(process.platform === "win32")(
87+
"keeps the source's permissions and modification time",
88+
async () => {
89+
const source = path.join(dir, "script.sh");
90+
const destination = path.join(dir, "script-copy.sh");
91+
await fs.writeFile(source, "#!/bin/sh\n");
92+
await fs.chmod(source, 0o750);
93+
const mtime = new Date("2001-02-03T04:05:06Z");
94+
await fs.utimes(source, mtime, mtime);
95+
const result = await call(client, "copy_file", { source, destination });
96+
expect(result.isError).toBeFalsy();
97+
const copied = await fs.stat(destination);
98+
expect(copied.mode & 0o777).toBe(0o750);
99+
expect(copied.mtime.getTime()).toBe(mtime.getTime());
100+
},
101+
);
102+
103+
it("refuses an existing destination and leaves it untouched", async () => {
104+
const source = path.join(dir, "a.txt");
105+
const destination = path.join(dir, "b.txt");
106+
await fs.writeFile(source, "new");
107+
await fs.writeFile(destination, "keep me");
108+
const result = await call(client, "copy_file", { source, destination });
109+
expect(result.isError).toBe(true);
110+
expect(textOf(result)).toBe(`Destination already exists: ${destination}`);
111+
expect(await fs.readFile(destination, "utf-8")).toBe("keep me");
112+
});
113+
114+
it("refuses a copy onto itself", async () => {
115+
const source = path.join(dir, "a.txt");
116+
await fs.writeFile(source, "same");
117+
const result = await call(client, "copy_file", {
118+
source,
119+
destination: source,
120+
});
121+
expect(result.isError).toBe(true);
122+
expect(textOf(result)).toBe(`Destination already exists: ${source}`);
123+
expect(await fs.readFile(source, "utf-8")).toBe("same");
124+
});
125+
126+
it.skipIf(process.platform === "win32")(
127+
"refuses a destination occupied by a dangling symlink, without following it",
128+
async () => {
129+
const source = path.join(dir, "a.txt");
130+
const destination = path.join(dir, "link.txt");
131+
const target = path.join(dir, "would-be-created.txt");
132+
await fs.writeFile(source, "x");
133+
await fs.symlink(target, destination);
134+
const result = await call(client, "copy_file", { source, destination });
135+
expect(result.isError).toBe(true);
136+
expect(fsSync.existsSync(target)).toBe(false);
137+
},
138+
);
139+
140+
it("refuses a directory", async () => {
141+
const source = path.join(dir, "folder");
142+
await fs.mkdir(source);
143+
const result = await call(client, "copy_file", {
144+
source,
145+
destination: path.join(dir, "folder-copy"),
146+
});
147+
expect(result.isError).toBe(true);
148+
expect(textOf(result)).toMatch(/^Cannot copy a directory: /);
149+
expect(fsSync.existsSync(path.join(dir, "folder-copy"))).toBe(false);
150+
});
151+
152+
it.skipIf(process.platform === "win32")(
153+
"refuses a source that is not a regular file",
154+
async () => {
155+
const source = path.join(dir, "fifo");
156+
const { execFileSync } = await import("child_process");
157+
execFileSync("mkfifo", [source]);
158+
const result = await call(client, "copy_file", {
159+
source,
160+
destination: path.join(dir, "fifo-copy"),
161+
});
162+
expect(result.isError).toBe(true);
163+
expect(textOf(result)).toBe(`Cannot copy: not a regular file: ${source}`);
164+
},
165+
);
166+
167+
it("reports a missing source", async () => {
168+
const result = await call(client, "copy_file", {
169+
source: path.join(dir, "missing.txt"),
170+
destination: path.join(dir, "copy.txt"),
171+
});
172+
expect(result.isError).toBe(true);
173+
expect(textOf(result)).toMatch(/ENOENT/);
174+
expect(fsSync.existsSync(path.join(dir, "copy.txt"))).toBe(false);
175+
});
176+
177+
it("refuses a source or destination outside the allowed directories", async () => {
178+
const outside = await makeTempDir("mcp-fs-copy-outside-");
179+
try {
180+
const secret = path.join(outside, "secret.txt");
181+
await fs.writeFile(secret, "SECRET");
182+
const inside = path.join(dir, "a.txt");
183+
await fs.writeFile(inside, "a");
184+
185+
const fromOutside = await call(client, "copy_file", {
186+
source: secret,
187+
destination: path.join(dir, "stolen.txt"),
188+
});
189+
expect(fromOutside.isError).toBe(true);
190+
expect(textOf(fromOutside)).toMatch(/^Access denied/);
191+
expect(fsSync.existsSync(path.join(dir, "stolen.txt"))).toBe(false);
192+
193+
const toOutside = await call(client, "copy_file", {
194+
source: inside,
195+
destination: path.join(outside, "leaked.txt"),
196+
});
197+
expect(toOutside.isError).toBe(true);
198+
expect(textOf(toOutside)).toMatch(/^Access denied/);
199+
expect(fsSync.existsSync(path.join(outside, "leaked.txt"))).toBe(false);
200+
} finally {
201+
await fs.rm(outside, { recursive: true, force: true });
202+
}
203+
});
204+
205+
it.skipIf(process.platform === "win32")(
206+
"refuses a symlink inside that points outside",
207+
async () => {
208+
const outside = await makeTempDir("mcp-fs-copy-outside-");
209+
try {
210+
await fs.writeFile(path.join(outside, "secret.txt"), "SECRET");
211+
const link = path.join(dir, "link.txt");
212+
await fs.symlink(path.join(outside, "secret.txt"), link);
213+
const result = await call(client, "copy_file", {
214+
source: link,
215+
destination: path.join(dir, "stolen.txt"),
216+
});
217+
expect(result.isError).toBe(true);
218+
expect(textOf(result)).toMatch(/^Access denied/);
219+
expect(fsSync.existsSync(path.join(dir, "stolen.txt"))).toBe(false);
220+
} finally {
221+
await fs.rm(outside, { recursive: true, force: true });
222+
}
223+
},
224+
);
225+
226+
it("reports a destination whose state it cannot read", async () => {
227+
const source = path.join(dir, "a.txt");
228+
await fs.writeFile(source, "x");
229+
const destination = path.join(dir, "copy.txt");
230+
// Validation lstats the missing destination first; the existence check
231+
// after it is the call that fails here, as it would for a directory made
232+
// unreadable in between.
233+
const realLstat = fs.lstat.bind(fs);
234+
let seen = 0;
235+
vi.spyOn(fs, "lstat").mockImplementation(((p: string, opts?: unknown) => {
236+
if (p === destination && ++seen === 2) {
237+
return Promise.reject(
238+
Object.assign(new Error("EACCES: permission denied, lstat"), {
239+
code: "EACCES",
240+
}),
241+
);
242+
}
243+
return realLstat(p, opts as never);
244+
}) as typeof fs.lstat);
245+
const result = await call(client, "copy_file", { source, destination });
246+
expect(seen).toBe(2);
247+
expect(result.isError).toBe(true);
248+
expect(textOf(result)).toBe("EACCES: permission denied, lstat");
249+
expect(fsSync.existsSync(destination)).toBe(false);
250+
});
251+
});
252+
253+
// The TOCTOU window, as server-tools.test.ts stages it for move_file: the
254+
// destination's directory is swapped for a symlink to a directory outside the
255+
// allowed one right after validation resolved it. copy_file must not create
256+
// its copy through it.
257+
describe.skipIf(process.platform === "win32")(
258+
"copy_file with the destination's directory swapped for a symlink after validation",
259+
() => {
260+
let outside: string;
261+
let flip: string;
262+
263+
beforeEach(async () => {
264+
outside = await makeTempDir("mcp-fs-copy-outside-");
265+
flip = path.join(dir, "flip");
266+
await fs.mkdir(flip);
267+
});
268+
269+
afterEach(async () => {
270+
await fs.rm(outside, { recursive: true, force: true });
271+
});
272+
273+
it("does not create the copy through it", async () => {
274+
const source = path.join(dir, "a.txt");
275+
await fs.writeFile(source, "data");
276+
const realRealpath = fs.realpath.bind(fs);
277+
let swapped = false;
278+
vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => {
279+
const resolved = await realRealpath(p, opts);
280+
if (!swapped && p === flip) {
281+
swapped = true;
282+
fsSync.renameSync(flip, path.join(dir, "flip-real"));
283+
fsSync.symlinkSync(outside, flip);
284+
}
285+
return resolved;
286+
});
287+
const result = await call(client, "copy_file", {
288+
source,
289+
destination: path.join(flip, "copy.txt"),
290+
});
291+
expect(result.isError).toBe(true);
292+
expect(textOf(result)).toMatch(/^Access denied/);
293+
expect(await fs.readdir(outside)).toEqual([]);
294+
});
295+
},
296+
);

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ const TOOL_NAMES = [
3737
"list_directory_with_sizes",
3838
"directory_tree",
3939
"move_file",
40+
"copy_file",
4041
"search_files",
4142
"get_file_info",
4243
"list_allowed_directories",
@@ -89,7 +90,7 @@ describe("server identity and tool list", () => {
8990
});
9091
});
9192

92-
it("lists the 14 tools in registration order", async () => {
93+
it("lists the tools in registration order", async () => {
9394
const { tools } = await client.listTools();
9495
expect(tools.map((t) => t.name)).toEqual(TOOL_NAMES);
9596
});
@@ -141,6 +142,13 @@ describe("server identity and tool list", () => {
141142
destructiveHint: true,
142143
openWorldHint: false,
143144
},
145+
copy_file: {
146+
title: "Copy File",
147+
readOnlyHint: false,
148+
idempotentHint: true,
149+
destructiveHint: false,
150+
openWorldHint: false,
151+
},
144152
search_files: { title: "Search Files", ...readOnly },
145153
get_file_info: { title: "Get File Info", ...readOnly },
146154
list_allowed_directories: {

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,13 @@ describe("the stdio transport", () => {
224224
session.send(7, "tools/list");
225225
const response = await session.response(7);
226226
expect(response.error).toBeUndefined();
227-
expect(response.result?.tools).toHaveLength(14);
227+
// Not a count: a test that pins the number breaks on every new tool;
228+
// server-tools.test.ts pins the full list.
229+
expect(response.result?.tools).toEqual(
230+
expect.arrayContaining([
231+
expect.objectContaining({ name: "list_allowed_directories" }),
232+
]),
233+
);
228234
});
229235

230236
// #4206: a malformed line is reported to the transport's onerror (unset,
@@ -248,7 +254,11 @@ describe("the stdio transport", () => {
248254
message: "Method not found",
249255
});
250256
session.send(3, "tools/list");
251-
expect((await session.response(3)).result?.tools).toHaveLength(14);
257+
expect((await session.response(3)).result?.tools).toEqual(
258+
expect.arrayContaining([
259+
expect.objectContaining({ name: "list_allowed_directories" }),
260+
]),
261+
);
252262
});
253263
});
254264

0 commit comments

Comments
 (0)