Local Tree-sitter code knowledge graph & MCP server that gives Claude Code, Cursor and other AI coding agents surgical edit context — cutting token usage by 80-95%.
pip install surgical-context-mcp Copy PIP instructions
Real run on this repo: editing a function in a 1,264-line file costs ~3.7k tokens instead of ~13.3k (−72%) — and you still get the skeleton, callers and helpers.
# 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 That's it — your agent now calls get_edit_context instead of reading whole files. Using Cursor, Windsurf, Cline or Claude Desktop? See Step 1. Also listed on the official MCP Registry as io.github.erayerturk/surgical-context-mcp.
In agentic coding tools (Claude Code, Cursor, Cline), every tool call re-sends the entire conversation history up to that point. When an agent reads a 2,500-line file (~22,000 tokens) on Turn 2 of a 12-turn coding task, those 22,000 tokens are billed on Turn 2, Turn 3, Turn 4 ... all the way to Turn 12 (22,000 × 10 = 220,000 cumulative context tokens).
By replacing full-file reads with get_edit_context (~2,500–3,500 tokens), surgical-context-mcp prevents context bloat from compounding across turns.
(Measured on a 593-file multi-language repository: 2,607-line Godot client controller + Go backend + JS web dashboard)
surgical-context-mcp strictly isolates language families (so a method in JavaScript or Go never collides with a method of the same name in Python or GDScript) and parses real ecosystem configuration files to resolve cross-file imports with exact confidence:
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 Confidence Levels on Every Graph Edge Every relationship in .code_graph.sqlite is tagged with one of three confidence levels:
Published on PyPI and the official MCP Registry.
# 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 This puts two commands on your PATH: code-graph (CLI + MCP server) and surgical-context-mcp (MCP server shortcut).
code-graph --help Prefer a persistent install (uv tool / pipx / pip) over one-off uvx runs: install-hooks writes the absolute path of the code-graph binary into your Claude Code settings, so it must not live in a temporary cache.
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 . How to Use (Step-by-Step Setup Guide) Step 1: Register the MCP Server with Your AI Coding Tool Option A: Claude Code (CLI) Run this once to register code-graph globally in Claude Code:
claude mcp add code-graph -- code-graph serve Option B: Cursor / Windsurf / Claude Desktop (.mcp.json or claude_desktop_config.json) Add the following to your .mcp.json (project root) or global MCP settings file (if your editor doesn't inherit your shell PATH, use the absolute path from which code-graph):
{ "mcpServers": { "code-graph": { "command": "code-graph", "args": ["serve"] } } } Step 2: Initialize Your Target Project & Install the Guard Hook Run install-hooks on any project repository you want to work on:
code-graph install-hooks /path/to/your/project What this command does automatically:
Tip: Add .code_graph.sqlite* to your project's .gitignore so the local SQLite database is not committed to git.
Copy the Recommended CLAUDE.md Configuration below into your project's CLAUDE.md (or .cursorrules).
Once configured, you don't need to run manual commands — your AI agent will automatically follow this workflow:
get_edit_context(symbol="computeFinalScore", project_path="/path/to/project") It gets the exact function body, the file skeleton (interface/struct/var declarations), used members, short helper bodies, and caller windows in one shot, and immediately applies Edit without reading the whole file. Renaming or Deleting Code: Before removing a function or changing its parameters, the agent calls: check_rename_or_delete(symbol="computeFinalScore", project_path="/path/to/project") It verifies all callers, inheritance overrides, scene/template links, and dynamic string references. Real Output Examples Example 1: get_edit_context on a Large File Command:
code-graph edit-context build_edit_context -p /path/to/surgical-context-mcp Output (abbreviated):
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. File Skeleton (src/code_graph/context_builder.py — imports, signals, vars, consts) 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. Used Members & Direct Callees Referenced File Members:
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 [] External Callees:
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. Other Function Signatures in 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( Coverage Warnings No unresolved textual references found. --- ## 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 Recommended CLAUDE.md / .cursorrules Configuration Paste this section into your project's CLAUDE.md, AGENTS.md, or .cursorrules so main agents and subagents follow the surgical workflow automatically:
## 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=" ", 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=" ")` 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=" ", 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=" ", to_symbol=" ")` to trace execution or event paths between two symbols. - Use `search_symbols(query=" ")` 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=" ")` 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). Custom Ignore Rules (.codegraphignore) By default, surgical-context-mcp automatically respects:
If you want to exclude additional directories or generated files from the graph without adding them to .gitignore, create a .codegraphignore file in your project root using standard .gitignore syntax:
# .codegraphignore *.pb.go *.generated.ts third_party/ fixtures/large_dumps/ Running the Test Suite .venv/bin/python tests/test_end_to_end.py Acknowledgements The GRAPH_REPORT.md / "God Nodes" architecture-summary idea was inspired by graphify. surgical-context-mcp is an independent implementation with a different focus: per-edit surgical context (get_edit_context), refactor safety checks (check_rename_or_delete), and a PreToolUse hook that keeps agents off full-file reads.
Issues and PRs are welcome — especially new language resolvers and real-world token benchmarks. If surgical-context-mcp saves you tokens, a ⭐ helps others find it.
MIT © Eray Erturk. Free for personal and commercial use.
All 2 files in this release have provenance metadata.
mcp model-context-protocol mcp-server claude-code cursor code-graph knowledge-graph tree-sitter ast llm ai-coding-agent token-optimization code-context static-analysis
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 1, 2026.
All 2 files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




