mcpField
S
surgical-context-mcp

surgical-context-mcp

ローカル
github.com/erayerturk開発ツール33 日前に更新

surgical-context-mcp について

surgical-context-mcpは、AIコーディングエージェント向けのローカルTree-sitter・SQLiteコードグラフMCPサーバーです。関数単位の編集コンテキストや呼び出し元、関連するコード契約を返し、ファイル全体を読み込まずにコードの調査や変更を支援します。

主な機能

  1. 01ローカルASTコードグラフの構築
  2. 02編集に絞ったコンテキストの取得
  3. 03呼び出し元と動的参照の検索
  4. 04言語横断の契約追跡
  5. 05テストと差分影響の特定
  6. 06トークン節約量の記録

活用シーン

  1. 01大きなファイル内の関数を編集
  2. 02リネーム前にコード参照を確認
  3. 03クライアントとサーバーのイベントフローを追跡
  4. 04変更の影響を受けるテストを特定

MCP 対応

`get_edit_context`、`check_rename_or_delete`、`tests_for`、`get_diff_impact`などのコードグラフ検索をMCPツールとして公開します。MCPクライアントは、絞り込んだコードコンテキストを取得し、呼び出し元、契約、テスト、変更の影響を調べられます。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

mcp.json · 共通設定
{
"mcpServers": {
"erayerturk-surgical-context": {
"command": "uvx",
"args": [
"surgical-context-mcp"
]
}
}
}
起動コマンドuvx surgical-context-mcp

ローカルサーバーにはマシン上の実行環境(Node.js 18 以上など)が必要です。設定ファイルの場所はクライアントごとに異なります。

パッケージ
pypisurgical-context-mcp0.1.0

ツール

7

掲載時のツール一覧 · 3 日前に更新

パラメーター型必須説明
top_nintegerいいえ
project_pathanyいいえ

詳細

surgical-context-mcp — AI コーディングエージェント向けの外科的 AST コードコンテキストとナレッジグラフ

PyPI Downloads MCP Registry CI License: MIT Python 3.10+ Claude Code GitHub stars

LLM のコンテキストウィンドウに、3,000 行のファイルを読み込ませるのはもうやめましょう。 surgical-context-mcp は、LLM のコストがかからない、SQLite と Tree-sitter を組み合わせた埋め込み型のコードナレッジグラフ兼 MCP サーバーです。AI コーディングエージェント(Claude Code、Cursor、Windsurf、Cline、Claude Desktop)が、コードベースを安全に編集、リファクタリング、ナビゲートするために必要な的確なコンテキストを提供します。コード品質を損なうことなく、トークン消費量を**70~95%**削減できます。

