PromptHub
Back to Blog
Developer Tools AI Infrastructure

tirth8205/code-review-graph: Cut AI Review Tokens 82x with Local Code Graphs

B

Bright Coding

Author

9 min read 125 views
tirth8205/code-review-graph: Cut AI Review Tokens 82x with Local Code Graphs

AI coding assistants have a token problem. Every review request, every architecture question, every "how does this work" query risks pulling in thousands of lines of irrelevant source code. The result? Slower responses, higher API costs, and context windows clogged with noise. code-review-graph solves this by building a persistent, queryable map of your codebase that feeds AI tools only what matters—benchmarked at a median 82x token reduction across real repositories.

What is tirth8205/code-review-graph?

code-review-graph is a local-first code intelligence graph designed for MCP (Model Context Protocol) and CLI workflows. Maintained by tirth8205 with 19,499 GitHub stars and 2,083 forks, it parses your repository into a structural graph of functions, classes, imports, and call relationships using Tree-sitter, then stores everything in a local SQLite database. When your AI assistant needs context, it queries the graph—not the entire corpus.

The project is written in Python↗ Bright Coding Blog 3.10+, released under the MIT License, and actively maintained (last commit June 14, 2026). It sits at the intersection of developer tooling, AI infrastructure, and static analysis: think "source code intelligence" for the LLM era, but without the cloud dependency or per-request latency of hosted solutions.

What makes it timely is the MCP ecosystem explosion. As Cursor, Claude Code, Codex, Windsurf, Zed, Continue, and a dozen other AI coding tools standardize on MCP for tool calling, code-review-graph offers a drop-in server that turns any repository into a structured knowledge base. The graph persists between sessions, updates incrementally on file changes, and requires zero external services—not even for embeddings, which are entirely optional.

Key Features

Persistent structural graph via Tree-sitter. Every function, class, import statement, call site, and inheritance relationship becomes a node or edge. The graph captures cross-file dependencies that grep misses and does so across 30+ languages including Python, JavaScript↗ Bright Coding Blog/TypeScript, Go, Rust, Java, C/C++, C#, Ruby, Kotlin, Swift, PHP↗ Bright Coding Blog, Scala, Solidity, Dart, and Jupyter notebooks.

Blast-radius analysis for reviews. When a file changes, the graph traces every caller, dependent, and affected test. Your AI reads only the "blast radius"—not the whole project. In a 27,700-file monorepo, this means ~15 files actually read instead of the full corpus.

Incremental updates under 2 seconds. File saves and git hooks trigger differential re-indexing. A 2,900-file project re-parses in under 2 seconds by hashing files and skipping unchanged content.

30 MCP tools with optional filtering. The server exposes tools for graph queries, semantic search, impact analysis, architecture overview, risk-scored reviews, and more. In token-constrained environments, limit exposed tools via --tools or CRG_TOOLS.

Multi-repo daemon (crg-daemon). Watch multiple repositories as background processes with health checks and auto-restart—no editor integration required.

Semantic search (optional). Vector embeddings via sentence-transformers, Google Gemini, MiniMax, or any OpenAI-compatible endpoint. Embeddings are function-signature-only (~10 tokens per node), keeping overhead minimal.

GitHub Action for CI. Sticky, risk-scored PR review comments with optional fail-on-risk merge gate. Runs entirely on the CI runner—no source code leaves your infrastructure.

Custom languages without forking. Drop a languages.toml in .code-review-graph/ to add any grammar from tree_sitter_language_pack.

Use Cases

Large-scale code review with AI assistants. A developer modifies authentication logic in a 500-file service. Instead of pasting 50 files into Claude Code's context window, they run code-review-graph detect-changes --brief and receive a 762-token impact analysis covering affected callers, test gaps, and risk scores—versus 12,921 tokens for raw file contents.

Monorepo navigation. Teams working in 10,000+ file repositories use the graph to answer "where is this used" and "what breaks if I change this" without grep -r across irrelevant packages. The Leiden community detection auto-clusters related code, surfacing architectural boundaries.

Onboarding and architecture exploration. New engineers use get_architecture_overview_tool and list_flows_tool to trace execution paths from entry points, identify hub nodes (architectural hotspots), and spot surprising cross-community coupling that violates intended modularity.

Pre-merge risk assessment. The GitHub Action posts a sticky comment on every PR push, highlighting risk-scored functions, affected execution flows, and untested hotspots. Teams use fail-on-risk to block merges when blast radius exceeds configured thresholds.

Multi-project knowledge bases. Consultants and platform teams register dozens of repositories via crg-daemon, enabling cross-repo search and unified code intelligence across microservices or client engagements.

Installation & Setup

The project requires Python 3.10+. For optimal MCP configuration, install uv first—the installer auto-detects uvx and uses it when available.

# Install the CLI
pip install code-review-graph
# Or via pipx for isolation:
pipx install code-review-graph

After installation, run the auto-configuration command:

code-review-graph install

This single command detects installed AI coding tools, writes correct MCP configurations for each, installs platform-native hooks where supported, and injects graph-aware instructions into platform rules. It auto-detects uvx versus pip/pipx installation and generates the appropriate config path.

Restart your editor or AI tool after installation. Then build the graph:

code-review-graph build

Initial build takes approximately 10 seconds for a 500-file project. For platform-specific configuration:

code-review-graph install --platform codex       # OpenAI Codex
code-review-graph install --platform cursor      # Cursor
code-review-graph install --platform claude-code  # Claude Code
code-review-graph install --platform gemini-cli   # Gemini CLI
code-review-graph install --platform copilot      # GitHub Copilot (VS Code)

To keep the graph fresh automatically, enable watch mode or use the daemon:

