乐于分享
好东西不私藏

CodeGraph:AI 编程助手的语义代码智能引擎,成本直降 35%

CodeGraph:AI 编程助手的语义代码智能引擎,成本直降 35%

CodeGraph:AI 编程助手的语义代码智能引擎,成本直降 35%

核心要点:CodeGraph 是一个 100% 本地运行的 MCP 服务器,为 Claude Code、Cursor 等 AI 编程助手提供预索引的知识图谱——符号关系、调用图和代码结构。查询结果即时返回,无需逐文件扫描,平均降低 35% 成本、减少 70% 工具调用

一句话介绍

CodeGraph 为 AI 编程助手建立代码知识图谱,让探索代码从"扫描文件"变为"查询索引",大幅提升效率。


性能数据

在 7 个开源项目上的基准测试结果(中位数):

指标
平均节省
成本
35% 更低
令牌消耗
59% 更少
响应速度
49% 更快
工具调用次数
70% 更少

代码库越大,收益越显著。大型仓库中,CodeGraph 的代理仅需少量调用即可从索引获取答案,零文件读取。

技术特点:收益规模与代码库大小正相关。大型仓库中,有 CodeGraph 的代理只需几次调用即可从索引获取答案,而无需通过 grep/find/Read 展开搜索


快速开始

1. 安装

无需 Node.js,一条命令即可:

# macOS / Linuxcurl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh# Windows (PowerShell)irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex

已有 Node.js?使用 npm:

npx @colbymchenry/codegraph        # 零安装,或npm i -g @colbymchenry/codegraph

CodeGraph 自带运行时,无需编译、无需原生构建,跨平台一致运行。交互式安装程序会自动配置你的代理——Claude Code、Cursor、Codex CLI、opencode、Hermes Agent。

2. 初始化项目

cd your-projectcodegraph init -i

构建项目的知识图谱索引。同时配置项目级本地代理配置。

3. 重启你的 AI 编程助手

重启你的代理(Claude Code / Cursor / Codex CLI / opencode / Hermes Agent),让 MCP 服务器加载生效。

完成——当 .codegraph/ 目录存在时,你的代理将自动使用 CodeGraph 工具。


卸载

一条命令从所有已配置的代理中移除 CodeGraph:

codegraph uninstall

逆向安装过程——从每个配置的代理中剥离 CodeGraph 的 MCP 服务器配置、指令和权限。项目索引(.codegraph/)不受影响,可使用 codegraph uninit 逐个移除。

使用 --target 指定目标代理,--yes 非交互式运行。


核心功能

功能
说明
智能上下文构建
一次调用返回入口点、相关符号和代码片段,无需耗时的探索代理
全文搜索
基于 FTS5 引擎,跨整个代码库按名称即时查找代码
影响分析
追踪任意符号的调用者、被调用者和完整影响范围
实时同步
使用原生 OS 事件(FSEvents/inotify/ReadDirectoryChangesW)进行文件监控,去抖自动同步
支持 19+ 语言
TypeScript、JavaScript、Python、Go、Rust、Java、C#、PHP、Ruby 等
框架感知路由
识别 Web 框架路由文件,将 URL 模式链接到处理程序
100% 本地
数据不离机、无需 API 密钥、无外部服务,仅 SQLite 数据库

框架感知路由

CodeGraph 检测 Web 框架的路由文件,生成通过引用边连接到处理函数或类的路由节点。查询视图/控制器的调用者时,现在能同时看到绑定它的 URL 模式。

框架
识别模式
Django
path()
re_path()url()include()
Flask
@app.route('/path')
、蓝图路由
FastAPI
@app.get()
@router.post() 等
Express
app.get()
router.post() 及中间件链
NestJS
@Controller
 + @Get/@Post、GraphQL @Resolver@MessagePattern
Laravel
Route::get()
Route::resource()
Spring
@GetMapping
@PostMapping@RequestMapping
Gin / chi / gorilla / mux
r.GET()
router.HandleFunc()
Axum / actix / Rocket
.route("/x", get(handler))
ASP.NET
[HttpGet("/x")]
 特性
Rails
get '/x', to: 'users#index'
React Router / SvelteKit
路由组件节点

CLI 命令参考

codegraph                          # 运行交互式安装程序codegraph install                   # 显式运行安装程序codegraph uninstall                 # 从代理中移除 CodeGraphcodegraph init [path]               # 在项目中初始化(--index 同时索引)codegraph uninit [path]             # 从项目中移除(--force 跳过确认)codegraph index [path]              # 完整索引(--force 重新索引)codegraph sync [path]               # 增量更新codegraph status [path]             # 显示统计信息codegraph query <search>            # 搜索符号(--kind、--limit、--json)codegraph files [path]              # 展示文件结构codegraph context <task>            # 为 AI 构建上下文codegraph callers <symbol>          # 查找函数的调用者codegraph callees <symbol>          # 查找函数调用的内容codegraph impact <symbol>           # 分析变更影响范围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/*"       # 自定义测试文件匹配

CI 钩子示例:

#!/usr/bin/env bashAFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet)if [ -n "$AFFECTED" ]; then  npx vitest run $AFFECTEDfi

