> ## Documentation Index
> Fetch the complete documentation index at: https://docs.morphllm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Tools (edit_file)

> Build precise AI agents that edit code fast without full file rewrites using Morph's edit_file tool

## Essential Supporting Tools

<AccordionGroup>
  <Accordion title="read_file: Get Context Before Editing">
    Always read files before editing to understand the structure:

    ```json theme={null}
    {
      "name": "read_file",
      "description": "Read the contents of a file to understand its structure before making edits",
      "parameters": {
        "properties": {
          "target_file": {
            "type": "string",
            "description": "The path of the file to read"
          },
          "start_line_one_indexed": {
            "type": "integer",
            "description": "Start line number (1-indexed)"
          },
          "end_line_one_indexed_inclusive": {
            "type": "integer",
            "description": "End line number (1-indexed, inclusive)"
          },
          "explanation": {
            "type": "string",
            "description": "Why you're reading this file"
          }
        },
        "required": ["target_file", "explanation"]
      }
    }
    ```

    **Best practice:** Read the relevant sections first, then edit with proper context.
  </Accordion>

  <Accordion title="codebase_search: Find What to Edit">
    Semantic search to locate relevant code:

    ```json theme={null}
    {
      "name": "codebase_search",
      "description": "Find snippets of code from the codebase most relevant to the search query",
      "parameters": {
        "properties": {
          "query": {
            "type": "string",
            "description": "The search query to find relevant code"
          },
          "target_directories": {
            "type": "array",
            "items": {"type": "string"},
            "description": "Optional: limit search scope to specific directories"
          },
          "explanation": {
            "type": "string",
            "description": "Why you're searching for this"
          }
        },
        "required": ["query", "explanation"]
      }
    }
    ```

    **Best practice:** Search first to understand the codebase, then read specific files.
  </Accordion>

  <Accordion title="grep_search: Find Exact Matches">
    When you need exact text or pattern matches:

    ```json theme={null}
    {
      "name": "grep_search",
      "description": "Fast text-based regex search that finds exact pattern matches within files",
      "parameters": {
        "properties": {
          "query": {
            "type": "string",
            "description": "The regex pattern to search for"
          },
          "include_pattern": {
            "type": "string",
            "description": "File types to include (e.g. '*.ts')"
          },
          "explanation": {
            "type": "string",
            "description": "Why you're searching for this pattern"
          }
        },
        "required": ["query", "explanation"]
      }
    }
    ```

    **Best practice:** Use for finding function names, imports, or specific strings.
  </Accordion>

  <Accordion title="list_dir: Explore Directory Structure">
    Navigate and understand the codebase structure:

    ```json theme={null}
    {
      "name": "list_dir",
      "description": "List the contents of a directory to understand project structure",
      "parameters": {
        "properties": {
          "relative_workspace_path": {
            "type": "string",
            "description": "Path to list contents of, relative to the workspace root"
          },
          "explanation": {
            "type": "string",
            "description": "Why you're listing this directory"
          }
        },
        "required": ["relative_workspace_path", "explanation"]
      }
    }
    ```

    **Best practice:** Use to explore unknown codebases or find related files before editing.
  </Accordion>
</AccordionGroup>

## Agent Workflow

Effective agents follow this pattern:

1. **🔍 Search**: Find relevant code with `codebase_search` or `grep_search`
2. **📖 Read**: Get context with `read_file` before editing
3. **✏️ Edit**: Make precise changes with `edit_file`
4. **✅ Verify**: Read again to confirm changes worked

## Common Patterns

**Delete a section in between:**

```javascript theme={null}
// ... existing code ...
function keepThis() {
  return "stay";
}

function alsoKeepThis() {
  return "also stay";
}
// ... existing code ...
```

**Add imports:**

```javascript theme={null}
import { useState, useEffect } from "react";
import { calculateTax } from "./utils"; // New import
// ... existing code ...
```

**Update configuration:**

```json theme={null}
{
  "name": "my-app",
  "version": "2.0.0",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "test": "jest"
  }
}
```

**Add error handling:**

```javascript theme={null}
// ... existing code ...
function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}
// ... existing code ...
```

**Update function parameters:**

```javascript theme={null}
// ... existing code ...
function authenticateUser(email, password) {
  const result = await verifyUser(email, password);
  if (result) {
    return "Authenticated";
  } else {
    return "Unauthenticated";
  }
}
// ... existing code ...
```

**Add new methods to a class:**

```javascript theme={null}
// ... existing code ...
class UserService {
  async getUser(id) {
    return await this.db.findUser(id);
  }

  async updateUser(id, data) {
    return await this.db.updateUser(id, data);
  }
}
// ... existing code ...
```

## Error Handling

Morph is trained to be robust to poor quality update snippets, but you should still follow these steps to ensure the best quality.
When tools fail, follow these steps:

1. **Check file permissions**: Ensure the target file is writable
2. **Verify file path**: Confirm the file exists and path is correct
3. **Review syntax**: Check that your edit snippet follows the `// ... existing code ...` pattern
4. **Retry with context**: Read the file again and provide more context around your changes
5. **Simplify changes**: Break complex edits into smaller, focused changes

**Common Error Patterns:**

```javascript theme={null}
// ❌ Wrong - missing context
function newFunction() {
  return "hello";
}

// ✅ Correct - with context
// ... existing code ...
function newFunction() {
  return "hello";
}
// ... existing code ...
```

## Next Steps

Ready to start building with Morph? Here's what to do next:

<Card title="Explore the Apply API" icon="code" href="/api-reference/endpoint/apply" horizontal>
  Learn about the Apply API endpoints, models, and message formats for
  production use
</Card>

<Card title="Quickstart Guide" icon="rocket" href="/quickstart" horizontal>
  Step-by-step guide to configure your agent with the edit\_file tool and
  integrate with Morph's Fast Apply API
</Card>

<Tip>
  For complex refactoring across multiple files, consider using multiple
  `edit_file` calls in sequence. For failed edits, read the file again and
  provide more context around your changes.
</Tip>
