Skip to main content
Glama
README.md
# mcp-slim

**Put `mcp-slim` in front of any stdio MCP server and Claude gets the same tool results with 50–80% fewer tokens.**

GitHub, Linear and most REST-backed MCP servers return raw API JSON: pretty-printed, full of `null`s, `node_id`s, avatar links and a dozen `*_url` hypermedia fields per object. Claude pays for every one of those tokens and gets nothing from them. `mcp-slim` is a transparent stdio proxy that strips that noise before it reaches the model. There is nothing to change in the server and nothing to change in the client.

```text
Claude Desktop / Claude Code  ⇄  mcp-slim  ⇄  any stdio MCP server
                                     │
          prune · cap · minify · redact secrets · slim schemas · dedupe
```

It does the following:

- **Compresses results** from `tools/call`, `resources/read` and `prompts/get`.
- **Redacts leaked credentials**, such as GitHub tokens, `sk-` keys, AWS keys, Bearer headers and PEM private keys, before Claude sees them.
- **Minifies tool schemas and descriptions** in `tools/list`, which clients re-send to the model on every turn.
- **Deduplicates repeat calls.** An identical result to an identical call becomes a one-line note.
- **Adds terse-mode instructions** that ask Claude for short replies, which cuts output tokens.
- **Includes two built-in tools,** `slim_fetch` and `slim_extract`. It also runs **standalone** with no wrapped server, for example on Koyeb or Render, so Claude on mobile and the web can reach it.

## Benchmark

These are realistic GitHub REST API payloads, generated deterministically by [`benchmark.py`](benchmark.py) (`python benchmark.py` reproduces them):

| Payload | Original Tokens | mcp-slim Tokens | % Saved |
|---|---:|---:|---:|
| GitHub `list_issues` (30 issues) | 29,179 | 11,804 | 59.5% |
| GitHub `get_issue` + 15 comments | 9,043 | 3,488 | 61.4% |
| GitHub `get_pull_request` | 4,655 | 1,006 | 78.4% |
| GitHub `list_pull_requests` (20 PRs) | 96,814 | 20,086 | 79.3% |
| GitHub `search_issues` (100 hits, capped at 50) | 89,875 | 14,055 | 84.4% |
| GitHub `list_issues`, already-minified JSON | 23,925 | 11,633 | 51.4% |
| Markdown README (plain text path) | 1,524 | 1,498 | 1.7% |
| **Total** | **255,015** | **63,570** | **75.1%** |

Tokens are estimated at about 4 characters per token, which is the same estimator the proxy uses for its footer. Most of the savings come from pruning, not whitespace: even JSON that is already minified shrinks by half. The `search_issues` row includes the 50-item array cap, which drops data. Every other row is lossless for the fields that remain. Plain prose has little to remove, and mcp-slim does not paraphrase or summarise.

## 30-second quickstart

```bash
# Wrap any stdio MCP server: everything after `--` is the original command.
uvx mcp-slim -- npx -y @modelcontextprotocol/server-github
```

Or install it:

```bash
pip install mcp-slim        # or: uv tool install mcp-slim
mcp-slim --help
```

Every compressed tool result ends with one short line:

```text
[mcp-slim: saved ~17,412 tokens · session total ~52,980]
```

Pass `--quiet` to turn it off. The footer is only added when a call saves more tokens than the footer itself costs.

