Token Optimizer MCP
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
๐ Introduction
Working with Agentic LLMs and large codebases usually means burning through massive context windows, leading to exorbitant API costs and slow response times.
Token Optimizer MCP solves this by providing a suite of highly-optimized tools that intercept requests and ensure the LLM only receives exactly what it needs. It leverages structural chunking, code skeleton extraction, unified Git diffing, and strict character limits to compress payloadsโall while maintaining the semantic context the LLM requires to function.
Additionally, the built-in Token Tracker persistently calculates exactly how many tokens (and estimated dollars) you save on every request.
Related MCP server: Smart Context MCP
๐ ๏ธ Installation
Requirements: Python 3.10+. You can install the package via pip. Choose the installation method based on whether you need semantic search capabilities.
1. Base Installation (Recommended)
This installs the core MCP server and all standard token-optimization tools. It is lightweight and sufficient for most users.
pip install token-optimizer-mcp2. Installation with Embeddings
Use this command if you want to enable the Semantic Search (Vector Store) feature. This installation includes additional dependencies like faiss-cpu and numpy.
Already installed the base package? No problem. Running this command will simply "upgrade" your installation by adding the missing embedding-related dependencies.
pip install "token-optimizer-mcp[embeddings]"โก Features
Smart File Chunking: Never send a 10,000 line file again. Read exact line ranges with hard caps.
Structural Summarization: Extract classes, imports, and function signatures to give the LLM a topological map of a file without the payload of raw code.
Trimmed Search: Recursive codebase searching that returns only file paths and micro-snippets.
Delta Diffing: Returns only the modified lines (
git diff), ensuring unmodified code is never re-processed.Memory Summarization: A persistent JSON store for the LLM to stash compressed conversational context, preventing the need to replay huge histories.
Semantic Code Search (Embeddings):
On-the-fly Indexing: Automatically chunks and indexes your codebase into a vector space.
Similarity Retrieval: Allows the LLM to find relevant code sections by meaning rather than just keywords, using an optimized FAISS vector store.
Efficient Context: Bridges the gap between "knowing the file exists" and "finding the exact relevant snippet" without reading the whole repo.
๐ Usage
Once installed, the CLI tool acts as both the MCP Server entry point and a management interface.
1. MCP Client Configuration
To hook the optimizer up to your agent (e.g., Claude Desktop, Cursor, or Codex, Antigravity), simply define the environment variables and point the command to token-optimizer-mcp:
{
"mcpServers": {
"token-optimizer": {
"command": "token-optimizer-mcp",
"args": ["run"],
"env": {
"ENABLE_TOKEN_TRACKING": "true",
"TOKEN_COST_PER_1K": "0.003"
}
}
}
}2. Management CLI Commands
You can run these commands manually in your terminal to manage the server's cache and view your savings.
Command | Description |
| Starts the MCP server via |
| Starts the MCP server via SSE (HTTP). |
| Prints your lifetime token and monetary savings. |
| Wipes the historical token tracker data. |
| Purges the persisted LLM memory stash. |
Therun commands are typically handled automatically by your MCP client (like Claude Desktop) once configured. You generally don't need to run them manually unless you are testing or debugging.
Example: Checking your savings
$ token-optimizer-mcp stats
๐ Lifetime Token Savings
======================================
Total Requests: 24
Tokens Used: 8,421
Tokens Saved: 114,290
Estimated Savings: $0.3428
Tracking Since: 2024-05-12T10:00:00Z
--------------------------------------โ๏ธ Configuration File (Environment Variables)
The optimizer is configured entirely via Environment Variables. Edit these in your mcpServers config block to tune the aggressiveness of the tokenizer.
Variable | Default | Description |
|
| Absolute path to the repository you are analyzing. |
|
| Hard cap on the number of lines returned by file read tools. |
|
| Global cutoff limit applied to all tool responses. |
|
| Snippet length returned alongside search hits. |
|
| Truncation limit for structural file summaries. |
|
| Toggle the persistent |
|
| Critical for Cost Estimation. This value represents the cost (in USD) of 1,000 input tokens for the model you are using. The tracker uses this to calculate your monetary savings. |
๐ก Understanding TOKEN_COST_PER_1K
Token savings are calculated using a standard heuristic: 1 token โ 4 characters. To get accurate dollar savings, you should match this value to your specific model's pricing:
Claude Sonnet 4.6:
0.003(Default)Claude Opus 4.6:
0.015Google Gemini 3 Pro:
0.0025GPT-5-codex:
0.0020
Check your provider's current pricing. The values above are illustrative and model pricing changes frequently. Always verify the latest "Input Token" price from your AI provider's official documentation.
The metric used is alwaysInput/Prompt tokens, as that is where the optimization (and savings) occur.
Optional Embeddings Variables
(Only relevant if installed via [embeddings])
EMBEDDING_CHUNK_SIZE(Default:50): Lines per chunk for vectorization.FAISS_INDEX_PATH: Absolute path to store the FAISS.faissdatabase.
๐ง Under the Hood
Because Claude, chatGPT, and most Agent frameworks don't know they have unlimited context, they frequently ask for the entire app.js file just to check an import. Token Optimizer MCP intercepts this behavior:
Tool Invocation: The LLM calls
read_file_chunk(path="app.js", start_line=1, end_line=5000).Cap Enforcement: The server intercepts the request limits it to
MAX_FILE_LINES(e.g. 300).Savings Calculation:
token_tracker.pycalculates the token delta between sending the 5000 lines vs the returned 300 lines using an industry-standard heuristic (len(str) / 4).Piggybacked Stats: The server returns the payload alongside the
_token_statsobject. The LLM sees exactly how many tokens it just saved by being constrained.
๐ Bug Reports & Feature Requests
If you encounter a bug or unexpected behavior, please open an issue to report it.
Likewise, if you need a new feature or have an idea for an improvement, you can request it by opening a feature request on GitHub.
๐ License
Distributed under the MIT License. See LICENSE for more information.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
This server cannot be deployed
Related MCP Connectors
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
Agent FinOps Spend Guard, Deterministic Budget Passport, LLM Token Cost Router & VIP Discounts.
Reduces AI Agent token usage by 40% via three-stage SOP workflow.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Related MCP Servers
- AlicenseAqualityBmaintenanceMCP file cache for AI coding agents. Re-reading an unchanged file costs ~40 tokens instead of the whole file; a changed file comes back as a diff. Adds grep, BM25 search and glob over cached files, atomic edits with dry_run, and token-budgeted batch reads. One local daemon serves every client. No API keys, no GPU. Works with Claude Code, Cursor, VS Code, Codex and OpenCode.1479 PyPI3MIT
- AlicenseNot gradedqualityBmaintenanceReduces token consumption for AI coding agents by 50-70% through intelligent code context filtering, Git delta tracking, and local SQLite/Tree-sitter indexing.167 npmMIT
- AlicenseAqualityBmaintenanceEnables AI coding agents to reduce token usage by condensing source code into AST skeletons, extracting specific symbols, compressing logs, and estimating token budgets.4MIT
- AlicenseNot gradedqualityCmaintenanceEnables autonomous context window management, prompt caching, token optimization, and real-time observability for AI coding agents across multiple IDEs, reducing token costs and improving performance.Apache 2.0