Metadata-Version: 2.4
Name: better-code-review-graph
Version: 3.18.0
Summary: Knowledge graph for token-efficient code reviews -- semantic search and call-graph resolution across your codebase.
Author: n24q02m
License-Expression: MIT
License-File: LICENSE
Keywords: claude-code,code-review,knowledge-graph,mcp,tree-sitter
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: ==3.13.*
Requires-Dist: alembic<2,>=1.18.5
Requires-Dist: defusedxml>=0.7.1
Requires-Dist: fastmcp<4,>=3.4.2
Requires-Dist: httpx
Requires-Dist: litellm>=1.90.2
Requires-Dist: mcp<2,>=1.28.1
Requires-Dist: n24q02m-mcp-core[llm]<2,>=1.18.0b14
Requires-Dist: networkx<4,>=3.6.1
Requires-Dist: pydantic-settings
Requires-Dist: pygments>=2.20.0
Requires-Dist: qwen3-embed>=1.12.0b3
Requires-Dist: tree-sitter-language-pack<1,>=0.13.0
Requires-Dist: tree-sitter<1,>=0.26.0
Requires-Dist: watchdog<6,>=4.0.2
Provides-Extra: security
Requires-Dist: semgrep<1.162,>=1.0; extra == 'security'
Description-Content-Type: text/markdown

# Better Code Review Graph

mcp-name: io.github.n24q02m/better-code-review-graph

**Knowledge graph for token-efficient code reviews -- semantic search and call-graph resolution across your codebase.**

