Skip to content

Commit 6575d87

Browse files
cliffhallclaude
andcommitted
feat(filesystem): show the closest file lines when an edit has no match
When an edit_file oldText matches nowhere, the error now names the edit that failed (edit k of n), states the matching rules, says nothing was written, and quotes the closest run of file lines with line numbers, plus the first differing line JSON-quoted so whitespace differences are visible. The tool description and README now state the matching rules. What matches is unchanged: the report never edits a near match. Closes #2034 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 446be48 commit 6575d87

6 files changed

Lines changed: 333 additions & 6 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": patch
3+
---
4+
5+
`edit_file`: when an edit's `oldText` matches nowhere, the error now names which edit failed, states the matching rules, and quotes the closest lines of the file with line numbers, plus the first differing line JSON-quoted so a whitespace difference is visible. The tool description now states the matching rules too. What matches is unchanged.

‎src/filesystem/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ The server's directory access control follows this flow:
135135
- `newText` (string): Text to replace with
136136
- `dryRun` (boolean): Preview changes without applying (default: false)
137137
- Returns detailed diff and match information for dry runs, otherwise applies changes
138+
- Matching: `oldText` must match the file's text exactly, except that line endings never matter and, when there is no exact match, a run of whole lines matches if each line is equal once leading and trailing whitespace is ignored. Whitespace inside a line must match; nothing fuzzier is tried
139+
- If any edit has no match, no edits are applied, and the error names the edit, quotes the closest lines of the file with line numbers, and shows the first line that differs (JSON-quoted, so tabs and trailing spaces are visible)
138140
- Best Practice: Always use dryRun first to preview changes before applying them
139141

