Sandbox
@tirth8205/code-review-graph

MCP code graph for AI coding tools

This tool builds a structural graph of your codebase with Tree-sitter, then uses that graph to pick the files and flows an agent actually needs for a review or question. It works through MCP and CLI, and it can also keep the graph fresh with hooks and watch mode.

31,311 stars2.9k forksPythonUpdated 7d ago
Your AI Reads 25,000 Tokens to Review 3 Functions. This Free Tool Reads 700 (code-review-graph)
Hyperautomation Labs1.7k views • 1 month ago

Videos about this repo

Who it's for

Builders who want their coding agent to review large repos without re-reading the whole tree.

What it delivers

You can give your agent a compact, relevant context set instead of the full repository.

What it does

Incremental graph updates

Re-parses only changed files and their affected dependents instead of rebuilding the whole index.

Blast-radius review context

Finds the functions, classes, files, and tests likely affected by a change.

MCP and CLI integration

Exposes the graph through MCP and a command-line interface so agents can query it during work.

Local storage

Stores the graph in SQLite under `.code-review-graph/` without requiring a cloud service.

Watch mode and hooks

Updates the graph as files change and through supported commit hooks.

Risk-scored PR reviews

Posts review comments in GitHub Action runs with affected flows and test gaps.

Broad language support

Parses many languages and notebooks through Tree-sitter and targeted resolvers.

Search and export tools

Adds keyword/vector search, graph diffing, visualization, and export formats like GraphML and Cypher.

