TokenSlim MCP — verifiable token reduction for agents

v1.0.0
io.github.kamalmosadegh/tokenslim-mcp Checks in progress Published 1 hour ago

TokenSlim

Cut LLM agent token usage by 72.5% on realistic work — measured, not claimed.

PyPI version CI Python License: MIT

Install

pip install tokenslim-py            # core library + CLI
pip install tokenslim-mcp           # MCP server, four tools
pip install tokenslim-gateway       # MCP proxy, trims results
pip install tokenslim-langgraph     # LangGraph + LangChain integration

One repo, four packages, same job at four layers: a zero-dependency Python library, an MCP server, an MCP gateway proxy, and a LangGraph / LangChain integration. All four are MIT and at v1.0.0; the three integrations depend on the library (tokenslim-py), not on a copy of it.

Quickstart

from tokenslim import audit, truncate_text, compact_history, compress

audit(messages)                                     # 1. find the waste
truncate_text(tool_output, max_tokens=400)           # 2. trim bulky outputs
compact_history(messages, max_tokens=8000)          # 3. compact old history
compress(prompt, rate=0.7)                           # 4. compress the prompt

Every number below was re-measured from a clean checkout on 2026-12-01 (Python 3.12, tiktoken 0.14.0, headroom-ai 0.45.0), and every benchmark is a runnable script in this repo — if a number can't be re-run from this checkout, it says so. Full measured results are right below.

Measured results

Realistic coding-agent transcript (exact tiktoken counting)

17 messages: system prompt, 3 tool schemas, grep / source / pytest / API-JSON tool outputs, one re-read file, 3 RAG chunks. Reproduce: python core/tests/benchmark_real.py

Step Tokens Cumulative reduction
0. raw transcript 2,150 —
1. + cache repeated tool calls 1,687 −21.5%
2. + truncate tool outputs (400 tok) 1,622 −24.6%
3. + compress RAG chunks (rate 0.75) 1,576 −26.7%
4. + compact history (budget 2,500) 592 −72.5%

On pathological inputs (the same 5k-token log pasted 10×) the pipeline reaches ~98%, but 72.5% is the honest number for realistic work — your mileage depends on how much of your context is tool output.

Head-to-head vs Headroom 0.45.0 (same inputs, same tiktoken counter)

Reproduce: python core/tests/benchmark_headroom.py

Scenario TokenSlim Headroom
Coding session, 40 turns, buried ERROR line (179,631 tok) 3,683 (−97.9%), 5/5 facts 57,111 (−68.2%), 5/5 facts
RAG, 12 chunks, 2 answer it (3,125 tok) 1,128 (−63.9%), 2/2 facts 3,125 (−0.0%), 2/2 facts

Honest reading: on English logs Headroom keeps the facts too — including the buried ERROR line. TokenSlim's edge is depth of savings on the same input, and one place where Headroom's routers do nothing at all: small messages under its 250-token floor. Headroom's ML text compressor (261 MB ONNX model) did not run in this environment, so this compares its heuristic routers only.

Accuracy eval: does the model still answer correctly after compression?

24 questions, exact verifiable answers, one run per model (GLM-5.3-Flash, temperature 0). Recorded 2026-11-28; re-derive the score without model calls: python core/tests/accuracy_eval.py --rescore

Condition Score Avg context tokens
Raw context 23/24 1,476
TokenSlim 23/24 386 (−73.8%)
Headroom 23/24 681

TokenSlim matches raw and Headroom — it does not beat them — while using 73.8% fewer context tokens. The one miss (rag-4) is missed by all three conditions. Small eval, stated plainly.

Larger fact table (recorded, not re-runnable from this checkout)

8 scenarios, 55 tracked facts. Totals re-derived from the saved core/tests/benchmark_headroom_own_extended_results.json: TokenSlim 55/55 facts at −97.9% (353,523 → 7,522 tokens); Headroom 52/55 at −41.7%. All three Headroom misses are the same systematic drop (an fs-search path fact). Caveat: the live script needs a real_world_agent_benchmark fixture module that is not committed to this repo, so this table cannot currently be re-run from a clean checkout. Committing the fixture is tracked as a pre-launch fix; until then, treat this row as recorded, not reproduced.

Integrations (each demo re-run 2026-12-01)