MCP 工具

作为 MCP 服务器运行时,CodeGraph 向 Claude Code 暴露以下工具:

工具
用途
codegraph_search
跨代码库按名称搜索符号
codegraph_context
为任务构建相关代码上下文
codegraph_callers
查找函数的调用者
codegraph_callees
查找函数调用的内容
codegraph_impact
分析变更符号的影响范围
codegraph_node
获取特定符号的详细信息(可选含源码)
codegraph_explore
一次调用返回多个相关符号及其关系映射
codegraph_files
获取已索引的文件结构
codegraph_status
检查索引健康状况和统计信息

原理架构

┌─────────────────────────────────────────────────────────────────┐│                        Claude Code                               ││                                                                  ││  "实现用户认证功能"                                                ││           │                                                      ││           ▼                                                      ││  ┌─────────────────┐      ┌─────────────────┐                   ││  │  Explore Agent  │ ──── │  Explore Agent  │                   ││  └────────┬────────┘      └────────┬────────┘                   ││           │                        │                             │└───────────┼────────────────────────┼─────────────────────────────┘            │                        │            ▼                        ▼┌───────────────────────────────────────────────────────────────────┐│                     CodeGraph MCP Server                          ││  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐               ││  │   搜索      │  │   调用者    │  │   上下文    │               ││  │  "auth"     │  │  "login()"  │  │   构建      │               ││  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘               ││         │                │                │                       ││         └────────────────┼────────────────┘                       ││                          ▼                                        ││              ┌───────────────────────┐                            ││              │   SQLite 图谱数据库    │                            ││              │   • 387 个符号        │                            ││              │   • 1,204 条边        │                            ││              │   • 即时查询          │                            ││              └───────────────────────┘                            │└───────────────────────────────────────────────────────────────────┘

工作流程:

  1. 提取 — tree-sitter 将源码解析为 AST。语言特定的查询提取节点(函数、类、方法)和边(调用、导入、继承、实现)
  2. 存储 — 所有数据存入本地 SQLite 数据库(.codegraph/codegraph.db),支持 FTS5 全文搜索
  3. 解析 — 提取完成后解析引用关系:函数调用 → 定义、导入 → 源文件、类继承和框架特定模式
  4. 自动同步 — MCP 服务器使用原生 OS 文件事件监控项目。变更经去抖(2 秒静默窗口)后增量同步。图谱随编码实时更新,零配置

作为库使用

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', {  maxNodes20includeCodetrueformat'markdown'});const impact = cg.getImpactRadius(results[0].node.id2);cg.watch();   // 文件变更自动同步cg.unwatch(); // 停止监控cg.close();

配置说明

CodeGraph 是零配置工具。它会索引所有扩展名对应支持语言的文件,并遵循 .gitignore 规则:

  • git 忽略的内容——node_modules、构建输出、.env 中的密钥——永远不会被索引
  • 没有需要编写或同步的配置文件,无需按语言设置
  • 超过 1 MB 的文件将被跳过(生成包、压缩 JS、第三方大文件)
  • 若提交了不被 gitignore 的文件(如 vendor/ 或 dist/),仍会被索引

常见问题排查

问题
解决方法
"CodeGraph not initialized"
先在项目目录运行 codegraph init
索引速度慢
检查 node_modules 等大型目录是否被排除
"database is locked"
更新至最新版:使用 bundled 运行时。如在网络共享或 WSL2 /mnt 上,将项目移至本地磁盘
MCP 服务器未连接
确保项目已初始化/索引,验证路径配置,检查 codegraph serve --mcp 是否正常工作
缺少符号
MCP 服务器在保存后自动同步(等待数秒)。也可手动运行 codegraph sync。检查文件语言是否被支持

平台与代理支持

支持平台:

平台
架构
Windows
x64, arm64
macOS
x64, arm64
Linux
x64, arm64

支持代理:

Claude Code、Cursor、Codex CLI、opencode、Hermes Agent

支持语言(共 19+):

TypeScript、JavaScript、Python、Go、Rust、Java、C#、PHP、Ruby、C、C++、Swift、Kotlin、Scala、Dart、Svelte、Vue、Liquid、Pascal/Delphi、Lua、Luau


安装选项参考

codegraph install --yes                              # 自动检测代理,全局安装codegraph install --target=cursor,claude --yes       # 指定目标代理codegraph install --target=auto --location=local     # 检测到的代理,项目级安装codegraph install --print-config codex               # 仅打印配置片段,不写文件
参数
可选值
默认
--target
auto、all、none 或 csv(claude,cursor,...)
交互式
--location
global、local
交互式
--yes
布尔值
每步确认
--no-permissions
布尔值
开启权限
--print-config <id>
为指定代理输出配置片段后退出

注意事项:CodeGraph 的收益规模与代码库大小正相关。在小型仓库(如 ~150 文件的 Gin)上,原生搜索成本已足够低,优势相对较小。对于中大型项目,效果尤为显著



文档来源:CodeGraph 

原始作者:Colby McHenry

本文由 AI 助手整理优化,欢迎关注、分享转载,请注明出处