compaction-mcp
Brings context compaction, history summarization, file re-hydration, and session persistence to GitHub Copilot in VS Code, enabling efficient long coding sessions without losing context.
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., "@compaction-mcp Check context pressure and compact history if needed."
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.
compaction-mcp
A portable MCP stdio server that brings Claude Code's /compact lifecycle to any
MCP host — GitHub Copilot (VS Code), Claude Desktop, or a custom local-LLM
agent loop (e.g. Qwen-Coder via Ollama).
It exposes context compaction as tools/resources/prompts so the agent can: gauge context
pressure, summarize accumulated history into a dense block (a real inference call, not
truncation), re-hydrate live files from disk, persist session-long rules and a
verification ledger across the compact_boundary, and run PreCompact/PostCompact
hooks.
See SPEC.md for the full protocol design and the host/server
responsibility split, ENTERPRISE.md for deploying under
GitHub Copilot Enterprise (org policy gates, MCP registry, in-tenant summarizer,
distribution), and runbooks/ for step-by-step operational guides for each
strategy (offload, recall, compact, re-seed, auto-compact, hooks/ledger).
Why a server can't just "do" /compact
In Claude Code, /compact is host-level — the CLI owns the context window. An MCP server
doesn't. So this server provides the mechanism (summarize, re-hydrate, persist,
snapshot ledger) and returns a compacted context block; the host installs that block
as its new ground truth and discards pre-boundary history. Read §1 of the spec first.
Related MCP server: SharedMemory MCP Server
Install
npm install
npm run build # → dist/index.jsConfiguration (env)
Var | Default | Purpose |
|
|
|
|
| OpenAI-compatible endpoint (Ollama) |
|
| summarizer model |
| — | optional bearer token |
| — | JSON of extra request headers (Azure |
|
|
|
|
| session + ledger persistence |
| cwd | colon-separated roots for file re-hydration |
| — | path to hooks JSON (see |
|
| set |
|
| default window size when host doesn't declare one |
|
| auto-compact on ingest when pressure ≥ |
|
|
|
| — | embeddings model for semantic recall (e.g. |
| = LLM base URL | OpenAI-compatible |
Manual vs auto
The server is manual by default — it only acts when a tool is called. context_status
tells you when to compact, but the host decides.
For deterministic auto behavior, use COMPACTION_MODE=store + COMPACTION_AUTO=true:
turn_add then checks pressure after each turn and, once it crosses the compact-now
threshold, runs compaction inline and returns the block under autoCompacted. Your agent
loop just installs autoCompacted whenever it's present. Passthrough mode stays manual
(the server doesn't hold continuous history).
Summarizer choice (important)
directworks on every host (incl. Copilot) — the server calls the LLM itself. Point it at Ollama for fully local operation.samplingneeds a sampling-capable host (Claude Desktop). Copilot does not support sampling — don't use it there.autouses sampling if the client offers it, else falls back todirect.
Host setup
GitHub Copilot (VS Code) — .vscode/mcp.json
Copilot is tools-only, so use passthrough mode + direct summarizer (Ollama):
{
"servers": {
"compaction": {
"type": "stdio",
"command": "node",
"args": ["${workspaceFolder}/compaction-mcp/dist/index.js"],
"env": {
"COMPACTION_SUMMARIZER": "direct",
"COMPACTION_LLM_BASE_URL": "http://localhost:11434/v1",
"COMPACTION_LLM_MODEL": "qwen2.5-coder:14b",
"COMPACTION_MODE": "passthrough",
"COMPACTION_ALLOWED_ROOTS": "${workspaceFolder}"
}
}
}
}Then instruct Copilot (e.g. in .github/copilot-instructions.md): when the conversation
grows long, call context_compact with the recent history as transcript, then continue
from the returned summary + rehydratedFiles + persistentRules.
No Ollama? (Copilot-only) Copilot doesn't lend its model to MCP servers (no sampling),
so direct must point at some OpenAI-compatible endpoint. Easiest for a Copilot user is
GitHub Models (free, OpenAI-compatible) — see
examples/vscode-mcp.github-models.json. It
uses VS Code's inputs to prompt for a GitHub token (scope models: read) once and store
it encrypted. Any other OpenAI-compatible provider (OpenAI, OpenRouter, Groq, …) works the
same way — just change COMPACTION_LLM_BASE_URL / COMPACTION_LLM_MODEL.
Claude Desktop — claude_desktop_config.json
{
"mcpServers": {
"compaction": {
"command": "node",
"args": ["/abs/path/compaction-mcp/dist/index.js"],
"env": { "COMPACTION_SUMMARIZER": "auto" }
}
}
}auto lets Claude Desktop run the summary via sampling (same model, no extra infra).
Enterprise (internal LLM gateway)
Point direct at your company's OpenAI-compatible gateway (LiteLLM, Portkey, Kong/Cloudflare
AI Gateway, or Azure OpenAI fronted by one) so code + transcripts stay in-tenant. Non-Bearer
auth goes in COMPACTION_LLM_HEADERS (e.g. Azure's {"api-key": "..."}). See
examples/vscode-mcp.enterprise-gateway.json.
Raw Azure OpenAI isn't drop-in (its URL is /openai/deployments/{d}/chat/completions?api-version=…),
so front it with a gateway rather than pointing the server at it directly.
On a Copilot Enterprise/Business plan there are also org-policy gates that block MCP
unless an admin opts in — see ENTERPRISE.md for the full deployment guide.
Custom local-LLM agent loop (full control)
Use COMPACTION_MODE=store: feed each message through turn_add, poll context_status,
and call context_compact (no transcript arg) when it returns compact-soon/compact-now.
Tool surface
context_status, context_compact, context_trim, context_clear, turn_add,
handoff_brief, read_offloaded, offload_store, offload_fetch, recall, files_track,
files_untrack, files_rehydrate, rules_set, rules_append, rules_get,
ledger_record, ledger_query, ledger_snapshot.
Resources: compaction://session/{id}, compaction://rules/{id},
compaction://ledger/{id}, compaction://summary/{id}/{boundaryId},
compaction://handoff/{id}, compaction://blob/{handle}.
Keeping the window small: offloading
Re-seed recovers after the window is big; offloading keeps it small in the first place.
Instead of dumping a full file or command output into chat, read_offloaded / offload_store
stash it and return a short digest + handle; the agent pulls the full body (or a line
slice) via offload_fetch only when needed. On Copilot this only helps if the agent uses
read_offloaded instead of the native file-read tool. See SPEC.md §10B.
On hosts with their own retrieval (e.g. Augment), add recall { query }: it searches the
ledger + offloaded blobs for already-known facts/content so the agent doesn't re-pull the same
files. Instruct the agent to recall before querying the codebase. Ranking is semantic
when COMPACTION_EMBED_MODEL is set (e.g. Ollama nomic-embed-text), else lexical; auto
falls back gracefully. See SPEC.md §10C.
Reclaiming tokens on Copilot: re-seed
On Copilot (passthrough), context_compact produces a great summary but doesn't shrink
the live window — the server can't evict the host's messages, so the summary is additive.
The way to actually reclaim tokens is re-seed: compact → open a new chat → seed it from handoff_brief → continue. A new chat starts with an empty window.
handoff_brief returns the seed (rules + latest summary + ledger + files to re-open) and
always writes it to disk (and to outPath, e.g. .compaction/handoff.md), so a new chat
can attach the file even if MCP is blocked for the account. See SPEC.md §10A.
Typical loop (passthrough)
rules_set— pin session-long rules (survive every boundary).files_track— list active files to re-hydrate.…work…
ledger_recordwhenever something is verified.context_status→compact-soon? →context_compact { transcript, preserve }.Install the returned block; drop everything before
boundary. Continue.
Status
v0.1 scaffold — stub logic is wired end-to-end and typechecks; replace the token
estimator (§ estimateTokens) with a real tokenizer and harden hook sandboxing before
production. Roadmap in SPEC.md §13.
Available Tools
19 toolscontext_clearClear context (tier-3 reset)C
Hard reset turns and boundaries. Keeps rules and ledger by default.
Inputs: keepRules, sessionId.
context_compactCompact contextA
Summarize accumulated history into a dense block, snapshot the ledger, re-hydrate tracked files, and run Pre/PostCompact hooks. Returns the compacted context block to install as new ground truth.
Inputs: preserve, sessionId, transcript.
context_statusContext statusC
Report context pressure and a compaction recommendation (ok | compact-soon | compact-now | at-limit).
Inputs: sessionId, tokenBudget, estTokensUsed.
context_trimTrim context (tier-1 prune)B
Remove low-value/duplicate tool output without an inference call. Store mode only.
Inputs: sessionId, dropToolOutputOlderThanTurns.
files_rehydrateRe-hydrate files nowB
Read tracked (or given) files from disk and return current contents.
Inputs: paths, sessionId.
files_trackTrack files for re-hydrationA
Mark files to silently re-read from disk on every compaction.
Inputs: paths (required), sessionId.
files_untrackUntrack filesB
Stop re-hydrating the given files.
Inputs: paths (required), sessionId.
handoff_briefBuild a re-seed handoff briefA
Produce a small, self-contained brief (rules + latest summary + verification ledger + active files) to START A FRESH CHAT with. This is how you actually reclaim tokens on hosts that own their window (e.g. Copilot): open a new chat and seed it with this brief. Always written to disk too, so a new chat can attach the file even if MCP is unavailable.
Inputs: outPath, sessionId, includeFileContents.
ledger_queryQuery the verification ledgerB
Filter ledger entries by claim substring and/or result.
Inputs: result, sessionId, claimContains.
ledger_recordRecord a verificationA
Append an entry to the verification ledger (maker/checker). Survives compaction; verified results are copied verbatim into summaries.
Inputs: claim (required), method (required), result (required), evidence (required), +3 more.
ledger_snapshotSnapshot the ledgerB
Return the full current ledger (used at boundaries for re-injection).
Inputs: sessionId.
offload_fetchFetch offloaded contentA
Retrieve a blob's full content, or a 1-indexed inclusive line slice. Use the smallest slice that answers the question to keep the window small.
Inputs: handle (required), endLine, startLine.
offload_storeOffload arbitrary textA
Stash large text (command output, grep results, logs, API payloads) as a blob and return a digest + handle instead of putting it all in the window.
Inputs: label (required), content (required).
read_offloadedRead a file without loading it into contextA
Read a file from disk and OFFLOAD it: returns a short digest (preview + structural outline + line/byte counts) and a handle, instead of dumping the full contents into the window. Prefer this over a normal file read for large files. Fetch the full body only when needed via offload_fetch or the compaction://blob/{handle} resource.
Inputs: path (required), label.
recallRecall cached facts before retrievingA
Search the verification ledger + offloaded blobs for already-known facts and content. CALL THIS BEFORE querying the codebase / context engine: a cached fact or a known blob line range avoids pulling whole files back into the window (token saver, esp. on hosts with their own retrieval like Augment). Semantic ranking when embeddings are configured, else lexical. Returns ledger hits + blob hits with line ranges (use with offload_fetch).
Inputs: query (required), limit, sessionId.
rules_appendAppend to persistent rulesC
Append a rule that survives every boundary.
Inputs: rule (required), sessionId.
rules_getGet persistent rulesB
Return the current persistent rules.
Inputs: sessionId.
rules_setSet persistent rulesA
Replace the CLAUDE.md-equivalent rules that survive every boundary.
Inputs: rules (required), sessionId.
turn_addAdd a turn (store mode)C
Append a message to the server-held transcript. Store mode only. When COMPACTION_AUTO=true and pressure crosses the compact-now threshold, compaction fires automatically and the compacted block is returned under autoCompacted.
Inputs: role (required), content (required), pinned, sessionId.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 19 tools
The tools cover distinct actions across context, files, offloading, rules, and ledger. Some close concepts (context_compact vs context_trim, handoff_brief vs context_compact, recall vs ledger_query) have subtle differences that require careful reading, but the descriptions disambiguate them. Overall, each tool has a specific role.
Most tools follow a resource_verb pattern (context_*, files_*, offload_*, rules_*, ledger_*), but a few outliers like read_offloaded and recall break this pattern. The prefix grouping is helpful and consistent within subgroups, making the set mostly predictable despite a few deviations.
At 19 tools, the set is on the heavier side. While each tool serves a distinct need across multiple subdomains (context, handoff, files, offload, rules, ledger), the number is above the typical 3-15 sweet spot, giving it a sense of bloat. A more focused server could combine some tools or drop rarely used ones.
The set covers the full lifecycle of context management: status, compact, trim, clear, handoff, turn recording, file tracking, offloading, recall, rules, and ledger. Missing operations include offload deletion and explicit restoration of compacted blocks, but these are minor and workarounds exist. Overall the surface is comprehensive.
Maintenance
Related MCP Connectors
Compress coding-agent context ~64%. Hosted Neural Keep MCP for Cursor/Claude/Codex.
Path-scoped team memories, rules and skills for Claude Code, Cursor, Codex and other MCP clients.
Cross-tool persistent memory and context for AI assistants over MCP.
Persistent memory for AI agents across Claude, ChatGPT and any MCP client.
Related MCP Servers
- AlicenseBqualityDmaintenancePortable, auditable, local-first MCP memory for MCP-compatible AI agents and coding workflows. It keeps durable project memory outside the model runtime, compresses continuity into smaller working packs, and carries forward operational state so agents can resume with less repetition.2841Apache 2.0
- AlicenseAqualityDmaintenanceGives Claude Code, Claude Desktop, Cursor, VS Code Copilot, and other MCP-compatible tools persistent memory.1866 npm1MIT
- AlicenseAqualityCmaintenanceProvides reversible context compression for AI agents, reducing token usage while preserving the ability to retrieve original content, and serves as an MCP server for integration with tools like GitHub Copilot and Claude Code.31Apache 2.0
- AlicenseNot gradedqualityBmaintenanceDeterministic context compression for MCP agents, reducing token usage via 11 tools for prompts, history, shell output, file deltas, and code navigation without ML or GPU.9MIT