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

# API Reference

> Complete MorphClient API and types

## MorphClient

Unified client for all Morph tools.

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

const morph = new MorphClient({
  apiKey?: string;          // Your Morph API key
  debug?: boolean;          // Default: false (enables logging)
  timeout?: number;         // Default: varies by tool
  retryConfig?: RetryConfig; // Optional retry configuration
});
```

### Namespaces

```typescript theme={null}
morph.fastApply         // FastApplyClient
morph.codebaseSearch    // CodebaseSearchClient
morph.git               // MorphGit
```

### Standalone Clients (Advanced)

Need custom configuration per tool? Use individual clients:

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

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

<Tip>
  **Use when:** You need tool-specific configuration that differs from defaults (custom URLs, different timeouts, etc.).
</Tip>

***

## Fast Apply

### `morph.fastApply.execute(input, overrides?)`

Edit files with AI-powered merge.

```typescript theme={null}
const result = await morph.fastApply.execute({
  target_filepath: 'src/auth.ts',
  baseDir: './my-project',      // Optional: defaults to cwd
  instructions: 'Add error handling',
  code_edit: '// ... existing code ...\nif (!user) throw new Error("Invalid");\n// ... existing code ...'
}, {
  // Optional overrides
  generateUdiff: true,
  autoWrite: true,
  timeout: 60000
});

console.log(result.udiff);
console.log(result.changes);  // { linesAdded, linesRemoved, linesModified }
```

### Framework Adapters

<CodeGroup>
  ```typescript Anthropic theme={null}
  import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/anthropic';

  const tool = createEditFileTool(morph.fastApply);
  // OR with config: createEditFileTool({ morphApiKey: '...' })
  ```

  ```typescript OpenAI theme={null}
  import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/openai';

  const tool = createEditFileTool(morph.fastApply);
  ```

  ```typescript Vercel theme={null}
  import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/vercel';

  const tool = createEditFileTool(morph.fastApply);
  ```
</CodeGroup>

### Types

```typescript theme={null}
interface EditFileInput {
  target_filepath: string;
  instructions: string;
  code_edit: string;
}

interface EditFileResult {
  success: boolean;
  filepath: string;
  udiff?: string;
  changes: {
    linesAdded: number;
    linesRemoved: number;
    linesModified: number;
  };
  error?: string;
}
```

***

## Codebase Search

### `morph.codebaseSearch.search(input, overrides?)`

Semantic code search with 2-stage retrieval.

```typescript theme={null}
const result = await morph.codebaseSearch.search({
  query: 'How does user authentication work?',
  repoId: 'my-project',             // Required per search
  target_directories: ['src/auth'], // or [] for entire repo
  explanation: 'Finding auth logic',
  limit: 10
}, {
  // Optional overrides
  timeout: 60000,
  searchUrl: 'https://custom-search.example.com'
});

console.log(result.results);  // Top 10 code chunks
console.log(result.stats);    // { totalResults, candidatesRetrieved, searchTimeMs }
```

### Framework Adapters

<CodeGroup>
  ```typescript Anthropic theme={null}
  import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/anthropic';

  const tool = createCodebaseSearchTool({ 
    client: morph.codebaseSearch, 
    repoId: 'my-project' 
  });
  // OR with config: createCodebaseSearchTool({ repoId: 'my-project' })
  ```

  ```typescript OpenAI theme={null}
  import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/openai';

  const tool = createCodebaseSearchTool({ 
    client: morph.codebaseSearch, 
    repoId: 'my-project' 
  });
  ```

  ```typescript Vercel theme={null}
  import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/vercel';

  const tool = createCodebaseSearchTool({ 
    client: morph.codebaseSearch, 
    repoId: 'my-project' 
  });
  ```
</CodeGroup>

### Types

```typescript theme={null}
interface CodebaseSearchInput {
  query: string;
  target_directories: string[];
  explanation: string;
  limit?: number;  // Default: 10
}

interface CodeSearchResult {
  filepath: string;              // "auth.ts::AuthService.login@L10-L25"
  symbolPath: string;            // "AuthService.login"
  content: string;               // Function/class code
  language: string;              // "typescript"
  startLine: number;
  endLine: number;
  embeddingSimilarity: number;   // 0-1
  rerankScore: number;           // 0-1 (higher = more relevant)
}

