morph-warpgrep

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Morph WarpGrep & Fast Apply

Morph WarpGrep 与 Fast Apply

Morph provides two tools that significantly improve coding agent performance:
  • WarpGrep: Agentic code search that's 5x faster than regular search, uses parallel tool calls, achieves 0.73 F1 in ~4 steps
  • Fast Apply: Merges AI edits into code at 10,500 tok/s with 98% accuracy (2x faster than search-replace)
Morph 提供两款可显著提升编码Agent性能的工具:
  • WarpGrep:智能代码搜索工具,速度比常规搜索快5倍,采用并行工具调用,约4步即可达到0.73的F1值
  • Fast Apply:以10500令牌/秒的速度将AI生成的编辑内容合并到代码中,准确率达98%(比搜索替换快2倍)

Prerequisites

前置条件

  1. Get a Morph API key from https://www.morphllm.com/dashboard
  2. Set environment variable:
bash
export MORPH_API_KEY="your-api-key"
  1. Install the Morph SDK:
bash
bun add @morphllm/morphsdk
  1. https://www.morphllm.com/dashboard 获取Morph API密钥
  2. 设置环境变量:
bash
export MORPH_API_KEY="your-api-key"
  1. 安装Morph SDK:
bash
bun add @morphllm/morphsdk

or

npm install @morphllm/morphsdk

4. Ensure `ripgrep` is installed (required for local search):

```bash
npm install @morphllm/morphsdk

4. 确保已安装`ripgrep`(本地搜索必需):

```bash

macOS

macOS

brew install ripgrep
brew install ripgrep

Ubuntu/Debian

Ubuntu/Debian

sudo apt install ripgrep
sudo apt install ripgrep

Verify installation

验证安装

rg --version
undefined
rg --version
undefined

Quick Test

快速测试

After setup, run the included test script on any local repository:
bash
undefined
设置完成后,在任意本地代码仓库运行附带的测试脚本:
bash
undefined

Clone a test repo (or use any existing codebase)

克隆测试仓库(或使用现有代码库)

Install SDK

安装SDK

cd test-repo bun add @morphllm/morphsdk
cd test-repo bun add @morphllm/morphsdk

Run test script

运行测试脚本

export MORPH_API_KEY="your-key" bun ../scripts/test-warpgrep.ts .

Expected output:

====================================================================== MORPH WARPGREP TEST

Repo: . SDK: @morphllm/morphsdk

QueryResultTimeFiles
Find the main entry point5.2s2
Find authentication logic4.1s4
Find where configuration is handled3.8s3
Find error handling patterns4.5s5

====================================================================== Results: 4 passed, 0 failed


---
export MORPH_API_KEY="your-key" bun ../scripts/test-warpgrep.ts .

预期输出:

====================================================================== MORPH WARPGREP TEST

Repo: . SDK: @morphllm/morphsdk

QueryResultTimeFiles
Find the main entry point5.2s2
Find authentication logic4.1s4
Find where configuration is handled3.8s3
Find error handling patterns4.5s5

====================================================================== Results: 4 passed, 0 failed


---

When to Use

使用场景

Use WarpGrep When:

适合使用WarpGrep的场景:

  • Searching large codebases (1000+ files)
  • Deep logic queries: bug tracing, code paths, control flow analysis
  • Need to find relevant context without polluting the context window
  • Regular grep returns too many irrelevant results
  • 搜索大型代码库(1000+文件)
  • 深度逻辑查询:Bug追踪、代码路径、控制流分析
  • 需要在不污染上下文窗口的情况下找到相关代码上下文
  • 常规grep返回过多无关结果时

Use Fast Apply When:

适合使用Fast Apply的场景:

  • Applying AI-generated code edits to existing files
  • Need reliable edit merging (98% accuracy vs ~70% for search-replace)
  • Working with large files where diff formats fail
  • 将AI生成的代码编辑内容应用到现有文件
  • 需要可靠的编辑合并功能(准确率98%,远高于搜索替换的约70%)
  • 处理差异格式失效的大型文件时

Don't Use When:

不适合使用的场景:

  • Simple exact-match searches (regular
    grep
    /
    rg
    is free and fast enough)
  • Surface-level queries where semantic search suffices
  • Cost is a major concern (Morph API has usage costs)

  • 简单精确匹配搜索(常规
    grep
    /
    rg
    免费且速度足够)
  • 语义搜索即可满足的表层查询
  • 成本为主要考虑因素(Morph API按使用量收费)

Quick Start: WarpGrep

快速开始:WarpGrep

Basic Usage

基础用法

typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

const result = await morph.warpGrep.execute({
  query: 'Find authentication middleware',
  repoRoot: '.'
});

if (result.success) {
  for (const ctx of result.contexts) {
    console.log(`File: ${ctx.file}`);
    console.log(ctx.content);
  }
} else {
  console.error('Search failed');
}
typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

const result = await morph.warpGrep.execute({
  query: 'Find authentication middleware',
  repoRoot: '.'
});

if (result.success) {
  for (const ctx of result.contexts) {
    console.log(`File: ${ctx.file}`);
    console.log(ctx.content);
  }
} else {
  console.error('Search failed');
}

Response Format

响应格式

typescript
interface WarpGrepResult {
  success: boolean;
  contexts: Array<{
    file: string;    // File path relative to repo root
    content: string; // File content with relevant code
  }>;
  summary?: string;  // Human-readable summary
}
typescript
interface WarpGrepResult {
  success: boolean;
  contexts: Array<{
    file: string;    // 相对于仓库根目录的文件路径
    content: string; // 包含相关代码的文件内容
  }>;
  summary?: string;  // 人类可读的摘要
}

Using as an Agent Tool

作为Agent工具使用

typescript
import { MorphClient } from '@morphllm/morphsdk';
import Anthropic from '@anthropic-ai/sdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });
const anthropic = new Anthropic();

// Define WarpGrep as a tool
const tools = [{
  name: 'warpgrep_search',
  description: 'Search codebase for relevant code. Use for finding implementations, tracing bugs, or understanding code flow.',
  input_schema: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'What to search for' }
    },
    required: ['query']
  }
}];

// Handle tool calls
async function handleToolCall(name: string, input: { query: string }) {
  if (name === 'warpgrep_search') {
    const result = await morph.warpGrep.execute({
      query: input.query,
      repoRoot: process.cwd()
    });
    
    if (result.success) {
      return result.contexts.map(c => `## ${c.file}\n${c.content}`).join('\n\n');
    }
    return 'No results found';
  }
}

typescript
import { MorphClient } from '@morphllm/morphsdk';
import Anthropic from '@anthropic-ai/sdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });
const anthropic = new Anthropic();

// 定义WarpGrep为工具
const tools = [{
  name: 'warpgrep_search',
  description: '搜索代码库以找到相关代码。用于查找实现逻辑、追踪Bug或理解代码流程。',
  input_schema: {
    type: 'object',
    properties: {
      query: { type: 'string', description: '搜索内容' }
    },
    required: ['query']
  }
}];

// 处理工具调用
async function handleToolCall(name: string, input: { query: string }) {
  if (name === 'warpgrep_search') {
    const result = await morph.warpGrep.execute({
      query: input.query,
      repoRoot: process.cwd()
    });
    
    if (result.success) {
      return result.contexts.map(c => `## ${c.file}\n${c.content}`).join('\n\n');
    }
    return '未找到结果';
  }
}

Quick Start: Fast Apply

快速开始:Fast Apply

Fast Apply merges AI-generated edits into existing code:
typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

const result = await morph.fastApply.apply({
  originalCode: `function divide(a, b) {
  return a / b;
}`,
  editSnippet: `function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}`
});

console.log(result.mergedCode);
Fast Apply 可将AI生成的编辑内容合并到现有代码中:
typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

const result = await morph.fastApply.apply({
  originalCode: `function divide(a, b) {
  return a / b;
}`,
  editSnippet: `function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}`
});

console.log(result.mergedCode);

Direct API (Alternative)

直接调用API(替代方案)

typescript
const response = await fetch('https://api.morphllm.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.MORPH_API_KEY}`
  },
  body: JSON.stringify({
    model: 'morph-v3-fast',  // or 'morph-v3-large' for complex edits
    messages: [{
      role: 'user',
      content: `<instruction>Add error handling</instruction>
<code>function divide(a, b) { return a / b; }</code>
<update>function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}</update>`
    }],
    temperature: 0
  })
});

const data = await response.json();
const mergedCode = data.choices[0].message.content;

typescript
const response = await fetch('https://api.morphllm.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.MORPH_API_KEY}`
  },
  body: JSON.stringify({
    model: 'morph-v3-fast',  // 复杂编辑场景可使用'morph-v3-large'
    messages: [{
      role: 'user',
      content: `<instruction>Add error handling</instruction>
<code>function divide(a, b) { return a / b; }</code>
<update>function divide(a, b) {
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}</update>`
    }],
    temperature: 0
  })
});

const data = await response.json();
const mergedCode = data.choices[0].message.content;

Tested Results

测试结果

Tested on the letta-code repository (~300 TypeScript files) using SDK v0.2.103:
QueryResultTimeFiles Found
"Find authentication logic"4.2s
src/auth/oauth.ts
,
src/auth/setup.ts
, +2
"Find the main CLI entry point"5.8s
src/index.ts
,
src/cli/App.tsx
"Find where models are configured"3.1s
src/agent/model.ts
,
src/models.json
, +1
"Find how memory blocks work"3.9s
src/agent/memory.ts
,
src/agent/memoryFilesystem.ts
, +1
"Find the settings manager"2.9s
src/settings-manager.ts
,
src/settings.ts
5/5 tests passed
使用SDK v0.2.103在letta-code仓库(约300个TypeScript文件)上测试的结果:
查询内容结果耗时找到的文件
"查找认证逻辑"4.2s
src/auth/oauth.ts
,
src/auth/setup.ts
, +2
"查找CLI主入口"5.8s
src/index.ts
,
src/cli/App.tsx
"查找模型配置位置"3.1s
src/agent/model.ts
,
src/models.json
, +1
"查找内存块工作机制"3.9s
src/agent/memory.ts
,
src/agent/memoryFilesystem.ts
, +1
"查找设置管理器"2.9s
src/settings-manager.ts
,
src/settings.ts
5项测试全部通过

Performance Summary

性能总结

  • Average time: 4.0 seconds
  • Token efficiency: 39% fewer input tokens vs manual search
  • Accuracy: Finds relevant code in 2-4 turns

  • 平均耗时:4.0秒
  • 令牌效率:比手动搜索减少39%的输入令牌
  • 准确率:2-4轮即可找到相关代码

How WarpGrep Works

WarpGrep 工作原理

WarpGrep is an agentic search that runs up to 4 turns:
┌─────────────────────────────────────────────────────────────┐
│  Turn 1: Analyze query, map repo structure, initial search  │
├─────────────────────────────────────────────────────────────┤
│  Turn 2-3: Refine search, read specific files               │
├─────────────────────────────────────────────────────────────┤
│  Turn 4: Return all relevant code locations                 │
└─────────────────────────────────────────────────────────────┘
The SDK handles the multi-turn conversation automatically, executing local tools:
ToolDescriptionImplementation
grep
Regex search across filesUses ripgrep (
rg
)
read
Read file contentsLocal filesystem
list_dir
Show directory structureLocal filesystem

