slimtoken
SlimToken's MCP server exposes prompt/token optimization and memory-pruning tools for agent/model requests.
Optimize messages: reduce prompt size while preserving structure and tool-call validity; returns minified messages plus token counts, with configurable format, system/tools, and max input tokens.
Estimate tokens: count a request body using the bundled cl100k_base tokenizer and return total plus per-message breakdown.
Prune context: perform RAG-style memory/conversation pruning, retrieve warm entries by query, summarize old turns, enforce a token budget, and return an injectable context block.
Minify tool results: lossily compress large tool_result content using type detection and emit a compact representation with metadata.
Inspect budget: read-only token-budget inspection showing system/tools/messages counts, headroom, and whether pruning would drop leading messages.
Get config: return the active SlimToken configuration from SLIMTOKEN_* environment knobs.
List model presets: show recommended local-model presets by VRAM tier, optionally with live measured token reduction.
List high-context presets: show VRAM-tier dense/MoE configs and effective context expansion, optionally only the best preset.
Optimizes requests to Ollama's local API by reusing the OpenAI conversion to normalize to Anthropic's format, applying token minification, and converting back, reducing input tokens for local model inference.
Optimizes requests to the OpenAI API by converting bodies to Anthropic's canonical format, running the token-minification pipeline, and converting back, thereby reducing input tokens for OpenAI-compatible endpoints.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@slimtoken Can you optimize this request to use fewer tokens?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
SlimToken
A token-optimization and memory layer between your agent and its model.
It rewrites each request before it leaves your machine: duplicate tool output is collapsed to a short pointer, old turns are distilled, and oversized requests are pruned to a token budget. Run it as a proxy, an MCP server, a CLI, or a plain Python library.
Overview · Screenshots · Quick start · Usage · Configuration · License
Overview
SlimToken sits between your agent and its model backend. It runs as a proxy, an MCP server, a CLI or a Python library, and speaks Anthropic, OpenAI and Ollama HTTP.
Why use it:
Cloud models: fewer tokens sent per request means lower API cost and lower rate-limit consumption. Nothing else about the interaction changes.
Local models: fewer tokens to process means faster first token and faster total response. On a CPU backend, prompt processing is often the majority of the wait, so trimming prompt tokens is the cheapest speedup available.
Both: it keeps the conversation below a token budget, so long agent sessions do not hit the model's context limit.
Measured on a local CPU backend with strict prompt caching:
Workload | Before | After | Effect |
Same large tool output read four times | 25,713 | 7,029 | 2.4× faster end-to-end |
13-request growing agent session | 14,161/request | 11,288/request | ~14% faster session |
No repeated content | unchanged | unchanged | no benefit, no harm (~5 ms overhead) |
Related MCP server: everything-slim
Screenshots

