TokenSaver MCP
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., "@TokenSaver MCP compress my 10-turn conversation history"
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.
TokenSaver MCP
Cut your AI API costs by up to 97% — without changing a single prompt.
An MCP (Model Context Protocol) server that gives AI agents ten tools to measure, compress, cache, and prune token usage — so developers on limited plans can do more with less.
Why TokenSaver?
Every API call sends more tokens than necessary. Conversation history accumulates. Web pages arrive as raw HTML. Tool results get re-fetched on every turn. System prompts bloat over iterations.
TokenSaver intercepts each of these patterns and fixes them at the agent level — no model changes, no prompt engineering, no plan upgrades.
Scenario | Before | After | Saved |
10-turn conversation history | 40,000 tokens | 8,000 tokens | 80% |
Webpage fetch (raw HTML) | 22,000 tokens | 1,200 tokens | 94% |
Bloated system prompt | 600 tokens | 220 tokens | 63% |
Repeated tool call (cached) | 1,500 tokens | 50 tokens | 97% |
Related MCP server: claw-tsaver
Tools
Tool | What it does |
| Measure token cost before sending — decide whether to compress first |
| Shrink long text or conversation history with offline LSA summarization |
| Persist tool results to disk with TTL — never run the same lookup twice |
| Fetch a URL and return only the readable content, not raw HTML |
| Get a structural + content summary of any file or directory |
| Remove filler turns and compress old messages in conversation history |
| Shorten verbose system prompts while preserving constraints |
| Diagnose token bloat and get targeted recommendations |
All tools work fully offline — no API key required for core features.
Installation
git clone https://github.com/pozii/tokensaver.git
cd tokensaver
pip install -e .Python 3.11+ required. On first use,
compress_contextwill auto-download the NLTKpunkt_tabtokenizer (~2 MB) if not already present.
How it connects to your AI client
TokenSaver has no URL and runs no background server by default. It uses stdio transport: the AI client reads your config, spawns python -m tokensaver as a child process, and talks to it through stdin/stdout. You never open a port or start anything manually — the client does it for you when it launches.
Your AI client ──spawn──▶ python -m tokensaver ──stdio──▶ tools availableThe alternative is SSE transport, where you start the server yourself on a local port and the client connects over HTTP. This is useful for multi-agent setups or when multiple clients share the same server instance.
Setup
Claude Desktop
Config file location:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"tokensaver": {
"command": "python",
"args": ["-m", "tokensaver"]
}
}
}Save the file and restart Claude Desktop. The tokensaver tools will appear in the tool list.
Claude Code
claude mcp add tokensaver -- python -m tokensaverOr add manually to ~/.claude/settings.json:
{
"mcpServers": {
"tokensaver": {
"command": "python",
"args": ["-m", "tokensaver"]
}
}
}OpenCode
Config file: ~/.config/opencode/config.json
{
"mcp": {
"servers": {
"tokensaver": {
"type": "local",
"command": ["python", "-m", "tokensaver"]
}
}
}
}Any MCP-compatible client (SSE mode)
Start the server once:
python -m tokensaver --transport sse --port 8765Then point your client at:
http://localhost:8765/sseFixing Python path issues
If your system has multiple Python versions and python resolves to the wrong one, use the full path:
# Find the right Python
which python3 # macOS / Linux
where python # WindowsThen use the full path in your config:
{
"mcpServers": {
"tokensaver": {
"command": "/usr/local/bin/python3",
"args": ["-m", "tokensaver"]
}
}
}{
"mcpServers": {
"tokensaver": {
"command": "C:\\Python314\\python.exe",
"args": ["-m", "tokensaver"]
}
}
}Usage
Recommended workflow
Each turn:
1. count_tokens → How large is my current context?
2. advise_context_window → Am I approaching the model's limit?
Before expensive tool calls:
3. cache_get → Did I already run this?
When fetching web content:
4. extract_webpage → Clean text, not raw HTML
When history grows long:
5. prune_conversation → Drop filler turns, compress old ones
6. compress_context → Shrink large injected context blocks
When writing system prompts:
7. optimize_prompt → Remove redundant phrasingTool reference
{
"content": "Some long text or list of messages...",
"model": "claude-sonnet-4",
"include_message_overhead": true
}Returns token_count, encoding_used, model. Accepts a plain string or an OpenAI-format message list.
{
"text": "3,000-token context block...",
"target_tokens": 600,
"mode": "extractive"
}extractive (default) uses LSA sentence ranking — free, offline, no API call.abstractive uses claude-haiku for higher quality — requires ANTHROPIC_API_KEY.
Returns compressed, original_tokens, compressed_tokens, reduction_pct.
# Standard pattern: check before running
key = cache_key("extract_webpage", {"url": "https://example.com"})
hit = cache_get(key=key)
if not hit["hit"]:
result = extract_webpage(url="https://example.com")
cache_store(key=key, value=str(result), ttl_seconds=3600)Cache is stored on disk at ~/.tokensaver/cache/ and survives server restarts.
{
"url": "https://example.com/article",
"max_tokens": 2000,
"include_links": false,
"include_metadata": true
}Uses trafilatura with BeautifulSoup as fallback. Returns content, title, token_count, truncated.
{
"path": "/home/user/myproject",
"mode": "both",
"max_tokens": 500,
"file_extensions": [".py", ".md"],
"max_depth": 3
}mode options: "structure" (tree only), "content" (summarized text), "both".
{
"messages": [...],
"max_output_tokens": 2000,
"keep_last_n": 4,
"prune_strategy": "hybrid"
}"remove" drops filler turns ("Sure!", "Got it.")."compress" summarizes older turns in place."hybrid" does both — recommended for most cases.
Returns the pruned messages list, original_tokens, pruned_tokens, counts of removed/compressed turns.
{
"prompt": "Please make sure to always answer questions...",
"optimization_level": "medium",
"preserve_constraints": true,
"output_format": "prose"
}"light" removes filler phrases. "medium" deduplicates sentences. "aggressive" restructures.preserve_constraints: true always keeps sentences containing never, must, always, do not.
{
"model": "gpt-4o",
"current_tokens": 110000,
"messages": [...],
"target_utilization": 0.75
}Returns status ("ok" / "warning" / "critical"), headroom_tokens, prioritized recommendations, and a per-turn breakdown sorted by token cost.
Supports: GPT-4o, GPT-4o-mini, Claude 3–4 series, Gemini 1.5/2.0/2.5, O1/O3, Llama 3, Mistral.
Optional: LLM-backed summarization
For higher-quality abstractive compression on very large texts (>5,000 tokens):
pip install "tokensaver-mcp[llm]"Set ANTHROPIC_API_KEY in your environment or a .env file, then use mode: "abstractive" in compress_context.
Running Tests
pip install -e ".[dev]"
python -m pytest tests/ -v38 tests — all offline, no API key or network required.
Project Structure
src/tokensaver/
server.py # FastMCP app, tool registration
models.py # Context window table, shared types
tools/
counter.py # count_tokens
compress.py # compress_context
cache.py # cache_store / cache_get / cache_invalidate
extractor.py # extract_webpage
summarizer.py # summarize_file
pruner.py # prune_conversation
optimizer.py # optimize_prompt
advisor.py # advise_context_window
utils/
token_utils.py # tiktoken wrapper
text_utils.py # sentence splitting, deduplicationAvailable Tools
10 toolsadvise_context_windowA
Analyze current token usage vs model context window and recommend what to trim. Use this meta-tool to know WHERE to apply compress_context, prune_conversation, or other tokensaver tools for maximum effect.
Inputs: model (required), current_tokens (required), messages, target_utilization. Returns: object
cache_getA
Retrieve a cached result. If hit, skip re-running the original tool.
Inputs: key (required), namespace. Returns: object
cache_invalidateA
Remove a stale cache entry (e.g. after file changes).
Inputs: key (required), namespace. Returns: object
cache_storeA
Store a tool result in the persistent cache with a TTL. Prevents re-running the same expensive operation twice. Recommended: set key = make_cache_key(tool_name, args).
Inputs: key (required), value (required), ttl_seconds, namespace. Returns: object
compress_contextA
Compress long text or conversation history into a dense summary. Use before re-injecting large context on repeated turns.
Extractive mode (default): offline, free, uses LSA sentence ranking. Abstractive mode: higher quality but requires ANTHROPIC_API_KEY env var.
Inputs: text (required), target_tokens, mode, preserve_format, +1 more. Returns: object
count_tokensA
Estimate token count for text or a message list before sending to an API. Use this to decide whether to compress, prune, or skip content.
Inputs: content (required), model, include_message_overhead. Returns: object
extract_webpageA
Fetch a webpage and return only its main readable content — no HTML, scripts, navigation, ads, or cookie banners. Saves 85–95% of tokens vs raw HTML.
Inputs: url (required), max_tokens, include_links, include_metadata, +1 more. Returns: object
optimize_promptA
Shorten a verbose or redundant prompt/system prompt while preserving intent. Typical savings: 30–65%. Run once on system prompts that accumulate over iterations.
Inputs: prompt (required), optimization_level, preserve_constraints, output_format, +1 more. Returns: object
prune_conversationC
Reduce conversation history token footprint by removing filler turns and compressing older verbose ones. Saves 60–80% on long conversations.
Inputs: messages (required), max_output_tokens, keep_last_n, prune_strategy, +1 more. Returns: object
summarize_fileB
Summarize a file or directory without reading every byte. Agents get full structural understanding in ~500 tokens instead of 50,000+.
Inputs: path (required), max_tokens, mode, file_extensions, +2 more. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Each tool targets a clearly distinct purpose: advising, caching, compressing, counting, extracting, optimizing, pruning, and summarizing. No two tools overlap in functionality, reducing the chance of misselection.
Most tools follow a verb_noun pattern (e.g., compress_context, count_tokens), but the cache tools use noun_verb (cache_get, cache_invalidate). This minor inconsistency prevents a perfect score.
With 10 tools, the server is well-scoped for token management. Each tool covers a necessary aspect (analysis, caching, compression, extraction, counting, optimization, pruning, summarization) without redundancy or bloat.
The tool surface covers the core lifecycle: analyze usage, apply various compressions, cache results, and count tokens. A minor gap is the lack of an automatic application tool that acts on advisement, but the exist set is sufficient for most workflows.
Maintenance
Related MCP Connectors
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
Cloudflare Workers MCP server: ai-cost-optimizer
MCP server for building and testing AI agents with multi-model experimentation and insights.
Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAn MCP server that reduces Manus AI credit usage by up to 75% through intelligent prompt compression, smart model routing, and intent classification. It provides tools to analyze and optimize prompts for maximum efficiency without sacrificing quality.1MIT
- AlicenseAqualityDmaintenanceAn MCP server that helps AI agents reduce token usage by compressing, summarizing, and managing conversation/context data more efficiently.11MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server that helps AI agents reduce token usage by converting data to TOON format and stripping comments and unnecessary whitespace from code files.29 PyPIMIT
- FlicenseAqualityDmaintenanceA fully offline MCP server for token estimation, prompt compression, model routing, and semantic caching to optimize LLM usage costs and efficiency.9-