> ## 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.

# Tools

> Four tools for building AI coding agents

Use the unified `MorphClient` to access all tools, or import individual clients for advanced use.

```typescript theme={null}
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: "YOUR_API_KEY" });

// All tools available via namespaces
morph.fastApply.execute({ ... });
morph.codebaseSearch.search({ ... });
morph.browser.execute({ ... });
morph.git.push({ ... });
```

***

## Fast Apply

Apply LLM edits to files at **10,500 tokens/s**. Handles lazy edits with `// ... existing code ...` markers.

```typescript theme={null}
await morph.fastApply.execute({
  target_filepath: 'src/auth.ts',
  baseDir: './my-project',      // Optional: defaults to cwd
  instructions: 'Add input validation',
  code_edit: `
function login(email, password) {
  // ... existing code ...
  if (!email || !password) throw new Error('Invalid input');
  // ... existing code ...
}
  `
});

// Returns: unified diff + change stats
```

**When to use:** Agent needs to edit code files

**Returns:** Unified diff + change stats (lines added/removed/modified)

**Speed:** 10,500+ tokens/s (40% faster than search-and-replace)

<Tip>
  **Path security:** SDK validates all file paths are within `baseDir` to prevent directory traversal attacks.
</Tip>

***

## Codebase Search

Two-stage semantic search: **embedding similarity + GPU reranking**. Returns top 10 results in \~1230ms.

```typescript theme={null}
const results = await morph.codebaseSearch.search({
  query: 'Where is user authentication handled?',
  repoId: 'my-project',
  target_directories: ['src/auth'],  // or [] for entire repo
  explanation: 'Finding auth logic',
  limit: 10
});

// Returns: Top 10 code chunks with:
// - File path + line numbers
// - Function/class context  
// - Similarity scores (embedding + rerank)
console.log(results.results[0].content);
console.log(results.results[0].rerankScore);
```

**When to use:** Agent needs to find relevant code

**Returns:** Ranked code chunks with scores + metadata

**Speed:** \~1230ms (vector search + GPU reranking)

<Note>
  **Requires git push:** Code must be pushed with MorphGit first to create searchable embeddings. Embeddings are generated automatically on push (takes \~8 seconds in background).
</Note>

<Warning>
  **First search after push:** Wait \~10 seconds after pushing before searching to allow embedding generation to complete.
</Warning>

### How It Works

```mermaid theme={null}
graph LR
    A[Query] --> B[Stage 1: Vector Search]
    B --> C[50 candidates]
    C --> D[Stage 2: GPU Rerank]
    D --> E[Top 10 results]
```

1. **Stage 1 (30ms):** Vector similarity search retrieves 50 candidates
2. **Stage 2 (150ms):** GPU reranking scores candidates for precision

**Result:** Best-in-class accuracy at 230ms total latency

***

## Git Operations

Remote repository storage with **automatic embedding generation** on push.

```typescript theme={null}
// Initialize new repo
await morph.git.init({ repoId: 'my-project', dir: './project' });

// Standard git operations
await morph.git.add({ dir: './project', filepath: '.' });
await morph.git.commit({ dir: './project', message: 'Initial commit' });
await morph.git.push({ dir: './project' });
// ✨ Push triggers automatic embedding generation (~8 seconds in background)

// Clone existing repo
await morph.git.clone({ repoId: 'my-project', dir: './project' });

// Branching
await morph.git.branch({ dir: './project', name: 'feature', checkout: true });
await morph.git.checkout({ dir: './project', ref: 'main' });

// History
const commits = await morph.git.log({ dir: './project', depth: 10 });
const branches = await morph.git.listBranches({ dir: './project' });
```

**When to use:** Agent builds apps and needs version control

**Returns:** Standard git operations (init, clone, push, pull, etc.)

**Bonus:** Auto-embeds code for semantic search on every push

<Tip>
  **Fast push response:** Git push returns in 200ms. Embedding generation happens asynchronously in the background (\~3-8 seconds).
</Tip>

***

## Browser Automation

Natural language browser testing with **session recording** and error detection.

### Basic Usage

```typescript theme={null}
const result = await morph.browser.execute({
  task: 'Test the signup flow',
  url: 'https://3000-abc.e2b.dev',
  maxSteps: 15,
  model: 'morph-computer-use-v0'  // or 'gemini-flash-latest'
});

console.log(result.success);        // true/false
console.log(result.result);         // Agent findings
console.log(result.stepsTaken);     // Browser actions executed
```

### With Video Recording

```typescript theme={null}
const result = await morph.browser.executeWithRecording({
  task: 'Test checkout for buying a pineapple',
  url: 'https://3000-abc.e2b.dev',
  maxSteps: 20,
  recordVideo: true,
  videoWidth: 1280,
  videoHeight: 720
});

if (result.recording?.videoUrl) {
  console.log('📹 Video:', result.recording.videoUrl);
  console.log('📊 Size:', result.recording.fileSize);
  
  // Get errors with screenshots
  const { errors } = await morph.browser.getErrors(result.recording.id);
  errors.forEach(e => console.log(e.screenshotUrl));
}
```

**When to use:** Agent needs to test web applications

**Returns:** Test results + optional session video + console logs + error screenshots

**Recording format:** WebM video, 7-day presigned S3 URLs, auto-deleted after 30 days

<Note>
  **Works with e2b.dev URLs:** The browser worker can access e2b.dev preview environments and other publicly accessible URLs.
</Note>

<Warning>
  **Max video length:** Videos are limited to 3 minutes. For longer tests, use `recordVideo: false`.
</Warning>

***

## Standalone Clients (Advanced)

Need custom configuration per tool? Use standalone clients instead of MorphClient:

```typescript theme={null}
import { BrowserClient, FastApplyClient } from 'morphsdk';

// Browser with custom API URL for local testing
const browser = new BrowserClient({
  apiKey: "YOUR_API_KEY",
  apiUrl: 'http://localhost:8000',
  timeout: 180000
});

await browser.execute({ task: 'Test login' });
await browser.waitForRecording(recordingId);

// FastApply with custom settings
const fastApply = new FastApplyClient({
  apiKey: "YOUR_API_KEY",
  timeout: 60000
});

await fastApply.execute({
  target_filepath: 'auth.ts',
  baseDir: './my-project',
  instructions: '...',
  code_edit: '...'
});
```

<Tip>
  **When to use:** You need tool-specific configuration that differs from defaults (e.g., custom URLs, different timeouts per tool).
</Tip>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Examples" icon="code" href="/sdk/examples">
    See real-world agent patterns
  </Card>

  <Card title="API Reference" icon="book" href="/sdk/reference">
    Complete function signatures
  </Card>
</CardGroup>
