Smart git diff context for LLMs and AI agents: budgeted fragment selection, deterministic, MCP server included
- ✓Open-source license (Apache-2.0)
- ✓Actively maintained (<30d)
- ✓Clear description
- ✓Topics declared
- ✓Mature repo (>1y old)
- ✓Documented (README)
claude mcp add diffctx -- npx -y diffctx{
"mcpServers": {
"diffctx": {
"command": "npx",
"args": ["-y", "diffctx"]
}
}
}MCP Servers overview
# diffctx — smart diff context for LLM code review
[](https://github.com/nikolay-e/diffctx/actions/workflows/ci.yml)
[](https://pypi.org/project/diffctx/)
[](https://crates.io/crates/diffctx)
[](https://www.npmjs.com/package/diffctx)
[](https://pypi.org/project/diffctx/)
**diffctx selects the minimum code an LLM needs to review a git diff.**
Instead of pasting whole files, it walks the dependency graph outward from the
changed lines and stops once more context stops paying for itself.
> Formerly published as `treemapper` — every command, flag, and API call works unchanged.
## How it compares
Whole-repo packers (repomix and friends) seed on the repository and export
everything; persistent code-graph servers answer structural queries against a
maintained index. diffctx is **diff-seeded**: the input is a change, the
output is the fragments needed to understand it, packed under a hard token
budget — local, deterministic, no index, no model calls. Measured results and
when the other two families fit better: [COMPARISON.md](COMPARISON.md).
## Install
```bash
uvx diffctx . --diff HEAD~1 # zero-install, run once via uv
pipx install diffctx # recommended: isolated CLI, no venv needed
pip install diffctx # or: into an active environment
pipx install 'diffctx[mcp]' # + MCP server for AI assistants
```
Without Python:
```bash
cargo install diffctx # native CLI from crates.io
npx diffctx . --diff HEAD~1 # npm wrapper over the native binary
docker run --rm -v "$PWD:/repo" ghcr.io/nikolay-e/diffctx . --diff HEAD~1
```
On Windows, via Scoop (this repository is the bucket):
```powershell
scoop bucket add diffctx https://github.com/nikolay-e/diffctx
scoop install diffctx/diffctx
```
Prebuilt binaries for linux (x86_64/aarch64), macOS (arm64) and Windows (x64)
are attached to every [release](https://github.com/nikolay-e/diffctx/releases/latest).
The native binary and Docker image cover diff mode with YAML/JSON output and
write to stdout (redirect to capture); tree mode, Markdown output, the `graph`
subcommand and the MCP server live in the Python package.
## Quick start
```bash
diffctx . --diff HEAD~1 # smart context for last commit → paste into Claude/ChatGPT
diffctx . -f md -c # full codebase export → clipboard in Markdown
```

*`diffctx . --diff HEAD~1` selects only the fragments an LLM needs to review the
last commit, instead of dumping every changed file in full.*
## Diff context mode
Finds the minimal set of fragments needed to understand a change — imports,
callers, type definitions, config dependencies — across 50+ file types. It
builds a code graph (imports, co-changes, type refs), propagates relevance
outward from the changed lines, and stops when relevance drops below `--tau` or
the `--budget` token cap is hit.
`--diff` takes a git range (`HEAD~1..HEAD`, `main..feature`) or a **duration
window ending now** — `24h`, `8d`, `90min`, `1h30m`, `2w` (units `s`, `m`/`min`,
`h`, `d`, `w`, composable). A window diffs the working tree against the last
commit before it, so it covers the commits made inside the window *plus* the
uncommitted and untracked work on top — `diffctx . --diff 24h` is "everything I
touched today". A ref that happens to look like a duration (a branch `24h`)
keeps its git meaning.
| Flag | Default | Description |
|-------------|---------|--------------------------------------------------------------------------|
| `--scoring` | `ego` | `ego` = bounded expansion around changed nodes (fast, predictable radius); `ppr` = Personalized PageRank (global, smoother decay, slower); `bm25` = lexical retrieval against the diff hunks (baseline for sparse graphs); `rrf` = reciprocal-rank fusion of `ego` and `bm25` (widest recall, no scale calibration between the two signals); `pit` = the same fusion on score percentiles |
| `--budget` | auto | Cap in o200k_base tokens on the whole rendered artifact (see [Token counting](docs/product/token-budget.md)): every changed file gets one witness first, relevance fills the rest, and the renderer drops context from the tail until the document fits. A budget smaller than the summary yields the summary alone. `N` = fixed cap, `-1` disables it, `0` is a strict-zero floor (no fragments; use `--full` for changed files only) |
| `--alpha` | 0.60 | PPR continuation probability: higher = relevance travels further from the change, lower = tighter around it (`--scoring ppr` only) |
| `--tau` | 0.05 | Relevance threshold for full fragment content; lower-scoring fragments are stubbed or dropped (lower = more context) |
| `--full` | false | Only the changed files, every fragment, no related-code context |
| `--timeout` | 300 | Wall-clock deadline in seconds; on expiry the run stops cooperatively and emits a partial artifact whose `coverage` block names the limit (exit 0). 124 is the watchdog behind it, 30 s later, for a phase that could not stop |
| `--with-raw-diff` | false | Also embed git's raw unified diff ahead of the selected fragments — additive (selection unchanged), not charged to `--budget`, lock/ignored/secret-like sections omitted. Python CLI only |
| `--mode` | `pack` | `locate` emits the same ranked selection as compact `diffctx.locate.v1` JSON — path, lines, score, provenance reasons, a blast-radius `summary` and per-item impact `group` (`test`/`type`/`config`), NO source bodies. Adds a `coverage` block naming what the run could not see (`unparsed_files`, `zero_edge_files`, `ppr_truncated`, `next_up`, a heuristic `confidence`) and an `overflow` ranking of what the budget left behind — omitted entirely when there is nothing to disclose. `diffctx . --diff --mode locate` = impact of your uncommitted change. The MCP tool takes it as `mode="locate"` |
Every JSON/YAML artifact opens with `schema: diffctx.context.v1` and validates
against [`schemas/diffctx.context.v1.json`](schemas/diffctx.context.v1.json),
generated from the engine's own type; it closes with a `provenance` block
(engine version, input object ids, the effective configuration and its hash,
the selection parameters, the tokenizer) and, when a limit stopped the run
short, a `coverage` block naming it.
### `graph` subcommand
Explore the underlying dependency graph directly, without a diff:
```bash
diffctx graph . # Mermaid graph of directory deps (default)
diffctx graph . --summary # cycles, hotspots, coupling metrics
diffctx graph . --level fragment -f json # fragment-level graph as JSON
diffctx graph . --level file -f graphml -o g.xml # file-level graph as GraphML
```
## Usage
<!-- BEGIN USAGE -->
```bash
# full codebase export:
diffctx . # Markdown to stdout + token count
diffctx . -f md -c # Markdown → clipboard
diffctx . -f json -o tree.json # JSON → file
diffctx . --no-content # structure only, no file contents
diffctx . --max-depth 3 # limit depth
diffctx . -i custom.ignore # custom ignore patterns
# diff context mode (requires git repo):
diffctx . --diff # uncommitted changes (working tree vs HEAD)
diffctx . --diff HEAD~1 # context for last commit
diffctx . --diff main..feature # context for feature branch
diffctx . --diff 24h # everything changed in the last 24 hours
diffctx . --diff 8d # same over 8 days (also 90s, 10min, 1h30m, 2w)
diffctx . --diff HEAD~1 --budget 30000 # limit to ~30k tokens
diffctx . --diff HEAD~1 -c # diff context to clipboard
diffctx . --diff HEAD~1 --with-raw-diff # raw patch + selected context
diffctx . --diff HEAD~1 --mode locate # ranked navigation JSON, no source
```
<!-- END USAGE -->
Every run reports token count and size on stderr — `12,847 tokens
(o200k_base), 52.3 KB`. Counts are exact only for the GPT-4o family; Claude,
Gemini and others tokenize differently, so treat `--budget` as an upper bound
and leave headroom ([details](docs/product/token-budget.md)). Unreadable files
become placeholders like `<binary file: N bytes>`.
## Python API
```python
from pathlib import Path
from diffctx import build_diff_context, map_directory, to_json, to_markdown, to_text, to_yaml
ctx = build_diff_context(
Path("."),
"HEAD~1..HEAD",
budget_tokens=None, # None = auto; 0 = no fragments; -1 = uncapped; N = cap on the whole artifact
alpha=0.6,
tau=0.05,
full=False,
scoring_mode="ego",
timeout=300,
with_raw_diff=False, # True also embeds the raw unified diff (not charged to budget)
)
print(to_markdown(ctx))
tree = map_directory(
".",
max_depth=None,
no_content=False,
max_file_bytes=None,
ignore_file=None,
no_default_ignores=False,
whitelist_file=None,
)
print(to_yaml(tree))
```
## MCP server
[](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.nikolay-e/diffctx)
[](https://glama.ai/mcp/servers/nikolay-e/diffctx)
diffctx includes an [MCP](https://modelcontextprotocol.io) server that lets AI
assistants (Claude Code, Cursor, Windsurf, etc.) call diff context analysis
automatically during code review. It is published in the official MCP regWhat people ask about diffctx
What is nikolay-e/diffctx?
+
nikolay-e/diffctx is mcp servers for the Claude AI ecosystem. Smart git diff context for LLMs and AI agents: budgeted fragment selection, deterministic, MCP server included It has 4 GitHub stars and its last recorded update is dated 2026-09-16.
How do I install diffctx?
+
You can install diffctx by cloning the repository (https://github.com/nikolay-e/diffctx) or following the README instructions on GitHub. ClaudeWave also provides quick install blocks on this page.
Is nikolay-e/diffctx safe to use?
+
Our security agent has analyzed nikolay-e/diffctx and assigned a Trust Score of 100/100 (tier: Verified). See the full breakdown of passed checks and flags on this page.
Who maintains nikolay-e/diffctx?
+
nikolay-e/diffctx is maintained by nikolay-e. The last recorded GitHub activity is dated 2026-09-16, with 35 open issues.
Are there alternatives to diffctx?
+
Yes. On ClaudeWave you can browse similar mcp servers at /categories/mcp, sorted by popularity or recent activity.
Deploy diffctx to your cloud
Ship this repo to production in minutes. Each platform spins up its own environment with editable env vars.
Maintain this repo? Add a badge to your README
Drop the badge into your GitHub README to show it's tracked on ClaudeWave. Each badge links back to this page and reflects the live Trust Score.
[](https://claudewave.com/repo/nikolay-e-diffctx)<a href="https://claudewave.com/repo/nikolay-e-diffctx"><img src="https://claudewave.com/api/badge/nikolay-e-diffctx" alt="Featured on ClaudeWave: nikolay-e/diffctx" width="320" height="64" /></a>More MCP Servers
Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.
User-friendly AI Interface (Supports Ollama, OpenAI API, ...)
An open-source AI agent that brings the power of Gemini directly into your terminal.
Real-time global intelligence dashboard. AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface
🕷️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ
The fastest path to AI-powered full stack observability, even for lean teams.