Copy-Paste Implementation

Get a production-ready edit_file tool that you can paste directly into Cursor, Windsurf, Cline, Continue, and other AI IDEs

Quick Copy-Paste Implementation

This example shows how to use standard tool calls to implement the edit_file tool. Many research papers have shown that having LLMs like Claude/Gemini do code edits via normal JSON tool calls results in worse overall coding performance due to constrained decoding. For the best coding performance, you can use XML tags for your tool calls. See how Cline and Cursor use XML tags for all their tool calls.

Copy-Paste Prompt

Copy this prompt and paste it into your AI IDE (Cursor, Windsurf, Cline, Continue, etc.):
Implement an edit_file tool that uses Morph's fast apply API to modify files. The tool should read the current file content, send it to Morph's API at https://api.morphllm.com/v1 using the morph-v3-large model with the format: `<instruction>${instructions}</instruction>\n<code>${originalCode}</code>\n<update>${codeEdit}</update>`, then write the updated content back to the file. Use the MORPH_API_KEY environment variable for authentication and an OpenAI-compatible client.

The tool parameters should match this exact definition:
- target_file (string, required): The target file to modify
- instructions (string, recommended): A single sentence written in the first person describing what you're changing. Used to help disambiguate uncertainty in the edit.
- code_edit (string, required): Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.

Tool Description:
"Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\nIf you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \\n Block 1 \\n Block 2 \\n Block 3 \\n code```, and you want to remove Block 2, you would output ```// ... existing code ... \\n Block 1 \\n  Block 3 \\n // ... existing code ...```.\nMake sure it is clear what the edit should be, and where it should be applied.\nALWAYS make all edits to a file in a single edit_file instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once."

Return success/error status with descriptive messages and handle file I/O and API errors gracefully. Implement this now using whatever framework I'm currently using.

Implementation Examples

TypeScript with OpenAI SDK

import OpenAI from "openai";
import * as fs from "fs/promises";

const openai = new OpenAI({
  apiKey: process.env.MORPH_API_KEY,
  baseURL: "https://api.morphllm.com/v1",
});

const response = await openai.chat.completions.create({
  model: "morph-v3-large",
  messages: [
    {
      role: "user",
      content: `<instruction>${instructions}</instruction>\n<code>${originalCode}</code>\n<update>${codeEdit}</update>`,
    },
  ],
});

const mergedCode = response.choices[0].message.content;

Vercel AI SDK with Zod Validation

import { tool } from "ai";
import { z } from "zod";
import * as fs from "fs/promises";
import { OpenAI } from "openai";

const morphClient = new OpenAI({
  apiKey: process.env.MORPH_API_KEY,
  baseURL: "https://api.morphllm.com/v1",
});

const editFile = tool({
  description:
    "Use this tool to make an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\nIf you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \\n Block 1 \\n Block 2 \\n Block 3 \\n code```, and you want to remove Block 2, you would output ```// ... existing code ... \\n Block 1 \\n  Block 3 \\n // ... existing code ...```.\nMake sure it is clear what the edit should be, and where it should be applied.\nALWAYS make all edits to a file in a single edit_file instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.",
  parameters: z.object({
    target_file: z.string().describe("The target file to modify."),
    instructions: z
      .string()
      .describe(
        "A single sentence instruction describing what you are going to do for the sketched edit. This is used to assist the less intelligent model in applying the edit. Use the first person to describe what you are going to do. Use it to disambiguate uncertainty in the edit."
      ),
    code_edit: z
      .string()
      .describe(
        "Specify ONLY the precise lines of code that you wish to edit. NEVER specify or write out unchanged code. Instead, represent all unchanged code using the comment of the language you're editing in - example: // ... existing code ..."
      ),
  }),
  execute: async ({ target_file, instructions, code_edit }) => {
    try {
      // Read the current file content
      const originalCode = await fs.readFile(target_file, "utf-8");

      // Use Morph's fast apply API to generate the updated code
      const response = await morphClient.chat.completions.create({
        model: "morph-v3-large",
        messages: [
          {
            role: "user",
            content: `<instruction>${instructions}</instruction>\n<code>${originalCode}</code>\n<update>${codeEdit}</update>`,
          },
        ],
      });

      const updatedCode = response.choices[0].message.content;

      // Write the updated content back to the file
      await fs.writeFile(target_file, updatedCode, "utf-8");

      return {
        success: true,
        message: `Successfully applied edit to ${target_file}: ${instructions}`,
      };
    } catch (error) {
      return {
        success: false,
        error: `Failed to edit ${target_file}: ${error.message}`,
      };
    }
  },
});

Setup Requirements

  1. Install dependencies: npm install openai or npm install ai zod
  2. Set API key: export MORPH_API_KEY="your-api-key-here"
  3. Get API key: Morph Dashboard

Next Steps

Ready to implement your edit_file tool? Here’s what to do next:

Agent Tools Guide

Learn about supporting tools and common patterns for building effective AI agents

Quickstart Guide

Step-by-step guide to configure your agent with the edit_file tool and integrate with Morph’s Fast Apply API

Apply API Reference

Explore the Apply API endpoints, models, and message formats for production use