Skip to content

Commit af8a01b

Browse files
cliffhallclaude
andcommitted
feat(filesystem): add an append_file tool
append_file appends text to the end of a file, exactly as given (no newline is added), creating the file if it does not exist. It is registered right after write_file and takes the same symlink-safe path: exclusive creation for a new file, and for an existing one an O_APPEND handle opened inside the pinned directory and checked to be the file lstat saw, so nothing swapped in after validation is written through. 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 #1208 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit af8a01b

8 files changed

Lines changed: 407 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-filesystem": minor
3+
---
4+
5+
Add an `append_file` tool that appends text to the end of a file, exactly as given, creating the file if it does not exist (#1208).

‎src/filesystem/README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ The server's directory access control follows this flow:
118118
`get_file_info` reports a file's `hardLinks` count; more than 1 means
119119
the file has other names
120120

121+
- **append_file**
122+
- Append text to the end of a file, creating the file if it does not exist
123+
- Inputs:
124+
- `path` (string): File location
125+
- `content` (string): Text to append
126+
- The text is appended exactly as given: no newline is added before or
127+
after it. To build a file line by line, end each `content` with `\n`
128+
- The existing content is never changed. The file is appended to in place,
129+
so it keeps its inode, creation time, hard links and permissions, and a
130+
path that is not a regular file (a directory, say) is refused. The same
131+
hard-link caveat as `write_file` applies
132+
121133
- **edit_file**
122134
- Make selective edits using advanced pattern matching and formatting
123135
- Features:
@@ -261,6 +273,7 @@ The mapping for filesystem tools is:
261273
| `list_allowed_directories` | `true` | – | – | Pure read |
262274
| `create_directory` | `false` | `true` | `false` | Re‑creating the same dir is a no‑op |
263275
| `write_file` | `false` | `true` | `true` | Overwrites existing files |
276+
| `append_file` | `false` | `false` | `false` | Adds to a file; repeating it appends again |
264277
| `edit_file` | `false` | `false` | `true` | Re‑applying edits can fail or double‑apply |
265278
| `move_file` | `false` | `false` | `true` | Deletes source file |
266279

Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
// Protocol-level tests for the append_file tool (#1208), driven through a real
2+
// Client over an in-memory transport. They pin the contract the README states:
3+
// text is appended exactly as given (no newline added), a missing file is
4+
// created, the existing content and the file's identity are kept, and the
5+
// write takes the same symlink-safe path as write_file, so nothing swapped in
6+
// after validation is written through.
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-append-");
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("append_file", () => {
40+
it("is listed right after write_file, with truthful annotations", async () => {
41+
const { tools } = await client.listTools();
42+
const names = tools.map((t) => t.name);
43+
expect(names.indexOf("append_file")).toBe(names.indexOf("write_file") + 1);
44+
const tool = tools.find((t) => t.name === "append_file");
45+
expect(tool?.title).toBe("Append File");
46+
expect(tool?.annotations).toEqual({
47+
readOnlyHint: false,
48+
idempotentHint: false,
49+
destructiveHint: false,
50+
openWorldHint: false,
51+
});
52+
});
53+
54+
it("appends to an existing file exactly as given, adding no newline", async () => {
55+
const file = path.join(dir, "log.txt");
56+
await fs.writeFile(file, "first");
57+
const result = await call(client, "append_file", {
58+
path: file,
59+
content: " second",
60+
});
61+
expect(result.isError).toBeFalsy();
62+
expect(textOf(result)).toBe(`Successfully appended to ${file}`);
63+
expect(result.structuredContent).toEqual({ content: textOf(result) });
64+
expect(await fs.readFile(file, "utf-8")).toBe("first second");
65+
});
66+
67+
it("builds a file up line by line when each append ends in a newline", async () => {
68+
const file = path.join(dir, "lines.txt");
69+
for (const line of ["one\n", "two\n", "three\n"]) {
70+
const result = await call(client, "append_file", {
71+
path: file,
72+
content: line,
73+
});
74+
expect(result.isError).toBeFalsy();
75+
}
76+
expect(await fs.readFile(file, "utf-8")).toBe("one\ntwo\nthree\n");
77+
});
78+
79+
it("keeps CRLF and other content byte for byte", async () => {
80+
const file = path.join(dir, "crlf.txt");
81+
await fs.writeFile(file, "a\r\n");
82+
await call(client, "append_file", { path: file, content: "b\r\nc" });
83+
expect(await fs.readFile(file, "utf-8")).toBe("a\r\nb\r\nc");
84+
});
85+
86+
it("creates a file that does not exist yet", async () => {
87+
const file = path.join(dir, "new.txt");
88+
const result = await call(client, "append_file", {
89+
path: file,
90+
content: "hello",
91+
});
92+
expect(result.isError).toBeFalsy();
93+
expect(await fs.readFile(file, "utf-8")).toBe("hello");
94+
});
95+
96+
it("leaves a file unchanged when the content is empty", async () => {
97+
const file = path.join(dir, "same.txt");
98+
await fs.writeFile(file, "kept");
99+
const result = await call(client, "append_file", {
100+
path: file,
101+
content: "",
102+
});
103+
expect(result.isError).toBeFalsy();
104+
expect(await fs.readFile(file, "utf-8")).toBe("kept");
105+
});
106+
107+
it("appends through the existing file, keeping its inode and hard links", async () => {
108+
const file = path.join(dir, "linked.txt");
109+
const link = path.join(dir, "other-name.txt");
110+
await fs.writeFile(file, "base");
111+
await fs.link(file, link);
112+
const before = await fs.stat(file, { bigint: true });
113+
await call(client, "append_file", { path: file, content: "+more" });
114+
const after = await fs.stat(file, { bigint: true });
115+
expect(after.ino).toBe(before.ino);
116+
expect(after.nlink).toBe(2n);
117+
expect(await fs.readFile(link, "utf-8")).toBe("base+more");
118+
});
119+
120+
it("refuses a path outside the allowed directories", async () => {
121+
const outside = await makeTempDir("mcp-fs-append-outside-");
122+
try {
123+
const target = path.join(outside, "x.txt");
124+
const result = await call(client, "append_file", {
125+
path: target,
126+
content: "nope",
127+
});
128+
expect(result.isError).toBe(true);
129+
expect(textOf(result)).toMatch(/^Access denied/);
130+
expect(fsSync.existsSync(target)).toBe(false);
131+
} finally {
132+
await fs.rm(outside, { recursive: true, force: true });
133+
}
134+
});
135+
136+
it("refuses a directory", async () => {
137+
const sub = path.join(dir, "sub");
138+
await fs.mkdir(sub);
139+
const result = await call(client, "append_file", {
140+
path: sub,
141+
content: "x",
142+
});
143+
expect(result.isError).toBe(true);
144+
expect(textOf(result)).toBe(
145+
`Refusing to append: not a regular file: ${sub}`,
146+
);
147+
});
148+
149+
it("fails, creating nothing, when the parent directory does not exist", async () => {
150+
const result = await call(client, "append_file", {
151+
path: path.join(dir, "missing", "x.txt"),
152+
content: "x",
153+
});
154+
expect(result.isError).toBe(true);
155+
expect(textOf(result)).toMatch(/ENOENT/);
156+
expect(fsSync.existsSync(path.join(dir, "missing"))).toBe(false);
157+
});
158+
159+
it("refuses when the file at the path is not the one it opened", async () => {
160+
const file = path.join(dir, "target.txt");
161+
const decoy = path.join(dir, "decoy.txt");
162+
await fs.writeFile(file, "original");
163+
await fs.writeFile(decoy, "decoy");
164+
// The lstat that names the file to append to describes another file, as
165+
// if the target had been replaced between that lstat and the open.
166+
const realLstat = fs.lstat.bind(fs);
167+
vi.spyOn(fs, "lstat").mockImplementation(((p: string, opts?: unknown) =>
168+
realLstat(p === file ? decoy : p, opts as never)) as typeof fs.lstat);
169+
const result = await call(client, "append_file", {
170+
path: file,
171+
content: "pwned",
172+
});
173+
expect(result.isError).toBe(true);
174+
expect(textOf(result)).toBe(
175+
`Refusing to append: ${file} was replaced while it was being opened`,
176+
);
177+
expect(await fs.readFile(file, "utf-8")).toBe("original");
178+
expect(await fs.readFile(decoy, "utf-8")).toBe("decoy");
179+
});
180+
181+
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
182+
"reports a file it cannot create",
183+
async () => {
184+
const locked = path.join(dir, "locked");
185+
await fs.mkdir(locked);
186+
await fs.chmod(locked, 0o500);
187+
try {
188+
const result = await call(client, "append_file", {
189+
path: path.join(locked, "x.txt"),
190+
content: "x",
191+
});
192+
expect(result.isError).toBe(true);
193+
expect(textOf(result)).toMatch(/EACCES/);
194+
} finally {
195+
await fs.chmod(locked, 0o700);
196+
}
197+
},
198+
);
199+
});
200+
201+
// The TOCTOU window, as server-tools.test.ts stages it for write_file: a
202+
// directory on the path is swapped for a symlink to a directory outside the
203+
// allowed one right after validation resolved the path. append_file must not
204+
// write through it, whether it would create the file or append to one.
205+
describe.skipIf(process.platform === "win32")(
206+
"append_file with a directory on the path swapped for a symlink after validation",
207+
() => {
208+
let outside: string;
209+
let flip: string;
210+
let flipReal: string;
211+
212+
beforeEach(async () => {
213+
outside = await makeTempDir("mcp-fs-append-outside-");
214+
flip = path.join(dir, "flip");
215+
flipReal = path.join(dir, "flip-real");
216+
await fs.mkdir(flip);
217+
});
218+
219+
afterEach(async () => {
220+
await fs.rm(outside, { recursive: true, force: true });
221+
});
222+
223+
/** Swap `flip` for a symlink to `outside` once validation realpath'd `target`. */
224+
const swapAfterRealpath = (target: string) => {
225+
const realRealpath = fs.realpath.bind(fs);
226+
let swapped = false;
227+
vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => {
228+
const resolved = await realRealpath(p, opts);
229+
if (!swapped && p === target) {
230+
swapped = true;
231+
fsSync.renameSync(flip, flipReal);
232+
fsSync.symlinkSync(outside, flip);
233+
}
234+
return resolved;
235+
});
236+
};
237+
238+
it("does not create a file through it", async () => {
239+
swapAfterRealpath(flip);
240+
const result = await call(client, "append_file", {
241+
path: path.join(flip, "created.txt"),
242+
content: "pwned",
243+
});
244+
expect(result.isError).toBe(true);
245+
expect(textOf(result)).toMatch(/^Access denied/);
246+
expect(await fs.readdir(outside)).toEqual([]);
247+
});
248+
249+
it("does not append to a file through it", async () => {
250+
const victim = path.join(flip, "victim.txt");
251+
await fs.writeFile(victim, "original");
252+
await fs.writeFile(path.join(outside, "victim.txt"), "SECRET");
253+
swapAfterRealpath(victim);
254+
const result = await call(client, "append_file", {
255+
path: victim,
256+
content: "pwned",
257+
});
258+
expect(result.isError).toBe(true);
259+
expect(textOf(result)).toMatch(/^Access denied/);
260+
expect(await fs.readFile(path.join(outside, "victim.txt"), "utf-8")).toBe(
261+
"SECRET",
262+
);
263+
expect(
264+
await fs.readFile(path.join(flipReal, "victim.txt"), "utf-8"),
265+
).toBe("original");
266+
});
267+
},
268+
);

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const TOOL_NAMES = [
3131
"read_media_file",
3232
"read_multiple_files",
3333
"write_file",
34+
"append_file",
3435
"edit_file",
3536
"create_directory",
3637
"list_directory",
@@ -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
});
@@ -114,6 +115,13 @@ describe("server identity and tool list", () => {
114115
destructiveHint: true,
115116
openWorldHint: false,
116117
},
118+
append_file: {
119+
title: "Append File",
120+
readOnlyHint: false,
121+
idempotentHint: false,
122+
destructiveHint: false,
123+
openWorldHint: false,
124+
},
117125
edit_file: {
118126
title: "Edit File",
119127
readOnlyHint: false,

‎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)