Skip to main content
Glama

grok-diff-guard

Local git diff review, powered by xAI Grok — as a CLI, and as a stdio MCP server for Grok Build.

grok-diff-guard reads the diff you already have (staged, working tree, or against a base branch), asks Grok for a small set of high-signal findings, and turns them into something a human or a CI job can act on: colour-coded terminal output, machine-readable JSON, Markdown for PR comments, or structured tool results over MCP.

It is deliberately small: one Python package, one git call, one API call, no server, no database, no configuration files. Run it with --mock and it works offline with zero credentials.

python 3.11+ · MIT · Pydantic v2 · Typer · rich · official MCP SDK

Why this exists

Most "AI code review" tools are dashboards that want your repository. grok-diff-guard is a quick local check that fits where you already work:

  • Local-first. Nothing is uploaded except the diff, and only in live mode. Mock mode is fully offline and makes no network calls at all.

  • Diff-shaped, not file-shaped. Grok only sees what changed, with lockfiles and binaries filtered out and a hard character budget so a huge refactor cannot blow up the prompt.

  • Structured, not chatty. Every finding has a severity, a category, a file, a best-effort line and a concrete suggestion. No "consider reviewing this".

  • CI-ready. --fail-on plus documented exit codes turn a review into a gate.

  • Agent-ready. The same pipeline is exposed as two MCP tools, so Grok Build can review its own edits before handing them back to you.

Related MCP server: diff-explainer

Features

Capability

Detail

Diff sources

--staged (default), --working, --base REF (git diff REF...HEAD)

Noise control

