colbymchenry/codegraph
摘要
CodeGraph 是一个开源工具,为代码库创建预索引的知识图谱,使 Claude Code 的探索代理能够即时查询符号关系和调用图,将工具调用次数减少高达 96%,探索时间减少 77%。
查看缓存全文
缓存时间: 2026/05/16 12:23
colbymchenry/codegraph
来源:https://github.com/colbymchenry/codegraph
CodeGraph
用语义化代码智能为 Claude Code 赋能
工具调用减少 94% · 探索速度提升 77% · 完全本地运行
npm 版本 (https://www.npmjs.com/package/@colbymchenry/codegraph)
许可证:MIT (https://opensource.org/licenses/MIT)
Node.js (https://nodejs.org/)
Windows macOS Linux
快速上手
npx @colbymchenry/codegraph
交互式安装程序会自动配置 Claude Code
初始化项目
cd your-project
codegraph init -i
1_C_VYnhpys0UHrOuOgpgoyw
为什么选择 CodeGraph?
当 Claude Code 探索代码库时,它会生成探索代理,通过这些代理使用 grep、glob 和 Read 来扫描文件——每次工具调用都会消耗 token。
CodeGraph 为这些代理提供了一个预索引的知识图谱——包含符号关系、调用图和代码结构。代理可以直接查询图谱,而无需扫描文件。
基准测试结果
在 6 个真实代码库上进行了测试,对比 Claude Code 的探索代理使用和未使用 CodeGraph 的情况:
平均:工具调用减少 92% · 速度提升 71%
| 代码库 | 使用 CG | 未使用 CG | 改进 |
|---|---|---|---|
| VS Code · TypeScript | 3 次调用, 17 秒 | 52 次调用, 1 分 37 秒 | 减少 94% · 快 82% |
| Excalidraw · TypeScript | 3 次调用, 29 秒 | 47 次调用, 1 分 45 秒 | 减少 94% · 快 72% |
| Claude Code · Python + Rust | 3 次调用, 39 秒 | 40 次调用, 1 分 8 秒 | 减少 93% · 快 43% |
| Claude Code · Java | 1 次调用, 19 秒 | 26 次调用, 1 分 22 秒 | 减少 96% · 快 77% |
| Alamofire · Swift | 3 次调用, 22 秒 | 32 次调用, 1 分 39 秒 | 减少 91% · 快 78% |
| Swift 编译器 · Swift/C++ | 6 次调用, 35 秒 | 37 次调用, 2 分 8 秒 | 减少 84% · 快 73% |
完整基准测试详情
所有测试均使用 Claude Opus 4.6(1M 上下文)和 Claude Code v2.1.91。每个测试启动一个探索代理,询问相同的问题。
查询内容:
| 代码库 | 查询 |
|---|---|
| VS Code | “扩展主机如何与主进程通信?” |
| Excalidraw | “协作编辑和实时同步是如何工作的?” |
| Claude Code(Python+Rust) | “工具执行端到端是如何工作的?” |
| Claude Code(Java) | “工具执行端到端是如何工作的?” |
| Alamofire | “跟踪一个请求从 Session.request() 到 URLSession 层的完整流程” |
| Swift 编译器 | “Swift 编译器如何处理错误诊断?” |
使用 CodeGraph——代理使用 codegraph_explore 并停止:
| 代码库 | 索引文件数 | 节点数 | 工具使用次数 | Token 数 | 耗时 | 文件读取数 |
|---|---|---|---|---|---|---|
| VS Code (TypeScript) | 4,002 | 59,377 | 3 | 56.6k | 17 秒 | 0 |
| Excalidraw (TypeScript) | 626 | 9,859 | 3 | 57.1k | 29 秒 | 0 |
| Claude Code (Python+Rust) | 115 | 3,080 | 3 | 67.1k | 39 秒 | 0 |
| Claude Code (Java) | — | — | 1 | 40.8k | 19 秒 | 0 |
| Alamofire (Swift) | 102 | 2,624 | 3 | 57.3k | 22 秒 | 0 |
| Swift 编译器 (Swift/C++) | 25,874 | 272,898 | 6 | 77.4k | 35 秒 | 0 |
未使用 CodeGraph——代理大量使用 grep、find、ls 和 Read:
| 代码库 | 工具使用次数 | Token 数 | 耗时 | 文件读取数 |
|---|---|---|---|---|
| VS Code (TypeScript) | 52 | 89.4k | 1 分 37 秒 | ~15 |
| Excalidraw (TypeScript) | 47 | 77.9k | 1 分 45 秒 | ~20 |
| Claude Code (Python+Rust) | 40 | 69.3k | 1 分 8 秒 | ~15 |
| Claude Code (Java) | 26 | 73.3k | 1 分 22 秒 | ~15 |
| Alamofire (Swift) | 32 | 52.4k | 1 分 39 秒 | ~10 |
| Swift 编译器 (Swift/C++) | 37 | 99.1k | 2 分 8 秒 | ~20 |
关键观察:
- 使用 CodeGraph 后,代理从未回退到读取文件——它完全信任 codegraph_explore 的结果
- 未使用 CodeGraph 时,代理大部分时间花在发现(find、ls、grep)上,然后才能开始读取相关代码
- Java 代码库仅需 1 次 codegraph_explore 调用就回答了全部问题
- 跨语言查询(Python+Rust)无缝工作——CodeGraph 的图遍历能够跨越语言边界找到连接
- Swift 基准测试(Alamofire)追踪了一个9 步调用链,从
Session.request()到URLSession.dataTask()——CodeGraph 在深度 3 的图遍历中,仅用一次探索调用就捕获了整个链条 - Swift 编译器基准测试是最大的代码库(25,874 个文件,272,898 个节点)——CodeGraph 在不到 4 分钟内完成了索引,代理通过 6 次探索调用和零次文件读取,在 35 秒内回答了一个复杂的跨领域问题
主要功能
| 智能上下文构建 | 单次工具调用返回入口点、相关符号和代码片段——无需昂贵的探索代理 |
| 全文搜索 | 基于 FTS5,可在整个代码库中按名称即时查找代码 |
| 影响分析 | 在进行更改之前,追踪任意符号的调用方、被调用方及完整影响范围 |
| 始终最新 | 文件监视器使用原生操作系统事件(FSEvents/inotify/ReadDirectoryChangesW),带防抖自动同步——图谱随编码实时更新,零配置 |
| 支持 19+ 种语言 | TypeScript、JavaScript、Python、Go、Rust、Java、C#、PHP、Ruby、C、C++、Swift、Kotlin、Dart、Svelte、Liquid、Pascal/Delphi |
| 框架感知路由 | 识别 Web 框架路由文件,将 URL 模式通过 references 边链接到对应的处理函数,支持 13 个框架 |
| 100% 本地运行 | 数据不会离开你的机器。无需 API 密钥。无需外部服务。仅使用 SQLite 数据库 |
框架感知路由
CodeGraph 检测 Web 框架路由文件,生成 route 节点,并通过 references 边链接到对应的处理类或函数。查询某个视图/控制器的调用者时,现在会显示出绑定它的 URL 模式。
| 框架 | 识别的模式 |
|---|---|
| Django | path(), re_path(), url(), include() 在 urls.py 中(CBV .as_view(), 点路径) |
| Flask | @app.route('/path', methods=[...]), 蓝图路由 |
| FastAPI | @app.get(...), @router.post(...), 所有标准方法 |
| Express | app.get(...), router.post(...) 带中间件链 |
| Laravel | Route::get(), Route::resource(), Controller@action, 元组语法 |
| Rails | get '/x', to: 'users#index', 哈希火箭 => 语法 |
| Spring | @GetMapping, @PostMapping, @RequestMapping 在方法上 |
| Gin / chi / gorilla / mux | r.GET(...), router.HandleFunc(...) |
| Axum / actix / Rocket | .route("/x", get(handler)) |
| ASP.NET | 动作方法上的 [HttpGet("/x")] 特性 |
| Vapor | app.get("x", use: handler) |
| React Router / SvelteKit | 路由组件节点 |
快速开始
1. 运行安装程序
npx @colbymchenry/codegraph
安装程序将:
- 提示全局安装
codegraph(MCP 服务器需要) - 在
~/.claude.json中配置 MCP 服务器 - 设置 CodeGraph 工具的自动允许权限
- 向
~/.claude/CLAUDE.md添加全局指令 - 可选地初始化当前项目
2. 重启 Claude Code
重启 Claude Code 以加载 MCP 服务器。
3. 初始化项目
cd your-project
codegraph init -i
就是这样!当项目目录中存在 .codegraph/ 时,Claude Code 将自动使用 CodeGraph 工具。
手动设置(替代方案)
全局安装:
npm install -g @colbymchenry/codegraph
添加到 ~/.claude.json:
{
"mcpServers": {
"codegraph": {
"type": "stdio",
"command": "codegraph",
"args": ["serve", "--mcp"]
}
}
}
添加到 ~/.claude/settings.json(可选,用于自动允许):
{
"permissions": {
"allow": [
"mcp__codegraph__codegraph_search",
"mcp__codegraph__codegraph_context",
"mcp__codegraph__codegraph_callers",
"mcp__codegraph__codegraph_callees",
"mcp__codegraph__codegraph_impact",
"mcp__codegraph__codegraph_node",
"mcp__codegraph__codegraph_status",
"mcp__codegraph__codegraph_files"
]
}
}
全局指令参考
安装程序会自动将这些指令添加到 ~/.claude/CLAUDE.md:
## CodeGraph
CodeGraph 构建代码库的语义知识图谱,实现更快、更智能的代码探索。
### 如果项目中存在 `.codegraph/`
**永远不要在主要会话中直接调用 `codegraph_explore` 或 `codegraph_context`。** 这些工具会返回大量源代码,占用主要会话的上下文空间。
相反,对于任何探索性问题(例如“X 是如何工作的?”、“解释 Y 系统”、“Z 在哪里实现?”),始终启动一个探索代理。
**启动探索代理时**,在提示中包含以下指令:
> 此项目已初始化 CodeGraph(存在 .codegraph/)。使用 `codegraph_explore` 作为主要工具——它能在一次调用中返回所有相关文件的完整源代码段落。
>
> **规则:**
> 1. 遵循 `codegraph_explore` 工具描述中的探索调用预算——它会根据项目大小自动调整。
> 2. 不要重新读取 codegraph_explore 已经返回源代码的文件。源代码段落是完整且权威的。
> 3. 仅对“其他相关文件”中列出的文件回退使用 grep/glob/read,如果你需要更多细节,或者 codegraph 没有返回结果时才使用。
**主要会话只能直接使用这些轻量级工具**(用于在编辑前进行针对性查找,而非探索):
| 工具 | 用途 |
|------|---------|
| `codegraph_search` | 按名称查找符号 |
| `codegraph_callers` / `codegraph_callees` | 追踪调用流 |
| `codegraph_impact` | 检查编辑前哪些代码受影响 |
| `codegraph_node` | 获取单个符号的详细信息 |
### 如果不存在 `.codegraph/`
在会话开始时,询问用户是否想要初始化 CodeGraph:“我注意到此项目尚未初始化 CodeGraph。是否希望我运行 `codegraph init -i` 来构建代码知识图谱?”
工作原理
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code │
│ │
│ "实现用户认证" │
│ │
│ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 探索代理 │ ──── │ 探索代理 │ │
│ └────────┬────────┘ └────────┬────────┘ │
│ │ │ │
└───────────┼──────────────────────────┼──────────────────────────┘
│ │
▼ ▼
┌───────────────────────────────────────────────────────────────────┐
│ CodeGraph MCP Server │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 搜索 │ │ 调用者 │ │ 上下文 │ │
│ │ "auth" │ │ "login()" │ │ for task │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └────────────────┼────────────────┘ │
│ ▼ │
│ ┌───────────────────────┐ │
│ │ SQLite 图谱数据库 │ │
│ │ • 387 个符号 │ │
│ │ • 1,204 条边 │ │
│ │ • 即时查询 │ │
│ └───────────────────────┘ │
└───────────────────────────────────────────────────────────────────┘
- 提取 — tree-sitter (https://tree-sitter.github.io/) 将源代码解析为 AST。针对不同语言编写特定查询来提取节点(函数、类、方法)和边(调用、导入、继承、实现)。
- 存储 — 所有内容存入本地 SQLite 数据库(
.codegraph/codegraph.db),启用 FTS5 全文搜索。 - 解析 — 提取完成后,解析引用:函数调用 → 定义,导入 → 源文件,类继承关系,以及框架特定的模式。
- 自动同步 — MCP 服务器使用原生操作系统文件事件监视项目变更。变更经过防抖处理(2 秒静默窗口),仅过滤源文件,并增量同步。图谱随编码保持最新——无需任何配置。
CLI 参考
codegraph # 运行交互式安装程序
codegraph install # 运行安装程序(显式)
codegraph init [path] # 在项目中初始化(--index 同时索引)
codegraph uninit [path] # 从项目中移除 CodeGraph(--force 跳过提示)
codegraph index [path] # 完整索引(--force 重新索引,--quiet 减少输出)
codegraph sync [path] # 增量更新
codegraph status [path] # 显示统计信息
codegraph query # 搜索符号(--kind, --limit, --json)
codegraph files [path] # 显示文件结构(--format, --filter, --max-depth, --json)
codegraph context # 为 AI 构建上下文(--format, --max-nodes)
codegraph affected [files...] # 查找受变更影响的测试文件(见下文)
codegraph serve --mcp # 启动 MCP 服务器
codegraph affected
通过传递性导入依赖追踪,找出受变更源文件影响的测试文件。
codegraph affected src/utils.ts src/api.ts # 直接将文件作为参数传入
git diff --name-only | codegraph affected --stdin # 从 git diff 管道输入
codegraph affected src/auth.ts --filter "e2e/*" # 自定义测试文件模式
| 选项 | 描述 | 默认值 |
|---|---|---|
--stdin | 从标准输入读取文件列表 | false |
-d, --depth <n> | 最大依赖遍历深度 | 5 |
-f, --filter <pattern> | 用于识别测试文件的自定义 glob | 自动检测 |
-j, --json | 以 JSON 格式输出 | false |
-q, --quiet | 仅输出文件路径 | false |
CI/钩子示例:
#!/usr/bin/env bash
AFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet)
if [ -n "$AFFECTED" ]; then
npx vitest run $AFFECTED
fi
MCP 工具
作为 MCP 服务器运行时,CodeGraph 向 Claude Code 暴露以下工具:
| 工具 | 用途 |
|---|---|
codegraph_search | 在整个代码库中按名称查找符号 |
codegraph_context | 为任务构建相关代码上下文 |
codegraph_callers | 查找哪些代码调用了某个函数 |
codegraph_callees | 查找某个函数调用了哪些代码 |
codegraph_impact | 分析修改某个符号会影响哪些代码 |
codegraph_node | 获取特定符号的详细信息(可选带源代码) |
codegraph_files | 获取已索引的文件结构(比文件系统扫描更快) |
codegraph_status | 检查索引健康状况和统计信息 |
库使用方式
import CodeGraph from '@colbymchenry/codegraph';
const cg = await CodeGraph.init('/path/to/project');
// 或者:
const cg = await CodeGraph.open('/path/to/project');
await cg.indexAll({ onProgress: (p) => console.log(`${p.phase}: ${p.current}/${p.total}`) });
const results = cg.searchNodes('UserService');
const callers = cg.getCallers(results[0].node.id);
const context = await cg.buildContext('fix login bug', { maxNodes: 20, includeCode: true, format: 'markdown' });
const impact = cg.getImpactRadius(results[0].node.id, 2);
cg.watch(); // 文件变更时自动同步
cg.unwatch(); // 停止监视
cg.close();
配置
.codegraph/config.json 文件控制索引行为:
{
"version": 1,
"languages": ["typescript", "javascript"],
"exclude": ["node_modules/**", "dist/**", "build/**", "*.min.js"],
"frameworks": [],
"maxFileSize": 1048576,
"extractDocstrings": true,
"trackCallSites": true
}
| 选项 | 描述 | 默认值 |
|---|---|---|
languages | 要索引的语言(为空则自动检测) | [] |
exclude | 要忽略的 glob 模式 | ["node_modules/**", ...] |
frameworks | 用于更好解析的框架提示 | [] |
maxFileSize | 跳过大于此大小(字节)的文件 | 1048576 (1MB) |
extractDocstrings | 从代码中提取文档字符串 | true |
trackCallSites | 追踪调用位置 | true |
支持的语言
| 语言 | 扩展名 | 状态 |
|---|---|---|
| TypeScript | .ts, .tsx | 完全支持 |
| JavaScript | .js, .jsx, .mjs | 完全支持 |
| Python | .py | 完全支持 |
| Go | .go | 完全支持 |
| Rust | .rs | 完全支持 |
| Java | .java | 完全支持 |
| C# | .cs | 完全支持 |
| PHP | .php | 完全支持 |
| Ruby | .rb | 完全支持 |
| C | .c, .h | 完全支持 |
| C++ | .cpp, .hpp, .cc | 完全支持 |
| Swift | .swift | 完全支持 |
| Kotlin | .kt, .kts | 完全支持 |
| Scala | .scala, .sc | 完全支持(类、特质、方法、类型别名、Scala 3 枚举) |
| Dart | .dart | 完全支持 |
| Svelte | .svelte | 完全支持 |
| Liquid | .liquid | 完全支持 |
| Pascal | .pas, .pp | 完全支持 |
| Delphi | .dpk, .dpr | 完全支持 |
相似文章
@GitHub_Daily: 用 Claude Code 开发项目,代码库一大,每次探索代码结构都要扫一堆文件,工具调用多、速度慢,token 也跟着烧。 于是找到 CodeGraph 这个开源工具,给代码库预建一张语义知识图谱,让 Claude Code 直接查图而…
CodeGraph 是一个开源工具,为代码库预建语义知识图谱,让 Claude Code 直接查图而不是逐文件扫描,从而大幅减少工具调用次数(减少 92%)并提升探索速度(提升 71%),支持 19 种编程语言和 13 个框架。
@justloveabit: https://x.com/justloveabit/status/2055263377006747820
介绍Claude Code 2.1.142新版本与CodeGraph、MCP的组合使用,通过本地语义知识图谱大幅提升大型代码库的探索效率,tool call减少92%,速度提升71%。
@GitTrend0x: Claude Code 工具调用砍 94% 本地代码知识图谱神器 https://github.com/Jakedismo/codegraph-rust… 这就是 CodeGraph-Rust,MCP 服务器直接把你的整个代码库提前索引成…
CodeGraph-Rust 是一个基于 MCP 协议的工具,能将代码库索引为本地知识图谱,声称可减少 Claude Code 等 AI 代理 94% 的工具调用次数,显著提升速度并节省 Token。
@BrooksWhaleX:重大消息:有人刚刚开源了一个面向代码库的知识图谱引擎,好得可怕。它……
GitNexus 是一个开源的知识图谱引擎,它能索引代码库、映射依赖关系和执行流程,并通过 MCP 与 AI 编程助手集成,提供完整的架构清晰度,以防止破坏性变更。
@TechFlow99: 突发:有人刚刚构建了 Andrej Karpathy 说应该有人去构建的工具。就在 Karpathy 发帖后 48 小时……
一款名为 Graphify 的新开源工具在 Andrej Karpathy 描述 LLM 知识库工作流后 48 小时内诞生。它能从任意文件夹生成可导航的知识图谱、Obsidian 知识库和 Wiki,与直接读取原始文件相比,每次查询所需 token 减少了 71.5 倍。该工具可与 Claude Code 集成,支持 13 种编程语言、PDF、图片和 Markdown。