<!-- Badge Row 1: Status -->
[![CI](https://github.com/n24q02m/better-code-review-graph/actions/workflows/ci.yml/badge.svg)](https://github.com/n24q02m/better-code-review-graph/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/n24q02m/better-code-review-graph/graph/badge.svg)](https://codecov.io/gh/n24q02m/better-code-review-graph)
[![PyPI](https://img.shields.io/pypi/v/better-code-review-graph?logo=pypi&logoColor=white)](https://pypi.org/project/better-code-review-graph/)
[![Docker](https://img.shields.io/docker/v/n24q02m/better-code-review-graph?label=docker&logo=docker&logoColor=white&sort=semver)](https://hub.docker.com/r/n24q02m/better-code-review-graph)
[![License: MIT](https://img.shields.io/github/license/n24q02m/better-code-review-graph)](LICENSE)

<!-- Badge Row 2: Tech -->
[![Python](https://img.shields.io/badge/Python_3.13-3776AB?logo=python&logoColor=white)](#)
[![MCP](https://img.shields.io/badge/MCP-000000?logo=anthropic&logoColor=white)](#)
[![semantic-release](https://img.shields.io/badge/semantic--release-e10079?logo=semantic-release&logoColor=white)](https://github.com/python-semantic-release/python-semantic-release)
[![Renovate](https://img.shields.io/badge/renovate-enabled-1A1F6C?logo=renovatebot&logoColor=white)](https://developer.mend.io/)

<!-- BEGIN: AUTO-GENERATED-CROSS-PROMO -->
<details>
  <summary><strong>Sister projects from n24q02m</strong> (click to expand)</summary>

| Project | Tagline | Tag |
|---|---|---|
| [better-code-review-graph](https://github.com/n24q02m/better-code-review-graph) | Knowledge graph for token-efficient code reviews -- semantic search and call-... | MCP |
| [better-email-mcp](https://github.com/n24q02m/better-email-mcp) | IMAP/SMTP email for AI agents -- read, send, organize folders, and manage att... | MCP |
| [better-godot-mcp](https://github.com/n24q02m/better-godot-mcp) | Composite MCP server for Godot Engine -- 17 composite tools for AI-assisted g... | MCP |
| [better-notion-mcp](https://github.com/n24q02m/better-notion-mcp) | Markdown-first Notion for AI agents -- pages, databases, blocks, and comments... | MCP |
| [better-telegram-mcp](https://github.com/n24q02m/better-telegram-mcp) | Telegram for AI agents -- messages, chats, media, and contacts across both bo... | MCP |
| [claude-plugins](https://github.com/n24q02m/claude-plugins) | Claude Code plugin marketplace for the n24q02m MCP servers -- install web sea... | Marketplace |
| [imagine-mcp](https://github.com/n24q02m/imagine-mcp) | Image and video understanding + generation for AI agents -- across Gemini, Op... | MCP |
| [jules-task-archiver](https://github.com/n24q02m/jules-task-archiver) | Chrome Extension for bulk operations on Jules tasks via batchexecute API -- a... | Tooling |
| [mcp-core](https://github.com/n24q02m/mcp-core) | Shared foundation for building MCP servers -- Streamable HTTP transport, OAut... | MCP |
| [mnemo-mcp](https://github.com/n24q02m/mnemo-mcp) | Persistent AI memory with hybrid search and embedded sync. Open, free, unlimi... | MCP |
| [qwen3-embed](https://github.com/n24q02m/qwen3-embed) | Lightweight Qwen3 text embedding and reranking via ONNX Runtime and GGUF | Library |
| [skret](https://github.com/n24q02m/skret) | Secrets without the server. | CLI |
| [tacet](https://github.com/n24q02m/tacet) | TACET: a self-distilling neuro-symbolic cascade that amortises LLM cost in kn... | Tooling |
| [web-core](https://github.com/n24q02m/web-core) | Shared web infrastructure package for search, scraping, HTTP security, and st... | Library |
| [wet-mcp](https://github.com/n24q02m/wet-mcp) | Open-source MCP server for AI agents: web search, content extraction, and lib... | MCP |

</details>
<!-- END: AUTO-GENERATED-CROSS-PROMO -->

<!-- Glama badge -->
<a href="https://glama.ai/mcp/servers/n24q02m/better-code-review-graph">
  <img width="380" height="200" src="https://glama.ai/mcp/servers/n24q02m/better-code-review-graph/badge" alt="better-code-review-graph MCP server" />
</a>

An MCP server that parses your codebase with [Tree-sitter](https://tree-sitter.github.io/tree-sitter/), builds a structural graph of functions/classes/imports, and gives Claude (or any MCP client) precise context so it reads only what matters instead of the whole tree. Semantic search runs on a local ONNX embedding model by default (zero config, no API key), with an optional cloud embedding chain. Fork of [code-review-graph](https://github.com/tirth8205/code-review-graph) with fixed multi-word search, qualified call resolution, dual-mode embeddings, output pagination, and production CI/CD.

## v2.0 migration (BREAKING)

v2.0 adds temporal columns (`valid_from_sha` / `valid_to_sha` on every node + edge) and an opt-in security scanner. The schema migration is auto-applied on first `GraphStore` open, and a backup of the pre-2.0 DB is saved to `<graph_db>.pre-2.0.bak` so you can roll back. See [BREAKING_CHANGES.md](BREAKING_CHANGES.md) for the full schema-change list, behavior changes, environment requirements, and the downgrade procedure (`CRG_DOWNGRADE_TO_1_X=1 uv run better-code-review-graph`).

## Table of contents

- [v2.0 migration (BREAKING)](#v20-migration-breaking)
- [Install](#install)
- [Configuration](#configuration)
- [Tools](#tools)
- [Features](#features)
- [Comparison](#comparison)
- [Security](#security)
- [Build from source](#build-from-source)
- [Trust model](#trust-model)
- [Migration & changelog](#migration--changelog)
- [Documentation](#documentation)
- [License](#license)

## Install

The server runs over **stdio** by default and works with any MCP client. The
recommended launcher is [`uvx`](https://docs.astral.sh/uv/) (no install step --
it fetches and runs the published package in an isolated environment):

```json
{
  "mcpServers": {
    "better-code-review-graph": {
      "command": "uvx",
      "args": ["--python", "3.13", "better-code-review-graph"],
      "env": { "MCP_TRANSPORT": "stdio" }
    }
  }
}
```

Or install it as a Python package:

```bash
uvx better-code-review-graph        # run without installing
pip install better-code-review-graph
```

The optional Semgrep engine for deeper security scans is a separate extra:

```bash
pip install 'better-code-review-graph[security]'
```

**Install with an AI agent** -- paste this to your AI coding agent:

> Install MCP server `better-code-review-graph` following the steps at
> https://raw.githubusercontent.com/n24q02m/claude-plugins/main/plugins/better-code-review-graph/setup-with-agent.md

Full per-client setup (Claude Code, Codex, Gemini CLI, Cursor, Windsurf, raw
`mcp.json`) is at
**[mcp.n24q02m.com/servers/better-code-review-graph/setup/](https://mcp.n24q02m.com/servers/better-code-review-graph/setup/)**.

## Configuration

Everything works **out of the box with zero configuration** -- semantic search
uses a local [qwen3-embed](https://github.com/n24q02m/qwen3-embed) ONNX model
(`Qwen3-Embedding-0.6B`, ~570 MB downloaded on first `graph embed`). All
environment variables below are optional and only needed for cloud embeddings
or LLM summaries.

### Model chains

Embeddings and summaries are each driven by an **ordered model chain** -- a
CSV of `provider/model` entries where the order is the litellm fallback order
(first entry is the active model). The provider is inferred from the model
prefix, so the matching `<PROVIDER>_API_KEY` is all you need to add.

| Variable | Purpose | Empty (default) |
|---|---|---|
| `EMBEDDING_MODELS` | Cloud embedding chain, e.g. `jina_ai/jina-embeddings-v5-text-small,gemini/gemini-embedding-001` | Local ONNX (qwen3-embed) |
| `SUMMARY_MODELS` | Summarizer chain for `graph(action="summarize")`, e.g. `gemini/gemini-2.5-flash,openai/gpt-4o-mini` | Summaries disabled |

All vectors are stored at a fixed 768 dimensions (MRL truncation), so the
embeddings table schema stays valid across providers. Switching embedding
*model* changes the vector space; embeddings are tracked per provider and a
provider switch triggers re-embedding rather than mixing incomparable vectors.

### Provider API keys

Cloud models need the provider key for whatever prefixes appear in your chains.
Without any cloud key the server stays on local ONNX. Summarizers must expose a
chat-completion API (so Jina and Cohere are embedding-only).

| Model prefix | API key env var | Get a key |
|---|---|---|
| `jina_ai/` | `JINA_AI_API_KEY` | <https://jina.ai/api-key> |
| `gemini/` | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) | <https://aistudio.google.com/apikey> |
| `openai/` (or bare `text-embedding-*`) | `OPENAI_API_KEY` | <https://platform.openai.com/api-keys> |
| `cohere/` | `COHERE_API_KEY` | <https://dashboard.cohere.com/api-keys> |

Any other [litellm provider](https://docs.litellm.ai/docs/providers) works via
its standard `<PROVIDER>_API_KEY`.

### Advanced

| Variable | Purpose |
|---|---|
| `EMBEDDING_API_BASE` | Custom OpenAI-compatible base URL for cloud embedding (SSRF-guarded) |
| `LLM_API_BASE` | Custom OpenAI-compatible base URL for the summarizer (SSRF-guarded) |
| `DISABLE_LOCAL_EMBED` | Skip the local ONNX download; embedding is unavailable unless a cloud chain is configured |
| `CRG_DATA_DIR` | Override the per-user data directory (default `~/.crg`) used for per-user graphs and credentials in HTTP multi-user mode |
| `EMBEDDING_BACKEND` / `EMBEDDING_MODEL` / `SUMMARY_MODEL` | **Deprecated** singular vars, honored one release with a warning -- migrate to the `*_MODELS` chains |

### Example -- cloud embeddings + summaries

```json
{
  "mcpServers": {
    "better-code-review-graph": {
      "command": "uvx",
      "args": ["--python", "3.13", "better-code-review-graph"],
      "env": {
        "MCP_TRANSPORT": "stdio",
        "EMBEDDING_MODELS": "jina_ai/jina-embeddings-v5-text-small,gemini/gemini-embedding-001",
        "SUMMARY_MODELS": "gemini/gemini-2.5-flash",
        "JINA_AI_API_KEY": "jina_...",
        "GEMINI_API_KEY": "AIza..."
      }
    }
  }
}
```

You can also configure cloud keys interactively in HTTP mode via the relay
setup form (`config(action="setup_start")` returns the browser URL). See the
[modes overview](https://mcp.n24q02m.com/get-started/modes-overview/) and
[multi-user setup](https://mcp.n24q02m.com/get-started/multi-user/).

## Tools

Seven tools, each grouping related actions to keep the tool surface small.

### `graph` -- Graph lifecycle

Actions: `build` | `update` | `stats` | `embed` | `export` | `summarize`

| Action | Description |
|:-------|:------------|
| `build` | Full or incremental graph build. Set `full_rebuild=true` to re-parse all files; pass `roots` to federate extra repo directories into one graph. |
| `update` | Alias for `build` with `full_rebuild=false` (incremental). |
| `stats` | Graph size, languages, node/edge breakdown, embedding count. |
| `embed` | Compute vector embeddings for semantic search. Dual-mode: local ONNX or cloud chain. |
| `export` | Export the graph as `graphml` / `json-ld` / `dot` / `cypher`. Inline or to `output_path`. |
| `summarize` | LLM-generated one-paragraph docstrings for `Function` nodes (via the `SUMMARY_MODELS` chain; no-op when no provider key is set). Cost-capped via `max_nodes`. |

### `query` -- Graph queries

Actions: `query` | `search` | `impact` | `large_functions` | `spot_check` | `renamed_in_diff` | `diff`

| Action | Description |
|:-------|:------------|
| `query` | Predefined patterns: `callers_of`, `callees_of`, `imports_of`, `importers_of`, `children_of`, `tests_for`, `inheritors_of`, `file_summary`. |
| `search` | Search code entities by name/keyword or semantic similarity. |
| `impact` | Blast radius of changed files. Auto-detects from git diff. Paginated with `max_results`. |
| `large_functions` | Find functions/classes exceeding a line-count threshold. |
| `spot_check` | Random callsite snippets from the last `callers_of`/`callees_of`/`inheritors_of`/`importers_of` result. |
| `renamed_in_diff` | Symbols whose callsite line shifted versus a base ref. |
| `diff` | Nodes added/removed/modified between two commit SHAs (`from_sha`, `to_sha`). |

Most read actions accept `as_of=<sha>` for temporal (point-in-time) snapshots
and `repo=<repo_id>` to scope a federated multi-repo graph.

### `review` -- Code review context

Actions: `context` (default) | `delta`

Token-optimized review context with structural summary, impacted nodes, source
snippets, and review guidance. `context` auto-detects changed files from the
git diff; `delta` (with `from_sha`/`to_sha`, optional `show_line_shifts`)
surfaces refactor moves between two commits.

### `config` -- Server configuration and credential setup

Actions: `status` | `set` | `cache_clear` | `setup_status` | `setup_start` | `setup_skip` | `setup_reset` | `setup_complete`

| Action | Description |
|:-------|:------------|
| `status` | Server info: version, graph path, node/edge counts, embedding backend, embeddings count. |
| `set` | Update a runtime setting (`key=log_level`). |
| `cache_clear` | Remove all computed embeddings. |
| `setup_status` | Show current credential state, providers configured, and setup URL. |
| `setup_start` | Start relay setup to configure API keys via browser (HTTP mode). |
| `setup_skip` | Set local mode (skip relay permanently, use ONNX only). |
| `setup_reset` | Clear credentials and reset state. |
| `setup_complete` | Re-resolve credentials from environment variables. |

### `security` -- Security scanning

Actions: `scan` | `report` | `suppress` | `rule_list`

| Action | Description |
|:-------|:------------|
| `scan` | Run a security scan (`engine='heuristic'` default = 5 regex rules, or `'semgrep'`). Findings persist on `nodes.security_tags`. |
| `report` | Re-emit cached findings as JSON (`format='json'`) or SARIF v2.1.0 (`format='sarif'`). |
| `suppress` | Suppress a finding by `rule_id` (or `remove=true` to un-suppress). |
| `rule_list` | List available rules for an engine. |

The `semgrep` engine requires the `[security]` extra and runs Semgrep's
`p/auto` registry pack plus a 3-rule curated overlay.

### `help` -- Full documentation

Topics: `graph` | `query` | `review` | `config` | `security` | `recipes`

Returns complete documentation for each tool. Use when the compressed
descriptions above are insufficient.

### `config__open_relay` -- Re-trigger the relay setup form

Registered automatically from [mcp-core](https://github.com/n24q02m/mcp-core).
In HTTP mode it returns `<PUBLIC_URL>/authorize` so the agent can re-open the
browser setup form (e.g. after credential expiry); in stdio mode it returns
`status: 'stdio_unsupported'`.

## Features

What this fork fixes versus the upstream [code-review-graph](https://github.com/tirth8205/code-review-graph):

| Feature | code-review-graph | better-code-review-graph |
|:--------|:------------------|:-------------------------|
| Multi-word search | Broken (literal substring) | AND-logic word splitting |
| callers_of/callees_of | Empty results (bare name targets) | Qualified name resolution + bare fallback |
| Embedding | sentence-transformers + torch (1.1 GB) | qwen3-embed ONNX + cloud (200 MB), dual-mode |
| Output size | Unbounded (500K+ chars) | Paginated (max_results, truncated flag) |
| Tool design | 9 individual tools | 7 grouped tools: graph + query + review + config + security + help + config__open_relay |
| Plugin hooks | Invalid PostEdit/PostGit | Valid PostToolUse |

## Comparison

How better-code-review-graph stacks up against direct competitors in each pillar:

| Capability | better-code-review-graph | Greptile | Sourcegraph (Cody / MCP) | CodeGraph (colbymchenry) |
|---|---|---|---|---|
| Codebase knowledge graph | Yes (Tree-sitter, 14 langs, SQLite) | Yes (functions/classes/deps) | Yes (precise code indexing) | Yes (Tree-sitter, 20+ langs, SQLite) |
| Persistent incremental updates | Yes (git-diff + file-hash re-parse) | ? | Yes (continuous indexing) | Yes (OS file-watcher debounced) |
| Qualified call resolution (callers/callees) | Yes (same-file bare-call resolution + fallback) | ? | Yes (go-to-def / find-references) | Yes (callers / callees / impact) |
| Semantic search / embeddings | Yes (qwen3 ONNX local + cloud Jina/Gemini/OpenAI/Cohere) | ? | Yes (semantic + keyword + regex) | No (FTS5 full-text only) |
| Token-optimized review context | Yes (`review` tool, git-diff scoped) | Yes (PR review comments) | No (code-context assistant) | No (context layer, not review) |
| Security scanning | Yes (Semgrep `p/auto` + 3-rule overlay, SARIF) | ? | ? | No |
| Self-hostable | Yes (stdio default, machine-bound) | Yes (Docker / K8s / air-gapped) | Yes (self-hosted instance) | Yes (100% local, no API keys) |
| Free / open source | Yes (MIT) | No (proprietary SaaS; free OSS tier) | No (Enterprise license, source private) | Yes (MIT) |

Sources: [Greptile](https://www.greptile.com/docs/introduction) · [Greptile pricing](https://www.greptile.com/pricing) · [Sourcegraph MCP](https://sourcegraph.com/mcp) · [CodeGraph](https://github.com/colbymchenry/codegraph). Cells marked `?` are capabilities the competitor does not publicly document, not confirmed absences.

## Security

- **Graceful fallbacks** -- Cloud embedding failure falls back to local ONNX.
- **Error handling** -- Tools return error strings with fix suggestions, never crash.
- **Read-only mount** -- Docker mode mounts the repo as `:ro` (read-only).
- **SSRF-guarded endpoints** -- Custom `EMBEDDING_API_BASE` / `LLM_API_BASE` URLs are validated before any outbound call.

To report a vulnerability, see [SECURITY.md](SECURITY.md).

## Build from source

```bash
git clone https://github.com/n24q02m/better-code-review-graph
cd better-code-review-graph
uv sync --group dev
uv run pytest
uv run better-code-review-graph
```

**Requirements:** Python 3.13, [uv](https://docs.astral.sh/uv/).

## Trust model

This plugin implements **TC-Local** (machine-bound, single trust principal). See the [mcp-core trust model](https://mcp.n24q02m.com/servers/mcp-core/trust-model/) for full classification.

| Mode | Graph DB | Cloud credentials | Who can read your data? |
|---|---|---|---|
| stdio (default) | `<repo>/.code-review-graph/graph.db` (git-ignored) | `~/.better-code-review-graph-mcp/config.json` (AES-GCM, machine-bound key) | Only your OS user |
| HTTP self-host (multi-user) | Per-user `~/.crg/subs/<sub>/graph.db` | Per-user `~/.crg/subs/<sub>/config.json` | Only the authenticated user |

## Migration & changelog

The v2.0 release added **temporal columns** (`valid_from_sha` / `valid_to_sha`
on every node and edge) plus an opt-in security scanner. The schema migration
is auto-applied on first `GraphStore` open, and a backup of the pre-2.0 DB is
written to `<graph_db>.pre-2.0.bak`. To downgrade and restore it:

```sh
CRG_DOWNGRADE_TO_1_X=1 uvx better-code-review-graph
```

Full schema-change list, behavior changes, and rollback procedure:
[BREAKING_CHANGES.md](BREAKING_CHANGES.md). Release-by-release history:
[CHANGELOG.md](CHANGELOG.md).

## Documentation

Full docs at
**[mcp.n24q02m.com/servers/better-code-review-graph/setup/](https://mcp.n24q02m.com/servers/better-code-review-graph/setup/)**:

- [Setup](https://mcp.n24q02m.com/servers/better-code-review-graph/setup/) -- install methods for Claude Code, Codex, Gemini CLI, Cursor, Windsurf, mcp.json
- [Modes overview](https://mcp.n24q02m.com/get-started/modes-overview/) -- stdio / local-relay / remote-relay / remote-oauth
- [Multi-user setup](https://mcp.n24q02m.com/get-started/multi-user/) -- per-JWT-sub credential model

Use the `help` tool from any MCP client for inline per-tool reference.

## License

MIT -- See [LICENSE](LICENSE).