Binary files, 18+ known lockfiles, *.lock/*.lockb skipped automatically

Prompt budget

--max-chars (default 24 000) shared across files, truncated at line boundaries

Structured output

summary, overall_risk, findings with severity/category/line_hint/suggestion

Renderers

terminal (rich), json (pure stdout), markdown (PR comments)

CI gate

--fail-on critical | high | medium | none, exit 0/1/2 contract

Benchmark

bench: p50/p95 latency, JSON schema validity rate, token usage

Offline mode

--mock: deterministic heuristic rules, no API key, no tokens

MCP

stdio server with review_git_diff and list_changed_files

Architecture

flowchart LR
    subgraph Entry
        CLI["grok-diff-guard<br/>review · bench · mcp-config"]
        MCP["grok-diff-guard-mcp<br/>stdio MCP server"]
    end

    P["git_parser<br/>git diff → FileDiff[]"]
    C["grok_client<br/>GrokReviewer"]
    M["models<br/>ReviewReport (Pydantic v2)"]
    R["reporter<br/>terminal / JSON / Markdown"]
    X["xAI API<br/>api.x.ai/v1"]
    H["mock heuristics<br/>offline rules"]

    CLI --> P
    MCP --> P
    P --> C
    C -->|live| X
    C -->|--mock| H
    C --> M
    M --> R
    M --> MCP
    ENV["XAI_API_KEY · XAI_BASE_URL · GROK_MODEL"] -.-> C

The diff parser and the reporter know nothing about the network; the client and its mock engine produce the same ReviewReport model, so every renderer and both MCP tools behave identically in offline and live mode.

Install

Requires Python 3.11+ and git on PATH.

# from source (this project is not on PyPI yet)
git clone https://github.com/lh17860272952-glitch/grok-diff-guard.git
cd grok-diff-guard
pip install -e ".[dev]"

This installs two console scripts:

Script

Purpose

grok-diff-guard

CLI: review, bench, mcp-config

grok-diff-guard-mcp

stdio MCP server

Quickstart

1. Offline smoke test (no API key)

git add -A
grok-diff-guard review --mock

You get a terminal report whose header says MOCK MODE (no API call). The findings come from deterministic local rules (hardcoded credentials, eval(, shell=True, bare except:, mutable defaults, TODO/FIXME, weak hashes, unsafe deserialisation, secret-looking files, very large deletions, and similar). A report produced this way is always labelled:

  • header/banner: MOCK MODE (no API call)

  • JSON and MCP: metrics.mock_mode: true

  • Markdown: a > MOCK MODE callout

  • summary text: prefixed with [MOCK]

Mock mode uses zero tokens (prompt_tokens/completion_tokens are 0) and does not touch the network.

2. Live review with xAI

export XAI_API_KEY="xai-..."          # required
export GROK_MODEL="grok-4.6"          # optional, this is the default
export XAI_BASE_URL="https://api.x.ai/v1"   # optional, this is the default

grok-diff-guard review --staged

Live mode sends the (filtered, truncated) diff to the xAI OpenAI-compatible endpoint with response_format={"type": "json_object"} and validates the answer against the ReviewReport schema. Transient 429/5xx responses are retried with exponential backoff (1 s, then 2 s, honouring Retry-After when present); malformed or partially invalid JSON is salvaged before giving up.

The diff leaves your machine in live mode. Use --mock for anything you cannot share.

3. Output formats

grok-diff-guard review --mock --format markdown > review.md
grok-diff-guard review --mock --format json | jq '.findings | length'

4. Gate CI

grok-diff-guard review --base origin/main --fail-on high

Exit code

Meaning

0

Clean, or every finding is below --fail-on

1

At least one finding is at or above --fail-on

2

Configuration error, git error, or the xAI API could not produce a usable review

--fail-on accepts critical, high, medium, or none (never fail).

Grok Build / MCP integration

Print a ready-to-paste registration snippet:

grok-diff-guard mcp-config
{
  "mcpServers": {
    "grok-diff-guard": {
      "command": "grok-diff-guard-mcp",
      "args": [],
      "env": {
        "XAI_API_KEY": "${XAI_API_KEY}",
        "XAI_BASE_URL": "https://api.x.ai/v1",
        "GROK_MODEL": "grok-4.6"
      }
    }
  }
}

Paste it into your MCP client configuration (for Grok Build, the MCP servers section of its settings). Environment-variable expansion in env is client-dependent: if your client does not expand ${XAI_API_KEY}, paste the literal key there, or omit the env block entirely to inherit the parent process environment. Use --mock-equivalent behaviour from MCP by passing mock: true to the tool, which needs no key.

Tools

Tool

Arguments

Returns

review_git_diff

repo_path, mode="staged"|"working"|"base", base_ref, mock

Report object: summary, overall_risk, findings, metrics, plus diff_stats (files/additions/deletions/skipped/truncated)

list_changed_files

repo_path, mode="staged"|"working"

[{path, status, additions, deletions}], heaviest first

Example agent loop: after editing files, call list_changed_files to see the shape of the change, then review_git_diff with mock: false for a model review or mock: true for an instant offline pass. Errors (not a repo, unknown ref, missing key) are returned as tool errors with actionable messages.

Benchmarking

grok-diff-guard bench --runs 5               # live: real latency and token usage
grok-diff-guard bench --mock --runs 5        # offline: local heuristic timing

bench reviews the current staged diff when there is one, otherwise a built-in sample diff, and reports per-run latency, findings, tokens, schema validity, plus p50/p95 latency and the JSON schema validity rate.

Honesty note: numbers produced in --mock mode measure the local heuristic engine and are always displayed under a MOCK MODE banner — they are not API benchmarks and consume no tokens. Live numbers include network round-trips and retries. No benchmark figures are hardcoded in this README because they depend on your machine, model, and diff.

Project layout

src/grok_diff_guard/
├── cli.py          # Typer app: review / bench / mcp-config, exit-code policy
├── bench.py        # benchmark harness, nearest-rank percentiles
├── git_parser.py   # subprocess git, unified diff parsing, filtering, truncation
├── grok_client.py  # xAI client (live) + deterministic mock engine
├── mcp_server.py   # FastMCP stdio server and config snippet
├── models.py       # Pydantic v2 contracts
├── reporter.py     # terminal / JSON / Markdown renderers
└── samples.py      # sample diff used by bench and docs
tests/              # pytest suite (no network access)

Development

pip install -e ".[dev]"
ruff check .
pytest -v

See AGENTS.md for architecture notes, conventions, and how to add a heuristic rule or CLI option. CI runs ruff check . and pytest on Python 3.11, 3.12, and 3.13.

Roadmap

  • GitHub PR comment bot — post the Markdown renderer's output as a sticky PR review comment, with deduplication across pushes.

  • Custom rule packs — load team-specific heuristic rules (TOML/YAML) for --mock, so offline mode can enforce internal conventions.

  • Multi-model evals — compare grok-4.6 vs grok-4.7 on a fixed diff corpus: agreement rate, severity calibration, cost per review, and p95 latency.

  • Incremental review — review only hunks changed since the last review, for long-running PRs.

  • Inline suggestions — emit GitHub-style fenced suggestion blocks from ReviewFinding.suggestion.

  • Prompt caching / token budgeting — per-file budgets and cached repository context for very large diffs.

License

MIT — see LICENSE.

Available Tools

2 tools
list_changed_filesA

List reviewable files in the repository's current git diff.

Args: repo_path: Path to the repository (any directory inside the work tree). mode: Diff source: "staged" (default), "working", or "base". "base" is not supported here; use review_git_diff for branch comparisons.

Returns: One entry per changed file with path, status, additions, deletions.

Inputs: repo_path (required), mode. Returns: result

review_git_diffA

Review a repository's git diff and return structured findings.

Args: repo_path: Path to the repository (any directory inside the work tree). mode: Diff source: "staged" (default), "working", or "base". base_ref: Branch or commit to diff against; required when mode="base". mock: Use the offline heuristic analyzer instead of calling the xAI API.

Returns: A JSON-serialisable report with summary, overall_risk, findings and metrics. Findings flagged in mock mode never came from the xAI API.

Inputs: repo_path (required), mock, mode, base_ref. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 2 tools

    Disambiguation4/5

    list_changed_files enumerates changed files while review_git_diff performs analysis, so their purposes are distinct. However, both operate on the same git diff and share arguments, which could cause minor hesitation about when to use which.

    Naming Consistency5/5

    Both tool names follow a clear verb_noun pattern in snake_case (list_changed_files, review_git_diff), making the naming fully predictable.

    Tool Count4/5

    Two tools is slightly under the typical 3–15 range but appropriate for this narrow diff-review purpose: one to preview changed files and one to produce findings.

    Completeness4/5

    The core workflow (list changed files, then review the diff) is fully covered, including staged/working/base modes and mock fallback. Minor gaps exist, such as no way to filter review to a specific file or manage rule configuration.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers