Metadata-Version: 2.5
Name: mcp-token-guard
Version: 0.1.0
Summary: Compress MCP tool results and measure the tokens saved — a stdio proxy and a CLI.
Project-URL: Homepage, https://github.com/partrita/mcp-token-guard
Project-URL: Issues, https://github.com/partrita/mcp-token-guard/issues
Author: Kim Taeyun
License: MIT License
        
        Copyright (c) 2026 Kim Taeyun
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: context-window,json,llm,mcp,model-context-protocol,proxy,tokens
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: mcp>=1.2; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Provides-Extra: tiktoken
Requires-Dist: tiktoken>=0.7; extra == 'tiktoken'
Description-Content-Type: text/markdown

# 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](https://github.com/partrita/mcp-token-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/partrita/mcp-token-guard/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![MCP](https://img.shields.io/badge/MCP-compatible-6f42c1)](https://modelcontextprotocol.io)
<!-- PyPI badge: enable after the first release
[![PyPI](https://img.shields.io/badge/pypi-mcp--token--guard-blue)](https://pypi.org/project/mcp-token-guard/)
-->

> 한국어 요약은 [아래](#한국어-요약)에 있습니다.

---

## 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:

```text
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

```bash
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.

```json
{
  "mcpServers": {
    "papers": {
      "command": "uvx",
      "args": [
        "mcp-token-guard", "--max-items", "10", "--max-string-chars", "500",
        "--", "uvx", "paper-radar-mcp"
      ]
    }
  }
}
```

```bash
# 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):

```text
[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:

```json
{"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

```bash
# 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:

```json
{"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

```python
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

```bash
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 프록시입니다.

```bash
# 기존 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
