Skip to main content

mcp-token-guard

Shrink what an MCP server sends back, and prove how many tokens you saved.

A stdio proxy and a CLI for MCP tool results: drop the nulls and empty fields, trim the kilometre-long abstracts, cap the 200-item arrays, compact the JSON — then report before_tokens, after_tokens and saved_pct for every call.

CI Python License: MIT MCP

한국어 요약은 아래에 있습니다.


The problem

An MCP tool that returns "everything" is easy to write and expensive to call. One search_papers response can carry six full abstracts, three copies of the same DOI block, null for every field the record does not have, and a debug object nobody asked for. The agent pays for all of it in context, every single turn.

mcp-token-guard sits between the client and the server, or compresses a saved response:

Claude Desktop / Cursor / Claude Code
        │  JSON-RPC over stdio (untouched)
        ▼
  mcp-token-guard  ── compress tool results, measure ──▶ stderr / stats file
        │  JSON-RPC over stdio
        ▼
  the MCP server you already use

Measured, not promised

Both numbers below come from the test suite and from mcp-token-guard demo, on the machine that built this repository:

Input Policy Before After Saved
Bundled sample: a real search_papers result from paper-radar-mcp (8.6 KB, 6 papers with 1–1.7 KB abstracts) default (400 chars, 20 items) 2,746 tokens 1,581 tokens 42.4 %
A real MCP server built with the official Python SDK, 25 results × 600-char abstracts + a 2 KB debug trace --max-items 10 4,759 tokens 1,524 tokens 68.0 %

Token counts use the built-in heuristic estimator (CJK-aware, ~4 ASCII characters per token); install the tiktoken extra for exact cl100k_base counts.


Install

uvx mcp-token-guard demo             # run without installing (once released)
uv add mcp-token-guard               # or add it to a project

No runtime dependencies: the package is standard-library only.

Use it as a proxy

Put mcp-token-guard -- in front of the command you already have in your MCP config. Nothing else changes — the client still talks JSON-RPC to what it thinks is the server.

{
  "mcpServers": {
    "papers": {
      "command": "uvx",
      "args": [
        "mcp-token-guard", "--max-items", "10", "--max-string-chars", "500",
        "--", "uvx", "paper-radar-mcp"
      ]
    }
  }
}
# Claude Code
claude mcp add papers -- uvx mcp-token-guard --max-items 10 -- uvx paper-radar-mcp

Each compressed call prints one line to stderr (stdout is the protocol channel and is never polluted):

[mcp-token-guard] tools/call id=2 4759→1524 tokens (-68.0%)
[mcp-token-guard] total 4759→1524 tokens (-68.0%) over 1 message

Add --stats-file tokens.jsonl to append one JSON record per call:

{"ts": "2026-12-05T07:41:12+00:00", "method": "tools/call", "id": 2,
 "before_tokens": 4759, "after_tokens": 1524, "saved_pct": 68.0, "token_method": "heuristic"}

What is touched, and what is not

  • Requests pass through byte for byte.
  • content[] text items are compressed only when the text is JSON. A "pong", a Markdown table or an HTML error page is returned unchanged.
  • Protocol fields (jsonrpc, id, content, type, isError, _meta) are never removed or renamed; the response stays a valid MCP response.
  • tools/list, initialize, errors and notifications are never rewritten.
  • structuredContent is left alone by default. It is schema-validated by some clients, so trimming it can break a server's outputSchema; opt in with --compress-structured when you know your client does not validate.
  • If compression would not make a payload smaller, the original is returned.

--compress-structured is the only setting with a compatibility caveat; everything else changes only the size of a JSON document that the agent reads.

Use it on a saved response

# compress stdin, print compact JSON + stats on stderr
cat response.json | mcp-token-guard compress

# stats only (this is what a benchmark loop wants)
cat response.json | mcp-token-guard compress --report-only

# measure without changing anything
mcp-token-guard measure response.json

# see the engine work on the bundled sample (a real tool response)
mcp-token-guard demo

--report-only prints exactly one JSON object:

{"before_tokens": 2746, "after_tokens": 1581, "saved_tokens": 1165, "saved_pct": 42.4,
 "ratio": 0.576, "before_chars": 8817, "after_chars": 3961, "token_method": "heuristic"}

Policy

Flag Default Effect
--max-string-chars N 400 Trim longer strings to N characters ending in …. 0 disables.
--max-items N 20 Keep the first N array items and append "... +K more". 0 disables.
--drop-key KEY — Remove this key wherever it appears. Repeatable (--drop-key debug --drop-key raw).
--keep-key KEY — Keep only these keys in objects inside arrays (the records); the envelope is untouched. Repeatable.
--keep-null off Keep null / "" / [] / {} instead of dropping them.
--pretty off Re-indent instead of compact JSON (usually larger — for humans, not tokens).
--token-method auto auto uses tiktoken when installed, otherwise the heuristic.
--stats-file PATH — Append one JSON line per compressed call.
--quiet off No per-call lines on stderr.

Library

from mcp_token_guard import Policy, compress_text, measure

