token-optimization-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., "@token-optimization-mcp Estimate tokens for 'Explain quantum computing in simple terms.'"
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.
token-optimization-mcp v0.2.0
Production-ready Model Context Protocol server for token counting, prompt compression, model routing and semantic caching. Zero external API calls — works fully offline.
Tools
Tool | Description |
| Count tokens for any text+model (calibrated chars/token ratios) |
| Shrink prompts with |
| Pick cheapest model meeting quality + context requirements |
| Semantic cache hit/miss by prompt or pre-computed key |
| Store prompt+result with token-savings metadata |
| Remove one or all cache entries |
| Conversation health: role breakdown, issues, recommendations |
| Session-level token/USD savings dashboard |
| Remove duplicate turns, count saved tokens |
Related MCP server: TokenSaver MCP
Quick Start
cd mcps/token-optimization-mcp
uv sync
# stdio – Claude Code / Copilot
uv run main.py
# SSE – LangGraph / CrewAI / browser
uv run main.py --sse --port 8001Environment Variables
Variable | Default | Description |
|
| Enable Redis backend |
|
| Redis connection URL |
|
| Default cache TTL (1 day) |
|
| Requests/min per client |
|
| Print audit log to stdout |
Registration
Claude Code (~/.claude/settings.json)
{
"mcpServers": {
"token-optimization": {
"command": "uv",
"args": ["run", "/path/to/token-optimization-mcp/main.py"]
}
}
}VS Code Copilot (.vscode/mcp.json)
{
"servers": {
"token-optimization": {
"type": "stdio",
"command": "uv",
"args": ["run", "${workspaceFolder}/mcps/token-optimization-mcp/main.py"]
}
}
}SSE (LangGraph / CrewAI / Cursor)
http://127.0.0.1:8001/sseSupported Models (routing catalogue)
Model | Context | Quality | Cost/1k |
| 128k | 8 | free |
| 128k | 7 | $0.00015 |
| 200k | 7 | $0.00025 |
| 1M | 6 | $0.000075 |
| 128k | 9 | $0.005 |
| 200k | 9 | $0.003 |
| 200k | 10 | $0.015 |
Testing
uv run --group test pytest
# 118 tests, 100% coverageArchitecture
token-optimization-mcp/
├── main.py ← FastMCP server (9 tools)
├── pyproject.toml
├── README.md
├── tests/
│ ├── conftest.py ← state-reset fixtures
│ ├── test_helpers.py ← unit tests + Hypothesis
│ └── test_tools.py ← integration tests per tool
└── mcp-servers/
└── context-cache-server/ ← standalone Redis-backed sub-server
├── server.py
├── config.py
└── security.pyAvailable Tools
9 toolsanalyze_contextA
Analyze a list of chat messages ({role, content}) for token usage and issues. Detects bloated system prompts, near-full context windows, and repeated content. Returns per-role breakdown, issues list, and recommendations.
Inputs: messages (required), model. Returns: object
cache_invalidateA
Invalidate one or all cache entries. Pass cache_key to remove one entry, or flush_all=true to wipe everything.
Inputs: cache_key, flush_all. Returns: object
cache_lookupA
Look up a cached result by prompt text or pre-computed cache key. Returns {hit: true, result, tokens_saved} or {hit: false}.
Inputs: prompt, cache_key, client_id. Returns: object
cache_storeA
Store a prompt+result in the cache. Provide prompt (auto-hashed), result text, tokens_saved estimate, optional TTL override and metadata dict.
Inputs: prompt (required), result (required), tokens_saved (required), metadata, +2 more. Returns: object
compress_promptB
Compress a prompt to reduce token usage. strategy: 'trim' (whitespace/blanks), 'summarize_hint' (mark long sections), 'aggressive' (strip comments, examples, filler). Returns compressed text + savings stats.
Inputs: prompt (required), model, strategy, target_tokens. Returns: object
deduplicate_messagesB
Remove duplicate messages from a conversation (keeps last occurrence). Returns deduplicated list + tokens saved.
Inputs: messages (required), model. Returns: object
estimate_tokensA
Estimate token count for a text string. Uses calibrated chars/token ratios per model. Example: estimate_tokens(text='Hello world', model='gpt-4o') → {tokens: 2, ...}
Inputs: text (required), model. Returns: object
route_modelA
Recommend the cheapest capable model for a task. Filter by min_quality (1-10, default 7) and max_cost_per_1k USD. Returns ranked candidates with per-call cost estimate.
Inputs: estimated_tokens (required), min_quality, prefer_free, max_cost_per_1k, +1 more. Returns: object
savings_reportB
Token savings dashboard for the current session. Shows cache hits, tokens saved, and estimated USD savings per client.
Inputs: model. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Each tool targets a distinct operation: caching (store/lookup/invalidate), compression, deduplication, analysis, estimation, model routing, and reporting. No two tools overlap in purpose.
All tool names follow a consistent verb_noun pattern in snake_case (e.g., cache_store, compress_prompt, route_model), making them predictable and easy to differentiate.
With 9 tools, the server covers the core aspects of token optimization without being excessive. Each tool serves a clear need within the domain.
The tool set covers analysis, caching, compression, deduplication, estimation, routing, and reporting. The only minor gap is the lack of a cache listing tool, but the core workflow is complete.
Maintenance
Related MCP Connectors
Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.
LLM cost optimization gateway, repo token-waste auditor & model arbitrage MCP server.
Cloudflare Workers MCP server: ai-cost-optimizer
Related MCP Servers
- AlicenseBqualityDmaintenanceA Model Context Protocol (MCP) server that optimizes token usage by caching data during language model interactions, compatible with any language model and MCP client.42ISC
- AlicenseAqualityDmaintenanceAn MCP server that reduces AI API costs by up to 97% through token measurement, compression, caching, and pruning, all without changing prompts.101Apache 2.0
- 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
- FlicenseNot gradedqualityDmaintenanceAn MCP server suite that optimizes prompt context by reducing tokens up to 98.8%, acting as persistent long-term memory and codebase scanner to save API costs.-