interface CodebaseSearchResult {
  success: boolean;
  results: CodeSearchResult[];
  stats: {
    totalResults: number;
    candidatesRetrieved: number;
    searchTimeMs: number;
  };
  error?: string;
}
```

<Note>
  **Requires git push:** Code must be pushed with MorphGit to generate embeddings before searching.
</Note>

***

## Git Operations

### `morph.git.*`

Access the MorphGit client via `morph.git`.

```typescript theme={null}
// All standard git operations available
await morph.git.init({ repoId: 'my-project', dir: './project' });
await morph.git.clone({ repoId: 'my-project', dir: './project' });
await morph.git.add({ dir: './project', filepath: '.' });
await morph.git.commit({ dir: './project', message: 'Update' });
await morph.git.push({ dir: './project' });
await morph.git.pull({ dir: './project' });
```

### Repository Management

```typescript theme={null}
// Initialize new repository
await morph.git.init({
  repoId: string;
  dir: string;
  defaultBranch?: string;  // Default: 'main'
});

// Clone existing repository
await morph.git.clone({
  repoId: string;
  dir: string;
  branch?: string;
  depth?: number;
  singleBranch?: boolean;  // Default: true
});
```

### Basic Operations

```typescript theme={null}
// Stage files
await morph.git.add({
  dir: string;
  filepath: string;  // Use '.' for all files
});

// Commit changes
const sha = await morph.git.commit({
  dir: string;
  message: string;
  author?: { name: string; email: string; };
});

// Push to remote (triggers auto-embedding)
await morph.git.push({
  dir: string;
  remote?: string;   // Default: 'origin'
  branch?: string;
});

// Pull from remote
await morph.git.pull({
  dir: string;
  remote?: string;
  branch?: string;
});
```

### Status & History

```typescript theme={null}
// Get file status
const status = await morph.git.status({
  dir: string;
  filepath: string;
});
// Returns: 'modified' | '*added' | 'deleted' | 'unmodified' | 'absent'

// Get all file statuses
const matrix = await morph.git.statusMatrix({ dir: string });
// Returns: { filepath: string; status: string; }[]

// Get commit history
const commits = await morph.git.log({
  dir: string;
  depth?: number;
  ref?: string;
});
```

### Branching

```typescript theme={null}
// Create branch
await morph.git.branch({
  dir: string;
  name: string;
  checkout?: boolean;  // Default: false
});

// Checkout branch/commit
await morph.git.checkout({
  dir: string;
  ref: string;
});

// List all branches
const branches = await morph.git.listBranches({ dir: string });

// Get current branch
const current = await morph.git.currentBranch({ dir: string });

// Get commit hash
const hash = await morph.git.resolveRef({ dir: string; ref: 'HEAD' });
```

<Tip>
  **Auto-embedding on push:** Every `git.push()` triggers automatic embedding generation for semantic search (\~8 seconds in background).
</Tip>

***

## Environment Variables

```bash theme={null}
# Required for most tools
MORPH_API_KEY=YOUR_API_KEY

# Optional overrides (advanced users only)
MORPH_API_URL=https://api.morphllm.com      # Fast Apply API
MORPH_SEARCH_URL=http://embedrerank.morphllm.com:8081  # Search API
MORPH_ENVIRONMENT=DEV                        # Use localhost for browser worker
```

Get your API key: [morphllm.com/dashboard/api-keys](https://morphllm.com/dashboard/api-keys)

***

## Import Patterns

### Main SDK (Recommended)

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

// Individual clients (for advanced use)
import { 
  FastApplyClient, 
  CodebaseSearchClient,
  MorphGit 
} from '@morphllm/morphsdk';

// All types
import type { 
  EditFileInput,
  CodebaseSearchInput,
  // ... etc
} from '@morphllm/morphsdk';
```

### Framework Adapters

```typescript theme={null}
// Anthropic
import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/anthropic';
import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/anthropic';

// OpenAI
import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/openai';
import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/openai';

// Vercel
import { createEditFileTool } from '@morphllm/morphsdk/tools/fastapply/vercel';
import { createCodebaseSearchTool } from '@morphllm/morphsdk/tools/codebase-search/vercel';
```

***

## Error Handling

All tools return results with `success: boolean` and optional `error: string`.

```typescript theme={null}
const result = await morph.fastApply.execute({ ... });

if (!result.success) {
  console.error('Edit failed:', result.error);
  // Handle error...
}

const searchResults = await morph.codebaseSearch.search({ ... });
if (!searchResults.success) {
  console.error('Search failed:', searchResults.error);
}
```

<Tip>
  **Automatic retries:** SDK automatically retries failed requests with exponential backoff for transient errors (rate limits, timeouts).
</Tip>

***

## Next Steps

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

  <Card title="Dashboard" icon="chart-line" href="https://morphllm.com/dashboard">
    Monitor usage and manage API keys
  </Card>
</CardGroup>
