TC

tirth8205/code-review-graph

Developer tools
32.5K stars 3K forks Quality 88 Trend 76MIT

Local-first code intelligence graph for MCP and CLI. Builds a persistent map of your codebase so AI coding tools read only what matters, with benchmarked context reductions on reviews and large-repo...

Overview

Stop burning tokens. Start reviewing smarter. 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. 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. 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).

README

code-review-graph

<a href=“https://trendshift.io/repositories/23329?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-23329” target=“_blank” rel=“noopener noreferrer”>

A local code knowledge graph that gives AI coding tools precise review context over MCP.

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

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

AI coding tools often re-read large parts of a codebase to review a change. code-review-graph builds a structural map of the code with Tree-sitter, keeps it updated incrementally, and serves compact context over MCP, so the assistant reads only the files a change touches.


Quick Start

pip install code-review-graph          # or: pipx install code-review-graph
code-review-graph install              # detect installed AI coding tools and configure each one
code-review-graph build                # parse the codebase

install detects which AI coding tools you have, writes an MCP server entry for each, installs hooks and skills where the platform supports them, and adds graph instructions to the platform’s rules file. The MCP entry uses poetry run or uv run inside a Poetry or uv project environment, uvx code-review-graph serve when uvx is on PATH, and otherwise the current Python interpreter. Restart the editor or tool afterwards.

To configure one platform, pass --platform with one of codex, claude-code, cursor, windsurf, zed, continue, opencode, antigravity, gemini-cli, qwen, kiro, qoder, copilot, copilot-cli, codebuddy, or hermes:

code-review-graph install --platform cursor
code-review-graph install --platform codebuddy

Config file locations are listed in docs/USAGE.md. Requires Python 3.10+.

uninstall removes CRG-owned files and entries from a Git or SVN working tree and leaves other MCP servers, hooks, skills and JSONC comments alone. Run it from anywhere inside the tree. Shared config files are replaced atomically, so a failed write leaves the original intact.

code-review-graph uninstall --dry-run    # preview only
code-review-graph uninstall              # preview, confirm, 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, keep graph databases
code-review-graph uninstall --keep-user-configs --repo .  # this project only

Then open the project and ask the assistant:

Build the code review graph for this project

Build time scales with repository size; a cold build of a ~3,000-file repository took about 40 seconds (measured). After that, hooks and watch mode keep the graph updated. If some files fail to parse, the result has status partial and names them in its summary; the CLI also prints a Warning: line on stderr, and those files keep their previous graph rows.

How It Works

The repository is parsed into ASTs with Tree-sitter and stored as a graph of nodes (functions, classes, imports) and edges (calls, inheritance, test coverage). At review time the graph is queried for the smallest set of files the assistant needs to read.

Blast-radius analysis

When a file changes, the graph traces every caller, dependent and test that could be affected. The assistant reads those files instead of scanning the whole project.

Incremental updates

Hooks, the pre-commit hook and watch mode trigger incremental updates. The update diffs changed files, finds their dependents through the graph’s import and call edges, and re-parses only the files whose SHA-256 hash 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.

Whole codebase or targeted answer?

Instead of feeding a whole corpus to the model, the graph returns a slice shaped to the question. In the 2026-08-02 capture of this repository at 84bde354, 208,821 source tokens became ~3,190 tokens per question. The repository has grown a lot since that snapshot, so both numbers are larger today.

Language coverage and notebooks

The parser extracts functions, classes, imports, call sites, inheritance and tests, using Tree-sitter where a grammar exists and targeted fallbacks elsewhere. Supported: 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 (.tf; other .hcl files become file nodes only), Ansible YAML (playbooks, roles, tasks), Spring Boot application config (application.properties, application.yml, application.yaml and their application- variants; key names and value types only, never values), Vue/Svelte SFCs, Astro files (parsed with the TypeScript grammar), Jupyter and Databricks notebooks (.ipynb), and Perl XS files (.xs). Other YAML and other .properties files are not treated as source code.

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

Java projects get Spring dependency-injection call resolution, request endpoints and WebFlux routes, scheduled triggers, application-event publisher-to-listener edges, and Temporal workflow and activity edges. Each resolver runs after the parse and needs the injected field, published event or workflow stub to be visible in the repository.

Add your own language

If your repository uses a language the parser does not cover, add a languages.toml to .code-review-graph/ that maps file extensions to any grammar bundled in tree_sitter_language_pack, plus the 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 does the extraction. Built-in languages cannot be overridden. See docs/CUSTOM_LANGUAGES.md for the schema, validation rules and a worked example.

Risk-scored PR reviews in CI (GitHub Action)

The same analysis runs as a composite GitHub Action. The graph is built and queried on your CI runner; no source code is sent to an external service. On each pull request the action posts one sticky comment with risk-scored functions, affected execution flows and test gaps, updated in place on every push. The optional fail-on-risk input turns it 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/[email protected]
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

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


Benchmarks

The median per-question token reduction across the 6 repositories is about 63x (whole-corpus baseline vs graph query). The 358x maximum is one repository (fastapi, the largest corpus), not the typical result.

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

Limitations

  • Impact “recall 1.0” is circular. The historical ground truth comes from the same graph edges the predictor walks, so it is an upper bound by construction. The co-change mode is not yet a usable measurement.
  • Small single-file changes. Graph context can exceed a plain file read for trivial edits. The overhead is the structural metadata that makes multi-file analysis possible.
  • Search ranking. Keyword search usually finds the right result near the top, but ranking needs work. Express queries can return no hits because of module-pattern naming.
  • Flow detection. Entry-point detection is strongest for Python and PHP/Laravel. JavaScript and Go flow detection needs work.
  • Precision vs recall. Impact analysis is conservative. It flags files that might be affected, which means false positives in large dependency graphs.

