code-graph-mcp
A high-performance code knowledge graph server implementing the Model Context Protocol (MCP). Indexes codebases into a structured AST knowledge graph with semantic search, call graph traversal, and HTTP route tracing — designed to give AI coding assistants deep, structured understanding of your code.
Features
- Multi-language parsing — Tree-sitter AST extraction across tiers of depth:
- Full (calls + imports + inheritance): TypeScript/TSX, JavaScript, Go, Python, Rust, Java. HTTP route extraction additionally covers TypeScript/TSX + JavaScript (Express/Connect), Go (
net/http), Python (Flask/FastAPI), and Rust axum (.route() chains with inline .nest() prefixes; named handlers only) — actix/rocket and Java Spring are not yet route-extracted
- Smoke-tested (calls + imports + inheritance): C#, Kotlin, Ruby, PHP, Swift, Dart
- Limited (functions + calls +
#include imports + gtest test markers + C++ base-class inheritance + Class::method scope qualification): C, C++
- Scripting: Bash (functions + commands +
source/. imports), Markdown (headings)
- File-FTS only (no AST symbol extraction): HTML, CSS, JSON
- Test markers — detected from the AST for Rust (
#[test] / #[cfg(test)]), JavaScript/TypeScript/TSX (describe/it/test blocks and their callbacks) and C/C++ (gtest TEST macros). Go, Python, Java and the rest fall back to path/name heuristics (tests/, src/test/java/, *_test.*, *.test.js, test_*, *Test)
- Value/type references — a
references relation for symbols that are used without being called, imported or inherited (path-qualified constants, type-position uses, functions passed as values): Rust, TypeScript/TSX, JavaScript, Python, Go, Java, C, C++
- Semantic code search — Hybrid BM25 full-text + vector semantic search with Reciprocal Rank Fusion (RRF), powered by sqlite-vec
- Call graph traversal — Recursive CTE queries to trace callers/callees with cycle detection
- HTTP route tracing — Map route paths to backend handler functions (Express, Flask/FastAPI, Go
net/http, Rust axum)
- Dead code detection — Find unreferenced symbols with smart Orphan/Exported-Unused classification
- Impact analysis — Determine the blast radius of code changes by tracing all dependents
- Incremental indexing — Merkle tree change detection with a file system watcher; changed files are re-indexed when the next MCP query tool call arrives (
get_index_status does not count). Smart event filtering skips metadata-only changes (chmod, xattr)
- Context compression — Token-aware snippet extraction for LLM context windows (L0→full code, L1→summaries, L2→file groups, L3→directory overview). Every MCP tool except
ast_search takes compact: true, which drops code bodies from the response; what else it trims is per-tool (get_ast_node keeps the signature, module_overview drops it), and how much it saves depends on the tool and the repo, so no fixed figure is quoted here
- Embedding model — Optional local embedding via Candle (feature-gated
embed-model). Context reordered to prioritize structural relations over code for better embedding quality
- Self-healing — Automatic SQLite corruption recovery with rebuild. Startup repair for incomplete indexing (Phase 3 failures)
- MCP protocol — JSON-RPC 2.0 over stdio, plug-and-play with Claude Code, Cursor, Windsurf, and other MCP clients
- Claude Code Plugin — First-class plugin with skills (
explore, index), a code-explorer agent, auto-indexing hooks, StatusLine integration, and self-updating
Why code-graph-mcp?
Unlike naive full-text search or simple AST dumps, code-graph-mcp builds a structured knowledge graph that understands the relationships between symbols across your entire codebase.
Incremental by Design
BLAKE3 Merkle tree tracks every file's content hash. On re-index, only changed files are re-parsed — unchanged directory subtrees are skipped entirely via mtime cache. When a function signature changes, dirty propagation automatically regenerates context for all downstream callers across files.
Hybrid Search, Not Just Grep
Combines BM25 full-text ranking (FTS5) with vector semantic similarity (sqlite-vec) via Reciprocal Rank Fusion (RRF) with raw score blending — so searching "handle user login" finds the right function even if it's named authenticate_session. Results are auto-compressed to fit LLM context windows.
Scope-Aware Relation Extraction
The parser doesn't just find function calls — it tracks them within their proper scope context. Extracts calls, imports, inheritance, interface implementations, exports (ESM export and CommonJS module.exports = { … } / exports.name = …), value/type references, and HTTP route bindings. Same-file targets are preferred over cross-file matches to minimize false-positive edges.
HTTP Request Flow Tracing
Unique to code-graph-mcp: trace from GET /api/users → route handler → service layer → database call in a single query. Supports Express/Connect, Flask/FastAPI, Go net/http, and Rust axum.
Zero External Dependencies at Runtime
Single binary, embedded SQLite, bundled sqlite-vec extension, optional local embedding model via Candle — no database server, no cloud API, no Docker required. Runs entirely on your machine.
Built for AI Assistants
Every design decision — from token-aware compression to node_id-based snippet expansion — is optimized for LLM context windows. Works out of the box with Claude Code, Cursor, Windsurf, and any MCP-compatible client.
Performance
Every row below is a line code-graph-mcp benchmark prints, measured on this
repository (283 files, 5,311 nodes, 11,215 edges) with a release build — median
of three consecutive runs on an otherwise idle machine. Run the same command on
your own project: the numbers that matter are yours, and these scale with tree
size and machine.
benchmark line |
This repo, v0.129.0 |
| Full index |
~2.0s (≈139 files/second, single-threaded) |
| Incremental (noop) |
~28ms no-change detection via BLAKE3 Merkle tree |
| Query latency P50 / P99 |
~655us / ~2.1ms |
| DB size |
~22.4MB (≈4.2MB per 1,000 nodes) |
| Avg tokens/node |
~242 |
Efficiency: code-graph vs Traditional Tools
How many TOOL CALLS each question takes, comparing code-graph-mcp against Grep
- Read + Glob. These are call counts, not token measurements: the left column is
the round trips the traditional approach needs before it can answer, the right
column is the single call that answers it. Token cost follows call count only
loosely — how much source lands in the context window depends on the files, so
this table does not claim a token ratio.
Tool Call Reduction
| Scenario |
Traditional |
code-graph |
Savings |
| Project architecture overview |
5-8 calls |
1 call (project_map) |
~85% |
| Find function by concept |
3-5 calls |
1 call (semantic_code_search) |
~75% |
| Trace 2-level call chain |
8-15 calls |
1 call (get_call_graph) |
~90% |
| Pre-change impact analysis |
10-20+ calls |
1 call (get_ast_node + include_impact) |
~95% |
| Module structure & exports |
5+ calls |
1 call (module_overview) |
~80% |
| File dependency mapping |
3-5 calls |
1 call (module_overview + include_deps) |
~75% |
| Similar code detection |
N/A |
1 call (get_ast_node + include_similar) |
unique |
Session token savings
tests/effectiveness_bench.rs is the only reproducible number here, and it is
worth being precise about what it measures. For each of five navigation tasks it
runs the real CLI on a fixture project and compares the response size in bytes
against a hand-set baseline_bytes for the Grep+Read approach. Bytes stand
in for tokens; the baselines are estimates committed once and held fixed, so its
value is regression tracking over releases, not a measurement of your project.
cargo build --no-default-features
cargo test --test effectiveness_bench --no-default-features -- --ignored --nocapture
On the fixture at v0.123.0 that prints 942 / 23000 = 0.04x, and the test fails
if the overall ratio ever exceeds 0.60. Earlier revisions of this README carried
an "Overall Session Efficiency" table (~80% fewer calls, ~95% fewer lines read,
40-60% session savings) whose first rows had no source at all; they are gone
rather than dressed up.
What code-graph Uniquely Enables
- Impact analysis — "Changing
conn affects 33 functions across 4 files, 78 tests at HIGH risk" — impossible to derive manually with Grep
- Transitive call tracing — Follow
main → run_serve → handle_message → handle_tools_call → conn in one query
- Semantic search — Find
authenticate_session when searching "handle user login"
- Dependency strength — Not just "file A imports file B", but "file A uses 38 symbols from file B"
When Traditional Tools Are Still Better
| Use Case |
Best Tool |
| Exact string / constant search |
Grep |
| Reading a file to edit it |
Read |
| Finding files by name pattern |
Glob |
What the Graph Does Not See
Call edges are resolved by name, so a few spellings produce no edge. These are
known boundaries, not bugs to report:
- A method call reached through a module path.
module::Type::method()
produces no call edge — the same whether the path starts with the crate name,
crate::, or a bare module. A bare Type::method() does resolve, and so does
a free function through the same kind of path: my_crate::cli::cmd_grep()
binds, which path_qualifier_strips_own_crate_name in
tests/integration_call_qualifier.rs exists to keep true. It is the Type::
segment in front of the method that drops the edge, not the length of the path.
Measured on this repo at v0.132.0: Database::open has 173 caller edges and
none of them come from the 53 call sites in tests/cli_e2e.rs spelled
code_graph_mcp::storage::db::Database::open(...).
- A receiver call whose method name is shared by several types.
obj.method()
normally resolves: the receiver has no statically-known type, so the resolver
binds it when exactly one same-language method carries that name
(receiver_call_resolves_unique_method). When several types define the same
name it is dropped rather than fanned out
(receiver_call_with_ambiguous_method_name_stays_unresolved).
- Cross-file constant and type-position uses, callbacks, and function
pointers. None of these are call edges, but none are invisible either: they
are carried as the
references relation, which find_references returns and
impact reports separately as value reference(s) — callbacks / fn-pointers / type positions. Together with the row above, this is why include_dead
results are candidates to verify rather than a verdict.
- Dispatch by name. A function reached through a string key, a reflection
call or an event name (
handlers["save"], getattr(obj, "save"),
send(:save), bus.on("save", …)) has no edge. When callgraph, impact
or refs finds no caller for a function, the answer lists up to 5 lines
where the name appears in such a shape or is passed as a value (boundaries
in --json and MCP), and a code-graph-mcp grep that shows every
occurrence. It is a disclosure, not an edge, and a lexical one: a line it
does not list is not proof that nothing dispatches to the function.
Architecture
src/
├── domain.rs # Shared constants, relation types, env-var config
├── resolve.rs # Shared symbol resolution + ambiguity verdicts (CLI and MCP)
├── outcome.rs # Retrieval-adoption metrics from session transcripts
├── budget.rs # Output budgets (--budget / max_tokens): rank, shorten, drop, next step
├── cli/ # Every `code-graph-mcp <cmd>` subcommand (one file per command)
├── mcp/ # MCP protocol layer (JSON-RPC, tool registry, server)
│ └── server/ # McpServer with IndexingState + CacheState sub-structs
├── parser/ # Tree-sitter parsing, relation extraction, LanguageConfig dispatch
├── indexer/ # 3-phase pipeline, Merkle tree, file watcher
├── storage/ # SQLite schema (v10), CRUD, FTS5, migrations
├── graph/ # Recursive CTE call graph queries
├── search/ # RRF fusion search combining BM25 + vector
├── embedding/ # Candle embedding model (optional, masked mean pooling)
├── snapshot/ # Portable graph snapshots (create / verify / install)
├── sandbox/ # Context compressor with token estimation
└── utils/ # Language detection, config
Installation