How to get it

  1. 1Run
    pip install code-review-graph                     # or: pipx install code-review-graph
    code-review-graph install          # auto-detects and configures all supported platforms
    code-review-graph build            # parse your codebase
  2. 2Then open your project and ask your AI assistant
    Build the code review graph for this project
  3. 3Both commands print the same compact panel showing how many tokens the graph saved you…
    ┌─────────────────────── Token Savings ────────────────────────┐
    │ Full context would be:     12,921 tokens                     │
    │ Graph context used:           762 tokens                     │
    │ Saved:                     12,159 tokens (~94%)              │
    │ Breakdown: Functions 244 · Tests 191 · Risk 244 · Other 83   │
    └──────────────────────────────────────────────────────────────┘
  4. 4To exclude paths from indexing, create a .code-review-graphignore file in your…
    generated/**
    *.generated.ts
    vendor/**
    node_modules/**
  5. 5Voyage embeddings need no extra install. Set VOYAGE_API_KEY and pass provider="voyage"…
    export VOYAGE_API_KEY=pa-...
    export CRG_ACCEPT_CLOUD_EMBEDDINGS=1
    code-review-graph embed --provider voyage --model voyage-code-3
  6. 6CRG exposes 30 MCP tools by default. In token-constrained environments, you can limit…
    # Via CLI flag
    code-review-graph serve --tools query_graph_tool,semantic_search_nodes_tool,detect_changes_tool
    
    # Via environment variable
    CRG_TOOLS=query_graph_tool,semantic_search_nodes_tool code-review-graph serve

README

code-review-graph

tirth8205%2Fcode-review-graph | Trendshift

Stop burning tokens. Start reviewing smarter.

English | 简体中文 | 日本語 | 한국어 | हिन्दी

PyPI Downloads Stars MIT Licence CI Python 3.10+ MCP Website Discord

Usage · Commands · FAQ · Troubleshooting · GitHub Action · Reproducing the benchmarks · Roadmap


AI coding tools can end up re-reading large parts of your codebase on review tasks. code-review-graph fixes that. It builds a structural map of your code with Tree-sitter, tracks changes incrementally, and gives your AI assistant precise context via MCP so it reads only what matters.

The Token Problem: reading flask's whole corpus costs 143,594 tokens, a graph answer costs 2,196 — 71.0x fewer


Quick Start

pip install code-review-graph                     # or: pipx install code-review-graph
code-review-graph install          # auto-detects and configures all supported platforms
code-review-graph build            # parse your codebase

One command sets up everything. install detects which AI coding tools you have, writes the correct MCP configuration for each one, installs platform-native hooks/skills where supported, and injects graph-aware instructions into your platform rules. It auto-detects whether you installed via uvx or pip/pipx and generates the right config. Restart your editor/tool after installing.

One Install, Every Platform: auto-detects Codex, Claude Code, CodeBuddy Code, Cursor, Windsurf, Zed, Continue, OpenCode, Antigravity, Gemini CLI, Qwen, Qoder, Kiro, GitHub Copilot, and GitHub Copilot CLI

To target a specific platform:

code-review-graph install --platform codex       # configure only Codex
code-review-graph install --platform cursor      # configure only Cursor
code-review-graph install --platform claude-code  # configure only Claude Code
code-review-graph install --platform gemini-cli   # configure only Gemini CLI
code-review-graph install --platform antigravity   # configure only Antigravity
code-review-graph install --platform windsurf     # configure only Windsurf
code-review-graph install --platform zed          # configure only Zed
code-review-graph install --platform continue     # configure only Continue
code-review-graph install --platform opencode     # configure only OpenCode
code-review-graph install --platform qwen         # configure only Qwen
code-review-graph install --platform qoder        # configure only Qoder
code-review-graph install --platform kiro         # configure only Kiro
code-review-graph install --platform copilot      # configure only GitHub Copilot (VS Code)
code-review-graph install --platform copilot-cli  # configure only GitHub Copilot CLI
code-review-graph install --platform codebuddy    # configure only CodeBuddy Code
code-review-graph install --platform hermes       # configure only Hermes Agent

Requires Python 3.10+. For the best experience, install uv (the MCP config will use uvx if available, otherwise falls back to the code-review-graph command directly).

To remove CRG from a Git or SVN project, use the symmetric uninstall command from anywhere inside its working tree. The target is normalized to the working tree root, and non-repository directories are refused. It removes only CRG-owned files and entries; unrelated MCP servers, hooks, skills, and JSONC comments remain untouched. Shared configuration changes use atomic replacement so a failed write leaves the original file intact.

code-review-graph uninstall --dry-run    # preview every action; write nothing
code-review-graph uninstall              # preview, ask for confirmation, then apply
code-review-graph uninstall --yes        # apply without prompting
code-review-graph uninstall --all-repos  # also clean every registered repository
code-review-graph uninstall --keep-data  # remove integrations but keep graph databases
code-review-graph uninstall --keep-user-configs --repo .  # clean this project only

Then open your project and ask your AI assistant:

Build the code review graph for this project

The initial build takes ~10 seconds for a 500-file project. After that, watch mode and supported hooks can keep the graph updated automatically.

How It Works

How your AI assistant uses the graph: User asks for review, AI checks MCP tools, graph returns blast radius and risk scores, AI reads only what matters

Your repository is parsed into an AST with Tree-sitter, stored as a graph of nodes (functions, classes, imports) and edges (calls, inheritance, test coverage), then queried at review time to compute the minimal set of files your AI assistant needs to read.

Architecture pipeline: Repository to Tree-sitter Parser to SQLite Graph to Blast Radius to Minimal Review Set

Blast-radius analysis

When a file changes, the graph traces every caller, dependent, and test that could be affected. This is the "blast radius" of the change. Your AI reads only these files instead of scanning the whole project.

Blast radius visualization showing how a change to login() propagates to callers, dependents, and tests

Incremental updates in seconds

When hooks or watch mode are enabled, file saves and supported commit hooks trigger incremental updates. The graph diffs changed files, finds their dependents through the graph's own import and call edges, and re-parses only the files whose SHA-256 hash actually changed. On a ~3,000-file project (django) a two-file edit re-indexes in about 2.5 seconds on the path the hooks use, of which ~1.4 s is process start-up; a no-op update costs only that start-up. See Incremental update latency for the full measurement.

Incremental update flow: a supported hook or watch update triggers a git diff, dependents are found through graph edges, and only files whose SHA-256 hash changed are re-parsed

Whole codebase or targeted answer?

The bigger the repository, the more token waste hurts. Instead of feeding a whole corpus to the model, the graph returns an answer-shaped slice of it: on this repository, 208,821 source tokens become ~3,190 tokens per question.

code-review-graph repo: 208,821 source tokens funnel down to ~3,190 token graph responses — 68x fewer tokens per question

Broad language coverage + Jupyter notebooks

Language coverage organized by category: Web, Backend, Systems, Mobile, Scripting, Shells, Domain, and Other, plus Jupyter and Databricks notebook support

Parser support covers functions, classes, imports, call sites, inheritance, and test detection across the current parser surface, using Tree-sitter where available and targeted fallbacks where needed. Current support includes Python, JavaScript/TypeScript/TSX, Go, Rust, Java, C/C++, C#, VB.NET, Ruby, Kotlin, Swift, PHP, Scala, Solidity, Dart, R, Perl, Lua/Luau, Objective-C, shell scripts, Elixir, Zig, PowerShell, Julia, ReScript, GDScript, Nix, Verilog/SystemVerilog, SQL, Terraform/OpenTofu structure (.tf; generic .hcl files are recognized as file nodes), Ansible playbooks/roles/tasks, Vue/Svelte SFCs, Astro files parsed through the TypeScript parser, Jupyter/Databricks notebooks (.ipynb), and Perl XS files (.xs). Generic YAML is not treated as source code.

PHP projects additionally get repository-bounded Composer PSR-4 resolution, Blade template references, and Laravel Route/Eloquent semantic edges when the source includes explicit framework imports, model inheritance, and receiver evidence.

Add your own language (no fork needed)

If your repo uses a language the parser does not cover yet, drop a languages.toml into .code-review-graph/ mapping file extensions to any grammar bundled in tree_sitter_language_pack, plus the tree-sitter node types for functions, classes, imports, and calls:

[languages.erlang]
extensions = [".erl"]
grammar = "erlang"
function_node_types = ["function_clause"]
class_node_types = ["record_decl"]
import_node_types = ["import_attribute"]
call_node_types = ["call"]

The generic tree-sitter walker handles extraction from there — no code changes, and built-in languages can never be overridden. See docs/CUSTOM_LANGUAGES.md for the schema reference, validation rules, and a worked end-to-end example.

Risk-scored PR reviews in CI (GitHub Action)

The same analysis runs as a composite GitHub Action — and it stays local-first: the knowledge graph is built and queried entirely on your CI runner, with no source code sent to any external service. On each pull request the action posts a single sticky comment with risk-scored functions, affected execution flows, and test gaps, updated in place on every push. An optional fail-on-risk input turns the review into a merge gate.

# .github/workflows/code-review-graph.yml
on:
  pull_request:

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: tirth8205/code-review-graph@v2.3.6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

See docs/GITHUB_ACTION.md for inputs, risk levels, and caching details, or the dogfood workflow this repo runs on itself in .github/workflows/pr-review.yml.


Benchmarks

Benchmarks across 6 real repositories: ~65x median per-question token reduction (376x max), 0.69 average impact F1 against graph-derived ground truth

Headline number: the median per-question token reduction across the 6 repos is ~65x (whole-corpus baseline vs graph query). The 376x maximum is a single best-case repo (fastapi, the largest corpus) — not the typical result.

All numbers come from the automated evaluation runner against 6 real open-source repositories (13 commits total). Every config pins an upstream SHA, the Leiden community detector runs with a fixed seed, and embeddings are deterministic on CPU — so two runs on different machines produce identical numbers. The full reproduction recipe with expected outputs is in docs/REPRODUCING.md. A weekly report-only run on the two smallest configs lives in .github/workflows/eval.yml.

Token efficiency: ~65x median per-question reduction (range 36x – 376x; whole-corpus vs graph query)

For a typical agent question ("how does authentication work", "what is the main entry point", etc.), the graph returns ~2,000–3,500 tokens of targeted search hits + neighbor edges instead of forcing the agent to read every source file. The table below averages over the 5 sample questions defined in code_review_graph/token_benchmark.py.

RepoSnapshot SHAnaive_corpus_tokensavg graph_tokensReduction
fastapi22381558948,7932,653375.6x
flaska29f88ce143,5942,19671.0x
code-review-graph84bde354208,8213,19068.1x
gin5c00df8a166,8682,76661.9x
httpxb55d4635142,3562,66160.6x
expressb4ab7d65136,0523,93636.0x

Median per-question reduction across the 6 repos: ~65x. The range is 36x – 376x, where 376x is the best case (fastapi, the largest corpus), not the headline.

Re-captured 2026-08-02 from clean clones at the pinned SHAs (crg 2.3.7, local all-MiniLM-L6-v2 embeddings). These numbers are lower than the 2026-05-25 capture they replace: the graph response grew as node embedding text became richer, so avg graph_tokens rose across every repo. fastapi is now measured at its current pin 22381558 rather than the retired 0227991a.

The whole-corpus baseline above is an upper bound no real agent pays: a competent agent greps for identifiers and reads only the best-matching files. The agent_baseline eval benchmark measures that realistic baseline — a pure-python grep over the corpus, top-3 files by match count, token-counted and compared to the graph query cost (evaluate/results/<repo>_agent_baseline_*.csv).

The formal eval/benchmarks/token_efficiency.py benchmark measures a different scenario — full get_review_context() JSON versus just the changed-file content of a commit — and reports ratios below 1 for small commits, because the review-context response carries impact-radius edges plus source snippets that exceed a tiny single-file diff. That is not a bug; the two benchmarks answer different questions. See docs/REPRODUCING.md for the full methodology.

Since v2.3.4, review and impact tools attach a compact context_savings estimate so MCP clients can see the approximate context saved per call. In v2.3.5 the CLI surfaces this as the boxed Token Savings panel shown above (see "Token Savings panel" in the Usage section) and adds --verify to cross-check against OpenAI's cl100k_base tokenizer. Calibration data in docs/REPRODUCING.md shows the estimate is within ~1% of real GPT-4 tokens in aggregate across 222 sample files.

Impact accuracy: 0.69 average F1 against graph-derived ground truth (recall 1.0 is a circular upper bound, not "100% recall")

Blast-radius analysis recovers every file in the ground truth on all 13 evaluation commits — but read that as an upper bound, not as "100% recall": in this mode the ground truth (changed files + files with call/import edges into them) is derived from the same graph the predictor traverses, so it is circular by construction. The over-prediction visible in the precision column is a deliberate trade-off: better to flag too many files than miss a broken dependency.

RepoCommitsAvg F1Avg PrecisionRecall (graph-derived upper bound)
httpx20.8630.7851.0
code-review-graph20.7340.5841.0
fastapi20.6970.5391.0
express20.6670.5001.0
flask20.6330.4851.0
gin30.6090.4391.0
Average130.6930.5461.000

The benchmark also runs an honest co-change mode: the predictor is seeded with a single changed file and graded against the other files the author actually touched in the same commit — independent-ish evidence from git history, not from the graph. Both modes appear side by side in the result CSVs (ground_truth_mode column). As of the 2026-08-02 capture that mode returns predicted_files = 0 on every graded commit, so it is not yet a usable measurement and no co-change number is quoted here — the harness needs fixing before the mode says anything about accuracy.

Build performance
RepoFilesNodesEdgesFlow DetectionSearch Latency
express1411,91017,553106ms0.7ms
fastapi1,1226,28527,117128ms1.5ms
flask831,4467,97495ms0.7ms
gin991,28616,762111ms0.5ms
httpx601,2537,89696ms0.4ms

Limitations and known weaknesses

  • Impact "recall 1.0" is graph-derived and circular: the historical ground truth comes from the same graph edges the predictor walks, so it is an upper bound by construction. The honest co-change mode (grade against files actually co-changed in the same commit) is measured alongside it; expect those numbers to be substantially lower.
  • Small single-file changes: Graph context can exceed naive file reads for trivial edits (see express results above). The overhead is the structural metadata that enables multi-file analysis.
  • Search quality (MRR 0.35): Keyword search finds the right result in the top-4 for most queries, but ranking needs improvement. Express queries return 0 hits due to module-pattern naming.
  • Flow detection (33% recall): Framework and conventional entry patterns are strongest for Python and PHP/Laravel. JavaScript and Go flow detection needs work.
  • Precision vs recall trade-off: Impact analysis is deliberately conservative. It flags files that might be affected, which means some false positives in large dependency graphs.

Features

FeatureDetails
Incremental updatesRe-parses only the files whose hash changed. On a ~3,000-file repo a two-file edit takes ~2.5s on the hook path (measured).
Broad language + notebook supportPython, JavaScript/TypeScript/TSX, Go, Rust, Java, C/C++, C#, VB.NET, Ruby, Kotlin, Swift, PHP, Scala, Solidity, Dart, R, Perl, Lua/Luau, Objective-C, shell scripts, Elixir, Zig, PowerShell, Julia, ReScript, GDScript, Nix, Verilog/SystemVerilog, SQL, Terraform/OpenTofu structure (.tf; generic .hcl files are file-only), Ansible playbooks/roles/tasks, Vue/Svelte SFCs, Astro files parsed through the TypeScript parser, Jupyter/Databricks (.ipynb), and Perl XS (.xs)
Framework-aware PHP parsingRepository-bounded Composer PSR-4 imports, Blade template references, and evidence-gated Laravel Route-to-controller and Eloquent relationship edges
Blast-radius analysisShows which functions, classes, and files are likely affected by a change
Auto-update hooksHooks and watch mode can update the graph on file saves and supported commit hooks
Semantic searchOptional vector embeddings via sentence-transformers, Google Gemini, MiniMax, Voyage AI, or any OpenAI-compatible endpoint (real OpenAI, Azure, new-api, LiteLLM, vLLM, LocalAI)
Interactive visualisationD3.js force-directed graph with search, community legend toggles, and degree-scaled nodes
Hub & bridge detectionFind most-connected nodes and architectural chokepoints via betweenness centrality
Surprise scoringDetect unexpected coupling: cross-community, cross-language, peripheral-to-hub edges
Knowledge gap analysisIdentify isolated nodes, untested hotspots, thin communities, and structural weaknesses
Suggested questionsAuto-generated review questions from graph analysis (bridges, hubs, surprises)
Edge confidenceThree-tier confidence scoring (EXTRACTED/INFERRED/AMBIGUOUS) with float scores on edges
Graph traversalFree-form BFS/DFS exploration from any node with configurable depth and token budget
Export formatsGraphML (Gephi/yEd), Neo4j Cypher, Obsidian vault with wikilinks, SVG static graph
Graph diffCompare graph snapshots over time: new/removed nodes, edges, community changes
Token benchmarkingMeasure naive full-corpus tokens vs graph query tokens with per-question ratios
Estimated context savingsCompact context_savings metadata on relevant MCP/CLI review outputs, labelled as estimated and kept to three small fields
Memory loopPersist Q&A results as markdown for re-ingestion, so the graph grows from queries
Community auto-splitOversized communities (>25% of graph) are recursively split via Leiden
Execution flowsTrace call chains from entry points, sorted by weighted criticality
Community detectionCluster related code via Leiden algorithm with resolution scaling for large graphs
Architecture overviewAuto-generated architecture map with coupling warnings
Risk-scored reviewsdetect_changes maps diffs to affected functions, flows, and test gaps
Custom languagesAdd new languages via .code-review-graph/languages.toml — no fork or code changes needed
GitHub ActionSticky risk-scored PR review comments in CI, with an optional fail-on-risk merge gate
Refactoring toolsRename preview, framework-aware dead code detection, community-driven suggestions
Wiki generationAuto-generate markdown wiki from community structure
Multi-repo registryRegister multiple repos, search across all of them
Multi-repo daemoncrg-daemon watches multiple repos as child processes, with health checks and auto-restart
MCP prompts5 workflow templates: review, architecture, debug, onboard, pre-merge
Full-text searchFTS5-powered hybrid search combining keyword and vector similarity
Local storageSQLite file in .code-review-graph/. Core graph storage needs no external database or cloud service.
Watch modeContinuous graph updates as you work

Usage

Slash commands

Files in the repo

Repository payload30 top-level entries
  • .beads
  • .github
  • .serena
  • code_review_graph
  • code-review-graph-vscode
  • diagrams
  • docs
  • evaluate
  • hooks
  • scripts
  • skills
  • tests
  • .gitignore
  • .mcp.json
  • action.yml
  • AGENTS.md
  • CHANGELOG.md
  • CLAUDE.md
  • CODE_OF_CONDUCT.md
  • CONTRIBUTING.md
  • GEMINI.md
  • LICENSE
  • pyproject.toml
  • README.hi-IN.md
  • README.ja-JP.md
  • README.ko-KR.md
  • README.md
  • README.zh-CN.md
  • SECURITY.md
  • uv.lock

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More connectors

High-performance code intelligence MCP server. Indexes codebases into a persistent knowledge graph — average repo in milliseconds. 158 languages, sub-ms queries, 99% fewer tokens. Single static binary, zero dependencies.

43k

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM (Claude, Gemini, Grok, DeepSeek, Ollama…) with Codex CLI, App, SDK, and Claude Code

14k
okf-memory/
okf-agent-memory

Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.

547
2akouwu/
reverify

Stop your AI from making things up — it proposes, deterministic tools decide, every claim checked against ground truth with evidence. Grounded facts and context survive resets. Reverse engineering is the proving ground. MCP server + CLI.

1.1k
t8y2/dbxConnectors

20 MB lightweight cross-platform database client for 90+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 90+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP Server。

19k

x64dbg-MCP Server is a native MCP (Model Context Protocol) plugin for x64dbg that exposes the debugger's full functionality over HTTP. Connect any MCP-compatible AI assistant and control x64dbg programmatically: set breakpoints, step through code, read memory, dump registers, and more. Built with Zig — zero dependencies, single-binary output, cros

1.9k