Features

Feature Details
Incremental updates Re-parses only files whose hash changed. On a ~3,000-file repo a two-file edit takes ~2.5 s on the hook path (measured).
Language and notebook support See Language coverage above.
Framework-aware PHP parsing Repository-bounded Composer PSR-4 imports, Blade template references, evidence-gated Laravel Route-to-controller and Eloquent relationship edges
Framework-aware Java parsing Spring dependency-injection call resolution, request endpoints and WebFlux routes, scheduled triggers, application-event publisher-to-listener edges, Temporal workflow and activity edges, and Spring Boot config keys indexed without their values
Blast-radius analysis Which functions, classes and files are likely affected by a change
Auto-update hooks Editor hooks, a git pre-commit hook and watch mode update the graph as you work
Semantic search Optional vector embeddings via sentence-transformers, Google Gemini, MiniMax, Voyage AI, or any OpenAI-compatible endpoint (OpenAI, Azure, new-api, LiteLLM, vLLM, LocalAI)
Interactive visualisation D3.js force-directed graph with search, community legend toggles and degree-scaled nodes
Hub and bridge detection Most-connected nodes and chokepoints (betweenness centrality)
Surprise scoring Unexpected coupling: cross-community, cross-language, peripheral-to-hub edges
Knowledge gap analysis Isolated nodes, untested hotspots, thin communities
Suggested questions Review questions generated from bridges, hubs and surprises
Edge confidence Two-tier confidence (EXTRACTED/INFERRED) with float scores on edges
Graph traversal BFS/DFS from any node with configurable depth and token budget
Export formats GraphML (Gephi/yEd), Neo4j Cypher, Obsidian vault, JSON, and SVG (SVG needs matplotlib from the eval extra)
Token benchmarking code_review_graph/token_benchmark.py measures whole-corpus tokens against graph query tokens per question
Estimated context savings context_savings metadata (estimated, saved_tokens, saved_percent) on review, impact, detect-changes and architecture responses
Community auto-split Communities above 25% of the graph are split recursively with Leiden
Execution flows Call chains from entry points, sorted by weighted criticality
Community detection Leiden clustering with resolution scaled to graph size
Architecture overview Community-based architecture map with coupling warnings
Risk-scored reviews detect_changes maps diffs to affected functions, flows and test gaps
Custom languages New languages via .code-review-graph/languages.toml, no fork needed
GitHub Action Sticky risk-scored PR review comments in CI, with an optional fail-on-risk merge gate
Refactoring tools Rename preview, framework-aware dead code detection, community-driven suggestions
Wiki generation Markdown wiki from community structure
Multi-repo registry Register several repos and search across them
Multi-repo daemon crg-daemon watches several repos as child processes, with health checks and restart
MCP prompts 5 workflow templates: review, architecture, debug, onboard, pre-merge
Full-text search FTS5 hybrid search combining keyword and vector similarity
Local storage One SQLite file in .code-review-graph/; no external database or cloud service

Usage


FAQ and comparisons

Answers in docs/FAQ.md:

Troubleshooting

More cases, including Windows/WSL, are in docs/TROUBLESHOOTING.md.

pip / pipx cannot download hatchling (or Errno 9 / Bad file descriptor to PyPI)

Installing from a source tree (for example pipx install .) needs build dependencies from PyPI. If you see Could not find a version that satisfies the requirement hatchling after connection warnings, the Python in that terminal may not be able to open an HTTPS connection to pypi.org. This is seen most often in an editor’s integrated terminal, and sometimes with a VPN, firewall or proxy.

  1. Run the same command from Terminal.app or iTerm instead of the editor’s terminal.

  2. Install from a checkout with uv, which uses different download machinery:

    cd /path/to/code-review-graph
    uv tool install . --force
    
  3. For development in a clone, use uv sync and uv run code-review-graph ....

To diagnose: python3 scripts/diagnose_pypi_connectivity.py. If it prints FAILED, the problem is the network environment, not the package name.

Windows: Invalid JSON: EOF while parsing or MCP error -32000: Connection closed

Do not use a cmd /c wrapper in the Claude Code config. Point ~/.claude.json at the .exe directly and set UTF-8 through the config:

"code-review-graph": {
  "command": "C:\\path\\to\\your\\venv\\Scripts\\code-review-graph.exe",
  "args": ["serve", "--repo", "C:\\path\\to\\your\\project"],
  "env": { "PYTHONUTF8": "1" }
}

Contributing

git clone https://github.com/tirth8205/code-review-graph.git
cd code-review-graph
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

Pull requests target staging (the default branch). Changes are promoted staging → testing → main, and releases are tagged from main. The first step runs once a day by itself when staging is green; promotion to main is never automatic. See CONTRIBUTING.md for the full flow.

To add a built-in language, edit code_review_graph/parser.py: add the extension to EXTENSION_TO_LANGUAGE and node type mappings to _CLASS_TYPES, _FUNCTION_TYPES, _IMPORT_TYPES and _CALL_TYPES. Include a test fixture and open a PR. For a language you only need in one repository, use languages.toml instead.

Licence

MIT. See LICENSE.

code-review-graph.com pip install code-review-graph && code-review-graph install

View the full README on GitHub

Install

This server does not publish a one-line install command.

Open the repository installation guide New to MCP? Start with the mcpskill.org guide →

Configuration

{ "mcpServers": { "code-review-graph": { "command": "code-review-graph", "args": ["serve", "--tools", "query_graph_tool,semantic_search_nodes_tool,detect_changes_tool,get_review_context_tool"] } } }