Run it with no command to get a standalone server that only has the [built-in tools](#built-in-tools):

```bash
uvx mcp-slim
```

## Setup

### Claude Desktop (`claude_desktop_config.json`)

Put `mcp-slim --` in front of the server's existing command. Environment variables are passed through to the wrapped server.

```json
{
  "mcpServers": {
    "github": {
      "command": "uvx",
      "args": ["mcp-slim", "--", "npx", "-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "<your-token>"
      }
    },
    "my-python-server": {
      "command": "uvx",
      "args": ["mcp-slim", "--config", "/Users/me/.mcpslim.json", "--", "python", "-m", "my_mcp_server"]
    }
  }
}
```

### Claude Code

```bash
claude mcp add github \
  -e GITHUB_PERSONAL_ACCESS_TOKEN=<your-token> \
  -- uvx mcp-slim -- npx -y @modelcontextprotocol/server-github
```

The same works in a project `.mcp.json`:

```json
{
  "mcpServers": {
    "github": {
      "command": "uvx",
      "args": ["mcp-slim", "--quiet", "--", "npx", "-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" }
    }
  }
}
```

### CLI reference

```text
mcp-slim [--config PATH] [--quiet] [--verbose] [-- <command> [args...]]

  (no command)    standalone mode: serve only slim_fetch and slim_extract

  --config PATH   use this .mcpslim.json instead of auto-discovery
  -q, --quiet     don't append the tokens-saved footer
  -v, --verbose   debug logging (to stderr)
  --version       print the version
```

## What gets compressed

| MCP message | What mcp-slim does |
|---|---|
| `tools/call` | Compresses and redacts text blocks, deduplicates repeat results and adds the footer |
| `resources/read` | Compresses and redacts text contents |
| `prompts/get` | Compresses and redacts text message content |
| `tools/list` | Strips `$schema`, `title`, `examples` and `default` from `inputSchema`, and truncates descriptions to 120 characters (`slim_schemas`) |
| `resources/list`, `resources/templates/list` | Truncates descriptions to 120 characters (`slim_schemas`) |
| `initialize` | Appends terse-mode instructions (`terse_mode`) |

Images, audio, embedded binary resources, `structuredContent`, `outputSchema` and errors pass through untouched.

**JSON payloads** (a text block that parses as a JSON object or array):

| Rule | Default |
|---|---|
| Drop `null`, `""`, `[]` and `{}` values from objects, recursively (`0` and `false` are kept) | on |
| Drop noisy keys: `avatar_url`, `gravatar_id`, `node_id`, `*_url`, `_links`, `etag`, `__typename` | on |
| …except keys in `keep_keys`: `html_url`, `web_url`, `download_url`, `image_url` | on |
| Cap arrays, adding a `"…[+N more items truncated by mcp-slim]"` marker | 50 items |
| Truncate long strings, adding a `"…[+N chars truncated by mcp-slim]"` marker | 1500 chars |
| Minify (`separators=(",", ":")`, UTF-8 kept readable) | on |

Empty items inside arrays are kept, so positional data such as table rows keeps its shape.

**Plain text and Markdown:** runs of blank lines collapse to one, and trailing whitespace is removed (Markdown hard line breaks are kept). Fenced code blocks (```` ``` ```` and `~~~`) are preserved byte for byte.

If compression would not make a block smaller, the original is sent unchanged, after secret redaction.

**Secret redaction** (`redact_secrets`) replaces these patterns with `[REDACTED:<kind>]`:

| Kind | Pattern |
|---|---|
| `github_token` | `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` tokens and fine-grained `github_pat_` tokens |
| `api_key` | OpenAI- and Anthropic-style `sk-…` keys (`sk-proj-…`, `sk-ant-…`) |
| `aws_access_key` | `AKIA…` and `ASIA…` access key IDs |
| `Bearer [REDACTED]` | `Authorization: Bearer <token>` values |
| `private_key` | PEM `-----BEGIN … PRIVATE KEY-----` blocks, including RSA, EC and OpenSSH keys |

Redaction runs on every string inside JSON payloads and on plain text. It catches common accidental leaks, such as a config file, a CI log or an `.env` file read by a tool. It does not replace a secret scanner.

**Schema minification** (`slim_schemas`) strips annotations only. Property names are never touched, even when a property is called `title` or `default`. `type`, `enum`, `required`, `minimum` and similar validation keywords stay exactly as they were.

**Deduplication** (`dedupe_calls`) keeps a SHA-256 hash of each `(tool name, arguments)` pair and of its compressed result. The cache holds hashes only, never tool output. When the same call returns the same output again in a session, mcp-slim sends `Unchanged from earlier in this session (see previous result).` instead. Error results are never deduplicated. Turn this off if your client drops old tool results from context, for example after compaction, and you need the model to always see the full output.

**Terse mode** (`terse_mode`) appends this to the server's `instructions`, which clients pass to Claude:

> Response style: be ultra-concise. No filler, no preamble, no restating the request, no closing summaries. Use bullet points or code blocks unless the user asks for prose.

This shapes how Claude writes, not only what tools return. Set `"terse_mode": false` if you want normal replies.

## Built-in tools

Built-in tools are on by default (`builtin_tools`). In proxy mode they are added to the wrapped server's tools, and if the wrapped server has a tool with the same name, that tool wins. In standalone mode they are the only tools.

| Tool | Arguments | Returns |
|---|---|---|
| `slim_fetch` | `url` | The page as readable text, with `<script>`, `<style>` and tags removed, then compressed. JSON and plain text are compressed as usual. |
| `slim_extract` | `url`, `query` | Only the paragraphs that match the keywords in `query`, best matches first, up to about 3,000 characters, kept in page order. |

Both tools are built on the standard library only (`urllib`, `re`, `html`). Because they can run on a public host, they are locked down:

- Only `http://` and `https://` URLs are allowed, and URLs with embedded credentials are refused.
- **No internal targets.** A host that resolves to a loopback, private (RFC 1918 or ULA), link-local (including the `169.254.169.254` cloud metadata endpoint), carrier-grade NAT, multicast or reserved address is refused. Every redirect hop is checked again.
- Responses are capped at 2 MB, requests time out after 15 seconds, and binary content types are refused.

To fetch from a local dev server, set `MCPSLIM_ALLOW_PRIVATE_URLS=1`. **Never set it on a public deployment.**

## Configuration (`.mcpslim.json`)

mcp-slim looks for config in this order: `--config PATH`, then the `$MCPSLIM_CONFIG` environment variable, then `./.mcpslim.json`, then `~/.mcpslim.json`. Every key is optional.

```json
{
  "ignore_keys": ["url", "reactions", "author_association", "debug_*"],
  "keep_keys": ["node_id"],
  "max_str_len": 4000,
  "max_list_len": 100,
  "max_desc_len": 200,
  "skip_tools": ["get_file_contents", "raw_*"],
  "use_default_keys": true,
  "redact_secrets": true,
  "slim_schemas": true,
  "dedupe_calls": true,
  "terse_mode": false,
  "builtin_tools": true
}
```

| Key | Type | Meaning |
|---|---|---|
| `ignore_keys` | `string[]` | Extra keys to drop. These are shell-style globs (`*_url`, `debug_*`) and are added to the defaults. |
| `keep_keys` | `string[]` | Keys that are never dropped by key rules. This wins over `ignore_keys`. |
| `max_str_len` | `int` | Truncate strings longer than this. `0` disables it. |
| `max_list_len` | `int` | Cap arrays at this many items. `0` disables it. |
| `max_desc_len` | `int` | Maximum length of tool, schema and resource descriptions when `slim_schemas` is on. Default `120`. `0` disables truncation. |
| `skip_tools` | `string[]` | Tool-name globs whose results are never touched, including by redaction and deduplication. |
| `use_default_keys` | `bool` | Set to `false` to start from empty `ignore_keys` and `keep_keys` lists. |
| `redact_secrets` | `bool` | Redact credentials in every compressed payload. Default `true`. |
| `slim_schemas` | `bool` | Minify `tools/list` schemas and descriptions, and `resources/list` descriptions. Default `true`. |
| `dedupe_calls` | `bool` | Replace repeated identical `tools/call` results with a short note. Default `true`. |
| `terse_mode` | `bool` | Append ultra-concise reply instructions to the server instructions. Default `true`. |
| `builtin_tools` | `bool` | Expose `slim_fetch` and `slim_extract`. Default `true`. Standalone mode needs it on. |

Invalid config exits with code 2 and a clear message. Unknown keys log a warning.

> **Tip:** On GitHub servers, adding `"url"` to `ignore_keys` drops the `api.github.com` self-link on every object for a few more percent. It isn't a default because for many other servers `url` is the payload.

## Remote deployment (Koyeb, Render, Claude mobile and web)

The included `Dockerfile` runs mcp-slim behind [supergateway](https://github.com/supercorp-ai/supergateway), which turns the stdio server into an HTTP/SSE endpoint on port `8000`:

- `GET /sse` is the event stream to connect to.
- `POST /message` carries client-to-server messages.
- `GET /healthz` is the health check.

```bash
docker build -t mcp-slim .

# Standalone: only slim_fetch and slim_extract
docker run --rm -p 8000:8000 mcp-slim

# Wrap a server: set TARGET_MCP_CMD and pass its credentials as env vars
docker run --rm -p 8000:8000 \
  -e TARGET_MCP_CMD="npx -y @modelcontextprotocol/server-github" \
  -e GITHUB_PERSONAL_ACCESS_TOKEN=<your-token> \
  -e MCPSLIM_ARGS="--quiet" \
  mcp-slim
```

| Env var | Meaning |
|---|---|
| `TARGET_MCP_CMD` | Optional. The stdio MCP server to wrap. If unset, mcp-slim runs standalone. |
| `MCPSLIM_ARGS` | Optional. Extra mcp-slim flags, such as `--quiet` or `--config /config/.mcpslim.json`. |
| `PORT` | The listen port. Default `8000`. |

**Koyeb:** create a Web Service from your fork of this repo with the **Dockerfile** builder. Expose port `8000` over HTTP, set the health check to `/healthz`, and add `TARGET_MCP_CMD` and any tokens as secrets.
**Render:** create a Web Service from the repo with the Docker runtime. Render sets `PORT`, and the image respects it.

**Connecting Claude:** in claude.ai, open **Settings → Connectors → Add custom connector** and enter `https://<your-app>/sse`. Connectors added on claude.ai are also available in the Claude mobile apps.

> ⚠️ **The SSE endpoint has no authentication.** Anyone who learns the URL can call every tool it exposes. That includes a wrapped GitHub server acting with *your* token. Before you wrap anything with credentials, put the service behind an authenticating proxy or a private network, or at minimum use an unguessable hostname and treat the URL as a secret. Standalone mode exposes only the built-in fetch tools, which are guarded against internal targets as described above.

## How it works

`mcp-slim` is built on the official [`mcp` Python SDK](https://github.com/modelcontextprotocol/python-sdk) and supports both the 1.x (≥ 1.10) and 2.x low-level APIs.

1. It spawns the wrapped command as a child process and connects to it as an MCP **client** (`ClientSession` over stdio). In standalone mode this step is skipped.
2. It initialises the upstream server, then serves a low-level MCP **server** on its own stdin and stdout. That server mirrors the upstream's name, version, instructions and capabilities, plus `tools` for the built-in tools.
3. `tools/list`, `tools/call`, `resources/list`, `resources/templates/list`, `resources/read`, `prompts/list` and `prompts/get` are forwarded with their params untouched, including pagination cursors. Upstream JSON-RPC errors are relayed with their original code and message. Built-in tools are appended to the first page of `tools/list`.
4. Results are slimmed on the way back, as described in [What gets compressed](#what-gets-compressed).

The compression code (`compressor.py`) and the built-in tools (`builtin_tools.py`) use only the standard library.

stdout carries only JSON-RPC. All logging, including the wrapped server's stderr, goes to stderr, which MCP clients show as server logs.

### Limitations

- **stdio only.** To wrap a remote (HTTP/SSE) server, put a stdio bridge such as `mcp-remote` after the `--`.
- **`structuredContent` is not modified,** because clients validate it against the tool's `outputSchema`. Clients that show structured output to the model instead of the text blocks won't see savings for those tools.
- **Server-to-client features are not relayed:** progress notifications, sampling, elicitation, roots and `list_changed` notifications are dropped. Tool calls still complete normally.
- Token counts are estimates (about 4 characters per token), not tokenizer-exact.
- The fetch tools check DNS answers before connecting, but `urllib` resolves the name again when it connects. A host that changes its DNS answer between those two lookups (DNS rebinding) can slip past the address check. On a public host, also block outbound traffic to private ranges at the network level.

## Use it as a library

```python
from mcp_slim import compress_payload, compress_schema, load_config, redact_secrets

text, saved = compress_payload(raw_json, load_config())
schema = compress_schema(tool_input_schema, max_desc_len=120)
clean = redact_secrets(log_text)
```

## Contributing

Contributions are welcome. Please open an issue before starting large changes.

```bash
git clone https://github.com/your-org/mcp-slim && cd mcp-slim
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest                    # unit tests plus end-to-end proxy tests
python benchmark.py       # update the README table if numbers change
```

Guidelines:

- **Never write to stdout** outside the MCP transport. Use `logging`, which is configured to write to stderr.
- **Compression must be safe by default.** If a rule could drop information an LLM needs, make it opt-in through `.mcpslim.json`.
- Add a test for every new rule, and a benchmark scenario for every new payload shape.
- Keep `compressor.py` and `builtin_tools.py` free of third-party dependencies.

New default `ignore_keys` for other noisy APIs (Jira, Slack, Notion, …) are especially welcome. Include a sample payload in `benchmark.py`.

## License

[MIT](LICENSE)