140142
- **create_directory**
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
// The edit_file no-match error (#2034). An edit whose oldText matches nowhere
2+
// used to fail with only "Could not find exact match", leaving a model to
3+
// guess at an invisible whitespace difference. The error now names the edit,
4+
// states what the matcher tolerates, and quotes the closest lines of the file
5+
// with line numbers and the first differing line JSON-quoted. These tests pin
6+
// that report, and that it stays a report: a near match is never applied.
7+
8+
import fs from "fs/promises";
9+
import path from "path";
10+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11+
import { describeEditMismatch } from "../lib.js";
12+
import {
13+
call,
14+
connect,
15+
makeTempDir,
16+
quietStderr,
17+
textOf,
18+
type Connected,
19+
} from "./helpers.js";
20+
21+
describe("edit_file no-match error, over the protocol", () => {
22+
let dir: string;
23+
let conn: Connected;
24+
let file: string;
25+
const original =
26+
"function greet() {\n" +
27+
" const name = 'world';\n" +
28+
" console.log('hello', name);\n" +
29+
" return name;\n" +
30+
"}\n";
31+
32+
beforeEach(async () => {
33+
quietStderr();
34+
dir = await makeTempDir("mcp-fs-edit-mismatch-");
35+
conn = await connect([dir]);
36+
file = path.join(dir, "greet.ts");
37+
await fs.writeFile(file, original);
38+
});
39+
40+
afterEach(async () => {
41+
vi.restoreAllMocks();
42+
await conn.close();
43+
await fs.rm(dir, { recursive: true, force: true });
44+
});
45+
46+
it("names the failed edit, quotes the closest lines and writes nothing", async () => {
47+
const result = await call(conn.client, "edit_file", {
48+
path: file,
49+
edits: [
50+
{ oldText: "return name;", newText: "return name.length;" },
51+
// A tab where the file has a space, inside the line: not tolerated.
52+
{
53+
oldText: " const name = 'world';\n console.log('hello',\tname);",
54+
newText: " console.log('bye');",
55+
},
56+
],
57+
});
58+
expect(result.isError).toBe(true);
59+
expect(textOf(result)).toBe(
60+
"Could not find exact match for edit 2 of 2. oldText must match the " +
61+
"file's text exactly; only line endings, and leading and trailing " +
62+
"whitespace on whole lines, may differ. No edits were applied.\n\n" +
63+
"oldText:\n const name = 'world';\n console.log('hello',\tname);\n\n" +
64+
"Closest text in the file (lines 1-5 of 5, after the earlier edits " +
65+
"in this call):\n" +
66+
"1: function greet() {\n" +
67+
"2: const name = 'world';\n" +
68+
"3: console.log('hello', name);\n" +
69+
"4: return name.length;\n" +
70+
"5: }\n\n" +
71+
"First difference, oldText line 2 against file line 3:\n" +
72+
" oldText: \" console.log('hello',\\tname);\"\n" +
73+
" file: \" console.log('hello', name);\"\n\n" +
74+
"Retry with oldText copied exactly from the file, without the " +
75+
"line-number prefixes.",
76+
);
77+
// The first edit matched, but a failed call applies none of them.
78+
expect(await fs.readFile(file, "utf-8")).toBe(original);
79+
});
80+
81+
it("still applies an edit that differs only in indentation", async () => {
82+
await call(conn.client, "edit_file", {
83+
path: file,
84+
edits: [{ oldText: " return name;\n}", newText: " return 0;\n}" }],
85+
});
86+
const edited = await fs.readFile(file, "utf-8");
87+
expect(edited).toContain("\n return 0;\n}");
88+
expect(edited).not.toContain(" return 0;");
89+
});
90+
91+
it("states the matching rules in the tool description", async () => {
92+
const { tools } = await conn.client.listTools();
93+
const description = tools.find((t) => t.name === "edit_file")?.description;
94+
expect(description).toContain("Whitespace inside a line must match.");
95+
expect(description).toContain("line endings (LF or CRLF) never matter");
96+
expect(description).toContain("nothing is written");
97+
});
98+
});
99+
100+
describe("describeEditMismatch", () => {
101+
const lines = (n: number, prefix = "line") =>
102+
Array.from({ length: n }, (_, i) => `${prefix} ${i + 1}`);
103+
104+
it("omits the earlier-edits note for the first edit", () => {
105+
const message = describeEditMismatch("alpha\nbeta\n", "betta", 0, 1);
106+
expect(message).toContain("edit 1 of 1");
107+
expect(message).toContain("(lines 1-2 of 2):\n1: alpha\n2: beta");
108+
expect(message).toContain(' oldText: "betta"\n file: "beta"');
109+
});
110+
111+
it("picks the most similar run of lines, the earliest on a tie", () => {
112+
const content = [...lines(10), "target x", ...lines(10), "target x"].join(
113+
"\n",
114+
);
115+
const message = describeEditMismatch(content, "target x", 0, 1);
116+
expect(message).toContain("(lines 9-13 of 22):");
117+
expect(message).toContain("11: target x");
118+
expect(message).toContain("oldText line 1 against file line 11");
119+
});
120+
121+
it("normalizes CRLF in oldText before comparing", () => {
122+
const message = describeEditMismatch("a\nb\nc\n", "a\r\nB\r\n", 0, 1);
123+
expect(message).toContain("oldText line 2 against file line 2");
124+
});
125+
126+
it("reports oldText that runs past the end of the file", () => {
127+
const message = describeEditMismatch("a\nb\n", "a\nb\nc", 0, 1);
128+
expect(message).toContain("(lines 1-2 of 2):");
129+
expect(message).toContain(
130+
'oldText line 3 ("c") runs past the end of the file, which ends at line 2.',
131+
);
132+
});
133+
134+
it("says so when no line resembles oldText", () => {
135+
const message = describeEditMismatch("abc\ndef\n", "xyz", 0, 1);
136+
expect(message).toContain("No line of the file resembles oldText.");
137+
expect(message).not.toContain("Closest text");
138+
});
139+
140+
it("handles an empty file", () => {
141+
const message = describeEditMismatch("", "x", 0, 1);
142+
expect(message).toContain("No line of the file resembles oldText.");
143+
});
144+
145+
it("caps the quoted region at 30 lines", () => {
146+
const content = lines(50).join("\n");
147+
const oldText = [...lines(39), "line 40 changed"].join("\n");
148+
const message = describeEditMismatch(content, oldText, 0, 1);
149+
expect(message).toContain("(lines 1-30 of 50):");
150+
expect(message).toContain("\n30: line 30\n");
151+
expect(message).not.toContain("\n31: ");
152+
expect(message).toContain("oldText line 40 against file line 40");
153+
});
154+
155+
it("skips the search on a file too large to compare", () => {
156+
const content = lines(2000).join("\n");
157+
const oldText = lines(1000, "other").join("\n");
158+
const message = describeEditMismatch(content, oldText, 1, 3);
159+
expect(message).toContain("edit 2 of 3");
160+
expect(message).toContain(
161+
"The file has 2000 lines, too many to search for the closest text.",
162+
);
163+
expect(message).not.toContain("Closest text");
164+
});
165+
});

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -871,8 +871,9 @@ describe("edit_file", () => {
871871
edits: [{ oldText: "return 9;", newText: "x" }],
872872
});
873873
expect(result.isError).toBe(true);
874-
expect(textOf(result)).toBe(
875-
"Could not find exact match for edit:\nreturn 9;",
874+
// #2034: the error also quotes the closest lines of the file.
875+
expect(textOf(result)).toMatch(
876+
/^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: return 1;\n/,
876877
);
877878
});
878879

