Metadata-Version: 2.5
Name: tokenslim-gateway
Version: 0.1.0
Summary: TokenSlim Gateway: an MCP proxy that trims tool results from any upstream MCP server before they reach your agent's context.
Project-URL: Homepage, https://kamalmosadegh.github.io/tokenslim/
Project-URL: Repository, https://github.com/kamalmosadegh/tokenslim
Project-URL: Benchmark, https://kamalmosadegh.github.io/tokenslim/
Author: Kamal Mosadegh
License: MIT
License-File: LICENSE
Keywords: agents,context,gateway,llm,mcp,model-context-protocol,proxy,tokens
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: mcp>=2.0
Requires-Dist: tokenslim-py>=0.1.0
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# tokenslim-gateway

**Code Mode shrinks tool definitions. TokenSlim Gateway shrinks tool results.**

The Gateway is an MCP proxy: it sits between your MCP client (Claude Code,
Cursor, Cline, …) and a real upstream MCP server. The client talks to the
gateway; the gateway spawns the upstream server as a subprocess, forwards
the protocol — and trims **every tool-call result** with
[TokenSlim](https://github.com/kamalmosadegh/tokenslim) before it reaches
the model's context.

Tool results are the silent budget-killer in agent loops: one log dump,
one search result, one file read gets re-sent to the model on every later
turn. Definitions were never the big half of that bill — results are.

- Benchmarks & live demo: https://kamalmosadegh.github.io/tokenslim/
- TokenSlim itself: https://github.com/kamalmosadegh/tokenslim

## Install

```bash
pip install tokenslim-gateway
```

Requires Python ≥ 3.10, `tokenslim-py >= 0.1.0`, and the official `mcp`
Python SDK ≥ 2.0 (the proxy is built on the 2.x lowlevel `Server` /
`ClientSession` APIs). This installs a `tokenslim-gateway` command.

## The one-line change

Wherever your client config names the upstream server's command, put the
gateway in front of it and move the original command after `--`.

**Claude Code** (`.mcp.json`, `~/.claude.json`, …):

```json
{
  "mcpServers": {
    "github": {
      "command": "tokenslim-gateway",
      "args": ["--", "npx", "-y", "@modelcontextprotocol/server-github"]
    }
  }
}
```

**Cursor** (`~/.cursor/mcp.json`) and **Cline** (`cline_mcp_settings.json`)
use the same `mcpServers` shape:

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "tokenslim-gateway",
      "args": ["--stats", "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/home/you/project"]
    }
  }
}
```

That is the whole integration. The upstream command runs with the
gateway's environment inherited, exactly as if the client had spawned it
directly.

## Usage

```
tokenslim-gateway [--tool-max-tokens N] [--trim-descriptions N] [--stats] -- <upstream command> [args...]
```

| Option | Default | Meaning |
|---|---|---|
| `--tool-max-tokens N` | `400` | Token cap applied to each text block of a tool result. |
| `--trim-descriptions N` | off | Also cap tool descriptions in `tools/list` at N tokens. Definitions are usually small; turn this on for servers with essay-length descriptions. |
| `--stats` | off | One line per trimmed call plus session totals, written to **stderr** (stdout is the protocol channel). |

Real `--stats` output from the bundled demo:

```
tokenslim-gateway: big_log: 8,062 -> 244 tokens (-97.0%)
tokenslim-gateway: totals: 1 call(s) trimmed, 8,062 -> 244 tokens (-97.0%)
```

## How it works

1. The gateway spawns the upstream and completes the MCP handshake with
   it *first*, then builds its own server advertising exactly the
   capabilities the upstream advertised (tools / prompts / resources /
   logging), with the upstream's `instructions` and list-changed flags
   mirrored.
2. `tools/list`, `prompts/list` + `prompts/get`, `resources/list` +
   `resources/templates/list` + `resources/read` and `logging/setLevel`
   are transparent forwards. Progress notifications for a tool call are
   forwarded under the client's own progress token. Upstream
   notifications (logging, list-changed, resource-updated) are forwarded
   to the client; `notifications/cancelled` and
   `notifications/roots/list_changed` are forwarded upstream.
3. On `tools/call`, each **text** content block of the result is trimmed
   with TokenSlim's `smart_truncate` — the single-text stage of the
   TokenSlim pipeline: duplicate lines collapse, then the budget is
   split between the head, the tail, and the highest-signal lines
   (ERROR lines, identifiers, numbers). Single-line JSON results are
   trimmed structurally, so identifiers in the middle survive. Text
   already under the cap passes through byte-identical.

Safety rules, in order of importance:

- **The proxy never breaks the protocol.** Any failure inside trimming
  returns the original result untouched; malformed upstream output is
  forwarded as-is; upstream protocol errors reach the client as the
  same errors.
- **`isError` results are never trimmed** — an error is the one payload
  whose every line may matter.
- **Non-text blocks are never touched**: image and embedded-resource
  blocks pass through as the identical objects, and `structuredContent`
  is left alone.

## Honest numbers

From the bundled demo (`examples/demo.py`, a fake upstream returning a
32k-char build log of mostly duplicate heartbeat lines):

```
direct from upstream :   8,062 tokens
through the gateway  :     244 tokens  (-97.0%)
facts preserved      : True  (job-88112, req-9f27c1, exit_code=137, tests_passed=342)
```

Read that honestly: the fixture is *redundant log output*, which is
where trimming wins big — duplicate collapse does most of the work.
Savings scale with redundancy. A result that is unique prose trims far
less (mostly its lowest-signal lines beyond the cap), and a result
already under the cap is not touched at all. TokenSlim's fact-recall
benchmark method — track concrete facts (ids, error codes, totals)
through the trim and count survivors — is documented on the
[benchmark page](https://kamalmosadegh.github.io/tokenslim/); the demo
and the tests apply the same method to the gateway.

## See it run

```bash
python examples/demo.py     # direct vs gateway, real counts, no network
python -m pytest            # 19 tests: unit + full stdio end-to-end
```

`examples/fake_upstream.py` is the small MCP server used by both: a
`big_log` tool (redundant log + embedded facts), a `fail` tool
(`isError` passthrough), a `small` tool, one prompt, one resource.

## Limitations

v0.1 is deliberately narrow — text results only, stdio only, one
upstream per process, no sampling/elicitation forwarding. The full
list, with the reasoning, is in [docs/limitations.md](docs/limitations.md).

## License

MIT — see [LICENSE](LICENSE).
