📇 本类导航
本页自动汇总「AI」分类下的全部笔记(含子分类),随笔记增删实时更新。
CodeGraph 使用指南
colbymchenry/codegraph — 为编程智能体预构建的代码知识图谱,更少 Token、更少工具调用,100% 本地运行。
一、是什么
CodeGraph 把你的代码库解析成一张语义知识图谱(节点 = 函数/类/方法,边 = 调用/导入/继承),存入本地 SQLite 数据库。AI 编程智能体(Claude Code、Cursor、Codex CLI 等)直接查询图谱,而不是反复用 grep/Read 扫描文件。
核心数据(7个真实代码库测试) :平均 35% 成本降低 · 57% Token 减少 · 46% 更快的响应 · 71% 更少的工具调用。
二、安装
Windows(PowerShell)
irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iexmacOS / Linux
curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh已有 Node.js 环境
npx @colbymchenry/codegraph # 零安装,直接使用 npm install -g @colbymchenry/codegraph # 全局安装无需 Node.js,安装脚本自带运行时,无需编译。
三、快速上手(3 步)
第 1 步:安装并配置智能体
codegraph install --yes交互式安装器会自动检测你已安装的编程智能体(Claude Code / Cursor / Codex CLI / opencode / Hermes Agent),并自动配置 MCP 服务器连接和指令文件。
第 2 步:在项目目录中初始化
cd 你的项目目录 codegraph init -i这会构建项目的知识图谱索引(
.codegraph/codegraph.db)。索引自动遵循.gitignore,node_modules等不会进入图谱。第 3 步:重启智能体
重启 Claude Code / Cursor / Codex CLI 等工具,MCP 服务器会自动加载。之后只要项目里有
.codegraph/目录,智能体就会自动使用 CodeGraph 工具。
四、核心命令速查
命令 作用 codegraph install运行交互式安装器 codegraph uninstall从所有智能体中移除 CodeGraph codegraph init [路径]在项目中初始化( -i交互模式)codegraph uninit [路径]从项目中移除 CodeGraph codegraph index [路径]全量索引( --force强制重建)codegraph sync [路径]增量更新索引 codegraph status [路径]查看索引统计信息 codegraph query <关键词>按名称搜索符号 codegraph context <任务描述>为 AI 构建上下文 codegraph callers <符号名>查找谁调用了某函数 codegraph callees <符号名>查找某函数调用了谁 codegraph impact <符号名>变更影响分析 codegraph affected [文件...]查找受改动影响的测试文件 codegraph serve --mcp启动 MCP 服务器
五、MCP 工具详解(智能体可用)
智能体在对话中可调用以下 10 个工具:
工具 用途 典型场景 codegraph_context一次调用获取入口点、相关符号和代码片段 架构理解任务的首选 codegraph_trace追踪两个符号之间的完整调用路径 “X 是如何调用到 Y 的?” codegraph_search按名称搜索符号 “找到 UserService” codegraph_callers找出谁调用了某个函数 了解调用方 codegraph_callees找出函数调用了什么 了解依赖 codegraph_impact分析修改某个符号的影响范围 改动前风险评估 codegraph_explore批量获取多个相关符号的源码 批量查看相关代码 codegraph_node获取单个符号详情 查看函数签名 codegraph_files获取索引的文件结构 比文件系统扫描更快 codegraph_status检查索引状态和统计 确认图谱是否最新
六、实际使用示例
场景 1:理解架构
对 Claude Code 说:
“How does the extension host communicate with the main process?”
智能体会先用
codegraph_context定位相关区域,再用codegraph_trace追踪调用路径,一次对话即可获得完整答案,而不是启动多个 Explore 子代理去扫描文件。场景 2:影响分析
先在终端用 CLI 分析:
codegraph impact handleRequest输出该函数的所有调用方、被调用方及其依赖链,评估改动风险。
场景 3:CI 集成
#!/usr/bin/env bash # 只运行受影响的测试 AFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet) if [ -n "$AFFECTED" ]; then npx vitest run $AFFECTED fi
七、语言支持(19+)
TypeScript · JavaScript · Python · Go · Rust · Java · C# · PHP · Ruby · C · C++ · Swift · Kotlin · Scala · Dart · Svelte · Vue · Lua · Luau
八、工作原理
你的代码 → tree-sitter 解析 AST → 提取节点(函数/类)和边(调用/导入) → SQLite 存储 + FTS5 全文搜索 → 引用解析(调用→定义) → 原生文件监视器自动同步(2秒防抖) → MCP 服务器暴露工具给智能体
九、手动配置(高级)
如需手动配置,在
~/.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" ] } }
十、常见问题
Q:索引慢怎么办?
A:检查node_modules等大目录是否已在.gitignore中。使用--quiet减少输出开销。Q:MCP 连接不上?
A:确保项目已codegraph init,确认配置路径正确,手动运行codegraph serve --mcp测试。Q:符号缺失?
A:MCP 服务器会自动同步(等待几秒)。手动运行codegraph sync。确认文件语言是否在支持列表中。Q:如何卸载?
A:codegraph uninstall从智能体中移除配置,codegraph uninit删除项目中的.codegraph/目录。
GitHub 仓库:https://github.com/colbymchenry/codegraph
许可证:MIT
本周新增 Star:18,136 · 总 Star:23,249
一、创建脚本
随便找个目录,新建一个install-rtk.ps1的文件,打开编辑,然后复制下面全部内容到文件里面,保存
# install-rtk.ps1 — RTK 一键安装脚本 for Windows # 用法: powershell -ExecutionPolicy Bypass -File .\install-rtk.ps1 $ErrorActionPreference = "Stop" Set-StrictMode -Version Latest Write-Host "========================================" -ForegroundColor Cyan Write-Host " RTK Windows 安装脚本" -ForegroundColor Cyan Write-Host "========================================" -ForegroundColor Cyan # === [1/5] 检查依赖 === Write-Host "`n=== [1/5] 检查依赖 ===" -ForegroundColor Yellow $NodeCheck = Get-Command node -ErrorAction SilentlyContinue if (-not $NodeCheck) { Write-Host "未找到 Node.js,RTK 本身不需要 Node,但 Claude Code/Codex CLI 需要。" -ForegroundColor DarkYellow Write-Host "如果尚未安装,请访问: https://nodejs.org" -ForegroundColor DarkYellow } # === [2/5] 下载 RTK === Write-Host "`n=== [2/5] 下载 RTK ===" -ForegroundColor Yellow $RtkDir = Join-Path $env:USERPROFILE "rtk" $RtkZip = Join-Path $RtkDir "rtk.zip" $RtkBinDir = Join-Path $env:USERPROFILE "bin" # 创建目录 New-Item -ItemType Directory -Path $RtkDir -Force | Out-Null New-Item -ItemType Directory -Path $RtkBinDir -Force | Out-Null # 获取最新版本 try { Write-Host "正在获取最新版本信息..." $Release = Invoke-RestMethod -Uri "https://api.github.com/repos/rtk-ai/rtk/releases/latest" -TimeoutSec 15 $Tag = $Release.tag_name Write-Host "最新版本: $Tag" $Asset = $Release.assets | Where-Object { $_.name -match "x86_64-pc-windows-msvc" } | Select-Object -First 1 if (-not $Asset) { Write-Host "未找到 Windows MSVC 二进制,尝试 fallback..." -ForegroundColor DarkYellow $Asset = $Release.assets | Where-Object { $_.name -match "windows" } | Select-Object -First 1 } if (-not $Asset) { Write-Error "未找到 Windows 可用下载资源" exit 1 } $AssetUrl = $Asset.browser_download_url } catch { Write-Host "GitHub API 请求失败,使用已知版本 v0.39.0" -ForegroundColor DarkYellow $Tag = "v0.39.0" $AssetUrl = "https://github.com/rtk-ai/rtk/releases/download/v0.39.0/rtk-x86_64-pc-windows-msvc.zip" } Write-Host "下载地址: $AssetUrl" Invoke-WebRequest -Uri $AssetUrl -OutFile $RtkZip # === [3/5] 解压并安装 === Write-Host "`n=== [3/5] 解压并安装 ===" -ForegroundColor Yellow Expand-Archive -Path $RtkZip -DestinationPath $RtkDir -Force $ExtractedRtkExe = Get-ChildItem -Path $RtkDir -Filter "rtk.exe" -Recurse | Select-Object -First 1 if (-not $ExtractedRtkExe) { Write-Error "解压后未找到 rtk.exe" exit 1 } Copy-Item -Path $ExtractedRtkExe.FullName -Destination (Join-Path $RtkBinDir "rtk.exe") -Force Remove-Item $RtkZip -Force Write-Host "rtk.exe 已安装到: $RtkBinDir" # === [4/5] 添加到 PATH === Write-Host "`n=== [4/5] 配置 PATH ===" -ForegroundColor Yellow $UserPath = [Environment]::GetEnvironmentVariable("Path", "User") if ($UserPath -notlike "*$RtkBinDir*") { $NewPath = if ($UserPath) { "$UserPath;$RtkBinDir" } else { $RtkBinDir } [Environment]::SetEnvironmentVariable("Path", $NewPath, "User") $env:Path = "$env:Path;$RtkBinDir" Write-Host "已将 $RtkBinDir 添加到用户 PATH" } else { Write-Host "$RtkBinDir 已在 PATH 中" } # 刷新当前会话 $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine") # === [5/5] 配置 AI 工具 === Write-Host "`n=== [5/5] 配置 AI 工具 Hook ===" -ForegroundColor Yellow $RtkExe = Join-Path $RtkBinDir "rtk.exe" # 验证 rtk 可用 try { & $RtkExe --version 2>&1 | Out-Null Write-Host "rtk 已验证: $( & $RtkExe --version )" -ForegroundColor Green } catch { Write-Error "rtk 执行失败,请检查安装" exit 1 } # Claude Code: 添加 PreToolUse Hook $ClaudeSettings = Join-Path $env:USERPROFILE ".claude\settings.json" if (Test-Path $ClaudeSettings) { Write-Host "`n检测到 Claude Code 配置,正在添加 RTK Hook..." -ForegroundColor Cyan $Settings = Get-Content $ClaudeSettings -Raw | ConvertFrom-Json # 检查是否已有 hooks if (-not $Settings.PSObject.Properties.Name.Contains("hooks")) { $Settings | Add-Member -MemberType NoteProperty -Name "hooks" -Value ([pscustomobject]@{}) -Force } if (-not $Settings.hooks.PSObject.Properties.Name.Contains("PreToolUse")) { $Settings.hooks | Add-Member -MemberType NoteProperty -Name "PreToolUse" -Value @() -Force } # 检查是否已有 rtk hook $HasRtkHook = $false foreach ($hook in $Settings.hooks.PreToolUse) { if ($hook.matcher -eq "Bash") { foreach ($h in $hook.hooks) { if ($h.command -match "rtk hook claude") { $HasRtkHook = $true break } } } } if (-not $HasRtkHook) { $RtkHook = @{ matcher = "Bash" hooks = @( @{ type = "command" command = "rtk hook claude" } ) } $Settings.hooks.PreToolUse += $RtkHook $Settings | ConvertTo-Json -Depth 10 | Set-Content $ClaudeSettings -Encoding UTF8 Write-Host " Claude Code RTK Hook 已添加" -ForegroundColor Green } else { Write-Host " Claude Code RTK Hook 已存在,跳过" -ForegroundColor DarkYellow } } else { Write-Host "`n未检测到 Claude Code 配置文件,跳过。(如果已安装,请手动配置)" -ForegroundColor DarkYellow } # Codex CLI: 添加 RTK.md 引用 $CodexAgents = Join-Path $env:USERPROFILE ".codex\AGENTS.md" if (Test-Path (Split-Path $CodexAgents -Parent)) { Write-Host "`n检测到 Codex CLI,正在添加 RTK 配置..." -ForegroundColor Cyan $RtkMdPath = Join-Path $env:USERPROFILE ".codex\RTK.md" # 创建 RTK.md $RtkMdContent = @" # RTK - Rust Token Killer (Codex CLI) **Usage**: Token-optimized CLI proxy for shell commands. ## Rule Always prefix shell commands with `rtk`. Examples: rtk git status rtk cargo test rtk npm run build rtk pytest -q ## Meta Commands rtk gain # Token savings analytics rtk gain --history # Recent command savings history rtk proxy # Run raw command without filtering "@ Set-Content -Path $RtkMdPath -Value $RtkMdContent -Encoding UTF8 # 确保 AGENTS.md 引用 RTK.md $AgentsContent = "@C:\Users\$env:USERNAME\.codex\RTK.md" if (Test-Path $CodexAgents) { $Existing = Get-Content $CodexAgents -Raw if ($Existing -notmatch "RTK.md") { $AgentsContent = "$Existing`n$AgentsContent" } else { $AgentsContent = $Existing Write-Host " Codex CLI AGENTS.md 已包含 RTK 引用" -ForegroundColor DarkYellow $AgentsContent = $null } } if ($AgentsContent) { Set-Content -Path $CodexAgents -Value $AgentsContent -Encoding UTF8 Write-Host " Codex CLI RTK 配置已添加" -ForegroundColor Green } } else { Write-Host "`n未检测到 Codex CLI 目录,跳过。" -ForegroundColor DarkYellow } # === 完成 === Write-Host "`n========================================" -ForegroundColor Green Write-Host " RTK 安装完成!" -ForegroundColor Green Write-Host "========================================" -ForegroundColor Green Write-Host "" # 验证 Write-Host "验证安装:" -ForegroundColor Cyan & $RtkExe --version Write-Host "" Write-Host "查看 token 节省数据:" -ForegroundColor Cyan Write-Host " rtk gain" Write-Host "" Write-Host "查看历史记录:" -ForegroundColor Cyan Write-Host " rtk gain --history" Write-Host "" Write-Host "重启 Claude Code / Codex CLI 后生效。" -ForegroundColor Yellow二、安装脚本(powershell):
cd 刚才创建脚本的目录 powershell -ExecutionPolicy Bypass -File .\install-rtk.ps1安装完之后,测试rtk是无效的,可以这样:
重新加载系统 PATH 和用户 PATH
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")再执行rtk就可以了
三、验证效果
重启 AI 工具后跑几个命令,然后查看节省数据:
rtk gain输出示例:
RTK Token Savings (Global Scope) ════════════════════════════════════════════════════════════ Total commands: 70 Input tokens: 31.7K Output tokens: 30.7K Tokens saved: 1.0K (3.3%) By Command ─────────────────────────────────────────────────────── git status 每次节省 ~90% ls -la 每次节省 ~90% pytest 每次节省 ~80% npm run build 每次节省 ~80%如果想看详细的命令历史:
rtk gain --history powershell1四、常用命令速查
命令 作用 rtk gain查看 token 节省统计 rtk gain --history查看每条命令的节省详情 rtk discover分析 Claude Code 历史,找出还没被 RTK 拦截的命令 rtk proxy <cmd>以原始模式运行命令(不做过滤,用于调试) rtk --version查看版本 rtk git diff超精简 diff(只显示改动行) rtk pytest -q运行 pytest 且只显示失败 rtk npm run build过滤构建输出的 warning 噪音 rtk ls -la紧凑的目录列表 五、支持的命令(部分)
RTK 内置了 100+ 个命令的过滤器:
版本控制:
git,gh,glab,gt
包管理:npm,npx,pnpm,cargo,pip
构建工具:tsc,next,lint,prettier,ruff
测试框架:pytest,jest,vitest,playwright,rspec
数据库:psql,prisma
容器:docker,kubectl
云:aws
日志:log(通用日志去重)完整列表见 RTK GitHub。
六、常见问题
Q: RTK 会影响命令执行结果吗?
不会。RTK 只在输出层面过滤,不修改命令行为也不修改源文件。如果 RTK 判断失败(比如命令 exit code 非 0),会自动退回完整输出。
Q: 怎么禁用某个命令的过滤?
rtk proxy git log --all # 以原始模式运行,不做过滤Q: Codex CLI 上似乎没用?
Codex CLI 没有 Hook 机制,RTK 靠 AGENTS .md 中的规则让 AI 主动加
rtk前缀。如果 AI 没遵守,可以用codexuwrapper(见下一篇博客)。Q: 和 GitHub Copilot 能一起用吗?
已支持。用
rtk init --copilot -g配置。七、总结
RTK 是那种"装上就忘了"的工具——你不需要学任何东西,它静默地帮你省 Token。
- 单二进制,零依赖,3MB
- 支持 100+ 个常用开发命令
- Claude Code / Codex / Copilot / Cursor 全兼容
- 开源 MIT 协议
GitHub: https://github.com/rtk-ai/rtk
