grok-diff-guard-mcp
Provides tools for reading a local Git repository's staged, working-tree, or base-branch diff and listing changed files with status and line-change counts.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@grok-diff-guard-mcp review my staged changes for security risks"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 SDKWhy 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-onplus 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 |
|
Noise control | Binary files, 18+ known lockfiles, |
Prompt budget |
|
Structured output |
|
Renderers |
|
CI gate |
|
Benchmark |
|
Offline mode |
|
MCP | stdio server with |
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"] -.-> CThe 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 |
| CLI: |
| stdio MCP server |
Quickstart
1. Offline smoke test (no API key)
git add -A
grok-diff-guard review --mockYou 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: trueMarkdown: a
> MOCK MODEcalloutsummary 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 --stagedLive 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
--mockfor 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 highExit code | Meaning |
| Clean, or every finding is below |
| At least one finding is at or above |
| 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 |
|
| Report object: |
|
|
|
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 timingbench 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 -vSee 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.6vsgrok-4.7on 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
suggestionblocks fromReviewFinding.suggestion.Prompt caching / token budgeting — per-file budgets and cached repository context for very large diffs.
License
MIT — see LICENSE.
Available Tools
2 toolslist_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
Scored across 2 tools
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.
Both tool names follow a clear verb_noun pattern in snake_case (list_changed_files, review_git_diff), making the naming fully predictable.
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.
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
Related MCP Connectors
Risk-scan a diff, flag AI-generated-code tells, find secrets. 5 of 7 tools need no account.
AI-native git hosting — repos, PRs, issues, CI gates, and AI code review over MCP (60 tools).
IaC, CI and dependency security review for coding agents: local scan CLI plus hosted OAuth MCP.
Screens public GitHub repos and PRs to generate risk maps, findings, and merge-readiness signals.
Related MCP Servers
- AlicenseAqualityDmaintenanceProvides MCP tools to review git changes using OpenAI Codex CLI, enabling code review of unstaged, staged, or last-commit changes.36 npmMIT
- AlicenseNot gradedqualityDmaintenanceAI-powered git diff analysis with human-readable explanations, risk flags, and review checklists. Enables to explain any diff text or currently staged git changes through an MCP server.MIT
- FlicenseNot gradedqualityDmaintenanceRuns a multi-agent code review pipeline via MCP, analyzing git diffs for security, quality, and logic issues and returning a pass/fail verdict.-
- FlicenseNot gradedqualityCmaintenanceEnables AI clients to inspect Git repository changes, run allowlisted validation commands, and generate Markdown review reports via MCP, with validation disabled by default for security.-