WarpGrep是一款智能搜索工具,最多执行4轮交互:
┌─────────────────────────────────────────────────────────────┐
│  第1轮:分析查询,映射仓库结构,初始搜索  │
├─────────────────────────────────────────────────────────────┤
│  第2-3轮:优化搜索,读取指定文件               │
├─────────────────────────────────────────────────────────────┤
│  第4轮:返回所有相关代码位置                 │
└─────────────────────────────────────────────────────────────┘
SDK会自动处理多轮对话,并执行本地工具:
工具描述实现方式
grep
跨文件正则搜索使用ripgrep (
rg
)
read
读取文件内容本地文件系统
list_dir
显示目录结构本地文件系统

Architecture

架构

┌──────────────────────────────────────────────────────────────┐
│                    Your Code / Agent                         │
└──────────────────────────┬───────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│              @morphllm/morphsdk                              │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │ 1. Build repo structure                                 │ │
│  │ 2. Send query to Morph API                              │ │
│  │ 3. Execute local tools (grep, read, list_dir)           │ │
│  │ 4. Multi-turn refinement                                │ │
│  │ 5. Return relevant code contexts                        │ │
│  └─────────────────────────────────────────────────────────┘ │
└──────────────────────────┬───────────────────────────────────┘
            ┌──────────────┴──────────────┐
            ▼                             ▼
┌───────────────────────┐    ┌───────────────────────┐
│    Morph API          │    │   Local Filesystem    │
│  (morph-warp-grep-v1) │    │   (ripgrep, fs)       │
└───────────────────────┘    └───────────────────────┘

┌──────────────────────────────────────────────────────────────┐
│                    你的代码 / Agent                         │
└──────────────────────────┬───────────────────────────────────┘
┌──────────────────────────────────────────────────────────────┐
│              @morphllm/morphsdk                              │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │ 1. 构建仓库结构                                 │ │
│  │ 2. 向Morph API发送查询                              │ │
│  │ 3. 执行本地工具(grep、read、list_dir)           │ │
│  │ 4. 多轮优化                                │ │
│  │ 5. 返回相关代码上下文                        │ │
│  └─────────────────────────────────────────────────────────┘ │
└──────────────────────────┬───────────────────────────────────┘
            ┌──────────────┴──────────────┐
            ▼                             ▼
┌───────────────────────┐    ┌───────────────────────┐
│    Morph API          │    │   本地文件系统    │
│  (morph-warp-grep-v1) │    │   (ripgrep、fs)       │
└───────────────────────┘    └───────────────────────┘

Morph's Benchmarks

Morph 基准测试

From Morph's SWE-bench evaluation with Claude 4.5 Opus:
MetricWithout WarpGrepWith WarpGrepImprovement
Input Tokens14K9K39% fewer
Agent Turns35.026.026% fewer
Tasks Solved74.4%81.9%10% more

来自Morph使用Claude 4.5 Opus进行的SWE-bench评估结果:
指标未使用WarpGrep使用WarpGrep提升幅度
输入令牌数14K9K减少39%
Agent交互轮数35.026.0减少26%
完成任务数74.4%81.9%提升10%

Common Patterns

常见使用模式

Reconnaissance-Then-Action

先侦察后操作

typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

// 1. Search for relevant code
const result = await morph.warpGrep.execute({
  query: 'Where is the payment processing logic?',
  repoRoot: '.'
});

// 2. Use found contexts to inform next steps
if (result.success) {
  const relevantFiles = result.contexts.map(c => c.file);
  console.log('Found relevant files:', relevantFiles);
  // Now read/edit these specific files
}
typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

// 1. 搜索相关代码
const result = await morph.warpGrep.execute({
  query: '支付处理逻辑位于何处?',
  repoRoot: '.'
});

// 2. 使用找到的上下文指导后续操作
if (result.success) {
  const relevantFiles = result.contexts.map(c => c.file);
  console.log('找到相关文件:', relevantFiles);
  // 现在可以读取/编辑这些指定文件
}

