About ooples/token-optimizer-mcp
ooples/token-optimizer-mcp is an MCP server published by ooples in the Data category: 91.5% fewer tokens on tool output on Headroom's own benchmark, where Headroom removes 61.4%. Separately, the same SWE-bench tasks resolved at 0.71x the cost of plain Claude Code. Plus memory across sessions and subscription quota pacing. Claude Code, Codex, Copilot, Gemini and 12 more. Local, MIT. Conduid read 45 tools from its source: analyze_optimization, analyze_project_tokens, cache_analytics, cache_audit, cache_benchmark, cache_compression and 39 more. It is published to npm as @ooples/token-optimizer-mcp and starts with npx.
The repository has 598 stars and 76 forks, is licensed MIT, and its last commit was on 1 Dec 2026. The latest release is v7.11.0 (14 Nov 2026): Features make agents cheap - cache ttl, agent overhead, spawn costs (#567) (#568) (6a7b75e) Documentation shorten the readme and tidy the repository root (#562) (e7e29ad… It follows v7.10.0 (11 Nov 2026), and the 5 most recent releases go back to v7.7.1 (26 Oct 2026). It passes 4 of the 6 static checks Conduid ran on the repository; it does not pass No dynamic code execution and Scoped permissions. Its topics include data.
Install
claude mcp add token-optimizer-mcp -- npx -y @ooples/token-optimizer-mcp@latestnpx -y @ooples/token-optimizer-mcp@latestgit clone https://github.com/ooples/token-optimizer-mcpTools (45)
analyze_optimizationAnalyze text and provide recommendations for optimization including compression benefits and token savings.| Parameter | Type | Description |
|---|---|---|
| text * | string | Text to analyze |
analyze_project_tokensAnalyze observed token usage across multiple sessions within a project. Aggregates session logs and identifies top contributors. Cost is Not priced unless the caller supplies an effective input-token rate; any resulting value is a cost equivalent, not an invoice.| Parameter | Type | Description |
|---|---|---|
| costPerMillionTokens | number | Optional effective USD cost per million input tokens. No provider price is assumed when omitted. |
| endDate | string | Optional end date filter (YYYY-MM-DD format). |
| projectPath | string | Path to the project directory. If not provided, uses the hooks data directory. |
| startDate | string | Optional start date filter (YYYY-MM-DD format). |
cache_analyticsComprehensive cache analytics with an unmeasured design target of 88%+ token reduction. Real-time dashboards, trend analysis, alerting, heatmaps, bottleneck detection, and cost optimization.| Parameter | Type | Description |
|---|---|---|
| aggregation | string | Aggregation method for metrics |
| alertConfig | object | Alert configuration |
| alertType | string | Type of alert to check |
| cacheTTL | number | Cache TTL in seconds (default: 30) |
| compareWith | string | Period to compare trends with |
| filePath | string | File path for data export |
| format | string | Export data format |
| granularity | string | Time granularity for aggregation |
| heatmapType | string | Type of heatmap to generate |
| metricTypes | array | Types of metrics to collect |
| operation * | string | Analytics operation to perform |
| resolution | string | Heatmap resolution |
| threshold | number | Threshold value for alerts |
| timeRange | object | Time range for analysis |
| trendType | string | Type of trend analysis |
| useCache | boolean | Enable caching of analytics results (default: true) |
cache_auditReport Anthropic prompt-cache economics for this project: measured cache-read input, cache-write input, hit rate, and warm prefix size read from a Claude Code transcript, plus likely invalidation sources. Cost equivalents are labeled Anthropic-specific, excluded from universal savings, and are not invoices.cache_benchmarkCache Performance Benchmarking with 89% token reduction through comprehensive testing and analysis. Features: - Strategy comparison (LRU vs LFU vs FIFO vs TTL vs size vs hybrid) - Load testing with configurable concurrency and ramp-up - Latency profiling with percentiles (p50, p90, p95, p99, p99.9) - Throughput testing (operations per second) - Comprehensive reports in markdown, HTML, JSON, PDF - Workload simulation (read-heavy, write-heavy, mixed, realistic) Operations: - run-benchmark: Execute complete benchmark suite - compare: Compare multiple cache configurations - load-test: Stress test cache under load - latency-test: Measure latency distribution with percentiles - throughput-test: Measure throughput limits - report: Generate comprehensive benchmark report Token Reduction: - Benchmark results: ~89% (summary only) - Comparison: ~91% (rankings + winner) - Load test: ~88% (summary + breaking point) - Latency test: ~87% (percentiles only) - Throughput test: ~90% (key metrics only) - Report: ~85% (formatted summary) - Average: 89% reduction| Parameter | Type | Description |
|---|---|---|
| benchmarkId | string | ID of benchmark results to generate report for |
| cacheTTL | number | Cache TTL in seconds (default: 604800 - 7 days) |
| concurrency | number | Number of concurrent workers (default: 10) |
| config | object | Cache configuration for single benchmark |
| configs | array | Multiple cache configurations for comparison |
| duration | number | Benchmark duration in seconds (default: 60) |
| format | string | Report format (default: markdown) |
| includeCharts | boolean | Include charts in report |
| maxConcurrency | number | Maximum concurrency for load test (default: 100) |
| operation * | string | Benchmark operation to perform |
| outputPath | string | Path to save report |
| percentiles | array | Percentiles to measure (default: [50, 90, 95, 99]) |
| rampUp | number | Ramp-up time in seconds (for load-test) |
| resultsPath | string | File to write the benchmark results to, in addition to returning them |
| stepSize | number | Concurrency step size for load test (default: 10) |
| targetTPS | number | Target transactions per second |
| useCache | boolean | Cache benchmark results (default: true) |
| warmupDuration | number | Warmup duration in seconds (default: 10) |
| workload | object | Shape of the synthetic load to run. Every field is optional. |
| workloadRatio | object | Custom read/write ratio |
| workloadType | string | Type of workload to simulate |
cache_compressionAdvanced compression strategies for cache optimization with an unmeasured design target of 89%+ token reduction. Supports 6 algorithms (gzip, brotli, lz4, zstd, snappy, custom), adaptive selection, dictionary-based compression, and delta compression for time-series data.| Parameter | Type | Description |
|---|---|---|
| algorithm | string | Compression algorithm (auto-selected if not specified) |
| algorithms | array | Algorithms to benchmark |
| autoSelect | boolean | Enable auto-selection of algorithm based on data type |
| cacheTTL | number | Cache TTL in seconds |
| data | any | Data to compress/decompress/analyze |
| dataType | string | Data type hint for adaptive compression |
| defaultAlgorithm | string | Default algorithm for configure operation |
| enableDelta | boolean | Enable delta compression for time-series data |
| includeMetrics | boolean | Include per-algorithm ratio and timing metrics in the result |
| iterations | number | Number of benchmark iterations |
| level | number | Compression level (0-9, higher = better compression) |
| maxLatency | number | Maximum acceptable latency in milliseconds |
| operation * | string | Compression operation to perform |
| sampleSize | number | Bytes of the input to sample when choosing an algorithm, instead of measuring all of it |
| targetRatio | number | Target compression ratio for optimize operation (0-1) |
| testData | any | Data to compress for a benchmark or analysis operation. Any JSON value; a string is used as-is and anything else is serialised first. |
| useCache | boolean | Enable caching of analysis/benchmark results |
| workloadType | string | Workload type for optimization |
cache_invalidationComprehensive cache invalidation with an unmeasured design target of 88%+ token reduction, dependency tracking, pattern matching, scheduled invalidation, and distributed coordination| Parameter | Type | Description |
|---|---|---|
| broadcastToNodes | boolean | Broadcast invalidation to distributed nodes |
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| cascadeDepth | number | Maximum depth for dependency cascade (default: 10) |
| childKey | string | Child key for dependency relationship |
| childKeys | array | Array of child keys for dependency relationship |
| cronExpression | string | Cron expression for scheduled invalidation |
| enableAudit | boolean | Enable audit logging (default: true) |
| executeAt | number | Timestamp when to execute invalidation |
| key | string | Cache key to invalidate |
| keys | array | Array of cache keys to invalidate |
| maxAuditEntries | number | Maximum audit log entries to keep (default: 10000) |
| mode | string | Invalidation mode |
| nodeId | string | Node ID for distributed coordination |
| operation * | string | The cache invalidation operation to perform |
| parentKey | string | Parent key for dependency relationship |
| pattern | string | Pattern for matching keys (wildcards: * for any chars, ? for single char) |
| repeatInterval | number | Interval in ms for repeating scheduled invalidation |
| revalidateOnInvalidate | boolean | Trigger revalidation after invalidation |
| scheduleId | string | ID of scheduled invalidation |
| skipExpired | boolean | Skip expired entries during validation (default: true) |
| strategy | string | Invalidation strategy |
| tag | string | Tag to invalidate all associated keys |
| tags | array | Array of tags to invalidate |
| useCache | boolean | Enable result caching (default: true) |
cache_optimizerAdvanced cache optimization with an unmeasured design target of 89%+ token reduction. Analyzes performance, benchmarks strategies, provides ML-based recommendations, detects bottlenecks, and performs cost-benefit analysis.| Parameter | Type | Description |
|---|---|---|
| analysisWindow | number | Time window in milliseconds for analysis (default: 3600000) |
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| constraints | object | Hard limits the recommendation must respect |
| currentConfig | object | Full cache configuration in use now |
| currentStrategy | string | Eviction strategy in use now, used as the comparison baseline |
| epochs | number | Number of training epochs for tuning (default: 50) |
| includeBottlenecks | boolean | Include the identified bottlenecks rather than the summary alone |
| includeCharts | boolean | Embed charts in a markdown or html report |
| includePredictions | boolean | Include forecast figures alongside the current measurements |
| includeRecommendations | boolean | Include the recommended changes, not just the measurements |
| iterations | number | How many times to repeat a simulation or tuning pass |
| learningRate | number | Step size for the adaptive tuner; larger converges faster and overshoots |
| objective | string | Optimization objective (default: balanced) |
| operation * | string | The optimization operation to perform |
| reportFormat | string | Format for a report operation |
| simulationDuration | number | Simulated time span in seconds |
| strategies | array | Eviction strategies to benchmark |
| targetConfig | object | Full cache configuration to evaluate against the current one |
| targetStrategy | string | Eviction strategy to evaluate against the current one |
| tuningMethod | string | ML tuning method (default: bayesian) |
| useCache | boolean | Enable result caching (default: true) |
| workloadPattern | string | Workload pattern for benchmarking |
| workloadSize | number | Number of synthetic operations to model when simulating a workload |
cache_partitionAdvanced cache partitioning and sharding with an unmeasured design target of 87%+ token reduction through consistent hashing, automatic rebalancing, and partition isolation| Parameter | Type | Description |
|---|---|---|
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| includeKeyDistribution | boolean | Include key distribution in statistics (default: true) |
| includeMemoryUsage | boolean | Include memory usage in statistics (default: true) |
| keyPattern | string | Regex pattern for keys to migrate |
| maxMigrations | number | Maximum number of migrations during rebalance (default: 1000) |
| operation * | string | The partition operation to perform |
| partitionFunction | string | Custom partition function (JavaScript code) |
| partitionId | string | Partition identifier (required for create/delete operations) |
| shardingStrategy | string | Sharding strategy configuration |
| sourcePartition | string | Source partition for migration |
| strategy | string | Partitioning strategy (default: hash) |
| targetDistribution | string | Target distribution strategy for rebalancing (default: even) |
| targetPartition | string | Target partition for migration |
| useCache | boolean | Enable result caching (default: true) |
| virtualNodes | number | Number of virtual nodes per partition (default: 150) |
cache_replicationDistributed cache replication with an unmeasured design target of 88%+ token reduction. Supports primary-replica and multi-primary modes, strong/eventual consistency, automatic conflict resolution, failover, incremental sync, and health monitoring.| Parameter | Type | Description |
|---|---|---|
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| conflictResolution | string | Conflict resolution strategy (for configure operation) |
| conflicts | array | Conflicts to resolve, for a resolve operation. Each entry names the key and the competing local and remote entries. |
| consistency | string | Consistency model (for configure operation) |
| deltaOnly | boolean | Sync only delta changes (for sync operation) |
| enableCompression | boolean | Compress replicated payloads before sending them to peers |
| endpoint | string | Node endpoint URL (for add-replica operation) |
| force | boolean | Force sync even if up-to-date (for sync operation) |
| heartbeatInterval | number | Heartbeat interval in milliseconds (for configure operation) |
| includeMetadata | boolean | Include snapshot data in response (for snapshot operation) |
| mode | string | Replication mode (for configure operation) |
| nodeId | string | Node ID (for add-replica/remove-replica operations) |
| operation * | string | Replication operation to perform |
| readQuorum | number | Number of replicas required for reads (for configure operation) |
| region | string | Region name (for add-replica operation) |
| snapshotId | string | Snapshot ID (for restore operation) |
| syncInterval | number | Sync interval in milliseconds (for configure operation) |
| targetNodeId | string | Target node ID (for promote-replica operation) |
| useCache | boolean | Enable result caching (default: true) |
| weight | number | Node weight for load balancing (for add-replica operation) |
| writeQuorum | number | Number of replicas required for writes (for configure operation) |
cache_warmupIntelligent cache pre-warming with an unmeasured design target of 87%+ token reduction, featuring schedule-based warming, pattern analysis, dependency resolution, and progressive warming strategies| Parameter | Type | Description |
|---|---|---|
| accessHistory | array | Access history for pattern-based warmup |
| batchSize | number | Batch size for warmup (default: 50) |
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| categories | array | Categories to warm (for selective operation) |
| dataSource | object | Where to fetch values from when warming keys that are not cached |
| delayBetweenBatches | number | Delay between batches in ms |
| dependencies | object | Dependency graph for dependency-based warmup |
| dryRun | boolean | Simulate warmup without executing (default: false) |
| enableRollback | boolean | Enable rollback on failures (default: true) |
| endTime | number | Epoch milliseconds after which a scheduled warmup stops |
| hotKeyThreshold | number | Minimum access count for hot keys |
| keys | array | Keys to warm (for immediate/selective operations) |
| maxConcurrency | number | Max concurrent warmup operations (default: 10) |
| maxRetries | number | Maximum retry attempts (default: 3) |
| minAccessCount | number | Minimum access count for hot keys (default: 5) |
| operation * | string | The warmup operation to perform |
| pattern | string | Regex pattern for key matching |
| priority | string | Warmup priority (default: normal) |
| progressInterval | number | Progress report interval in ms |
| reportProgress | boolean | Enable progress reporting (default: true) |
| resolveDependencies | boolean | Warm each key’s dependencies first, in graph order, rather than the listed keys alone |
| retryDelay | number | Delay between retries in ms |
| schedule | string | Cron expression for scheduled warmup (e.g., '0 * * * *' for hourly) |
| scheduleId | string | Schedule ID for cancel operation |
| startTime | number | Epoch milliseconds at which a scheduled warmup becomes active |
| strategy | string | Warmup strategy (default: progressive) |
| timeWindow | number | Time window for pattern analysis in ms (default: 3600000) |
| timeout | number | Timeout for warmup operations in ms (default: 30000) |
| useCache | boolean | Enable result caching (default: true) |
| validateBeforeCommit | boolean | Check each fetched value before writing it into the cache |
| warmupPercentage | number | Percentage of cache to warm (default: 80) |
checkpoint_handoffCreate or restore a resumable checkpoint and return a takeover receipt.| Parameter | Type | Description |
|---|---|---|
| boundary | string | |
| checkpoint * | object | |
| consumer | string | |
| currentState | object | |
| operation * | string |
clear_cacheClear all cached data. Use with caution.| Parameter | Type | Description |
|---|---|---|
| confirm * | boolean | Must be true to confirm cache clearing |
cognition_recordVerify external grader evidence, then propose and activate evidence-backed cognition authored by the active model. Use operation=verify-evidence before recording unfamiliar evidence.| Parameter | Type | Description |
|---|---|---|
| evidenceReceipts * | array | Receipts signed by the configured external deterministic grader. Models must pass them unchanged. |
| kind | string | |
| operation | string | verify-evidence is read-only and returns authenticated observations; record compiles and persists model-authored cognition. |
| semanticObject | object | Compact model-authored delta. Always include trigger, applicability, nonApplicability, invalidators, scope, confidence, confidenceLabel, and expectedOutcome. A failure/guard also includes attemptedAction, observedFailure, rootCause, correction, and verificationEvidence. Other kinds include their kind-specific evidence fields. The server validates the complete contract and rejects omissions. |
| sessionId | string | |
| taskId | string |
compress_textCompress text using Brotli, returned as a base64 string. Intended for AT-REST STORAGE/caching (reduces bytes ~50%). NOTE: base64 tokenizes poorly, so the output usually has MORE LLM tokens than the input — do NOT feed the result into a model context expecting savings. The response includes originalTokens/compressedTokens and a warning when the output would increase tokens.| Parameter | Type | Description |
|---|---|---|
| quality | number | Compression quality (0-11, default 11) |
| text * | string | Text to compress |
context_deltaCompute a unified-diff delta for a file in a given session so the model only sees changes since the last snapshot. Operations: compute-delta, seed, clear.| Parameter | Type | Description |
|---|---|---|
| currentContent | string | The file as it stands now. Required for compute-delta and seed. |
| filePath * | string | File being tracked. Required by every operation. |
| operation * | string | compute-delta: diff currentContent against the last snapshot. seed: record a baseline without producing a diff. clear: forget the snapshot for this file. |
| sessionId * | string | Session the snapshot belongs to. Required by every operation. |
context_pageObtain bounded decision-specific cognition. Returns an explicit empty result when nothing safe applies.| Parameter | Type | Description |
|---|---|---|
| budget | number | |
| query * | string | The current decision or question. |
| sessionId | string | |
| taskId | string | |
| trigger | string |
context_receipt_verifyVerify that one adapter-delivered context receipt and its correction trace to authenticated external grader evidence.| Parameter | Type | Description |
|---|---|---|
| deliveryEventId * | string | The delivery receipt ID supplied by the host adapter. |
count_tokensCount tokens in text using the pluggable tokenizer framework (#124). Picks a model-specific tokenizer (tiktoken for GPT/Claude, Google AI REST for Gemini, content-aware heuristic fallback).| Parameter | Type | Description |
|---|---|---|
| modelName | string | Model name (e.g. gpt-4, claude-opus-4-7, gemini-2.5-flash). Defaults to the server-configured model when omitted. |
| text * | string | Text to count tokens for |
decompress_textDecompress base64-encoded Brotli-compressed text.| Parameter | Type | Description |
|---|---|---|
| compressed * | string | Base64-encoded compressed text |
export_analyticsExport all analytics data in JSON or CSV format. Supports filtering by date range, hook phase, tool name, and MCP server. Useful for external analysis, reporting, and data integration.| Parameter | Type | Description |
|---|---|---|
| endDate | string | Optional end date filter in ISO 8601 format (e.g., 2025-12-31T23:59:59Z) |
| format * | string | Output format: json or csv |
| hookPhase | string | Optional filter by hook phase |
| mcpServer | string | Optional filter by MCP server name |
| startDate | string | Optional start date filter in ISO 8601 format (e.g., 2025-01-01T00:00:00Z) |
| toolName | string | Optional filter by tool/action name |
fleet_auditLook across every project on this machine at once: which projects hold the cost (ranked with dollar figures), which fixes proven in one project apply to others containing the SAME FILE CONTENTS, and how enforcing clients compare with directive ones as a natural experiment (reported with its confound). Reads transcripts and graphs locally, uploads nothing, and names every directory it opened. Use dryRun=true to see what it would read before it reads anything; mode="explicit" with `projects` to scan only what you name.| Parameter | Type | Description |
|---|---|---|
| dryRun | boolean | List what would be read, and read nothing |
| exclude | array | Substrings to skip |
| limit | number | Maximum projects in enumerate mode |
| mode | string | enumerate (default, bounded), all (no cap), explicit (only what you list) |
| projects | array | Project directories, for explicit mode |
| sessionsPerMonth | number | Assumption behind monthly figures. Default 60 |
| tier | string | Pricing tier for dollar figures. Default opus |
get_action_analyticsGet detailed token usage analytics broken down by tool/action (Read, Write, Grep, Bash, count_tokens, etc.). Shows which tools consume the most tokens and identifies optimization opportunities for specific operations.| Parameter | Type | Description |
|---|---|---|
| endDate | string | Optional end date filter in ISO 8601 format (e.g., 2025-12-31T23:59:59Z) |
| startDate | string | Optional start date filter in ISO 8601 format (e.g., 2025-01-01T00:00:00Z) |
get_cache_statsGet cache statistics including hit rate, compression ratio, and token savings.get_cachedRetrieve previously cached and optimized text. Returns the original text if found in cache.| Parameter | Type | Description |
|---|---|---|
| key * | string | Cache key to retrieve |
get_hook_analyticsGet detailed token usage analytics broken down by hook phase (PreToolUse, PostToolUse, SessionStart, PreCompact, UserPromptSubmit). Shows which hook phases consume the most tokens and where optimization efforts should be focused.| Parameter | Type | Description |
|---|---|---|
| endDate | string | Optional end date filter in ISO 8601 format (e.g., 2025-12-31T23:59:59Z) |
| startDate | string | Optional start date filter in ISO 8601 format (e.g., 2025-01-01T00:00:00Z) |
get_mcp_server_analyticsGet detailed token usage analytics broken down by MCP server (token-optimizer, filesystem, github, etc.). Shows which MCP servers are contributing the most to token usage and helps identify cross-server optimization opportunities.| Parameter | Type | Description |
|---|---|---|
| endDate | string | Optional end date filter in ISO 8601 format (e.g., 2025-12-31T23:59:59Z) |
| startDate | string | Optional start date filter in ISO 8601 format (e.g., 2025-01-01T00:00:00Z) |
get_optimization_reportGet a provenance-gated token report. Verified savings require a materialized MCP payload before and after optimization; historical and tool-reported estimates are excluded. Direct API-price equivalents use each exact captured model and route; ambiguous operations remain unpriced.| Parameter | Type | Description |
|---|---|---|
| endDate | string | Optional end date filter in ISO 8601 format (e.g., 2025-12-31T23:59:59Z) |
| sessionId | string | Optional session ID to scope the report to a single session. |
| startDate | string | Optional start date filter in ISO 8601 format (e.g., 2025-01-01T00:00:00Z) |
| topN | integer | Limit each breakdown to the top N rows by tokens saved (default: 10). |
get_session_statsGet comprehensive statistics from the PowerShell wrapper session tracker including system reminders, tool operations, and total tokens with accurate tiktoken-based counting.| Parameter | Type | Description |
|---|---|---|
| sessionId | string | Optional session ID to query. If not provided, uses current session. |
install_doctorCheck that this installation actually works. Runs the real hook binaries with synthetic payloads and asserts a large read is refused and a small one is not, that session-start emits the policy, and that the graph directory is writable and private -- rather than checking that config files exist, which can pass while the plugin saves nothing. Every failure names its fix. Pass uninstallPlan=true to see exactly what a removal would delete and what it would refuse to touch.| Parameter | Type | Description |
|---|---|---|
| client | string | Diagnose this client instead of the one that opened the session (for example "codex"). Defaults to the client named in the MCP handshake. |
| uninstallPlan | boolean | Show what uninstall would remove, changing nothing |
model_routingWhich model tier this project's work actually goes better on, measured from episode outcomes in the client transcript rather than guessed from task size. Reports expected cost per tier including retries, and prices BOTH mistakes: what an overpowered model wastes and what an underpowered one costs in retries. Pass `shape` (multi-file-change, single-file-change, investigation, build-or-test, conversation) and `currentModel` for a decision note that also states what switching would cost in discarded prompt cache.| Parameter | Type | Description |
|---|---|---|
| currentModel | string | The model in use now, e.g. claude-sonnet-5 |
| shape | string | The kind of work about to be done |
optimization_storagePersist and retrieve brotli-compressed optimization results keyed by text hash. Operations: store, retrieve.| Parameter | Type | Description |
|---|---|---|
| operation * | string | store: persist an optimization result. retrieve: read one back by hash. |
| optimizedText | string | The optimized text to store. Required for store. |
| optimizedTokens | number | Token count after optimization. Required for store. |
| originalTextHash * | string | Stable hash of the original uncompressed text. Required by both operations. |
| originalTokens | number | Token count of the original text. Required for store. |
| tokensSaved | number | Tokens saved by optimization. Required for store. |
optimize_sessionAnalyzes operations in the current session from the session JSONL log, identifies large text blocks from file-based tools (Read, Write, Edit), compresses them, and stores them in the cache to reduce future token usage. Returns a summary of the optimization.| Parameter | Type | Description |
|---|---|---|
| min_token_threshold | number | Minimum token count for a file operation to be considered for compression. Defaults to 30. |
| sessionId | string | Optional session ID to optimize. If not provided, uses the current active session. |
optimize_textCompress and cache text to reduce token usage. Returns compressed version and saves to cache for future use.| Parameter | Type | Description |
|---|---|---|
| key * | string | Cache key for storing the optimized text |
| quality | number | Compression quality (0-11, default 11) |
| text * | string | Text to optimize |
outcome_reportRecord correctness-first task outcome and deterministic grader evidence.| Parameter | Type | Description |
|---|---|---|
| episodeId * | string | |
| graderReceipt * | object | |
| outcome * | object | |
| sessionId | string | |
| taskId | string |
predictive_cacheML-based predictive caching with an unmeasured design target of 91%+ token reduction using ARIMA, exponential smoothing, LSTM, and collaborative filtering| Parameter | Type | Description |
|---|---|---|
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| compress | boolean | Compress model export (default: true) |
| confidence | number | Minimum confidence threshold (default: 0.7) |
| epochs | number | Number of training epochs (default: 10) |
| horizon | number | Prediction horizon in seconds (default: 60) |
| key | string | Cache key (for record-access and get-patterns) |
| learningRate | number | Learning rate for training (default: 0.01) |
| maxPredictions | number | Maximum predictions to return (default: 100) |
| metadata | object | Arbitrary key/value context stored alongside the entry and available to the predictor |
| modelFormat | string | Model export format (default: json) |
| modelPath | string | Path to model file (for export/import) |
| modelType | string | Model type (default: hybrid) |
| operation * | string | The predictive cache operation to perform |
| timestamp | number | Access timestamp (for record-access) |
| trainData | array | Training data (for train operation) |
| useCache | boolean | Enable result caching (default: true) |
| warmBatchSize | number | Number of keys to warm (default: 50) |
| warmStrategy | string | Cache warming strategy (default: adaptive) |
smart_api_fetchExecute HTTP requests with intelligent caching and retry logic. Features: - Automatic retry with exponential backoff (1s, 2s, 4s, 8s) - Response caching with TTL-based invalidation (default: 5 minutes) - Request deduplication for in-flight requests - Circuit breaker pattern (opens after 5 consecutive failures) - ETag/Cache-Control header support - 83% average token reduction through intelligent output formatting Token Reduction Strategy: - Cached responses: 95% reduction (summary only) - Error responses: 90% reduction (error details only) - Retried requests: 85% reduction (success summary with retry info) - First requests: 80% reduction (compact summary) Perfect for: - API integration and testing - Webhook handling - External service communication - Data fetching with resilience| Parameter | Type | Description |
|---|---|---|
| body | any | Request body for POST/PUT/PATCH (optional) |
| followRedirects | boolean | Follow HTTP redirects (default: true) |
| force | boolean | Force fresh request, ignore cache (default: false) |
| headers | object | Request headers (optional) |
| includeFullResponse | boolean | Return the full response body alongside the compacted summary (default: false) |
| maxRetries | number | Maximum retry attempts (default: 3) |
| method * | string | HTTP method |
| parseJson | boolean | Parse response as JSON (default: true) |
| timeout | number | Request timeout in milliseconds (default: 30000) |
| ttl | number | Cache TTL in seconds (default: 300) |
| url * | string | Request URL |
smart_cacheAdvanced multi-tier cache with an unmeasured design target of 90%+ token reduction, 6 eviction strategies, stampede prevention, and automatic tier management| Parameter | Type | Description |
|---|---|---|
| cacheTTL | number | Cache TTL in seconds (default: 300) |
| compressionEnabled | boolean | Compress entries before storing them |
| defaultTTL | number | Default TTL in milliseconds (for configure operation) |
| evictionStrategy | string | Eviction strategy (for configure operation) |
| exportDelta | boolean | Export only changes since last snapshot (for export operation) |
| importData | string | JSON data to import (for import operation) |
| key | string | Cache key (for get/set/delete/promote/demote operations) |
| keys | array | Array of keys (for batch-get operation) |
| l1MaxSize | number | Maximum L1 cache size (for configure operation) |
| l2MaxSize | number | Maximum L2 cache size (for configure operation) |
| metadata | object | Arbitrary key/value context stored alongside the entry |
| operation * | string | The cache operation to perform |
| targetTier | string | Target tier (for promote/demote operations) |
| tier | string | Cache tier (for set operation, default: L1) |
| ttl | number | Time-to-live in milliseconds |
| useCache | boolean | Enable result caching (default: true) |
| value | string | Value to store (for set operation) |
| values | array | Array of key-value pairs (for batch-set operation) |
| writeMode | string | Write mode (for configure operation) |
smart_cache_apiAPI Response Caching with 83% token reduction through intelligent cache management. Features: - Multiple caching strategies (TTL, ETag, Event-based, LRU, Size-based) - Intelligent cache key generation with query normalization - Pattern-based and tag-based invalidation - Stale-while-revalidate support - Cache hit rate analysis and recommendations - Cache warming and preloading Actions: - get: Retrieve cached API response - set: Cache an API response - invalidate: Remove cached entries (pattern/tag/manual) - analyze: Get cache performance metrics - warm: Pre-cache specific endpoints Token Reduction: - Cache hit: ~95% (summary only) - Cache miss: 0% (full response) - Stale cache: ~95% (stale summary) - Invalidation: ~98% (count only) - Analysis: ~90% (statistics only) - Average: 83% reduction| Parameter | Type | Description |
|---|---|---|
| action * | string | Cache operation to perform |
| endpoints | array | Endpoints to warm (for warm action) |
| ignoreHeaders | array | Headers to exclude from cache key |
| includeDetails | boolean | Include per-entry detail rather than totals only |
| invalidationPattern | string | Invalidation pattern to use |
| maxCacheSize | number | Maximum cache size in bytes |
| maxEntries | number | Maximum number of cache entries |
| normalizeQuery | boolean | Normalize query parameters (default: true) |
| pattern | string | URL pattern for invalidation (e.g., /api/users/*) |
| request | object | API request data (for get/set) |
| response | any | API response data (for set) |
| since | string | Only entries created or updated after this ISO-8601 timestamp |
| staleTime | number | Time before considering cache stale (seconds) |
| staleWhileRevalidate | boolean | Enable stale-while-revalidate |
| strategy | string | Caching strategy to use |
| tags | array | Tags for grouping cached entries |
| ttl | number | Time-to-live in seconds (default: 3600) |
smart_databaseDatabase query optimizer with connection pooling, circuit breaking, and an unmeasured design target of 83% token reduction. Supports query execution, EXPLAIN analysis, performance optimization, health monitoring, slow query detection, and batch operations.| Parameter | Type | Description |
|---|---|---|
| action | string | Action to perform (default: query) |
| analyzeIndexUsage | boolean | Report which indexes the query used, and which were available but unused |
| batchSize | number | Batch size for batch operations (default: 100) |
| circuitBreakerThreshold | number | Consecutive failures before the breaker opens |
| circuitBreakerTimeout | number | Milliseconds the breaker stays open before retrying |
| connectionString | string | Full connection string. Takes precedence over the individual host/port/database fields. |
| connectionTimeout | number | Milliseconds to wait for a connection before failing |
| database | string | Database name |
| detectN1 | boolean | Flag repeated similar queries that look like an N+1 pattern |
| enableCache | boolean | Enable query result caching (default: true) |
| enableCircuitBreaker | boolean | Enable circuit breaker pattern (default: true) |
| enableRetry | boolean | Enable automatic retry on failure (default: true) |
| engine | string | Database engine (default: generic) |
| explain | boolean | Attach the query plan for a SELECT |
| force | boolean | Force fresh query, bypassing cache (default: false) |
| host | string | Database host |
| idleTimeout | number | Milliseconds an idle connection is kept before being closed |
| includeMetadata | boolean | Include column types and row counts alongside the rows |
| limit | number | Maximum rows to return (default: 10) |
| maxPoolSize | number | Maximum pool size (default: 20) |
| maxRetries | number | Maximum retry attempts (default: 3) |
| minPoolSize | number | Connections kept open even when idle |
| parallelBatches | number | Number of parallel batch operations (default: 4) |
| params | array | Query parameters for prepared statements |
| password | string | Password. Prefer a connection string sourced from the environment over passing this in a tool call, which puts the secret in the transcript. |
| poolSize | number | Connection pool size (default: 10) |
| port | number | Database port |
| queries | array | Array of queries for batch execution |
| query | string | SQL query to execute (required for query/explain/analyze/optimize) |
| slowQueryThreshold | number | Slow query threshold in milliseconds (default: 1000) |
| timeout | number | Query timeout in milliseconds (default: 30000) |
| ttl | number | Cache TTL in seconds (default: 300) |
| user | string | Username |
smart_graphqlGraphQL query optimizer with complexity analysis and caching (unmeasured design target: 83% token reduction)| Parameter | Type | Description |
|---|---|---|
| analyzeComplexity | boolean | Enable complexity analysis (default: true) |
| detectN1 | boolean | Detect N+1 query problems (default: true) |
| endpoint | string | GraphQL endpoint for schema introspection (optional) |
| force | boolean | Force fresh analysis (bypass cache) |
| operationName | string | Operation name (optional) |
| query * | string | GraphQL query to analyze |
| suggestOptimizations | boolean | Suggest query optimizations (default: true) |
| ttl | number | Cache TTL in seconds (default: 300) |
| variables | object | Query variables (optional) |
smart_migrationDatabase migration tracker with status monitoring and an unmeasured design target of 83% token reduction. Supports listing migrations, checking status, viewing history, rollback operations, and migration generation.| Parameter | Type | Description |
|---|---|---|
| action | string | Action to perform (default: list) |
| direction | string | Migration direction for rollback (default: down) |
| force | boolean | Force fresh analysis, bypassing cache |
| limit | number | Maximum number of results (default: 20 for list/pending, 50 for history) |
| migrationId | string | Migration ID (required for rollback and generate actions) |
| ttl | number | Cache TTL in seconds (default: 3600) |
smart_ormORM query optimizer with N+1 detection (unmeasured design target: 83% token reduction)| Parameter | Type | Description |
|---|---|---|
| analyzeRelationships | boolean | Analyze relationship patterns (default: false) |
| detectN1 | boolean | Detect N+1 query problems (default: true) |
| estimateQueries | boolean | Estimate generated SQL queries (default: false) |
| force | boolean | Force fresh analysis, bypass cache (default: false) |
| modelDefinitions | string | Optional schema/model definitions for enhanced analysis |
| ormCode * | string | ORM query code to analyze (Prisma, TypeORM, Sequelize, Mongoose) |
| ormType * | string | ORM framework type |
| suggestEagerLoading | boolean | Suggest eager loading optimizations (default: true) |
| ttl | number | Cache TTL in seconds (default: 3600) |
token_auditThe one thing to run. A single ranked queue of what is costing the most in this project -- waste detectors, prompt-cache invalidation attributed to a file and line, and model routing -- each priced per session and per month, each naming how to act on it. Reports what already-applied fixes actually saved, whether habits improved since the advice, and its own token cost; findings worth less than their printing cost are withheld unless full=true. Pass decline="<id>" to stop being told about something.| Parameter | Type | Description |
|---|---|---|
| decline | string | A finding id you do not want raised again |
| full | boolean | Show every finding, including ones cheaper than printing them |
| sessionsPerMonth | number | Assumption behind the monthly figures. Default 60 |
| tier | string | Pricing tier for the dollar figures (haiku, sonnet, opus). Default opus |
waste_auditReport behavioural token waste in this project, ranked by cost per session and compared against the previous week. Detectors are a shipped floor plus patterns derived from this project's own history, each carrying what it has actually saved. Use action="apply" to put the fixes we own into force (reversible and measured), or action="revert" with an id to undo one. Changes to your own files are only ever proposed as a diff.| Parameter | Type | Description |
|---|---|---|
| action | string | Default "report" |
| id | string | Rule id, required for revert and optional for apply |
Security checks
Static checks derived from the repository 2 days ago. Heuristics on the source, not an audit.
- ✓README presentThe repository's README runs to about 2.6K words.
- ✓License declaredThe repository declares the MIT license.
- ✓Tests presentA test suite exists in the repository.
- ✓Dependencies pinnedDependency versions are pinned by package-lock.json.
- !No dynamic code executionScanned 1.5K source files and found 26 calls to eval or shell execution, in src/hooks-core/harvest.mjs:720, src/hooks-core/toolprune.mjs:749 and src/integrations/cline/hooks/token-optimizer/lib/harvest.mjs:722 among others. Review how tool inputs reach them before granting credentials.
- !Scoped permissionsDoesn't declare a permission scope. Assume it can do anything its process can.
What the source scan found
- Transport
- stdiosrc/server/mcp-server.ts:9
- Starts other programs
- 238 callssrc/cli-wrapper.mjs:118, src/hooks-core/ask.mjs:23, src/hooks-core/codexprune.mjs:366
- Outbound network calls
- 33 callssrc/core/summarization.ts:130, src/core/summarization.ts:216, src/core/tokenizers/google-ai-tokenizer.ts:69
- Writes or deletes files
- 12 callssrc/analytics/analytics-storage.ts:66, src/core/cache-engine.ts:260, src/core/cache-engine.ts:286
- Lockfile
- package-lock.json
Pattern matches on the source text of 1516 files: places to read, not proof of what the code does at run time.
Releases
README
The repository's README runs to about 2.6K words, fetched 2 days ago. The original in the repository is authoritative.
Read full README