surgical-context-mcp のデモ:get_edit_context は、13k トークンのファイル全体を読み込む代わりに、約 3.6k トークンを返します
このリポジトリでの実行例:1,264 行のファイル内の関数を編集する際、約 13.3k トークンではなく約 3.7k トークンで済みます(−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

これで完了です。エージェントはファイル全体を読み込む代わりに、get_edit_context を呼び出すようになります。Cursor、Windsurf、Cline、Claude Desktop をお使いですか?ステップ 1をご覧ください。また、公式 MCP Registry に io.github.erayerturk/surgical-context-mcp として登録されています。


目次

  1. クイックスタート(30 秒)
  2. surgical-context-mcp を使う理由
  3. どのくらい削減できる?いつ使うべき?
  4. 対応言語とエコシステムリゾルバー
  5. 仕組み(アーキテクチャ)
  6. インストール
  7. 使い方(ステップごとのセットアップガイド)
  8. 実際の出力例
  9. MCP ツールのリファレンス
  10. CLI リファレンス
  11. 推奨する CLAUDE.md / .cursorrules の設定

surgical-context-mcp を使う理由は?

現在の AI コーディングエージェントが抱える3つの主要な問題
  1. ファイル全体の読み込みで、数十万トークンが消費されます: AI エージェント(またはそのエージェントが起動するサブエージェント)にバグ修正や機能追加を依頼すると、デフォルトではまず Grep を実行し、続いて1,500~3,000行のファイル全体をコンテキストウィンドウに Read で読み込もうとします。後続のツール呼び出しごとに会話履歴全体が再送信される(キャッシュ読み取り)ため、セッションの早い段階で大きなファイルを1つ読み込むだけで、10万~30万トークンが無駄に消費されます。
  2. 狭い行範囲だけを読み込むと、ハルシネーションやコードの重複が発生します: トークンを節約するために、ファイルの lines 240–260 だけを読むようエージェントに強制すると、エージェントは次の情報を把握できなくなります:
    • ファイル先頭にあるクラス属性、self.x フィールド、@onready / @export 変数、定数、struct / interface 定義。
    • 同じファイル内にすでに存在するヘルパー関数(LLM が重複したコードを書く原因になります)。
    • 呼び出し元が実際に関数へ引数を渡す方法(呼び出し箇所の前後 ±5 行)。
    • ファイルのコーディングスタイル(インデント、型指定の規則、エラー処理の慣例)。
  3. 静的 AST グラフだけでは、動的ディスパッチやシーン/テンプレートの接続を検出できません: 標準的な呼び出しグラフが検出するのは、静的な foo() 呼び出しだけです。Python の getattr(obj, "foo")、Godot の call("foo") や .tscn のシグナル接続、Unity/C# の SendMessage("foo") を通じて関数が呼び出されている場合や、.vue / .html / .proto ファイル内で参照されている場合、単純なグラフは 「呼び出し元0件 — 安全に削除できます」 と報告し、本番コードを壊してしまいます。
surgical-context-mcp が3つすべての問題を解決する方法
  • get_edit_context(symbol) — 編集前に 1 回呼び出す: 2,500 行のファイルを読む代わりに、エージェントは MCP を1 回呼び出し(get_edit_context)、厳密に予算が設定された(≤ 4,000 トークン)外科的なパッケージを受け取ります。このパッケージには以下が含まれます。
    1. 対象関数の全本体(Edit 用の正確な行番号付き)
    2. ファイルの骨格(すべてのインポート、interface/struct/enum ブロック、クラスフィールド、定数。ただし、その他の関数本体は含みません)
    3. 使用メンバーと直接呼び出す関数(対象関数が使用するクラスフィールドの定義、および短い同一ファイル内ヘルパーの全本体(≤ 25 行))
    4. 直接の呼び出し元(d=1、±5 行ウィンドウ)(200 行の呼び出し元関数全体を出力せず、正確な呼び出し箇所のコンテキストを提示)
    5. ファイル内のその他の関数シグネチャ(エージェントが重複実装せず、既存のヘルパーを再利用できるようにします)
    6. スタイルのヒントとカバレッジ警告(動的な文字列呼び出し、.tscn の接続、テンプレート、プロトコル参照にフラグを付けます)
  • check_rename_or_delete(symbol) — リファクタリング前に 1 回呼び出す: AST の呼び出し元(exact/scoped)、親クラス/子クラスにまたがる継承オーバーライド、.tscn/テンプレート接続、シグナルの emit/connect 箇所、ワークスペース全体の動的な文字列参照を確認します。
  • 言語間コントラクト(shares_contract)— サーバー ↔ クライアント ↔ 設定を 1 回で確認:
    • プロトコルのオペコード(contract::opcode::0xCC): 言語間の 16 進数オペコード定数を自動的に関連付けます(例: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)を、自動的に 1 つの共有コントラクトノードに関連付けます。
  • データ、シード、翻訳(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 シンボルに対応付け、その呼び出し元、影響を受ける言語間コントラクト、実行可能なテストコマンドを 1 回の呼び出しで報告します。コードレビュー用サブエージェント(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 はトークンをいくつ節約したか?」 に答えられます。
  • LLM インデックス作成コストゼロ、サブ秒の高速処理: ネイティブの C Tree-sitter 文法と組み込み SQLite(WAL モード)を基盤としています。API トークンを0個使用して約 600 ファイルを < 0.6 秒でインデックス化し、すべてのクエリで変更されたファイルを(mtime と SHA-1 を使って)自動的に更新します。
  • Claude Code PreToolUse フックによる強制: 組み込みのフックガード(code-graph install-hooks)を備えており、> 300 行のファイルに対する無制限の Read 呼び出しをブロックし、ファイルの AST シンボルテーブル(Lstart-end: signature)を返します。これにより、メインエージェントとサブエージェントの両方が、外科的な変更手順に沿って作業できます。

どれくらい節約でき、いつ使うべきですか?

1. トークンとコストの経済性(単一ターンとマルチターンで累積する節約)

エージェント型コーディングツール(Claude Code、Cursor、Cline)では、ツールを呼び出すたびに、それまでの会話履歴全体が再送信されます。12ターンのコーディングタスクの2ターン目に、エージェントが2,500行のファイル(~22,000 トークン)を読み込む場合、その 22,000 トークンは2ターン目、3ターン目、4ターン目から12ターン目まで、毎回課金されます(22,000 × 10 = 220,000 累積コンテキストトークン)。

ファイル全体の読み込みを get_edit_context(~2,500–3,500 トークン)に置き換えることで、surgical-context-mcp はターンを重ねるごとに累積するコンテキストの肥大化を防ぎます。

よくある開発タスクのベンチマーク

(593ファイルからなる多言語リポジトリで測定:2,607行のGodotクライアントコントローラー + Goバックエンド + JSウェブダッシュボード)

開発シナリオ標準的なエージェント(Read + Grep)surgical-context-mcp 使用時直接的なトークン節約10ターンで累積する節約
1. リポジトリの初期把握(「このコードベースはどのような構成ですか?」)~18,500 トークン(複数回の ls、Glob、Read の呼び出し)~650 トークン(GRAPH_REPORT.md / get_architecture_map)トークンを96%削減約178,000トークンを節約
2. 大きなファイル内の関数を変更(2,607 行)~22,400 トークン(対象ファイル全体と呼び出し元ファイル1つを読み込み)~2,900 トークン(get_edit_context が骨格 + 本体 + 呼び出し元を返す)トークンを87%削減約195,000トークンを節約
3. リクエスト/イベントのエンドツーエンドのフローを追跡(クライアント -> パケット -> サーバーハンドラー)~31,000 トークン(文字列の検索と4~6個のファイルの読み込み)~1,200 トークン(find_flow + get_symbol_impact)トークンを96%削減約298,000トークンを節約
4. 安全なリファクタリング/デッドコードの削除(「このメソッドは削除または名前変更できますか?」)~14,000 トークン(候補ファイルの検索と読み込み。動的参照は見落とす可能性があります)~450 トークン(check_rename_or_delete がAST + オーバーライド + .tscn + 動的文字列を確認)トークンを97%削減約135,000トークンを節約
5. 複数のサブエージェントによる並列実行(バックエンド/フロントエンド用に2~3個のサブエージェントを起動)200,000–350,000 トークン(各サブエージェントがそれぞれ巨大なファイルを読み込み)35,000–60,000 トークン(PreToolUse フックがすべてのサブエージェントで300行を超える読み込みをブロック)トークンを80~85%削減レート制限とコンテキストの圧縮を防止

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/JSの EventEmitter / bus.on、Pythonの @on_event デコレーター、C#のイベントを使うコードベースでは、標準的な Grep で送信元からリスナーまでの実行フローを追跡できません。
  • 多言語対応のフルスタック・モノレポ: Go + TypeScript、Python + React、または Godot + Go + JS を組み合わせたプロジェクトでは、単純なテキスト検索で、言語をまたいだ同名のメソッド(connect、refresh、update、send)が混同されることがあります。
  • 長時間のコーディングセッションとサブエージェントのワークフロー: メインの会話ウィンドウをすっきり保ち、15分間作業した後にClaude Code/Cursorがコンテキスト上限に達したり、推論の品質が低下したりするのを防ぎます。
節約効果が小さくなるのはどんなときですか?(すべて開示します)
  • 小さなファイル(< 300 行): ファイルがわずか 150 行の場合、骨組みと本文に分割するのは不要なオーバーヘッドです。surgical-context-mcp はこれを自動的に検出します。< 300 行のファイルでは、get_edit_context は番号付きのファイル全体をそのまま返します。
  • テストランナー/コンパイラの出力だけを繰り返し処理する場合: サブエージェントが 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、.cjsclass、interface、type、enum、関数、アローコンポーネント、React フック、モジュールの consttsconfig.json/jsconfig.json(paths、baseUrl)、React/Vue/Angular/Next.js のライフサイクルフック、/api/... のルートコントラクト、vitest/jest のテストコマンド
Python.pyclass、def/async def、@decorator のイベント/ルートリンク、dataclass/Pydantic の Field(alias=...)、__init__ 内の self.attr相対インポート(from .models import ...)、__dunder__ と pytest のライフサイクルフック、getattr の警告、pytest -k のテストコマンド
Go.gopackage、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.rsstruct、enum、trait、impl Type、fn、const/static、use 宣言crate::... と impl の解決、#[serde(rename = "...")] のフィールドコントラクト、Drop/Default/From トレイトのフック、#[test]/cargo test のコマンド
C#(.NET/Unity/Godot).csnamespace、class、interface、struct、enum、プロパティ、フィールド、メソッド、[Attributes][JsonPropertyName]/[JsonProperty] のコントラクト、Unity(Awake、Update、FixedUpdate、SendMessage)と Godot C#(_Ready、_Process)のライフサイクルフック、dotnet test --filter のコマンド
Java.javapackage、class、interface、enum、record、フィールド、コンストラクター、メソッド、@Annotations@JsonProperty/@SerializedName のコントラクト、Spring/Android/JUnit のライフサイクルフック(afterPropertiesSet、onCreate)、getMethod の警告、mvn test/./gradlew test のコマンド
Godot 4(GDScript とシーン).gd、.tscn、project.godotextends、class_name、signal、const、enum、@export、@onready、var、funcproject.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::* を介して構造体タグとドット区切りの設定キーをリンクし、tr()/noticeT() 呼び出しを i18n::* キーと照合して監査します

仕組み(アーキテクチャ)

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 内のすべての関係には、次の3つの信頼度レベルのいずれかが付与されます。

  • exact:同じファイル/クラス内、明示的なファイルインポート(tsconfig.json の @/ エイリアス、go.mod のパッケージ、Python の相対インポート、Godot の project.godot Autoload、.tscn スクリプト)、または直接の super/継承チェーンを通じて解決されます。
  • scoped:インポートされたモジュールを通じて解決された、曖昧さのないシンボル、または同じ言語ファミリー内で一意のシンボルです。
  • name_only:複数の候補がある、曖昧な名前の一致です。主要な出力からは除外され、### Uncertain (name_only, max 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 に2つのコマンドが追加されます。code-graph(CLI + MCP サーバー)と surgical-context-mcp(MCP サーバーのショートカット)です。

code-graph --help

単発の uvx 実行よりも、永続的なインストール(uv tool / pipx / pip)をおすすめします。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)

これを一度実行すると、code-graph が Claude Code にグローバル登録されます。

claude mcp add code-graph -- code-graph serve
オプション B:Cursor / Windsurf / Claude Desktop(.mcp.json または claude_desktop_config.json)

.mcp.json(プロジェクトのルート)またはグローバル MCP 設定ファイルに以下を追加します(エディターがシェルの PATH を引き継がない場合は、which code-graph で確認した絶対パスを使用してください)。

{
  "mcpServers": {
    "code-graph": {
      "command": "code-graph",
      "args": ["serve"]
    }
  }
}

ステップ 2:対象プロジェクトを初期化し、ガードフックをインストールする

作業対象のプロジェクトリポジトリで install-hooks を実行します。

code-graph install-hooks /path/to/your/project

このコマンドは次の処理を自動的に行います。

  1. /path/to/your/project/.code_graph.sqlite に .code_graph.sqlite を構築します(.gitignore、ネストされた .gitignore、.codegraphignore を尊重し、node_modules、.venv、.git のワークツリー、ビルド成果物などはスキップします)。
  2. プロジェクトのルートに GRAPH_REPORT.md を生成します。サブシステムクラスター、God Nodes(本番コードで最も多く接続されているクラス/関数)、Autoloads、および上位のイベント/シグナルバスチャネルを記載した、簡潔なアーキテクチャ概要(約60行)です。
  3. Claude Code の PreToolUse フックを /path/to/your/project/.claude/settings.local.json にインストールします。
    • Claude Code(または Claude Code が起動したサブエージェント)が、300 行を超えるコードファイルに対して上限のない Read を実行しようとすると、フックが呼び出しをインターセプトし、3,000 行の読み取りをブロックして、そのファイル内のすべての関数/クラスと行番号(Lstart-end: signature)を簡潔な一覧で返し、エージェントに get_edit_context または Read(offset, limit) を呼び出すよう指示します。
    • エージェントがシンボル名を Grep で検索すると、フックは .code_graph.sqlite にある正確な AST 定義位置を追加します。

ヒント: ローカルの SQLite データベースが git にコミットされないよう、プロジェクトの .gitignore に .code_graph.sqlite* を追加してください。


ステップ 3:ワークフロールールを CLAUDE.md または .cursorrules に追加する

以下の推奨 CLAUDE.md 設定をプロジェクトの CLAUDE.md(または .cursorrules)にコピーします。


ステップ 4:AI エージェントの実際の使用方法

設定が完了すると、手動でコマンドを実行する必要はありません。AI エージェントが以下のワークフローを自動的に実行します。

  1. プロジェクトの調査: エージェントは GRAPH_REPORT.md を読み込むか、get_architecture_map() を呼び出して、プロジェクトのディレクトリクラスターとハブクラスをすぐに確認します。
  2. 関数またはメソッドの編集: シンボルに触れる前に、エージェントは次を呼び出します。
    get_edit_context(symbol="computeFinalScore", project_path="/path/to/project")
    
    関数本体、ファイルのスケルトン(interface/struct/var 宣言)、使用されているメンバー、短いヘルパー本体、呼び出し元の周辺コードを一度に取得し、ファイル全体を読み込まずにすぐ Edit を適用します。
  3. コードの名前変更または削除: 関数を削除したり、パラメーターを変更したりする前に、エージェントは次を呼び出します。
    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 = 300
  • 23: 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 に貼り付けて、メインエージェントとサブエージェントがこのピンポイントなワークフローに自動的に従うようにします。

## 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 に追加せずに、グラフから追加のディレクトリや生成ファイルを除外するには、標準の .gitignore 構文を使って、プロジェクトのルートに .codegraphignore ファイルを作成します。

# .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)、そしてエージェントによるファイル全体の読み込みを防ぐ PreToolUse フックを提供します。

コントリビューション

Issue や PR を歓迎します。特に、新しい言語リゾルバーや実環境でのトークンベンチマークをお待ちしています。surgical-context-mcp によってトークンを節約できた場合は、⭐ を付けていただくと、ほかのユーザーにも見つけてもらいやすくなります。

ライセンス

MIT © Eray Erturk。個人利用および商用利用は無料です。

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。