mcpField
M
morph-warpgrep

morph-warpgrep

github.com/letta-aiAgent 工作流152174 次安装4 周前更新
代码仓库

关于 morph-warpgrep

Morph WarpGrep & Fast Apply 是面向编码 Agent 的代码库搜索与代码修改技能。WarpGrep 通过迭代调用本地文件工具搜索上下文,Fast Apply 则将生成的修改合并到现有代码中。

主要功能

  1. 01使用 WarpGrep 搜索代码库
  2. 02通过本地文件工具细化搜索
  3. 03返回相关代码上下文
  4. 04用 Fast Apply 合并生成的修改
  5. 05作为 MCP 搜索工具使用

适用场景

  1. 01追踪大型代码库中的逻辑
  2. 02查找与错误相关的代码
  3. 03将生成的修改应用到现有文件

MCP 相关

README 介绍了可供 Claude Code 和 Cursor 等客户端安装的 MCP 服务。它提供 `warpgrep_codebase_search` 工具。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/letta-ai/skills --skill morph-warpgrep

安装后在 Claude Code 中输入/morph-warpgrep确认已加载。

附带文件LICENSEscripts/test-warpgrep.ts

详细介绍

Morph WarpGrep 与 Fast Apply

Morph 提供了两种可显著提升编码 Agent 性能的工具:

  • WarpGrep:Agent 式代码搜索,速度比常规搜索快 5 倍,使用并行工具调用,约 4 步即可达到 0.73 F1
  • Fast Apply:以 10,500 tok/s 的速度将 AI 编辑合并到代码中,准确率达 98%(比搜索替换快 2 倍)

前提条件

  1. 从 https://www.morphllm.com/dashboard 获取 Morph API 密钥
  2. 设置环境变量:
export MORPH_API_KEY="your-api-key"
  1. 安装 Morph SDK:
bun add @morphllm/morphsdk
# or
npm install @morphllm/morphsdk
  1. 确保已安装 ripgrep(本地搜索所需):
# macOS
brew install ripgrep

# Ubuntu/Debian  
sudo apt install ripgrep

# Verify installation
rg --version

快速测试

完成设置后,在任意本地仓库中运行随附的测试脚本:

# Clone a test repo (or use any existing codebase)
git clone https://github.com/letta-ai/letta-code.git test-repo

# Install SDK
cd test-repo
bun add @morphllm/morphsdk

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

预期输出:

======================================================================
MORPH WARPGREP TEST
======================================================================
Repo: .
SDK: @morphllm/morphsdk
======================================================================

| Query                              | Result | Time   | Files |
|------------------------------------|--------|--------|-------|
| Find the main entry point          | ✅     | 5.2s   | 2     |
| Find authentication logic          | ✅     | 4.1s   | 4     |
| Find where configuration is handled | ✅     | 3.8s   | 3     |
| Find error handling patterns       | ✅     | 4.5s   | 5     |

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

适用场景

适合使用 WarpGrep 的情况:
  • 搜索大型代码库(1000 多个文件)
  • 深度逻辑查询:追踪 Bug、查找代码路径、分析控制流
  • 需要查找相关上下文,同时避免污染上下文窗口
  • 常规 grep 返回了太多无关结果
适合使用 Fast Apply 的情况:
  • 将 AI 生成的代码编辑应用到现有文件
  • 需要可靠地合并编辑(准确率为 98%,而搜索替换约为 70%)
  • 处理 diff 格式无法胜任的大型文件
不适合使用的情况:
  • 简单的精确匹配搜索(常规 grep/rg 免费且速度足够快)
  • 语义搜索即可满足需求的浅层查询
  • 成本是主要顾虑(Morph API 使用会产生费用)

快速入门:WarpGrep

基本用法
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');
}
响应格式
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
}
用作 Agent 工具
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';
  }
}

快速入门:Fast Apply

Fast Apply 可将 AI 生成的编辑合并到现有代码中:

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);
直接调用 API(替代方案)
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;

测试结果

使用 SDK v0.2.103 在 letta-code 仓库(约 300 个 TypeScript 文件)中进行测试:

查询结果耗时找到的文件
"查找身份验证逻辑"✅4.2ssrc/auth/oauth.ts、src/auth/setup.ts、+2
"查找主 CLI 入口点"✅5.8ssrc/index.ts、src/cli/App.tsx
"查找模型配置位置"✅3.1ssrc/agent/model.ts、src/models.json、+1
"查找内存块的工作方式"✅3.9ssrc/agent/memory.ts、src/agent/memoryFilesystem.ts、+1
"查找设置管理器"✅2.9ssrc/settings-manager.ts、src/settings.ts

5/5 项测试通过

性能概要
  • 平均耗时:4.0 秒
  • Token 效率:与手动搜索相比,输入 Token 减少 39%
  • 准确率:2–4 轮内找到相关代码

WarpGrep 的工作原理

WarpGrep 是一种 Agent 式搜索,最多运行 4 轮:

┌─────────────────────────────────────────────────────────────┐
│  Turn 1: Analyze query, map repo structure, initial search  │
├─────────────────────────────────────────────────────────────┤
│  Turn 2-3: Refine search, read specific files               │
├─────────────────────────────────────────────────────────────┤
│  Turn 4: Return all relevant code locations                 │
└─────────────────────────────────────────────────────────────┘

SDK 会自动处理多轮对话,并执行本地工具:

工具描述实现方式
grep跨文件进行正则表达式搜索使用 ripgrep(rg)
read读取文件内容本地文件系统
list_dir显示目录结构本地文件系统

架构

┌──────────────────────────────────────────────────────────────┐
│                    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)       │
└───────────────────────┘    └───────────────────────┘

Morph 的基准测试

以下数据来自 Morph 使用 Claude 4.5 Opus 进行的 SWE-bench 评估:

指标不使用 WarpGrep使用 WarpGrep提升
输入 Token14K9K减少 39%
Agent 轮次35.026.0减少 26%
已解决任务74.4%81.9%增加 10%

来源:Morph WarpGrep 基准测试


常见模式

先侦察,再行动
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
}
结合使用 WarpGrep 与 Fast Apply
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);
}

MCP 集成

供个人在 Claude Code、Cursor 或其他 MCP 客户端中使用:

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

这会在你的 MCP 客户端中添加一个 warpgrep_codebase_search 工具。


故障排除

未找到 ripgrep
# Install ripgrep
brew install ripgrep  # macOS
sudo apt install ripgrep  # Ubuntu/Debian

# Verify
rg --version
API 密钥问题
# Verify API key works
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"}]}'
SDK 版本问题

确保使用最新版本的 SDK:

bun add @morphllm/morphsdk@latest
# or
npm install @morphllm/morphsdk@latest

成本考量

  • WarpGrep 每次搜索会使用 1-4 次 API 调用(通常为 2-3 次)
  • Fast Apply 每次编辑会使用 1 次 API 调用
  • 定价:每 1M 个 token $0.80(输入和输出)
  • 通过 Morph Dashboard 监控用量
  • 简单的精确匹配搜索请使用常规 grep/ripgrep(免费)

资源

评论

支持 Markdown