关于 surgical-context-mcp
surgical-context-mcp 是面向 AI 编码 Agent 的本地 Tree-sitter 与 SQLite 代码图 MCP 服务。它提供函数级编辑上下文、调用方和相关代码契约,帮助 Agent 导航和修改代码,而无需读取整个文件。
主要功能
- 01构建本地 AST 代码图
- 02提供聚焦的编辑上下文
- 03查找调用方和动态引用
- 04追踪跨语言契约
- 05发现测试并分析差异影响
- 06记录 Token 节省量
适用场景
- 01编辑大型文件中的函数
- 02重命名前检查代码引用
- 03追踪客户端与服务端事件流
- 04查找变更影响的测试
MCP 相关
通过 MCP 工具提供代码图查询,包括 `get_edit_context`、`check_rename_or_delete`、`tests_for` 和 `get_diff_impact`。MCP 客户端可获取精简代码上下文,并检查调用方、契约、测试和变更影响。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
7收录的工具列表 · 更新于 3 天前
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| top_n | integer | 否 | |
| project_path | any | 否 |
详细介绍
surgical-context-mcp — 面向 AI 编码 Agent 的精准 AST 代码上下文与知识图谱
别再把 3,000 行的文件塞进大模型的上下文窗口了。
surgical-context-mcp是一个零大模型成本、基于嵌入式 SQLite + Tree-sitter 的代码知识图谱和 MCP 服务,可为 AI 编码 Agent(Claude Code、Cursor、Windsurf、Cline、Claude Desktop)提供安全编辑、重构和浏览代码库所需的精准上下文,在不牺牲代码质量的前提下将令牌消耗降低 70–95%。
在此仓库中的实际运行结果:编辑一个包含 1,264 行的文件中的函数,成本约为 3.7k 个令牌,而不是 13.3k(−72%)——同时仍能获取代码骨架、调用方和辅助函数。
⚡ 快速开始(30 秒)
# 1. Install (or: pipx install / pip install surgical-context-mcp)
uv tool install surgical-context-mcp
# 2. Register with Claude Code
claude mcp add code-graph -- code-graph serve
# 3. Index your project + install the token-saving guard hook
code-graph install-hooks /path/to/your/project
就这么简单——现在你的 Agent 会调用 get_edit_context,而不是读取整个文件。使用 Cursor、Windsurf、Cline 或 Claude Desktop?请参阅步骤 1。本项目也已列入官方 MCP Registry,名称为 io.github.erayerturk/surgical-context-mcp。
目录
- 快速开始(30 秒)
- 为什么使用
surgical-context-mcp? - 能节省多少?什么时候应该使用?
- 支持的语言与生态系统解析器
- 工作原理(架构)
- 安装
- 如何使用(分步设置指南)
- 实际输出示例
- MCP 工具参考
- CLI 参考
- 推荐的
CLAUDE.md/.cursorrules配置
为什么使用 surgical-context-mcp?
当今 AI 编码 Agent 面临的 3 个核心问题
- 读取整个文件会浪费数十万个令牌:
当你要求 AI Agent(或它启动的子 Agent)修复 Bug 或添加功能时,它的默认做法是运行
Grep,然后将整份 1,500–3,000 行的文件读入上下文窗口。由于后续每次工具调用都会重新发送完整的对话历史(缓存读取),在会话早期读取一个大型文件,最终就会累积造成 浪费 100k–300k 个令牌。 - 只读取少量行会导致幻觉和代码重复:
如果你强制 Agent 只读取文件中的
lines 240–260来节省令牌,它就会看不到:- 文件顶部的类属性、
self.x字段、@onready/@export变量、常量以及struct/interface定义。 - 同一文件中已经存在的辅助函数(导致 LLM 编写重复代码)。
- 调用方实际传递给该函数的参数(调用点周围的
±5行)。 - 文件的编码风格(缩进、类型标注约定、错误处理惯例)。
- 文件顶部的类属性、
- 纯静态 AST 图会遗漏动态分派和场景/模板连接:
标准调用图只能看到静态的
foo()调用。如果某个函数通过 Python 中的getattr(obj, "foo")、Godot 中的call("foo")或.tscn信号连接、Unity/C# 中的SendMessage("foo")调用,或者在.vue/.html/.proto文件中被引用,简单的图就会报告 “0 个调用方 — 可以安全删除”,从而破坏生产代码。
surgical-context-mcp 如何解决这三个问题
get_edit_context(symbol)— 每次编辑前先调用一次: 不再阅读 2,500 行的文件,Agent 只需调用一次 MCP(get_edit_context),即可获得严格限制(≤ 4,000 个令牌)的精准上下文包,其中包含:- 目标函数的完整函数体(含
Edit所需的精确行号) - 文件结构骨架(所有导入、
interface/struct/enum块、类字段、常量——不含其他函数体) - 已用成员和直接被调用函数(目标函数所用类字段的定义,以及同一文件内短辅助函数的完整函数体(≤ 25 行))
- 直接调用者(
d=1,±5 行窗口)(精确的调用点上下文,不会倾倒 200 行的调用者函数) - 文件中的其他函数签名(让 Agent 复用现有辅助函数,而不是重复实现)
- 风格提示和覆盖范围警告(标记动态字符串调用、
.tscn连接、模板和协议引用)
- 目标函数的完整函数体(含
check_rename_or_delete(symbol)— 每次重构前先调用一次: 检查 AST 调用者(exact/scoped)、父类与子类之间的继承重写、.tscn/模板连接、信号emit/connect位置,以及整个工作区范围内的动态字符串引用。- 跨语言契约(
shares_contract)— 一次调用即可检查服务端 ↔ 客户端 ↔ 配置:- 协议操作码(
contract::opcode::0xCC): 自动关联不同语言中的十六进制操作码常量(例如,Go 的OpSGMOnline = 0xCC与 GDScript/TypeScript 的const S_GM_ONLINE = 0xCC),因此查询任一常量时,都会同时显示服务端发送方和客户端数据包处理器。 - 配置与架构键(
contract::config::<key>): 自动将 Go 结构体字段标签json:"max_chars_per_ip"、前端/面板架构字符串('multi_guard.max_chars_per_ip')以及seed/*.json配置项("max_chars_per_ip": 2)关联为一个共享契约节点。
- 协议操作码(
- 数据、种子与翻译(
i18n)图(check_translations): 将seed/*.json、shared/maps/*.json、locales/*.json和.po文件与代码一并索引。将tr("...")和noticeT(..., "n.x")调用关联到语言区域定义,并审计缺失的键、意外使用的原始非键字符串、%d/%s/{}占位符数量不匹配,以及未使用的语言区域键。 - 自动发现测试(
tests_for)与 Git 差异影响范围(get_diff_impact):tests_for(symbol)可识别所有测试某个符号的测试,并返回可直接运行的 CLI 命令(go test ./pkg -run '^TestFoo$'、godot --headless --path client -s tests/...、pytest ... -k ...)。get_diff_impact(base_ref="HEAD")会解析git diff代码块,将变更行映射到已修改的 AST 符号,并在一次调用中报告这些符号的调用者、受影响的跨语言契约和可运行的测试命令——专为代码审查子 Agent(final-reviewer)打造。
- 概念搜索与引擎生命周期噪声抑制:
- 索引行内注释、前置注释和文档字符串(
doc_comment),因此按概念(例如"attack stat")搜索时可以找到KOAP(// attack power stat bonus)。 - 识别由引擎调用的虚拟回调(
_ready、_draw、_process、_physics_process、_input、Awake、Update),并在 AST 上游为空时抑制错误的文本匹配噪声警告。
- 索引行内注释、前置注释和文档字符串(
- 直接统计令牌节省量(
get_token_savings): 每次 MCP/CLI 查询都会在 SQLite(usage_telemetry)中记录返回的令牌数量与触及文件的原始令牌大小,从而用直接测量值而非估算值回答*“code-graph节省了多少令牌?”*。 - 零大模型索引成本与亚秒级速度:
基于原生 C Tree-sitter 语法和内嵌 SQLite(
WAL模式)构建。使用0个 API 令牌,在< 0.6秒内索引约 600 个文件,并在每次查询时自动刷新已修改的文件(mtime+SHA-1)。 - 通过 Claude Code
PreToolUseHook 强制执行: 内置 Hook 防护(code-graph install-hooks)可阻止对超过 300 行文件进行不受限制的Read调用,并返回文件的 AST 符号表(Lstart-end: signature),确保主 Agent 和子 Agent 都遵循精准操作路径。
能节省多少?何时应该使用?
1. Token 与成本效益(单轮与多轮累积节省)
在 Agent 编码工具(Claude Code、Cursor、Cline)中,每次调用工具都会重新发送截至当时的完整对话历史。当 Agent 在 12 轮编码任务的第 2 轮读取一个 2,500 行的文件(~22,000 个 token)时,这 22,000 个 token 会在第 2、3、4 轮……一直到第 12 轮重复计费(22,000 × 10 = 220,000 个累积上下文 token)。
通过用 get_edit_context(~2,500–3,500 个 token)替代完整文件读取,surgical-context-mcp 可避免上下文膨胀在多轮中累积。
常见开发任务基准测试
(在一个包含 593 个文件的多语言代码仓库中测量:2,607 行的 Godot 客户端控制器 + Go 后端 + JS Web 仪表板)
| 开发场景 | 标准 Agent(Read + Grep) | 使用 surgical-context-mcp | 直接节省的 Token | 10 轮累积节省 |
|---|---|---|---|---|
| 1. 初步了解代码仓库(“这个代码库的结构是怎样的?”) | ~18,500 个 token(多次调用 ls、Glob、Read) | ~650 个 token(GRAPH_REPORT.md / get_architecture_map) | 减少 96% 的 token | 节省约 178,000 个 token |
2. 修改大型文件中的函数(2,607 行) | ~22,400 个 token(读取整个目标文件 + 1 个调用方文件) | ~2,900 个 token(get_edit_context 返回骨架 + 函数体 + 调用方) | 减少 87% 的 token | 节省约 195,000 个 token |
| 3. 追踪端到端请求 / 事件流(客户端 -> 数据包 -> 服务端处理程序) | ~31,000 个 token(搜索字符串并读取 4–6 个文件) | ~1,200 个 token(find_flow + get_symbol_impact) | 减少 96% 的 token | 节省约 298,000 个 token |
| 4. 安全重构 / 删除死代码(“我可以删除或重命名这个方法吗?”) | ~14,000 个 token(搜索并读取候选文件;仍会漏掉动态引用) | ~450 个 token(check_rename_or_delete 检查 AST + 重写方法 + .tscn + 动态字符串) | 减少 97% 的 token | 节省约 135,000 个 token |
| 5. 多子 Agent 并行执行(启动 2–3 个子 Agent 处理后端 / 前端) | 200,000–350,000 个 token(每个子 Agent 都会独立读取大型文件) | 35,000–60,000 个 token(PreToolUse 钩子会阻止所有子 Agent 读取超过 300 行的文件) | 减少 80–85% 的 token | 避免触发速率限制和上下文压缩 |
2. surgical-context-mcp 何时能带来最大收益?
高影响场景(节省 80%–97%,并提高代码准确性)
- 大型或单体源文件(
300到5,000+行): 游戏控制器(main.gd、PlayerController.cs)、大型后端服务(server.go、views.py)或复杂的 React/TypeScript 模块;你只需编辑 1–2 个函数,同时又不想忽略类字段、类型和现有辅助函数。 - 跨文件重构与签名变更:
更改广泛使用的函数或方法的参数时,
check_rename_or_delete和get_edit_context会显示每个调用方的精确±5行调用上下文,而无需将整个调用方文件载入内存。 - 事件驱动、信号与场景连接架构:
使用 Godot 信号与
.tscn连接、Node/JSEventEmitter/bus.on、Python@on_event装饰器或 C# 事件的代码库——在这些代码库中,标准Grep无法追踪从发射器到监听器的执行流程。 - 多语言与全栈单体代码仓库:
由 Go + TypeScript、Python + React 或 Godot + Go + JS 组合而成的项目;在这些项目中,简单的文本搜索会混淆不同语言中同名的方法(
connect、refresh、update、send)。 - 长时间编码会话与子 Agent 工作流: 保持主对话窗口精简,避免 Claude Code / Cursor 在工作 15 分钟后触及上下文限制,或推理质量下降。
何时节省较少?(完全透明)
- 小文件(
< 300行): 如果文件只有 150 行,将其拆分为骨架和正文会带来不必要的开销。surgical-context-mcp会自动检测:对于< 300行的文件,get_edit_context会直接返回完整的带行号文件。 - 纯测试运行器 / 编译器输出循环:
如果子 Agent 花 20 分钟循环运行
go test ./...或pytest,并从终端stdout中读取 5,000 行堆栈跟踪,那么这些令牌来自 bash 测试输出,而非源文件读取。 - 从零搭建脚手架(现有文件数为 0): 从空目录开始生成全新项目时,在写入第一个文件之前,没有现有代码库图可供查询。
支持的语言和生态系统解析器
surgical-context-mcp 会严格隔离不同语言系列(因此 JavaScript 或 Go 中的方法不会与 Python 或 GDScript 中的同名方法冲突),并解析真实的生态系统配置文件,以 exact 置信度解析跨文件导入:
| 语言 / 生态系统 | 文件扩展名 | 提取的骨架和符号 | 语言专属智能(导入、契约、生命周期和测试) |
|---|---|---|---|
| TypeScript / JavaScript / React | .ts、.tsx、.js、.jsx、.mjs、.cjs | class、interface、type、enum、函数、箭头组件、React hooks、模块 const | tsconfig.json / jsconfig.json(paths、baseUrl)、React/Vue/Angular/Next.js 生命周期钩子、/api/... 路由契约、vitest / jest 测试命令 |
| Python | .py | class、def / async def、@decorator 事件/路由链接、dataclass/Pydantic Field(alias=...)、__init__ 中的 self.attr | 相对导入(from .models import ...)、__dunder__ 和 pytest 生命周期钩子、getattr 警告、pytest -k 测试命令 |
| Go | .go | package、import、type ... struct、type ... interface、const/var、函数和 (r *Recv) 方法 | go.mod 跨包调用、json:/yaml:/mapstructure:/env: 结构体标签、0x... 操作码、ServeHTTP/MarshalJSON 生命周期、标准库接收者过滤(strings、strconv、fmt)、go test -run 命令 |
| Rust | .rs | struct、enum、trait、impl Type、fn、const/static、use 声明 | crate::... 和 impl 解析、#[serde(rename = "...")] 字段契约、Drop/Default/From trait 钩子、#[test] / cargo test 命令 |
| C#(.NET / Unity / Godot) | .cs | namespace、class、interface、struct、enum、属性、字段、方法、[Attributes] | [JsonPropertyName] / [JsonProperty] 契约、Unity(Awake、Update、FixedUpdate、SendMessage)和 Godot C#(_Ready、_Process)生命周期钩子、dotnet test --filter 命令 |
| Java | .java | package、class、interface、enum、record、字段、构造函数、方法、@Annotations | @JsonProperty / @SerializedName 契约、Spring/Android/JUnit 生命周期钩子(afterPropertiesSet、onCreate)、getMethod 警告、mvn test / ./gradlew test 命令 |
| Godot 4(GDScript 和场景) | .gd、.tscn、project.godot | extends、class_name、signal、const、enum、@export、@onready、var、func | project.godot [autoload] 单例、res:// preload/load、.tscn [connection signal=...]、引擎虚拟生命周期抑制(_ready、_draw、_process)、内置 KEY_*/MOUSE_*/ERR_* 常量过滤、godot --headless -s 测试命令 |
| 数据、种子和区域设置文件 | .json、.po | 种子/地图记录(seed/*.json、shared/maps/*.json)、配置键,以及 locales/*.json / .po 翻译条目 | 通过 contract::config::* 链接结构体标签和点分隔配置键,并根据 i18n::* 键审计 tr() / noticeT() 调用 |
工作原理(架构)
flowchart LR
subgraph Workspace["Project Workspace"]
Code["Source Files\n(.py, .ts, .tsx, .go, .rs, .cs, .java, .gd, .tscn)"]
Configs["Ecosystem Configs\n(tsconfig.json, go.mod, project.godot)"]
end
subgraph Engine["surgical-context-mcp (Local, Zero-LLM)"]
Scanner["Incremental Scanner\n(mtime + SHA-1 + .gitignore)"]
Parser["Tree-sitter Polyglot AST\n+ Config Resolver"]
DB[(".code_graph.sqlite\nNodes & Scoped Edges")]
Scanner --> Parser --> DB
Configs --> Parser
end
subgraph AgentTools["MCP Tools & Claude Hooks"]
Map["get_architecture_map\n(God Nodes & Clusters)"]
EditCtx["get_edit_context\n(Skeleton + Body + Callers)"]
Safety["check_rename_or_delete\n(Callers + Overrides + Dynamic Refs)"]
Hook["PreToolUse Hook Guard\n(Blocks >300L Read)"]
end
Code --> Scanner
DB --> Map
DB --> EditCtx
DB --> Safety
DB --> Hook
每条图边上的置信度级别
.code_graph.sqlite 中的每条关系都标记为以下三种置信度级别之一:
exact:在同一文件/类中解析,或通过显式文件导入(tsconfig.json的@/别名、go.mod包、Python 相对导入、Godotproject.godotAutoload、.tscn脚本),或直接的super/继承链解析。scoped:通过导入的模块解析无歧义符号,或在同一语言家族中唯一的符号。name_only:匹配到存在多个候选项的模糊名称。从主要输出中排除,并在### 不确定项(name_only,最多 5 项)下单独汇总,因此不会污染上下文。
安装
前置条件
- Python 3.10 – 3.13(推荐 Python 3.12)
- macOS、Linux 或 Windows
快速安装(推荐)
已发布到 PyPI 和 官方 MCP 注册表。
# with uv (fastest)
uv tool install surgical-context-mcp
# or with pipx
pipx install surgical-context-mcp
# or plain pip
pip install surgical-context-mcp
这会在你的 PATH 中添加两个命令:code-graph(CLI + MCP 服务)和 surgical-context-mcp(MCP 服务快捷命令)。
code-graph --help
建议使用持久安装方式(
uv tool/pipx/pip),而不是一次性的uvx运行:install-hooks会将code-graph二进制文件的绝对路径写入 Claude Code 设置,因此该文件不能位于临时缓存中。
从源代码安装
git clone https://github.com/erayerturk/surgical-context-mcp.git
cd surgical-context-mcp
python3.12 -m venv .venv
source .venv/bin/activate
pip install -e .
使用方法(分步设置指南)
第 1 步:在 AI 编码工具中注册 MCP 服务
选项 A:Claude Code(CLI)
运行一次此命令,即可在 Claude Code 中全局注册 code-graph:
claude mcp add code-graph -- code-graph serve
选项 B:Cursor / Windsurf / Claude Desktop(.mcp.json 或 claude_desktop_config.json)
将以下内容添加到你的 .mcp.json(项目根目录)或全局 MCP 设置文件中(如果编辑器不会继承 shell 的 PATH,请使用 which code-graph 获取绝对路径):
{
"mcpServers": {
"code-graph": {
"command": "code-graph",
"args": ["serve"]
}
}
}
第 2 步:初始化目标项目并安装防护钩子
在你要处理的任意项目仓库中运行 install-hooks:
code-graph install-hooks /path/to/your/project
此命令会自动执行以下操作:
- 在
/path/to/your/project/.code_graph.sqlite中构建.code_graph.sqlite(遵循.gitignore、嵌套的.gitignore、.codegraphignore,并跳过node_modules、.venv、.git工作树、构建产物等)。 - 在项目根目录中生成
GRAPH_REPORT.md— 一份精简的架构摘要(约 60 行),列出你的子系统集群、核心节点(连接最多的生产类/函数)、Autoload,以及主要事件/信号总线通道。 - 将 Claude Code 的
PreToolUse钩子安装到/path/to/your/project/.claude/settings.local.json中:- 每当 Claude Code(或它启动的任何子 Agent)尝试对超过
300行的代码文件执行无界Read时,钩子都会拦截调用,阻止读取 3,000 行内容,并返回该文件中所有函数/类及其行号的精简列表(Lstart-end: signature),指示 Agent 调用get_edit_context或Read(offset, limit)。 - 每当 Agent 对符号名称运行
Grep时,钩子都会附加来自.code_graph.sqlite的精确 AST 定义坐标。
- 每当 Claude Code(或它启动的任何子 Agent)尝试对超过
提示: 将
.code_graph.sqlite*添加到项目的.gitignore中,以免将本地 SQLite 数据库提交到 git。
第 3 步:将工作流规则添加到 CLAUDE.md 或 .cursorrules
将下方的推荐 CLAUDE.md 配置复制到项目的 CLAUDE.md(或 .cursorrules)中。
第 4 步:AI Agent 在实际工作中的使用方式
配置完成后,你无需手动运行命令——AI Agent 会自动遵循以下工作流:
- 探索项目: Agent 会读取
GRAPH_REPORT.md,或调用get_architecture_map(),立即了解项目的目录集群和中心类。 - 编辑函数或方法: 在修改任何符号之前,Agent 会调用:
它一次性获取准确的函数体、文件骨架(get_edit_context(symbol="computeFinalScore", project_path="/path/to/project")interface/struct/var声明)、已使用的成员、简短的辅助函数体以及调用方代码窗口,然后立即应用Edit,而无需读取整个文件。 - 重命名或删除代码: 在移除函数或更改参数之前,Agent 会调用:
它会检查所有调用方、继承重写、场景/模板链接以及动态字符串引用。check_rename_or_delete(symbol="computeFinalScore", project_path="/path/to/project")
实际输出示例
示例 1:对大型文件调用 get_edit_context
命令:
code-graph edit-context build_edit_context -p /path/to/surgical-context-mcp
输出(节选):
index: fresh
## Edit Context: `build_edit_context` (`src/code_graph/context_builder.py:462-649`, 188L / file 1264L)
### Style Hint
- indent: 4 spaces
- conventions: type annotations (`-> ReturnType`); `_private` helpers
### 1. Target Function Body (`src/code_graph/context_builder.py:462-649`, exact)
```python
462: def build_edit_context(
463: db: CodeGraphDB,
464: symbol: str,
465: budget_tokens: int = 4000,
466: refreshed_files: int = 0,
467: ) -> dict[str, Any]:
...
2. 文件骨架(src/code_graph/context_builder.py — 导入项、信号、变量、常量)
3: from __future__ import annotations
5: import os
6: import re
7: from pathlib import Path
10: from .db import CodeGraphDB
12: from .models import GraphNode
22: SMALL_EDIT_FILE_LINES = 300
23: SHORT_CALLEE_MAX_LINES = 25
3. 已使用的成员和直接被调用项
被引用的文件成员:
22: SMALL_EDIT_FILE_LINES = 30023: SHORT_CALLEE_MAX_LINES = 25同文件中的被调用项:_read_file_lines[exact](src/code_graph/context_builder.py:26-30):
26: def _read_file_lines(full_path: Path) -> list[str]:
27: try:
28: return full_path.read_text(encoding="utf-8", errors="replace").splitlines()
29: except OSError:
30: return []
外部被调用项:
CodeGraphDB.find_symbol_nodes[scoped](src/code_graph/db.py:694-781)—def find_symbol_nodes(self, symbol: str) -> list[GraphNode]:
4. 直接调用方(d=1,±5 行代码窗口)
_cmd_edit_context[scoped, calls @src/code_graph/cli.py:130](代码窗口src/code_graph/cli.py:125-135):
128: stats = indexer.index(force=False)
129: refreshed = stats.files_indexed + stats.files_removed
130: ctx = build_edit_context(
131: db=indexer.db,
132: symbol=args.symbol,
5. src/code_graph/context_builder.py 中的其他函数签名
- L419-455(37L):
def format_coverage_warnings_section( - L652-797(146L):
def format_edit_context_markdown(ctx: dict[str, Any]) -> str: - L826-988(163L):
def build_rename_or_delete_check(
覆盖率警告
- 未发现无法解析的文本引用。
---
## MCP Tools Reference
All MCP tools have concise `≤ 2`-sentence docstrings to minimize system-prompt overhead in every session, and all tools auto-refresh modified files before running.
| MCP Tool | Parameters | Description |
| :--- | :--- | :--- |
| **`get_edit_context`** | `symbol`, `budget_tokens=4000`, `project_path=None` | **Call before editing any symbol.** Returns file skeleton, full target body, used members, short same-file callees, `±5L` caller windows, other function signatures, style hints, and coverage warnings within `budget_tokens` (or full file if `<300` lines). |
| **`get_architecture_map`** | `top_n=15`, `project_path=None` | **Call to understand repo structure.** Returns Subsystem Clusters (directories), God Nodes (highest-centrality production classes/functions), Godot Autoloads, and Top Event/Signal Hubs. |
| **`check_rename_or_delete`** | `symbol`, `project_path=None` | **Call before deleting, renaming, or changing a signature.** Returns all `exact`/`scoped` call sites, inheritance overrides, `.tscn`/template connections, signal `emit`/`connect` sites, and dynamic string matches. |
| **`get_symbol_impact`** | `symbol`, `depth=2`, `max_lines=300`, `max_tokens=800`, `include_uncertain=False`, `project_path=None` | Returns upstream callers, downstream callees, event bus connections, cross-language contracts (`contract::opcode::*`, `contract::config::*`), and surgical `±5L` read windows up to `depth` hops. |
| **`find_flow`** | `from_symbol`, `to_symbol`, `max_depth=8`, `project_path=None` | Finds the shortest call/event path between two symbols across functions, methods, and signals/events. |
| **`search_symbols`** | `query=""`, `kind=None`, `limit=30`, `project_path=None` | Searches AST nodes, data/i18n entries, and inline comments/docstrings (`doc_comment`) by name, substring, or multi-word concept query (`function`, `method`, `class`, `event`, `constant`, `field`, `data`, `i18n`). |
| **`tests_for`** | `symbol`, `project_path=None` | **Call to find tests for a symbol.** Traverses call/contract graphs and test naming conventions to return all tests exercising `symbol` along with exact runnable CLI commands (`go test -run ...`, `godot --headless -s ...`, `pytest -k ...`). |
| **`get_diff_impact`** | `base_ref="HEAD"`, `project_path=None` | **Call during code review (`final-reviewer`) or pre-commit.** Parses `git diff` hunks, identifies modified AST symbols, and returns their upstream callers, affected cross-language contracts, and runnable test commands in one report. |
| **`check_translations`** | `project_path=None` | **Call to audit `i18n` / translation keys.** Links `tr("...")` and `noticeT(..., "n.x")` calls with `.json`/`.po` locale files and reports missing keys (flagging suspicious raw non-key words), `%d`/`%s`/`{}` placeholder count mismatches, and unused keys. |
| **`get_token_savings`** | `project_path=None`, `reset=False` | **Call to measure exact MCP token savings.** Returns cumulative telemetry comparing returned tokens against raw touched file token sizes across all recorded tool calls. |
| **`reindex_project`** | `project_path=None`, `force=False` | Runs incremental `mtime` + `SHA-1` indexing (or full re-index if `force=True`) and updates `.code_graph.sqlite`. |
---
## CLI Reference
You can also use `code-graph` directly from your terminal:
```bash
# 1. Index a project (fast incremental mtime + SHA-1 scan)
code-graph index /path/to/project
# 2. Force a full re-index from scratch
code-graph index /path/to/project --force
# 3. Generate GRAPH_REPORT.md + install Claude Code PreToolUse guard hooks
code-graph install-hooks /path/to/project
# 4. Get surgical edit context for a symbol (<= 4000 tokens)
code-graph edit-context MyClass.my_method -p /path/to/project --budget 4000
# 5. Check if a symbol is safe to rename, change signature, or delete
code-graph check my_method -p /path/to/project
# 6. Inspect upstream callers, downstream callees & cross-language contracts (depth 1..5)
code-graph impact OpSGMOnline --depth 2 -p /path/to/project
# 7. Find tests exercising a symbol and get exact runnable commands
code-graph tests-for BroadcastGMOnline -p /path/to/project
# 8. Analyze git diff blast radius (modified symbols, callers, contracts, runnable tests)
code-graph diff-impact --base HEAD -p /path/to/project
# 9. Audit translation keys (missing keys, raw non-key literals, %d/%s mismatches, unused keys)
code-graph i18n -p /path/to/project
# 10. Search symbols, data entries, or concepts (comments/docstrings)
code-graph search "attack stat" -p /path/to/project
# 11. View measured token savings telemetry
code-graph savings -p /path/to/project
# 12. Find shortest call/event path between two symbols
code-graph flow handle_request send_notification -p /path/to/project
# 13. Print or write the Architecture Map (GRAPH_REPORT.md)
code-graph report /path/to/project --write
# 14. Run diagnostics (DB size, language breakdown, confidence breakdown, token savings)
code-graph doctor /path/to/project
# 15. Watch directory for live changes and auto-update .code_graph.sqlite
code-graph watch /path/to/project
# 16. Start the MCP server over stdio
code-graph serve
推荐的 CLAUDE.md / .cursorrules 配置
将本节粘贴到项目的 CLAUDE.md、AGENTS.md 或 .cursorrules 中,让主 Agent 和子 Agent 自动遵循精细化工作流:
## Code Graph (`code-graph` MCP) — Mandatory Token-Saving Workflow
1. **Architecture First (`GRAPH_REPORT.md` / `get_architecture_map`):**
- At the start of a task, check `GRAPH_REPORT.md` (or call `get_architecture_map`) to identify subsystem clusters, God Nodes, and event channels before browsing directories.
2. **Before Editing Any Symbol (`get_edit_context`):**
- Always call `get_edit_context(symbol="<name>", budget_tokens=4000)` BEFORE modifying a function, method, or class.
- It provides: (1) File skeleton (imports, types, structs/interfaces, class vars, constants), (2) Full target function body with line numbers, (3) Used member definitions & short same-file callee bodies, (4) Direct caller `±5L` windows, (5) Other function signatures in the file, (6) Style hints, and (7) `Coverage Warnings`.
- Do **NOT** read the full file after calling `get_edit_context`; apply your `Edit` directly using the returned line numbers.
3. **Before Deleting, Renaming, or Changing Signatures (`check_rename_or_delete`):**
- Always call `check_rename_or_delete(symbol="<name>")` before removing a symbol or changing its signature to verify all `exact`/`scoped` callers, inheritance overrides, scene/template connections, and dynamic string references (`getattr`, `call("x")`).
4. **Targeted Impact, Cross-Language Contracts & Flow Queries:**
- Use `get_symbol_impact(symbol="<name>", depth=2)` to inspect upstream/downstream call chains and cross-language contracts (`OpSGMOnline` <-> `S_GM_ONLINE = 0xCC`, `json:"max_chars_per_ip"` <-> `'multi_guard.max_chars_per_ip'` <-> `seed/*.json`).
- Use `find_flow(from_symbol="<A>", to_symbol="<B>")` to trace execution or event paths between two symbols.
- Use `search_symbols(query="<concept or name>")` to search code symbols, comments/docstrings (`"attack stat"` -> `KOAP`), `seed/*.json` records, and `locales/*.json` keys together.
5. **Testing, Translation Audits & Code Review (`tests_for`, `check_translations`, `get_diff_impact`):**
- Call `tests_for(symbol="<name>")` instead of guessing test commands (`go test -run ...`, `godot --headless -s ...`).
- Call `check_translations()` after touching `tr("...")`, `noticeT(...)`, or `locales/` files to catch missing keys, accidental raw non-key strings, and `%d`/`%s` placeholder mismatches.
- For code review (`final-reviewer`), call `get_diff_impact(base_ref="HEAD")` to get modified symbols, affected callers, cross-language contracts, and runnable tests in a single call.
6. **No Unbounded Reads on Large Files (>300 Lines):**
- Never call `Read` on a source file >300 lines without `offset` and `limit` (enforced by the `code-graph` `PreToolUse` hook).
自定义忽略规则(.codegraphignore)
默认情况下,surgical-context-mcp 会自动遵循:
- 根目录及嵌套的
.gitignore文件 - 嵌套的 Git 工作树/子模块(任何包含自身
.git的子目录) - 内置忽略目录(
.git、.claude、.aider*、.venv、venv、node_modules、dist、build、target、vendor、.next、.godot、Library、Temp、Binaries等)
如果你想在不将额外目录或生成文件加入 .gitignore 的情况下,将它们从图谱中排除,可以在项目根目录创建 .codegraphignore 文件,并使用标准的 .gitignore 语法:
# .codegraphignore
*.pb.go
*.generated.ts
third_party/
fixtures/large_dumps/
运行测试套件
.venv/bin/python tests/test_end_to_end.py
致谢
GRAPH_REPORT.md /“God Nodes”架构摘要的构想受到 graphify 的启发。surgical-context-mcp 是一个独立实现,侧重点不同:每次编辑的精细化上下文(get_edit_context)、重构安全检查(check_rename_or_delete),以及防止 Agent 读取完整文件的 PreToolUse 钩子。
贡献
欢迎提交 Issue 和 PR,尤其是新的语言解析器和真实场景下的 token 基准测试。如果 surgical-context-mcp 帮你节省了 token,点一个 ⭐ 就能帮助其他人发现它。
许可证
MIT © Eray Erturk。可免费用于个人和商业用途。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。