Quick start
git clone https://github.com/greyok00/slimtoken
cd slimtoken
./scripts/install.sh # pip install -e . + slimtoken install
slimtoken serve # proxy on port 8181; point your client at itslimtoken install rewrites ANTHROPIC_BASE_URL to point at the proxy. Any
client that sends Anthropic, OpenAI or Ollama requests through it is optimized
without further setup.
Usage
1. In front of a local model server
If a local backend (llama.cpp's llama-server, Ollama, or anything
OpenAI-compatible) answers on port 8080, this is zero-configuration — every
request is trimmed before it reaches the CPU:
llama-server --port 8080 & # your model, unchanged
slimtoken serve --upstream http://127.0.0.1:8080
# clients now point at http://127.0.0.1:8181 instead of :8080On CPU, prompt processing dominates long-context requests, so cutting prompt tokens directly shortens time-to-first-token.
2. In front of a cloud API or coding agent
The proxy speaks HTTPS to the upstream with system CAs, so pointing it at
api.anthropic.com works without certificate setup:
slimtoken serve --upstream https://api.anthropic.com
ANTHROPIC_BASE_URL=http://127.0.0.1:8181 claudeBilling metering reads the same wire format the API does, so the token counts you stop sending are the token counts you stop paying for.
3. As a service, with measured savings
The proxy writes a cumulative stats ledger when SLIMTOKEN_STATS_FILE is set:
# /etc/systemd/system/slimtoken.service
[Service]
Environment=SLIMTOKEN_UPSTREAM=https://api.anthropic.com
Environment=SLIMTOKEN_STATS_FILE=/var/lib/slimtoken/stats.json
ExecStart=/usr/local/bin/slimtoken serveslimtoken savings # requests minified, tokens in/out/saved, mean %, trend
slimtoken savings --json # same, for dashboards
slimtoken latency --port 8181 # per-request timings against a running proxy4. One-off, without a server
The CLI runs the same pipeline over a saved request file, and everything dropped by the dedup stage can be recalled verbatim:
cat request.json | slimtoken optimize # print token counts in/out
slimtoken recall <digest> # return the exact dropped bytes
slimtoken modes --measure # what each mode saves on your text
slimtoken savings # the running proxy's ledger5. Inside an MCP-aware agent runtime
slimtoken-mcp exposes the same pipeline as MCP tools (optimize_messages,
estimate_tokens, prune_context, minify_tool_result, inspect_budget,
get_config, list_model_presets). Also shipped: slimtoken-reframe-mcp
(turns a rambling prompt into a tight instruction with no model call) and
slimtoken-memory-mcp (the memory store).
Web lanes
Every SlimToken proxy answers Ollama-style web routes on its own port, so tools that expect them work even when the local Ollama daemon lacks the routes:
curl -X POST http://127.0.0.1:8181/api/web_search \
-d '{"query": "free ai testing tools", "max_results": 5}'
curl -X POST http://127.0.0.1:8181/api/web_fetch \
-d '{"url": "https://example.com/article"}'web_search: SearXNG first (SLIMTOKEN_SEARXNG, defaulthttp://127.0.0.1:8888), with a keyless DuckDuckGo-lite fallback. Returns{query, lane, results: [{title, url, description}]}.web_fetch: polite user agent, redirects followed, HTML stripped to readable text with a 200 KB cap. Returns{url, status, text, content_type}.Both routes also answer at the unprefixed
/web_searchand/web_fetch.They bypass the minify pipeline, run network I/O off the event loop, and degrade with a JSON error rather than a hang when every lane fails.
What runs by default
The default code mode never rewrites a tool result, never touches model
output, and keeps the newest four messages verbatim. What it removes is a
byte-identical duplicate of something already in the conversation, and it
stores every dropped byte for exact recall.
Stage | Default | Toggle | What it does |
Tool-result dedup | on |
| A byte-identical repeat is replaced with a short pointer at its later position; the last copy stays |
Distill old turns | on |
| Old assistant prose beyond the newest four turns is compressed to extractive summaries; code and JSON are exempt |
Token budget | on (131,072) |
| Prunes whole turns without splitting tool_use/tool_result pairs |
Tool-schema minify | off |
| Drops redundant JSON-schema fields from tool definitions |
System-prompt minify | off |
| Shrinks the system prompt; fenced code stays verbatim |
Message minify | off |
| Collapses blank lines outside code fences |
Output caps | off |
| Caps or truncates streamed completions |
Whole pipeline | on |
| Disables all rewriting for that process |
Two guarantees sit on top:
Prompt-cache safety. A repeat is stubbed at its later position, so earlier messages never change and exact-prefix caches stay valid. Set
SLIMTOKEN_DEDUP_APPEND_ONLY=0only to restore the pre-0.7.2 behavior.Reversibility. Every dropped byte is stored under its SHA-256 digest in
~/.slimtoken/artifactsand can be recalled verbatim.
Modes
slimtoken modes lists them; slimtoken modes --measure prints what each one
saves on your own text.
code(default) — dedup + distill + token budget. Not lossy: nothing is removed that is not stored elsewhere.realtime— lossy, for speech-to-speech conversation only: all five stages on, prose cut to 160 characters per turn, user turns elided too. Do not use it for agent work; elided text still reads as complete, so the model can answer confidently from evidence it no longer has.
SLIMTOKEN_MODE selects a mode; any explicit SLIMTOKEN_MINIFY_<STAGE>
switch overrides the mode for that one stage.
Configuration
Variable | What it controls |
|
|
|
|
| Per-stage toggle ( |
| Token-budget ceiling (default 131072) |
| Newest messages kept verbatim (default 4) |
| Minimum result size before dedup applies (default 200) |
| Prose cutoff per old turn (mode default 4096) |
|
|
| Comma-separated tool names never deduplicated |
|
|
| Backend URL (default |
| Proxy listen port (default 8181) |
| Opt-in HTTP/2 forwarding |
| Path for cumulative minify stats JSON |
| Output caps; off by default |
| Where recalled originals are stored |
| Root for artifacts and stats state |
| TLS to the backend |
| Memory store root (default |
| Path of the lazy-MCP server list |
For provider-side prompt caching, keep the cache-safe stage set:
SLIMTOKEN_MINIFY_MESSAGES=0 SLIMTOKEN_MINIFY_DISTILL=0 SLIMTOKEN_MINIFY_SYSTEM=0. Tools, append-only dedup and the loop guard stay on.
Lossy passes rewrite earlier turns and invalidate the cached prefix.
# Local llama.cpp server (default)
export SLIMTOKEN_UPSTREAM="http://127.0.0.1:8080"
# Ollama instead - local :11434 or an Ollama cloud host
export SLIMTOKEN_UPSTREAM="http://127.0.0.1:11600/v1"Install
Requirements: Python 3.13+ and pip. There are no compiled modules or platform
restrictions. tiktoken is the only non-trivial dependency, and its tokenizer
table ships inside the package for offline use.
git clone https://github.com/greyok00/slimtoken
cd slimtoken && ./scripts/install.sh
# or: pip install .Verify
slimtoken modes --measure # what each mode saves, measured on your tokenizer
slimtoken latency --port 8181 # per-request timings through a running proxy
slimtoken savings # hard savings facts from the stats ledger
python3 -m pytest tests/ # test suiteHow it compares
Tool | Relationship to SlimToken |
CLI coding agents | The agent runs the loop and calls the model directly; SlimToken shrinks each call in between |
Open Interpreter / OpenHands | They host the agent loop in-process; SlimToken is a network sidecar underneath any host |
aider | Manages git-integrated edits; SlimToken edits nothing — it makes the requests around it cheaper |
LangChain-style frameworks | Shape requests inside your app; SlimToken applies the same passes externally to every client |
License
Apache-2.0. See LICENSE.
Available Tools
8 toolsslimtoken.estimate_tokensA
Count tokens in a request body using the real cl100k_base tokenizer (bundled, offline). Returns total + per-message breakdown. The model arg is accepted for forward-compat but the count is cl100k-approximate for non-cl100k models.
Inputs: messages (required), model, tools, format, +1 more.
slimtoken.get_configA
Return the slimtoken config in use: the always-on MinifyConfig built from SLIMTOKEN_* env knobs (the single config surface shared by the proxy, CLI, and MCP server). Useful to see what slimtoken will do.
Inputs: no named parameters.
slimtoken.high_context_presetsA
High-context VRAM-tier configs (dense AND MoE) showing how slimtoken compression expands the effective context window. Each row gives the largest nominal context that fits fully in VRAM (computed by config_optimizer, q4_0 KV, flash attn, full offload) and the effective raw-token capacity = nominal_ctx / (1 - reduction). Use best=true for just the largest-effective-context preset of a tier.
Inputs: best, vram_gb.
slimtoken.inspect_budgetA
Read-only token-budget inspection: counts system/tools/messages, reports headroom against a token_budget, and whether the pair-safe pruner would drop any leading messages. Does not modify the body.
Inputs: messages (required), tools, format, system, +2 more.
slimtoken.list_model_presetsA
List recommended local-model presets by GPU VRAM tier (4/8/16GB), each with a usable context. With measure=true, enriches each row with the live measured token reduction on a bloated payload (run by the pipeline itself).
Inputs: measure, vram_gb.
slimtoken.minify_tool_resultA
Compress a large tool_result content block using type detection (directory listing, git output, logs, JSON, source). LOSSY — emits a compact representation plus a [slimtoken-compressed] metadata header. Pair-safe by construction (only the content field changes).
Inputs: content (required).
slimtoken.optimize_messagesA
Reduce prompt size while preserving message structure and tool-call validity (pair-safe, fence-aware). Returns the minified messages plus token counts. Lossy by default (distill + tool-result compression); disable stages via the SLIMTOKEN_MINIFY_* env knobs.
Inputs: messages (required), tools, format, system, +1 more.
slimtoken.prune_contextA
RAG-style context pruning for a memory/conversation store: strip low-value text, retrieve warm entries relevant to a query, sliding-window summarize old turns, and enforce a token budget. Returns a ready-to-inject <cold_memory>/<recent_context> prompt block.
Inputs: warm_entries (required), query, cold_data, max_tokens.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Several tools overlap in purpose: optimize_messages, prune_context, and minify_tool_result all reduce token counts, while list_model_presets and high_context_presets both list presets. However, descriptions clarify distinct use cases (full prompt vs. memory store vs. tool result; standard vs. high-context configs), so most boundaries are navigable.
Most tools follow a clear verb_noun pattern (optimize_messages, estimate_tokens, prune_context, minify_tool_result, inspect_budget, get_config, list_model_presets), but high_context_presets breaks the pattern as an adjective_noun phrase, causing a minor inconsistency.
With 8 tools, the set is well-scoped for a specialized token optimization server. Each tool addresses a distinct aspect (estimation, minification, pruning, budget inspection, config, presets) without unnecessary bloat or redundancy.
The tool surface covers the core lifecycle of token optimization: estimating, minifying, pruning, inspecting budgets, and retrieving config/presets. Minor gaps exist (e.g., no explicit tool to reverse or restore compressed content), but these are not essential given the lossy and config-driven design.
Maintenance
Related MCP Connectors
MCP server for progressive tool usage at any scale (see https://klavis.ai)
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Free, no-key MCP server: token estimates, JSON Schema conversion, MCP configs, tool search.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceA proxy server that wraps existing MCP servers to significantly reduce token consumption by compressing tool descriptions into a two-step interface. It enables users to integrate extensive toolsets without exceeding context limits or incurring high API costs.144Apache 2.0
- AlicenseNot gradedqualityDmaintenanceToken-optimized MCP server that reduces context window usage by 59.5% by grouping 12 tools into 5 semantic operations, preserving all original functionality for AI assistants.14 npm1MIT
- AlicenseBqualityDmaintenanceLocal MCP server for token optimization, providing tools to compress code/JSON, optimize prompts, and manage placeholder-based content redaction and hydration to reduce LLM token usage.5ISC
- AlicenseNot gradedqualityDmaintenanceMCP server for deterministic, zero-dependency context-window math, enabling token estimation, text truncation, and budget reporting without a tokenizer.MIT