Skip to main content

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

Install

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, …):

{
  "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:

{
  "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; the demo and the tests apply the same method to the gateway.

See it run

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.

License

MIT — see LICENSE.

Metadata

Release files for tokenslim-gateway 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 tokenslim-gateway 0.1.0
File Size Uploaded Provenance Actions
tokenslim_gateway-0.1.0.tar.gz 18.2 kB With provenance Details for tokenslim_gateway-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tokenslim-gateway 0.1.0
File Interpreter ABI Platform Actions
tokenslim_gateway-0.1.0-py3-none-any.whl Python 3 none any Details for tokenslim_gateway-0.1.0-py3-none-any.whl

Total release size: 31.0 kB

Release files / tokenslim_gateway-0.1.0.tar.gz

Download URL tokenslim_gateway-0.1.0.tar.gz
Size 18.2 kB
Tags Source
SHA-256 checksum
How to use checksums
275f8ad0f0da260b8f04aa9d7a5f4590e4c4964953d94742503fe506f9709b23
BLAKE2b-256 checksum
How to use checksums
d825bff62f02e339714f03ebe3fd2f4a4e915d34159a1275ff6cc2f3a03f3267
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 Nov 28, 2026.

Transparency log

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

Download URL tokenslim_gateway-0.1.0-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3ca9966a96cc9ca3de30e97bdab42e572f20ecc8865b7bd9d2d819c67a6fefac
BLAKE2b-256 checksum
How to use checksums
16b5b007c19a6c6b7eee0b5a801bc9933c2301502a84cb9819178b9756697aea
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 Nov 28, 2026.

Transparency log

Security for tokenslim-gateway 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 tokenslim_gateway-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 Nov 28, 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