Integration Demo Result
Gateway proxy python gateway/examples/demo.py 8,062 → 241 tokens (−97.0%), 4/4 facts kept
LangGraph node python langgraph/examples/mini_graph.py tool output 10,261 → 409 (96.0%); total state 10,317 → 465 (95.5%) with exact tiktoken counting (chars/4 estimator: 6,487 → 397, 93.9%; 6,534 → 444, 93.2%)
MCP server trim asserted in mcp/tests/test_tokenslim_mcp.py 3,297 → 196 tokens (−94.1%), buried ERROR line kept 1/1

Install

pip install tokenslim-py            # core library + CLI, zero required dependencies
pip install tokenslim-mcp           # MCP server (needs mcp<2)
pip install tokenslim-gateway       # MCP proxy (needs mcp>=2)
pip install tokenslim-langgraph     # LangGraph/LangChain (needs langchain>=1.0)

Or from this repo:

pip install -e ./core
pip install -e ./mcp ./gateway ./langgraph

Quickstart

from tokenslim import audit, suggestions, truncate_text, compact_history, compress

report = audit(messages)          # where do the tokens go?
for tip in suggestions(report):
    print(tip)

for m in messages:                # trim bulky tool outputs
    if m["role"] == "tool":
        m["content"] = truncate_text(m["content"], max_tokens=400)

messages, saved = compact_history(messages, max_tokens=8000, keep_recent=6)
short = compress(prompt, rate=0.7, protected={"OAuth", "my_api_key"})

One-line integrations:

# MCP server (Claude Code, Cursor, …)
claude mcp add tokenslim -- tokenslim-mcp

# Gateway proxy: put it in front of any MCP server
tokenslim-gateway -- npx -y @modelcontextprotocol/server-github
# LangGraph: one node between tools and model
graph.add_node("trim", trim_tool_messages)
graph.add_edge("tools", "trim")
graph.add_edge("trim", "model")

Tests

./run_tests.sh                    # everything: core + 3 integrations

Per package (all passing, re-run 2026-12-01):

Suite Result
Core unit tests (offline estimator) 43 passed
Core stress tests 12/12 passed
Core adversarial cases 112 total: 106 PASS / 0 FAIL / 6 by-design OBSERVE
Core smart tests (fact-recall scripts) 2/2 PASS
Gateway tests (unit + stdio end-to-end) 19 passed
LangGraph tests 13/13 with exact tiktoken counting and with the chars/4 estimator
MCP server tests (incl. live stdio protocol test) 10 passed

Known issues

  • Fixed 2026-12-01: LangGraph middleware fact-preservation test failed under exact tiktoken counting. smart_truncate at a 200-token budget split the fact exit_code=137 across the elision boundary (exit_code=1 … [10057 tokens elided] … 37 (OOM)). Root cause: the head/tail cuts were blind character cuts that could land mid-token, and the signal line overlapping the boundary was truncated at the same cut. Fix: head/tail cuts now snap to the nearest newline or space (_snap_head_tail in core/src/tokenslim/smart.py, snap bounded to 200 chars), so a fact is never split across the cut. Verified 2026-12-01: LangGraph tests 13/13 with exact tiktoken counting and with the chars/4 estimator; full suites green (core 43, gateway 19, LangGraph 13, MCP 10). Demo numbers moved slightly with the fix (gateway 8,062 → 241; LangGraph tool output 10,261 → 409) and the numbers in this README are the re-measured ones.

Honest limits

  • Compression is heuristic (LLMLingua-style), not model-grade. Facts are scored to survive, but no heuristic is a guarantee for arbitrary text.
  • Savings scale with redundancy. Unique prose trims far less; content already under the cap is not touched at all.
  • The ~98% figures are mostly history compaction — deletion, not compression — and are labelled as such wherever they appear.
  • The gateway trims text results only, stdio only, one upstream per process (see docs/gateway-limitations.md).
  • The LangGraph integration trims per-message only; it never compacts history inside a live graph, because LangGraph state is keyed by message id (see docs/langgraph-integration.md).

Repo map

core/        library + CLI (src/tokenslim), tests, examples, docs
mcp/         MCP server (tokenslim_mcp), server.json, tests
gateway/     MCP proxy (src/tokenslim_gateway), examples, tests
langgraph/   LangGraph node + LangChain middleware, examples, tests
docs/        benchmark page (docs/index.html), llms.txt, integration docs

License

MIT — see LICENSE.