AI file editing at 10,500 tokens/s - 1.8x faster, 40% fewer tokens
AI agents edit files using // ... existing code ... markers instead of sending full files. Morph merges server-side at 10,500 tokens/s.Why this matters: Traditional search-replace uses 40% more tokens and takes more turns. Fast Apply is instant.
import Anthropic from '@anthropic-ai/sdk';import { MorphClient } from '@morphllm/morphsdk';const morph = new MorphClient({ apiKey: "YOUR_API_KEY" });const anthropic = new Anthropic();// Tool inherits API key from MorphClientconst tool = morph.anthropic.createEditFileTool();const response = await anthropic.messages.create({ model: "claude-sonnet-4-5-20250929", max_tokens: 12000, tools: [tool], messages: [{ role: "user", content: "Add error handling to src/auth.ts" }]});
Copy
Ask AI
import OpenAI from 'openai';import { MorphClient } from '@morphllm/morphsdk';const morph = new MorphClient({ apiKey: "YOUR_API_KEY" });const openai = new OpenAI();// Tool inherits API key from MorphClientconst tool = morph.openai.createEditFileTool();const response = await openai.chat.completions.create({ model: "gpt-5-high", tools: [tool], messages: [{ role: "user", content: "Add error handling to src/auth.ts" }]});
OpenAI high thinking models often output in patch format—Morph handles this automatically. If you see patch-style outputs, tune your system prompt to prefer // ... existing code ... markers for better results.
Copy
Ask AI
import { generateText, stepCountIs } from 'ai';import { anthropic } from '@ai-sdk/anthropic';import { MorphClient } from '@morphllm/morphsdk';const morph = new MorphClient({ apiKey: "YOUR_API_KEY" });// Create the tool that is compatible with the Vercel AI SDKconst editFileTool = morph.vercel.createEditFileTool();const result = await generateText({ model: anthropic('claude-sonnet-4-5-20250929'), tools: { editFile: editFileTool }, prompt: "Add error handling to src/auth.ts", stopWhen: stepCountIs(5)});
Copy
Ask AI
import { MorphClient } from '@morphllm/morphsdk';const morph = new MorphClient({ apiKey: "YOUR_API_KEY" });// Direct executionconst result = await morph.fastApply.execute({ target_filepath: 'src/auth.ts', instructions: 'I will add null check', code_edit: '// ... existing code ...\nif (!user) throw new Error("Not found");\n// ... existing code ...'});console.log(result.success); // trueconsole.log(`+${result.changes.linesAdded} -${result.changes.linesRemoved}`);
Copy
Ask AI
from openai import OpenAIclient = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.morphllm.com/v1",)original_code = open("src/auth.ts").read()code_edit = "// ... existing code ...\nif (!user) throw new Error('Not found');\n// ... existing code ..."instruction = "I will add null check"response = client.chat.completions.create( model="morph-v3-fast", messages=[ { "role": "user", "content": f"<instruction>{instruction}</instruction>\n<code>{original_code}</code>\n<update>{code_edit}</update>" } ],)merged_code = response.choices[0].message.contentwith open("src/auth.ts", "w") as f: f.write(merged_code)
The response is an OpenAI-compatible chat completion. The merged code is in choices[0].message.content.
The instructions parameter provides crucial context for ambiguous edits, helping the apply model make correct decisions and achieve near perfect accuracy. Have the parent model generate the instructions.
Add the edit_file tool to your agent. Use one of the formats below.
General Prompt
JSON Tool (Claude)
Output Parsing (No Tool)
Copy
Ask AI
When editing files, use the edit_file tool with these parameters:- target_filepath: Path of the file to modify- instructions: Brief first-person description of what you're changing- code_edit: Only the changed lines with // ... existing code ... markersUse "// ... existing code ..." to represent unchanged code blocks. Includejust enough surrounding context to locate each edit precisely.Example format:// ... existing code ...FIRST_EDIT// ... existing code ...SECOND_EDIT// ... existing code ...Rules:- ALWAYS use "// ... existing code ..." for unchanged sections (omitting this marker will cause deletions)- Include minimal context around edits only when needed for disambiguation- Preserve exact indentation- For deletions: show context before and after, omit the deleted lines- Batch multiple edits to the same file in one call
Pass this tool definition directly to Claude or any model that supports JSON tool schemas.
Copy
Ask AI
{ "name": "edit_file", "description": "Edit an existing file by showing only the changed lines. Use // ... existing code ... to represent unchanged sections. Include just enough surrounding context to locate each edit precisely. ALWAYS use the marker for unchanged sections (omitting it will cause deletions). Preserve exact indentation. For deletions, show context before and after. Batch multiple edits to the same file in one call.", "input_schema": { "type": "object", "properties": { "target_filepath": { "type": "string", "description": "Path of the file to modify" }, "instructions": { "type": "string", "description": "A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit." }, "code_edit": { "type": "string", "description": "Specify ONLY the precise lines of code that you wish to edit. Use // ... existing code ... for unchanged sections." } }, "required": ["target_filepath", "instructions", "code_edit"] }}
If your model doesn’t support tool use, have it output edits in a structured format you parse yourself.
Copy
Ask AI
When editing files, output a fenced code block with the filepath as the language tag:```src/auth.ts// ... existing code ...if (!user) throw new Error("Not found");// ... existing code ...```Before each block, write a one-line instruction starting with "I will":I will add a null check before creating the session.
Parse the filepath from the code fence, the instruction from the preceding line, and the code edit from the block contents. Then send all three to Morph.
Parameters:
Parameter
Type
Required
Description
target_filepath
string
yes
Path of the file to modify
instructions
string
yes
Brief first-person description of what you’re changing (helps disambiguate uncertainty in the edit)
code_edit
string
yes
Only the changed lines with // ... existing code ... markers for unchanged sections
The instructions param should be generated by the model, not hardcoded. Example: “I am adding error handling to the user auth and removing the old auth functions”
Why do I need the instructions to be generated by the model?
The instructions parameter provides crucial context for ambiguous edits, helping the apply model make correct decisions and achieve near 100% accuracy even in edge cases.
2
Merge with Morph Fast Apply
When the agent calls your tool, send the original file + the edit snippet to Morph’s API. It returns the merged file. Write it to disk.
What to add to your System Prompt
Copy
Ask AI
When editing code, use the edit_file tool. Output only the changed sections and use`// ... existing code ...` markers to skip over unchanged code. Do not reread a filebefore editing. The edit is applied semantically, so you do not need the file's exactcurrent contents to make a correct edit.
Pass the diff back to the agent so it can verify the changes match its intent. To save tokens, you can limit this to cases where the linter reports errors.
Copy
Ask AI
import { createTwoFilesPatch } from 'diff';const udiff = createTwoFilesPatch( toolCall.target_filepath, toolCall.target_filepath, originalCode, mergedCode, '', '');// Send back to agent for verificationconsole.log("Changes applied:", udiff);
This catches unexpected changes before they hit disk.
{ target_filepath: string, // Relative to baseDir instructions: string, // What the model is changing code_edit: string // Code with // ... existing code ...}
{ originalCode: string, // Current file contents codeEdit: string, // Code with // ... existing code ... instructions: string // What the model is changing}
Returns (ApplyEditResult):
Copy
Ask AI
{ success: boolean, mergedCode?: string, // The merged result changes: { linesAdded, linesRemoved, linesModified }, udiff?: string, error?: string}
All types are exported from the SDK root:
Copy
Ask AI
import type { EditFileInput, EditFileResult, ApplyEditInput, ApplyEditResult, EditChanges} from '@morphllm/morphsdk';