code-review-graph watch              # foreground file watching
crg-daemon add ~/my-project          # register for background watching
crg-daemon start                     # start multi-repo daemon

Real Code Examples

Basic workflow: build, query, review

# Build graph for current directory
code-review-graph build

# Check status and statistics
code-review-graph status

# Review current changes with token savings panel
code-review-graph detect-changes --brief

The --brief flag produces a compact panel showing context reduction:

┌─────────────────────── 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   │
└──────────────────────────────────────────────────────────────┘

Add --verify to cross-check against OpenAI's cl100k_base tokenizer (requires pip install tiktoken). Calibration data shows estimates within ~1% of real GPT-4 tokens.

Custom language configuration

For repositories using unsupported languages, create .code-review-graph/languages.toml:

[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 automatically. Built-in languages cannot be overridden, ensuring stability.

GitHub Action integration

# .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@v4
      - uses: tirth8205/code-review-graph@v2.3.6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

This composite action builds and queries the graph entirely on the CI runner. No source code is transmitted to external services. The optional fail-on-risk: true input converts review comments into a merge gate.

Environment configuration for embeddings

# Local embeddings (no network)
pip install code-review-graph[embeddings]

# OpenAI-compatible endpoint (self-hosted or cloud)
export CRG_OPENAI_BASE_URL=http://127.0.0.1:3000/v1
export CRG_OPENAI_API_KEY=sk-...
export CRG_OPENAI_MODEL=text-embedding-3-small
export CRG_OPENAI_DIMENSION=1536  # optional dimension pinning

The cloud-egress warning auto-skips for localhost endpoints (127.0.0.1, localhost, 0.0.0.0, ::1).

Advanced Usage & Best Practices

Prefer detect-changes --brief over update --brief for speed. The former is read-only (~1 second) and assumes your hooks or daemon keep the graph current. Use update --brief only after rebases, large change sets, or when you suspect graph staleness.

Tool filtering for constrained clients. MCP clients with tight context limits should limit exposed tools. The four most essential: query_graph_tool, semantic_search_nodes_tool, detect_changes_tool, get_review_context_tool.

Model selection for embeddings. Avoid -preview / -beta / -exp model IDs for production graphs—weight changes can alter dimensions and force full re-embedding. Prefer stable releases: text-embedding-3-small / text-embedding-3-large (OpenAI), gemini-embedding-001 (Google native), or self-hosted Qwen/Qwen3-Embedding-8B.

Memory loop for evolving knowledge. Persist Q&A results as markdown↗ Smart Converter via generate_wiki_tool and re-ingest them. The graph grows from queries, improving suggestions over time.

Windows MCP users: Avoid cmd /c wrappers. Execute .exe directly with PYTHONUTF8=1 environment variable to prevent JSON parsing errors.

Comparison with Alternatives

Tool Approach Key Difference
code-review-graph Persistent structural graph (AST edges) Local-first, incremental updates, blast-radius analysis, 30+ languages
LSP / Language Servers Per-language daemon, precise symbol resolution More accurate per-symbol; no cross-language graph, no persistent storage between sessions
RAG / Embedding chunks Similarity search over code snippets No structural relationships; misses callers-of-callers, inheritance chains, test coverage
grep / agentic search Text pattern matching Faster for single-hop lookups; fails on multi-hop impact analysis and architectural queries
Serena / codegraph Comparable code intelligence tools See docs/FAQ.md for detailed factual comparison; trade-offs vary by language support and update latency

The honest assessment: code-review-graph wins when you need persistent, cross-language structural analysis with minimal per-request latency. LSP wins for IDE-grade symbol precision within a single language. RAG wins for semantic similarity when exact relationships don't matter. For trivial single-file changes or one-off questions, the graph's overhead may not justify its benefits.

FAQ

Is code-review-graph free? Yes, MIT licensed. No paid tiers, no feature gates.

Does it send my code to external services? No. Core functionality is entirely local. Cloud embeddings are opt-in and configurable to self-hosted endpoints.

Which AI tools are supported? Codex, Claude Code, Cursor, Windsurf, Zed, Continue, OpenCode, Antigravity, Gemini CLI, Qwen, Qoder, Kiro, GitHub Copilot, and GitHub Copilot CLI.

How accurate is the token reduction claim? The 82x median comes from automated evaluation against 6 real repositories (13 commits total). The frequently quoted 528x is the maximum (fastapi repo), not typical. Full reproduction methodology is in docs/REPRODUCING.md.

What about the "6.8x" in some mentions? That figure appears in social media↗ Bright Coding Blog context but does not match the README's benchmarked 82x median or 528x maximum. The README's evaluated numbers supersede informal claims.

Can I use it without MCP? Yes, the full CLI works standalone: build, update, detect-changes, visualize, wiki, and more.

How do I verify it's working? Run code-review-graph status, detect-changes --brief, or check /mcp in your AI tool for available tools.

Conclusion

code-review-graph is best suited for teams working in medium-to-large codebases where AI-assisted review, architecture exploration, and cross-file impact analysis are daily needs. The 19,499-star project delivers on a concrete promise: stop feeding entire repositories to language models, and start querying structured code intelligence instead.

The local-first design, incremental updates, and broad language support make it particularly compelling for privacy-conscious organizations and monorepo environments. It's not a magic bullet—trivial single-file changes see overhead, and flow detection remains weaker for JavaScript and Go than Python—but the benchmarked token reductions and active maintenance make it a credible addition to the modern AI coding stack.

Ready to cut your AI review context by an order of magnitude? Install from PyPI, run code-review-graph install, and point your MCP client at a smarter way to read code.

Get started: https://github.com/tirth8205/code-review-graph

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!

Recommended Prompts

View All
All tools