‎src/filesystem/lib.ts‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,146 @@ function reindentLine(
729729
return indent + body;
730730
}
731731

732+
// What the no-match error shows (#2034). A model that sent oldText which
733+
// differs from the file in a way the matcher does not tolerate (whitespace
734+
// inside a line, a typo, stale content) needs the file's real text to retry
735+
// with, so the error quotes the closest run of lines with their line
736+
// numbers. Finding it compares every window of the file against oldText, so
737+
// the search is skipped past a fixed number of line comparisons rather than
738+
// stalling the error on a huge file.
739+
const MISMATCH_SCAN_LIMIT = 1_000_000;
740+
const MISMATCH_CONTEXT_LINES = 2;
741+
const MISMATCH_MAX_REGION_LINES = 30;
742+
743+
interface LineGrams {
744+
grams: Map<string, number>;
745+
size: number;
746+
}
747+
748+
/** A line's character bigrams with all whitespace removed, for similarity. */
749+
function lineGrams(line: string): LineGrams {
750+
const text = line.replace(/\s+/g, "");
751+
const grams = new Map<string, number>();
752+
if (text.length === 1) grams.set(text, 1);
753+
for (let i = 0; i < text.length - 1; i++) {
754+
const gram = text.slice(i, i + 2);
755+
grams.set(gram, (grams.get(gram) ?? 0) + 1);
756+
}
757+
let size = 0;
758+
for (const count of grams.values()) size += count;
759+
return { grams, size };
760+
}
761+
762+
/** Dice similarity of two lines' bigrams: 1 for two blank lines, 0 for nothing shared. */
763+
function lineSimilarity(a: LineGrams, b: LineGrams): number {
764+
if (a.size + b.size === 0) return 1;
765+
let shared = 0;
766+
for (const [gram, count] of a.grams) {
767+
shared += Math.min(count, b.grams.get(gram) ?? 0);
768+
}
769+
return (2 * shared) / (a.size + b.size);
770+
}
771+
772+
/**
773+
* The error message for an edit that matched nowhere in `content` (the file
774+
* as the earlier edits in the same call left it). It names the edit, says
775+
* what the matcher tolerates, and quotes the run of file lines most similar
776+
* to oldText, numbered, with the first line that differs shown quoted so
777+
* whitespace is visible. It only reports: it never changes what matches.
778+
*/
779+
export function describeEditMismatch(
780+
content: string,
781+
oldText: string,
782+
editIndex: number,
783+
editCount: number,
784+
): string {
785+
const oldLines = normalizeLineEndings(oldText).split("\n");
786+
const fileLines = content.split("\n");
787+
if (fileLines.length > 1 && fileLines[fileLines.length - 1] === "") {
788+
fileLines.pop();
789+
}
790+
791+
const parts = [
792+
`Could not find exact match for edit ${editIndex + 1} of ${editCount}. ` +
793+
"oldText must match the file's text exactly; only line endings, and " +
794+
"leading and trailing whitespace on whole lines, may differ. " +
795+
"No edits were applied.",
796+
`oldText:\n${oldText}`,
797+
];
798+
799+
const width = Math.min(oldLines.length, fileLines.length);
800+
const windows = fileLines.length - width + 1;
801+
if (windows * width > MISMATCH_SCAN_LIMIT) {
802+
parts.push(
803+
`The file has ${fileLines.length} lines, too many to search for the ` +
804+
"closest text. Read the file and copy oldText from it exactly.",
805+
);
806+
return parts.join("\n\n");
807+
}
808+
809+
const oldGrams = oldLines.map(lineGrams);
810+
const fileGrams = fileLines.map(lineGrams);
811+
let best = 0;
812+
let bestScore = 0;
813+
for (let i = 0; i < windows; i++) {
814+
let score = 0;
815+
for (let j = 0; j < width; j++) {
816+
score += lineSimilarity(oldGrams[j], fileGrams[i + j]);
817+
}
818+
if (score > bestScore) {
819+
best = i;
820+
bestScore = score;
821+
}
822+
}
823+
824+
if (bestScore === 0) {
825+
parts.push(
826+
"No line of the file resembles oldText. Read the file and copy " +
827+
"oldText from it exactly.",
828+
);
829+
return parts.join("\n\n");
830+
}
831+
832+
const start = Math.max(0, best - MISMATCH_CONTEXT_LINES);
833+
const end = Math.min(
834+
fileLines.length,
835+
best + width + MISMATCH_CONTEXT_LINES,
836+
start + MISMATCH_MAX_REGION_LINES,
837+
);
838+
const numbered = fileLines
839+
.slice(start, end)
840+
.map((line, k) => `${start + k + 1}: ${line}`);
841+
const after = editIndex > 0 ? ", after the earlier edits in this call" : "";
842+
parts.push(
843+
`Closest text in the file (lines ${start + 1}-${end} of ` +
844+
`${fileLines.length}${after}):\n${numbered.join("\n")}`,
845+
);
846+
847+
// Some line differs beyond leading and trailing whitespace, or oldText runs
848+
// past the file's end: otherwise the line-by-line matcher would have
849+
// matched this window. Math.max only keeps the index a valid one.
850+
const differs = Math.max(
851+
0,
852+
oldLines.findIndex(
853+
(line, j) => j >= width || line.trim() !== fileLines[best + j].trim(),
854+
),
855+
);
856+
parts.push(
857+
differs >= width
858+
? `oldText line ${differs + 1} (${JSON.stringify(oldLines[differs])}) ` +
859+
`runs past the end of the file, which ends at line ${fileLines.length}.`
860+
: `First difference, oldText line ${differs + 1} against file line ` +
861+
`${best + differs + 1}:\n` +
862+
` oldText: ${JSON.stringify(oldLines[differs])}\n` +
863+
` file: ${JSON.stringify(fileLines[best + differs])}`,
864+
);
865+
parts.push(
866+
"Retry with oldText copied exactly from the file, without the " +
867+
"line-number prefixes.",
868+
);
869+
return parts.join("\n\n");
870+
}
871+
732872
export async function applyFileEdits(
733873
filePath: string,
734874
edits: FileEdit[],
@@ -742,7 +882,7 @@ export async function applyFileEdits(
742882

743883
// Apply edits sequentially
744884
let modifiedContent = content;
745-
for (const edit of edits) {
885+
for (const [index, edit] of edits.entries()) {
746886
const normalizedOld = normalizeLineEndings(edit.oldText);
747887
const normalizedNew = normalizeLineEndings(edit.newText);
748888

@@ -798,7 +938,14 @@ export async function applyFileEdits(
798938
}
799939

800940
if (!matchFound) {
801-
throw new Error(`Could not find exact match for edit:\n${edit.oldText}`);
941+
throw new Error(
942+
describeEditMismatch(
943+
modifiedContent,
944+
edit.oldText,
945+
index,
946+
edits.length,
947+
),
948+
);
802949
}
803950
}
804951

‎src/filesystem/server.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -464,8 +464,15 @@ export function createServer(
464464
{
465465
title: "Edit File",
466466
description:
467-
"Make line-based edits to a text file. Each edit replaces exact line sequences " +
468-
"with new content. Returns a git-style diff showing the changes made. " +
467+
"Make line-based edits to a text file. Edits apply in order, each to the " +
468+
"result of the ones before it, and each replaces the first match of its " +
469+
"oldText with newText. oldText must match the file's text exactly, except " +
470+
"that line endings (LF or CRLF) never matter and, when there is no exact " +
471+
"match, a run of whole lines matches if each line is equal once leading and " +
472+
"trailing whitespace is ignored (newText then takes the file's indentation). " +
473+
"Whitespace inside a line must match. If any edit has no match, nothing is " +
474+
"written and the error shows the closest lines of the file, numbered, to " +
475+
"copy oldText from. Returns a git-style diff showing the changes made. " +
469476
"Only works within allowed directories.",
470477
inputSchema: jsonSchema2020(EditFileArgsSchema.shape),
471478
outputSchema: jsonSchema2020({ content: z.string() }),

0 commit comments

Comments
 (0)