string_replace
Replace text in files by specifying the old string and new string, enabling content updates without manual editing.
Instructions
Replace a string in a file with a new string
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Absolute path to the file | |
| old_str | Yes | String to replace | |
| new_str | No | Replacement string (empty string if omitted) |
Implementation Reference
- src/editor.ts:96-138 (handler)The strReplace method in the FileEditor class executes the string_replace tool: validates the path, reads the file, ensures exactly one occurrence of old_str, replaces it with new_str, updates the file and history, and returns a contextual snippet of the change.async strReplace(args: StringReplaceArgs): Promise<string> { await validatePath('string_replace', args.path); const fileContent = await readFile(args.path); const oldStr = args.old_str.replace(/\t/g, ' '); const newStr = args.new_str?.replace(/\t/g, ' ') ?? ''; const occurrences = fileContent.split(oldStr).length - 1; if (occurrences === 0) { throw new ToolError( `No replacement was performed, old_str \`${args.old_str}\` did not appear verbatim in ${args.path}.` ); } if (occurrences > 1) { const lines = fileContent.split('\n') .map((line, idx) => line.includes(oldStr) ? idx + 1 : null) .filter((idx): idx is number => idx !== null); throw new ToolError( `No replacement was performed. Multiple occurrences of old_str \`${args.old_str}\` in lines ${lines}. Please ensure it is unique` ); } const newContent = fileContent.replace(oldStr, newStr); await writeFile(args.path, newContent); if (!this.fileHistory[args.path]) { this.fileHistory[args.path] = []; } this.fileHistory[args.path].push(fileContent); const replacementLine = fileContent.split(oldStr)[0].split('\n').length; const startLine = Math.max(0, replacementLine - SNIPPET_LINES); const endLine = replacementLine + SNIPPET_LINES + newStr.split('\n').length; const snippet = newContent.split('\n').slice(startLine, endLine + 1).join('\n'); let successMsg = `The file ${args.path} has been edited. `; successMsg += makeOutput(snippet, `a snippet of ${args.path}`, startLine + 1); successMsg += 'Review the changes and make sure they are as expected. Edit the file again if necessary.'; return successMsg; }
- src/server.ts:81-102 (registration)Registers the string_replace tool in the list of tools provided by the MCP server, including its name, description, and input schema.{ name: "string_replace", description: "Replace a string in a file with a new string", inputSchema: { type: "object", properties: { path: { type: "string", description: "Absolute path to the file" }, old_str: { type: "string", description: "String to replace" }, new_str: { type: "string", description: "Replacement string (empty string if omitted)" } }, required: ["path", "old_str"] } },
- src/server.ts:162-166 (registration)Dispatches calls to the string_replace tool by validating arguments with isStrReplaceArgs and invoking the editor's strReplace method.case "string_replace": if (!request.params.arguments || !isStrReplaceArgs(request.params.arguments)) { throw new ToolError("Invalid arguments for string_replace command"); // Fixed } result = await this.editor.strReplace(request.params.arguments);
- src/types.ts:24-28 (schema)TypeScript interface defining the input arguments for the string_replace tool.export interface StringReplaceArgs extends Record<string, unknown> { path: string; old_str: string; new_str?: string; }
- src/types.ts:52-56 (schema)Type guard function for validating string_replace arguments at runtime.export function isStrReplaceArgs(args: Record<string, unknown>): args is StringReplaceArgs { return typeof args.path === "string" && typeof args.old_str === "string" && (args.new_str === undefined || typeof args.new_str === "string"); }