result = compress_text(tool_text, Policy(max_string_chars=300, max_items=10))
print(result.stats.before_tokens, result.stats.after_tokens, result.stats.saved_pct)
print(result.changes.as_dict())      # {"strings_trimmed": 4, "items_dropped": 15, ...}
print(result.text)                   # the compact JSON to send

# or compress an already-parsed object
from mcp_token_guard import compress_json
compressed, changes, stats = compress_json(payload, Policy(drop_keys=frozenset({"debug"})))

How the measurement works

Method What it is When to use it
heuristic (default fallback) CJK characters 1 token each, Latin/digit runs ceil(len/4), punctuation 1 — dependency-free CI, offline use, relative comparisons
tiktoken exact cl100k_base counts when you need numbers that match OpenAI billing

Both are applied to the same text before and after, so the saved percentage is stable across methods; the absolute counts differ by a few percent.

Design notes

  • The proxy never buffers a whole conversation. It relays line by line; a long-running server keeps streaming, and a client that closes stdin ends the session cleanly.
  • Compression is conservative by default. Nulls, empties, over-long strings, over-long arrays and whitespace — not content. --keep-null turns the first two off.
  • keep_keys is a record whitelist, not a document whitelist. It applies to objects inside arrays, so results[].{id,title} is easy while the top-level envelope survives.
  • It tells you when it does nothing. Non-JSON, tiny payloads and errors produce no stats line, so -0.0% noise never hides a real regression.

Limitations

  • Only JSON text blocks are compressed. A server that returns Markdown or CSV is untouched.
  • Trimming a string can remove information an agent needed; pick --max-string-chars with the tool in mind, or use --drop-key for known-noise fields instead.
  • Exact token counts require pip install "mcp-token-guard[tiktoken]".
  • The proxy is stdio-only. HTTP/SSE MCP transports are not proxied.

Development

git clone https://github.com/partrita/mcp-token-guard
cd mcp-token-guard
uv venv && source .venv/bin/activate
uv pip install -e ".[dev]"

ruff check .
pytest            # 49 tests, including two end-to-end proxy runs

The end-to-end tests start a real MCP server as a subprocess — one hand-written JSON-RPC fixture, one built with the official mcp SDK — and check that a client still gets a valid, smaller response.

한국어 요약

MCP 서버가 돌려주는 JSON 응답을 압축하고, 절감된 토큰 수를 측정하는 경량 stdio 프록시입니다.

# 기존 MCP 명령 앞에 붙이기만 하면 됩니다
mcp-token-guard --max-items 10 -- uvx paper-radar-mcp
  • 프록시 모드: 요청은 그대로 통과시키고, tools/call 응답의 JSON 텍스트만 압축합니다. 프로토콜 필드(jsonrpc, id, content, isError)는 건드리지 않습니다.
  • 압축 규칙: null·빈 값 제거, 긴 문자열 자르기(…), 배열 개수 제한("... +K more"), 빈 공백 없는 compact JSON. --drop-key, --keep-key로 세밀하게 조정합니다.
  • 측정: 호출마다 before_tokens → after_tokens (-저장률%)을 stderr에 남기고, --stats-file로 JSONL 기록을 남깁니다. saved_pct는 before_tokens, after_tokens와 함께 리포트에 담깁니다.
  • CLI: compress, measure, demo 서브커맨드로 저장된 응답도 같은 엔진으로 측정합니다.

번들 샘플(실제 search_papers 응답 8.6KB)에서 2,746 → 1,581 토큰(42.4%), 공식 SDK로 만든 테스트 서버 응답에서 4,759 → 1,524 토큰(68.0%)을 측정했습니다.

License

MIT

Metadata

Release files for mcp-token-guard 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mcp-token-guard 0.1.0
File Size Uploaded Provenance Actions
mcp_token_guard-0.1.0.tar.gz 25.8 kB With provenance Details for mcp_token_guard-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mcp-token-guard 0.1.0
File Interpreter ABI Platform Actions
mcp_token_guard-0.1.0-py3-none-any.whl Python 3 none any Details for mcp_token_guard-0.1.0-py3-none-any.whl

Total release size: 48.0 kB

Release files / mcp_token_guard-0.1.0.tar.gz

Download URL mcp_token_guard-0.1.0.tar.gz
Size 25.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f8f04e38d91dac31588fdd77732009c3dd0bba2e948b23ae797dbaf0d3b50c51
BLAKE2b-256 checksum
How to use checksums
de99ce11ebe64cd482a1835bbb1710431ad5b392b5ebdec8b197c74c3c682d7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / mcp_token_guard-0.1.0-py3-none-any.whl

Download URL mcp_token_guard-0.1.0-py3-none-any.whl
Size 22.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f3fd1212deefc9867be7d8404d3d89af1ea3903794764c2fb48593a67d597db5
BLAKE2b-256 checksum
How to use checksums
6b4f34ac2f48736a478d694aa1505e2a28307b606212acef9359eaf06881c420
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for mcp-token-guard 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for mcp_token_guard-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page