Combining WarpGrep + Fast Apply

结合使用WarpGrep与Fast Apply

typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

// 1. Find the code to modify
const search = await morph.warpGrep.execute({
  query: 'Find the user validation function',
  repoRoot: '.'
});

if (search.success && search.contexts.length > 0) {
  const targetFile = search.contexts[0];
  
  // 2. Apply an edit
  const result = await morph.fastApply.apply({
    originalCode: targetFile.content,
    editSnippet: '// Add your modified version here'
  });
  
  console.log(result.mergedCode);
}

typescript
import { MorphClient } from '@morphllm/morphsdk';

const morph = new MorphClient({ apiKey: process.env.MORPH_API_KEY });

// 1. 找到需要修改的代码
const search = await morph.warpGrep.execute({
  query: '查找用户验证函数',
  repoRoot: '.'
});

if (search.success && search.contexts.length > 0) {
  const targetFile = search.contexts[0];
  
  // 2. 应用编辑内容
  const result = await morph.fastApply.apply({
    originalCode: targetFile.content,
    editSnippet: '// 在此处添加你的修改版本'
  });
  
  console.log(result.mergedCode);
}

MCP Integration

MCP 集成

For personal use with Claude Code, Cursor, or other MCP clients:
bash
undefined
如需在Claude Code、Cursor或其他MCP客户端中个人使用:
bash
undefined

Install MCP server

安装MCP服务器

claude mcp add morph --scope user -e MORPH_API_KEY=YOUR_API_KEY --npx -y @morphllm/morphmcp

This adds a `warpgrep_codebase_search` tool to your MCP client.

---
claude mcp add morph --scope user -e MORPH_API_KEY=YOUR_API_KEY --npx -y @morphllm/morphmcp

此操作会为你的MCP客户端添加`warpgrep_codebase_search`工具。

---

Troubleshooting

故障排除

ripgrep Not Found

未找到ripgrep

bash
undefined
bash
undefined

Install ripgrep

安装ripgrep

brew install ripgrep # macOS sudo apt install ripgrep # Ubuntu/Debian
brew install ripgrep # macOS sudo apt install ripgrep # Ubuntu/Debian

Verify

验证安装

rg --version
undefined
rg --version
undefined

API Key Issues

API密钥问题

bash
undefined
bash
undefined

Verify API key works

验证API密钥是否有效

curl -X POST https://api.morphllm.com/v1/chat/completions
-H "Authorization: Bearer $MORPH_API_KEY"
-H "Content-Type: application/json"
-d '{"model":"morph-v3-fast","messages":[{"role":"user","content":"test"}]}'
undefined
curl -X POST https://api.morphllm.com/v1/chat/completions
-H "Authorization: Bearer $MORPH_API_KEY"
-H "Content-Type: application/json"
-d '{"model":"morph-v3-fast","messages":[{"role":"user","content":"test"}]}'
undefined

SDK Version Issues

SDK版本问题

Ensure you're using the latest SDK:
bash
bun add @morphllm/morphsdk@latest
确保使用最新版本的SDK:
bash
bun add @morphllm/morphsdk@latest

or

npm install @morphllm/morphsdk@latest

---
npm install @morphllm/morphsdk@latest

---

Cost Considerations

成本考量

  • WarpGrep uses 1-4 API calls per search (typically 2-3)
  • Fast Apply uses 1 API call per edit
  • Pricing: $0.80 per 1M tokens (input and output)
  • Monitor usage via Morph Dashboard
  • Use regular grep/ripgrep for simple exact-match searches (free)

  • WarpGrep每次搜索使用1-4次API调用(通常为2-3次)
  • Fast Apply每次编辑使用1次API调用
  • 定价:每100万令牌0.8美元(包含输入和输出令牌)
  • 可通过Morph控制台监控使用情况
  • 简单精确匹配搜索建议使用常规grep/ripgrep(免费)

Resources

相关资源