{
  "markdown": "[![MCP Toplist](https://mcptoplist.com/badge/io.github.ooples%2Ftoken-optimizer-mcp.svg)](https://mcptoplist.com/server/io.github.ooples%2Ftoken-optimizer-mcp)\n\n<h1 align=\"center\">Token Optimizer MCP</h1>\n\n<p align=\"center\">\n  <strong>Spend less context, keep the conclusions, and audit every claim across 16 coding clients.</strong>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://www.npmjs.com/package/@ooples/token-optimizer-mcp\"><img src=\"https://img.shields.io/npm/v/%40ooples%2Ftoken-optimizer-mcp?logo=npm\" alt=\"npm version\"></a>\n  <a href=\"https://github.com/ooples/token-optimizer-mcp/actions/workflows/ci.yml\"><img src=\"https://github.com/ooples/token-optimizer-mcp/actions/workflows/ci.yml/badge.svg?branch=master\" alt=\"CI\"></a>\n  <a href=\"./LICENSE\"><img src=\"https://img.shields.io/badge/license-MIT-blue.svg\" alt=\"MIT license\"></a>\n  <a href=\"https://nodejs.org/\"><img src=\"https://img.shields.io/badge/node-%3E%3D22-339933?logo=node.js&logoColor=white\" alt=\"Node.js 22+\"></a>\n</p>\n\n<p align=\"center\">\n  <img src=\"https://img.shields.io/badge/enforced-by%20default-2ea043\" alt=\"Enforced by default\">\n  <img src=\"https://img.shields.io/badge/clients-16-8b5cf6\" alt=\"16 clients\">\n  <img src=\"https://img.shields.io/badge/direct%20savings-before%20%2F%20actual%20return-3b82f6\" alt=\"Direct savings measured before and after\">\n  <img src=\"https://img.shields.io/badge/telemetry-none-2ea043\" alt=\"No telemetry\">\n  <img src=\"https://img.shields.io/badge/commercial%20use-MIT%2C%20allowed-0d9488\" alt=\"MIT, commercial use allowed\">\n</p>\n\n<p align=\"center\">\n  <img alt=\"Live Token Optimizer dashboard separating verified net MCP transport savings, excluded reports, per-agent attribution, and graph evidence\" src=\"./docs/media/live/overview-live.png\" width=\"1000\">\n</p>\n\n<p align=\"center\"><em>One local ledger for optimizer tools, live-graph substitutions, every agent, and the graph's own cost.</em></p>\n\n---\n\n## The 30-second version\n\nYour agent burns most of its context on work it already did: re-reading files\nthat have not changed, dumping a whole file to see three lines, running\nunbounded searches, and re-deriving conclusions it reached last session and then\nforgot.\n\nToken Optimizer attacks that on four fronts.\n\n**1. It makes the expensive call impossible.** Install the plugin and a built-in\n`Read` of a 200 KB file is **denied**, with the refusal naming the cached,\ndiffed replacement. Same for `Grep`, `Glob`, `Edit`, `Write`, and `cat` /\n`head` / `grep -r` through the shell. **Re-reading a file you already read this\nsession returns only a diff** — usually the single biggest win, and one that\nsize-based rules structurally cannot catch. There is no setting to turn on.\n\n**2. It remembers what your agent worked out.** A per-project knowledge graph\naccumulates findings, decisions and dead ends as a side effect of working, then\nfeeds them back the moment the agent touches the relevant file. A finding costs\n~150 tokens to carry. Re-deriving it costs 5k–50k.\n\n**3. It measures itself, in public, and tells you when it is losing.** A\nmaterialized before/actual-return measurement for MCP progressive disclosure,\nwith later expansions debited from the same net. Modeled graph substitutions\nand the randomized control arm for downstream graph effects remain separate.\nEvery number is measured, visibly collecting, excluded, or absent.\n\n**4. It attributes the traffic.** Returned context, optional cost equivalents,\nand net transport avoided are grouped by operation and MCP handshake identity. Codex, Claude Code,\nGemini, and any other connected client get separate rows. Old records without\nidentity remain explicitly unattributed instead of being assigned to whichever\nagent happens to be open now.\n\nNo account, no telemetry, no hosted service. MIT, so it is usable at work.\n\n### What the dashboard proves on a real machine\n\nThe screenshots in this README come from the shipped server reading persisted\nlocal data, not a design mockup. In the capture above it reports:\n\n- **43,491 net verified MCP transport tokens avoided** in the current live\n  proof: 54,037 gross reduction minus a deliberate 10,546-token expansion;\n- **486,074,740 historical/tool-reported tokens quarantined**, dominated by\n  repository scan volume that never entered model context;\n- a live Codex / Claude Code / Gemini stdio smoke against AiDotNet, with each\n  client attributed independently;\n- **2,648 graph nodes, 6,527 edges, and 58 findings** across 11 local projects;\n- **more than 1,000 hook runs with zero failures and zero timeouts** across six\n  active CLI clients in the selected rolling 24-hour window;\n- **6,332 tokens of modeled graph-substitution potential**, excluded from the\n  verified headline while the causal graph-reuse study remains `Collecting`.\n\nThe dashboard now reads native CLI usage receipts and prices uncached input,\ncache reads, cache writes, and output with the exact captured provider, model,\nroute, request-time tier, and versioned official source. Ambiguous model ids stay\n**Not priced** instead of receiving a blended guess. API/list-price equivalents\nare kept separate from provider-reported charges and are never labeled as a\nsubscription invoice. See the [token accounting contract](./docs/TOKEN_ACCOUNTING.md).\n\n## Quick start\n\n**Claude Code** — install the plugin, not the bare MCP server. The plugin is\nwhat enforces; adding the server alone just gives the model tools it can ignore.\n\n```text\n/plugin marketplace add ooples/token-optimizer-mcp\n/plugin install token-optimizer@token-optimizer\n/reload-plugins\n```\n\nThat is the entire installation. [All sixteen clients →](#installation)\n\nThen, whenever you want to know what to do next:\n\n```text\ntoken_audit\n```\n\nOne ranked queue: what is costing the most per session, with an optional monthly\ncost equivalent only after you configure your own effective rate. Each line\nnames how to fix it. Not a dashboard, not six reports — a queue.\n\n---\n\n## The knowledge graph — the part nothing else has\n\nEvery agent session ends the same way: the reasoning evaporates. The next\nsession re-derives it, at full price, forever.\n\nThis builds a **living per-project graph** — nodes for files, symbols, tasks and\nfindings; edges for `derived_from`, `contains`, `supersedes`, `contradicts`,\n`related` — and it fills itself in from real work. No ingestion job, no\nembedding model, no rebuild step, no query to formulate.\n\n```\nyou touch  src/auth.ts\n           │\n           ├─ verify() compares exp against the LOCAL clock          (finding, 0.9)\n           ├─ per-host retry budgets; global was rejected — deadlock (decision)\n           ├─ ! the skew fix was reverted once already               (dead end)\n           └─ [git] 47 changes in 90d, last three: \"fix token expiry\",\n                    \"revert skew fix\", \"fix token expiry again\"\n```\n\nNone of that is in your repository. It exists only because an agent once burned\ntokens finding it out — and every other tool throws it away at the end of the\nsession.\n\n**What a default install actually produces.** The structural graph — files,\nsymbols, tasks, and the edges between them — is captured from ordinary tool\ntraffic with no configuration at all. Findings are produced two ways. At session\nend, `derive` reads evidence already on disk (command outcomes and exit codes,\nred-to-green transitions, corrections, re-read churn) and writes findings from\nit: no model call, no credential, nothing sent anywhere. And the active model\nrecords durable conclusions itself through `wiki_write`.\n\nThe **model-based semantic harvest** is the third path, and the only one that\nneeds something you do not already have. It is **not opt-in** —\n`TOKEN_OPTIMIZER_HARVEST=0` turns it *off* — but its real gate is a credential:\nwith none it reports `off:no-key`, which is the state on CI, corporate machines,\nand subscription-only logins. Point `TOKEN_OPTIMIZER_HARVEST_ENDPOINT` at a\nlocal model and it runs **free and private, with nothing leaving the machine**.\n`npx token-optimizer-doctor` states which of these is live.\n\n### Why this is not RAG\n\n| Classic RAG                                                    | This                                                                          |\n| -------------------------------------------------------------- | ----------------------------------------------------------------------------- |\n| Retrieves **evidence**; the model re-derives meaning each time | Retrieves **verdicts** — the reasoning already happened                       |\n| Index built by a **batch ingestion job**                       | Accretes from **real agent traffic** — coverage follows attention             |\n| **Similarity** search                                          | **Traversal** — this symbol _and its callers_                                 |\n| Model must **formulate a query**                               | Fires when the model **reaches for a file**                                   |\n| Staleness **invisible**; serves rotted chunks confidently      | Staleness **computed** from content hashes, served with the invalidating diff |\n| Returns only what is **in the documents**                      | Returns **dead ends**, which exist nowhere in your source tree                |\n\nTraversal plus lexical search: deterministic, instant, explainable, and it works\noffline.\n\n### The zero-turn refusal\n\nA plain deny costs a full turn: the model calls `Read`, is refused, re-plans,\ncalls `smart_read`. But at refusal time we already hold the file _and_ the\nsnapshot the graph stored — so the refusal **carries the answer inside it**.\nNothing to re-plan, no second call. Turn cost drops from one to zero.\n\nAnd when the graph already holds the verdict a tool output would support, the\noutput never enters context at all. Not compressed. Absent.\n\n---\n\n## The dashboard\n\n```bash\nnpm install\nnpm run build\nnpm run dashboard      # http://localhost:3100\n```\n\n<p align=\"center\">\n  <img alt=\"Per-agent token accounting with historical rows left unattributed and live Codex, Claude Code, and Gemini rows measured separately\" src=\"./docs/media/live/agent-accounting-live.png\" width=\"1000\">\n</p>\n\nThe overview answers the questions a token optimizer should answer first:\n\n1. **How much MCP context did it avoid?** The headline is gross materialized\n   payload reduction minus every later linked expansion. Graph estimates are\n   intentionally separate.\n2. **How much context still reached the agents?** Every successful current MCP\n   result records its actual returned text, even when no valid before-state\n   exists. That row is context-accounted but savings-unmeasured.\n3. **Which agent and action spent it?** The client ledger and action table show\n   operations, returned context, optional cost equivalent, and net tokens\n   avoided. Lifecycle-only clients say `Not measured`; no zero is invented.\n4. **Did remembering cost more than it saved?** Delivery and semantic-harvest\n   tokens are charged to the graph. A causal benefit is added only after the\n   treated/holdout evidence gate passes.\n\n### Walkthrough: get useful data, not an empty dashboard\n\n1. Install the MCP server and the native adapter for your CLI. The MCP handshake\n   provides per-client accounting; native lifecycle hooks provide automatic\n   routing, capture, health, and delivery where the client protocol permits it.\n2. Use `smart_read`, `smart_grep`, `smart_glob`, `smart_edit`, or any other MCP\n   operation normally. Every successful result records returned context; tools\n   with a comparable materialized before-state also record a gross reduction;\n   later `expand` calls debit that reduction.\n3. Let the active model record durable conclusions with `wiki_write`. Before a\n   new agent re-derives work, call `wiki_read` for the project or the files it is\n   about to touch. Native clients can also deliver matching knowledge\n   automatically.\n   Use `wiki_query` to read the graph directly — one finding by key, a ranked\n   BM25 search over claims, a node with its neighbours, or the graph's own audit\n   — which is how a subagent that never sees the SessionStart briefing reaches\n   what previous sessions established.\n4. Open `http://localhost:3100`. Use **Overview** for combined accounting and\n   **What it knows** for capture health, graph exploration, audits, and causal\n   evidence.\n5. To register existing local repositories without reading their source, run\n   `npm run projects:discover -- /absolute/path/to/repos`. This makes coverage\n   gaps explicit; it does not fabricate findings.\n\nFor maintainers, this live smoke exercises the shipped stdio transport and\ncreates separately attributed rows without seeding the analytics database:\n\n```bash\nnpm run dashboard:attribution-smoke -- /absolute/path/to/project /absolute/path/to/large-file\nnpm run dashboard:verify-live -- http://localhost:3100\n```\n\n<p align=\"center\">\n  <img alt=\"Structured cross-client hook and MCP health cards from live local data\" src=\"./docs/media/live/capture-health-live.png\" width=\"1000\">\n</p>\n\nThe health panel is deliberately operational rather than a raw text dump. Each\nclient has activity, runtime failures/timeouts, policy outcomes, and observed\nsurface coverage. Diagnostics keep no prompts, commands, paths, or tool output.\n\n<p align=\"center\">\n  <img alt=\"Direct graph savings, remembering cost, holdouts, and an honest collecting causal study\" src=\"./docs/media/live/graph-balance-live.png\" width=\"1000\">\n</p>\n\nModeled substitution potential and causal graph effects are different claims.\nThe first is a full-file counterfactual and is never promoted to the verified\nMCP headline. The second asks whether delivered knowledge prevented later reads;\nit uses a control arm and remains `Collecting` until there are at least 20\ntreated file touches and 5 holdouts with valid downstream joins.\n\n<p align=\"center\">\n  <img alt=\"Interactive 3D knowledge graph spanning eleven local projects\" src=\"./docs/media/live/graph-explorer-live.png\" width=\"1000\">\n</p>\n\nDrag to orbit, scroll to zoom, click a node for provenance, or switch to the\nbounded one-hop focus view. The default **All known projects** scope pools local\ngraphs through opaque project IDs; filesystem paths never reach the browser.\n\n**Audit tab.** Contradictions, stale findings, and low-confidence claims remain\nreviewable instead of silently becoming model truth.\n\n**Evidence console.** Client/model/task cohorts, matched effects with 95%\nintervals, live outcome joins, harm feedback, and capability tiers for all 16\nclients. Release and superiority claims fail closed while evidence is missing.\n\n**One-click Markdown export.** The accumulated graph becomes documentation you\ncan inspect, edit, and commit.\n\nServer-side by design: the browser asks for a neighbourhood, a search result or\na page. A mature graph holds thousands of nodes, and shipping it wholesale would\nmake every page load a multi-megabyte download for a view that shows twenty\nthings.\n\nThe default **All known projects** scope combines captured graphs through an\nopaque machine-local project registry; filesystem paths never reach the\nbrowser. Lifecycle hooks register repositories as they are used. To backfill\nexisting local checkouts without reading their source files, run the bounded\ndiscovery command against one or more explicit roots:\n\n```bash\nnpm run projects:discover -- /absolute/path/to/repos /absolute/path/to/worktrees\n```\n\nCoverage distinguishes repositories with graph data from known repositories\nwhose capture has not started. The balance cards are backed by persisted events:\n**Memory deliveries** counts graph context actually supplied to an agent,\n**Kept back for comparison** counts randomized control touches, and **Cost of\nremembering** combines delivered-context tokens with measured semantic-write\npayload cost. **Reading avoided** stays `Collecting` or `Not measured` until at\nleast 20 treated file touches and 5 holdouts exist with a downstream join; the\ndashboard does not manufacture a savings estimate from missing data.\n\nSee [the causal evidence protocol](docs/EVIDENCE_PROTOCOL.md), the\n[cross-client capability contract](docs/CLIENT_SUPPORT.md), and the\n[live evaluation suite](evals/README.md).\n\n### Cross-client lifecycle diagnostics\n\nEvery native hook writes the same bounded JSONL lifecycle record, including\nClaude Code's custom router and compaction paths. Records carry the client and\nplugin versions, event, hashed session/turn correlation, latency, outcome,\ninput/output byte counts, and response key shape. They deliberately retain no\nprompt, command, tool output, file content, or raw working-directory path. The\nfields include OpenTelemetry log severity and resource semantics so the local\nfiles can be collected without inventing a second schema.\n\n```bash\nnpm run diagnostics                         # last 24 hours, summary-first JSON\nnpm run diagnostics -- --hours 72 --output hook-summary.json\nnpm run diagnostics -- --include-events --limit 100 --output hook-report.json\n```\n\nRaw event rows are opt-in and capped at 1,000. The default report contains aggregate health and\nat most twenty recent failures/timeouts, keeping routine troubleshooting output small enough for\nCLI and model context windows.\n\nThe dashboard's **Capture health** panel shows runs, failures, timeouts and\np50/p95 latency by client. Logs rotate at 5 MiB, retain at most 40 files for 14\ndays, and live under `.token-optimizer/logs` when a state directory is set (or\n`~/.token-optimizer/logs` otherwise). `TOKEN_OPTIMIZER_LOG_DIR`,\n`TOKEN_OPTIMIZER_LOG_MAX_BYTES`, `TOKEN_OPTIMIZER_LOG_MAX_FILES`, and\n`TOKEN_OPTIMIZER_LOG_RETENTION_DAYS` override those operational defaults.\n\n---\n\n## What it does that other optimizers do not\n\n### Compaction is consolidation, not loss\n\nEveryone else checkpoints and restores what you _had_ — which spends the\nscarcest budget in the session replaying context you already paid for.\n\nSelection here is **derived**, not a category list: `cost-to-rederive ×\nirrecoverability × reuse-probability`, with dead ends and decisions on a floor,\nbecause cheap-to-find is not the same as cheap-to-find-_again_. Restoration then\nadapts to the situation — mid-problem, cold resume, or in-flow — within a\nmeasured budget:\n\n> **Where you were:** does clock skew explain the 401s?\n> ruled out: token signing, clock drift on the client\n> untested: NTP skew on the server\n\nThat is resuming a thought. A summary describes one.\n\n### Progressive disclosure that knows what you asked\n\nA large tool result becomes a preview chosen by the **session's actual\nquestion**, after parsing the output's shape (test report, diff, stack trace,\nlog, JSON) — not the first 40 lines because they are first.\n\n```\n[selected against: \"which shard fails?\"]\n--- failures ---\n  FAILED  DBNetTests.BceOnRelu -- expected 0.0 got NaN\n  FAILED  TftGradientFlow -- gradient did not reach the encoder\n---- omitted: 1,760 lines of passing tests (expand 8bb6bd66) ----\n```\n\nEvery cut is **named**, because a model reasoning over a silent truncation\ncannot know it is missing anything. `expand` serves from a content-addressed\nstore — it never re-runs your test suite — and expanding both teaches the next\npreview and promotes what you needed into the graph, so the second expansion\nnever happens.\n\n### Prompt-cache economics, measured from your own transcript\n\nProvider caches are billable and provider-specific; a cache hit is not a free\ninput token. For example, Anthropic publishes separate cache-read and\ncache-write multipliers, while OpenAI and Gemini expose their own cached-input\nusage and pricing rules. Token Optimizer reads native cache fields when the\nclient supplies them and keeps reads, writes, uncached input, and output\nseparate. It never applies one provider's cache multiplier to another client.\nThe attribution view then does the part a hit rate cannot:\n\n```\n! CLAUDE.md:2 has an embedded timestamp, invalidating everything after it\n    about 329,421 tokens re-written per session\n```\n\nAttributed to a line, priced by what sits _behind_ it. Keep-warm is decided by\nexpected value from your observed gaps, per TTL tier — and when neither tier\npays, it says so.\n\n### Model routing decided by outcomes, not by task size\n\nEveryone guesses from task shape and never checks. This reads which model ran\neach episode and what happened — retries, errors, turns — and prices **both**\nmistakes: what an overpowered model wastes, and what an underpowered one costs\nin retries. A tier that needs a retry in more than half its episodes is excluded\nat any price, because four cheap turns that fail are not cheap.\n\n### Waste detection that becomes a ratchet\n\nA report is read once and forgotten. Here a detection produces a **durable,\nmeasured, reversible fix** — a skip rule, a composite touch — plus a ~50-token\nsession-start briefing so the waste never starts. Detectors are a shipped floor\n_plus_ patterns derived from your project's own history, each carrying what it\nhas actually saved:\n\n```\ngenerated/schema.d.ts: read in 9/9 sessions, never the source of a finding\n    3,400 tokens/session; cost equivalent not priced; apply: waste_audit action=\"apply\"\n```\n\nAnything that touches **your** files is proposed as a diff and never applied.\n\n### One audit across every project\n\n`fleet_audit` ranks your whole machine by measured cost, and does something a\nper-project scanner cannot: a fix proven in one project is offered to the others\ncontaining the **same file contents**, carrying the evidence from where it was\nmeasured. Matching is by content hash, never by filename.\n\nIt also runs the natural experiment nobody else can — enforcing clients versus\ndirective ones — and reports it whichever way it falls, with the confound\nstated.\n\n---\n\n## Trust: we ship hooks that refuse your tool calls\n\nThat is a bigger ask than a normal dependency makes, so:\n\n**Verify the release.** Published from CI with npm provenance — `npm audit\nsignatures` ties the artifact to the workflow run and the commit, without\ntrusting us. `CHECKSUMS.sha256` ships alongside for offline checking.\n\n**If nothing seems to be happening, the lifecycle bundle is probably not\ninstalled.** An MCP server process cannot modify the host that launched it, and\nnpm 11 gates lifecycle scripts behind `allow-scripts`. Install the native\nplugin/hook bundle listed for your client below; adding only the MCP server gives\nthe model tools but no pre-execution veto. For a legacy global Claude Code\ninstallation, recovery is one line:\n\n```bash\nnpx token-optimizer-install     # wire Claude Code hooks\nnpx token-optimizer-doctor      # prove the Claude hooks work\n```\n\n**Check that it works — not that files exist.**\n\n```bash\nnpx token-optimizer-doctor      # or npm run doctor, from a clone\n```\n\nIt feeds a synthetic payload to the _real_ hook binary and asserts a large read\nis refused and a small one is not. A checklist would have passed on the exact\nbug this project once shipped, where the plugin was connected, visible in\n`/mcp`, and saving nothing. Every failure names its own fix.\n\n**Every refusal carries its own off switch.** Enforcement that hides its disable\nis coercive, and the person who needs it is mid-refusal, not reading a README:\n\n```\nauth.ts is 91 KB. Call smart_read instead.\n(Not what you wanted? TOKEN_OPTIMIZER_MODE=off disables enforcement.)\n```\n\n**Removal is exact.** The installer records every file it wrote, with hashes.\nUninstall removes only what still matches; anything you edited since is left in\nplace and named. Your own hooks are never touched, and we never rewrite your\n`settings.json` — we merge into it.\n\n```bash\nnpm run uninstall-hooks              # show the plan; changes nothing\nnpm run uninstall-hooks -- --apply   # carry it out\n```\n\n---\n\n## It separates direct savings from causal graph evidence\n\nEvery tool in this space reports \"tokens saved\" computed from its own\nassumptions. That number cannot be wrong, because nothing checks it.\n\nFor optimizer results, this records the materialized before-state and the text\nactually returned to the client, then subtracts any linked expansion responses.\nNative graph-substitution counterfactuals stay labeled as modeled and outside\nthe main headline.\n\nThe graph's broader claim—whether delivered knowledge prevented later\nre-reading—is causal, so it runs a **randomized holdout**. Delivery is silently\nwithheld on a slice of file touches, stratified by file, and the effect is the\ndifference in downstream reads between arms. That effect is not added to the\ncombined net until the experiment can support it, and the page will tell you\nplainly:\n\n> the graph is NOT yet paying for itself\n\nA tool that can only ever report good news is not reporting. The same discipline\nruns throughout: an unmeasurable saving renders as **unknown**, never as zero,\nand never as `$0.00` — because \"cannot tell yet\" printed as \"saved nothing\" is a\nsilent false negative, and dollars get quoted to other people.\n\n## It runs everywhere, and says which tier\n\nThe tier is a protocol guarantee, not a preference:\n\n- **Lifecycle continuation:** Claude Code, Codex, GitHub Copilot CLI, Gemini CLI,\n  Qwen Code, and Cursor. Native routing/capture/delivery plus one active-model\n  completion reflection.\n- **Native observation:** Cline, OpenCode, Kilo, and Windsurf. Native\n  routing/capture/delivery; the active model performs semantic writes.\n- **MCP + rules:** Roo Code, Zed, Amp, Continue, Crush, and Droid. MCP-visible\n  activity and explicit graph tools, with no claim over hidden built-in calls.\n\nThe exact surfaces still differ. For example, a protocol that can replace a\nlarge read before it reaches the model provides a stronger token guarantee than\none that can only observe it. The generated registry, adapters, dashboard, and\ncertification report all read the same capability source so those claims cannot\ndrift independently.\n\nEvery config shape is confirmed against that client's published documentation,\nwith the source URL recorded in its README.\n\n## Everything here is verified, and you can run it\n\n```bash\nnpm run verify:all\n```\n\n| Suite            | Checks | What it proves                                                                                                          |\n| ---------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- |\n| `test`           | 2,437  | Enforcement, staleness, injection, consolidation, disclosure, cache, routing, trust — driving the real hooks over stdin |\n| `verify:clients` | 253    | Every client config, lifecycle manifest, and enforcement surface matches its documented schema                          |\n| `verify:harvest` | 26     | Request shape, response parsing, and that **no secret from a tool result crosses the wire**                             |\n| `verify:ui`      | 22     | Real headless Chromium: layout, label collisions, legibility                                                            |\n| `doctor`         | 10     | The installed hooks actually refuse, and the server actually answers                                                    |\n\nThese are not decoration. They found six client configs that would have failed\n**silently**, an installer that destroyed user hooks, a Windows path bug that\nmade enforcement blind to half its own refusals, and an uninstaller that printed\na plan and deleted nothing.\n\n## Honest comparison\n\n|                              | Token Optimizer                                                      | Typical alternatives                                 |\n| ---------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------- |\n| **License**                  | MIT — commercial use fine                                            | Often noncommercial-only; check before using at work |\n| Default behaviour            | Refuses the wasteful call                                            | Suggests a better tool                               |\n| Re-read of an unchanged file | Returns a diff                                                       | Returns the file again                               |\n| Savings figure               | Direct before/return ledger; causal graph effect separately held out | Computed from the tool's own assumptions             |\n| Cross-session memory         | Findings, decisions, dead ends                                       | Usually none                                         |\n| Compaction                   | Consolidation, ranked by cost-to-rederive                            | Checkpoint and replay                                |\n| Cache economics              | Measured from the transcript, attributed to a line                   | Rarely addressed                                     |\n| Model routing                | Measured from episode outcomes                                       | Guessed from task size                               |\n| Cross-project                | Fixes transfer by content hash                                       | Per-project only                                     |\n| Clients                      | 16                                                                   | 3–6 typical                                          |\n| Telemetry                    | None                                                                 | Varies                                               |\n\n---\n\n## Installation\n\nEvery client launches the same stdio server — `npx -y @ooples/token-optimizer-mcp@latest` —\nbut they differ in what they let a hook _do_, and that difference is the whole\nproduct. A client with a pre-execution veto can have the wasteful call refused;\none without can only be told. Both are listed honestly below.\n\nReady-made configuration for all sixteen lives in\n[`integrations/`](./integrations), generated from one source and validated by\n`npm run verify:clients`. Full matrix: [`docs/CLIENT_SUPPORT.md`](./docs/CLIENT_SUPPORT.md).\n\nEvery MCP connection also receives capability-aware mandatory routing\ninstructions in its `initialize` response. That gives all clients a universal\nalways-on policy, but only the ten clients with native pre-tool surfaces can\nhard-veto a wasteful built-in call; install their lifecycle bundle for actual\nenforcement.\n\n### Enforcing tier — the wasteful call is refused\n\nThese ten clients expose a pre-execution hook. Their packaged lifecycle bundle\ndefaults to enforcement and shares one capability-aware decision engine; set\n`TOKEN_OPTIMIZER_MODE=advise` or `off` only when you deliberately want the\nescape hatch.\n\n| Client                 | Installable lifecycle surface                                                                                                                    |\n| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |\n| **Claude Code**        | Native plugin: `/plugin marketplace add ooples/token-optimizer-mcp`, then `/plugin install token-optimizer@token-optimizer`                      |\n| **Codex**              | Native plugin in [`integrations/codex/plugin`](./integrations/codex/plugin), or standalone hooks in [`integrations/codex`](./integrations/codex) |\n| **GitHub Copilot CLI** | Project hooks in [`integrations/copilot`](./integrations/copilot)                                                                                |\n| **Gemini CLI**         | Gemini extension at the repository root, backed by [`integrations/gemini`](./integrations/gemini)                                                |\n| **Qwen Code**          | Extension bundle in [`integrations/qwen`](./integrations/qwen)                                                                                   |\n| **Cursor**             | Project hooks and always-applied rule in [`integrations/cursor`](./integrations/cursor)                                                          |\n| **Cline**              | Project hooks and rule in [`integrations/cline`](./integrations/cline)                                                                           |\n| **OpenCode**           | In-process plugin and hooks in [`integrations/opencode`](./integrations/opencode)                                                                |\n| **Kilo**               | In-process plugin and hooks in [`integrations/kilo`](./integrations/kilo)                                                                        |\n| **Windsurf**           | Project hooks and rule in [`integrations/windsurf`](./integrations/windsurf)                                                                     |\n\n### Rules tier — mandatory routing where the host has no veto API\n\nRoo Code, Zed, Amp, Continue, Crush, and Droid do not expose a packaged\npre-execution bridge that can safely veto built-in calls. Their generated,\nalways-on rules make optimized routing mandatory whenever the exact MCP schema\nis visible, and fail open to a bounded native operation when it is not. The\nintegration directories contain both the MCP config and the rules file at the\npaths documented by each host.\n\n> **These paths are checked, not assumed.** Verifying them against each client's\n> published docs found six configs that would have installed cleanly and never\n> loaded — including Kilo, whose schema shares nothing with the `mcpServers`\n> convention the other clients use. A convention is not a schema.\n\n### Codex\n\n#### 1. Add the MCP server or native plugin\n\nFor the best experience, install the Codex plugin. It bundles the MCP server, the token-optimization skill, session guidance, and a large-read hook:\n\n```bash\ncodex plugin marketplace add ooples/token-optimizer-mcp\ncodex plugin add token-optimizer@token-optimizer\n```\n\nReview and trust the bundled hooks with `/hooks`, then start a new conversation. If you prefer an MCP-only installation, use:\n\n```bash\ncodex mcp add token-optimizer -- npx -y @ooples/token-optimizer-mcp@latest\n```\n\nOn Windows, if PowerShell blocks the `codex.ps1` shim, use the command launcher directly:\n\n```powershell\ncodex.cmd mcp add token-optimizer -- npx -y @ooples/token-optimizer-mcp@latest\n```\n\nThis writes the server to `~/.codex/config.toml`. Codex CLI, the Codex IDE extension, and the Codex app on the same host share that configuration.\n\n#### 2. Verify the installation\n\n```bash\ncodex mcp get token-optimizer\ncodex mcp list\n```\n\n![Codex MCP list showing token-optimizer installed and enabled](./docs/assets/codex-mcp-installed.png)\n\nStart a new Codex conversation after installation so the new tools are discovered. In an interactive CLI session, `/mcp` shows the tools available to the conversation.\n\n#### 3. Add optimization guidance and hooks\n\nThe plugin supplies both automatically. For an MCP-only installation, add the guidance from [`integrations/AGENTS.md`](./integrations/AGENTS.md) to a project or global `AGENTS.md`. A ready-made standalone hook is also available under [`integrations/codex/hooks`](./integrations/codex/hooks); merge its `hooks.json` into `~/.codex/hooks.json`, copy the script to `~/.codex/hooks/`, and review it once with `/hooks`.\n\nThe Codex hook injects guidance at `SessionStart` and blocks expensive native operations by default when the bundled MCP has an exact replacement. That includes a single unambiguous code-mode shell call such as `cat` or `Get-Content`; multi-operation orchestration remains advisory so unrelated work is not discarded. A second attempt at the same target passes through if the MCP is unavailable. Set `TOKEN_OPTIMIZER_MODE=advise` for guidance without vetoes or `TOKEN_OPTIMIZER_MODE=off` to disable the hooks. The `AGENTS.md`/skill guidance remains important.\n\nIf you prefer a smaller instruction block:\n\n```markdown\n## Token optimization\n\nUse the token-optimizer MCP for large or repeated reads:\n\n- `smart_read` for files over roughly 400 lines and for files already read once.\n- `smart_glob`/`smart_grep` for large search results.\n- `optimize_text` to store bulky text outside the model context.\n- `get_optimization_report` when the user asks for token or compression stats.\n\nUse normal tools for small, one-off operations.\n```\n\nSee the current [Codex hooks documentation](https://learn.chatgpt.com/docs/hooks.md) for hook trust, matching, and tool-coverage details.\n\n#### Equivalent manual Codex configuration\n\nIf you prefer to edit `~/.codex/config.toml` yourself:\n\n```toml\n[mcp_servers.token-optimizer]\ncommand = \"npx\"\nargs = [\"-y\", \"@ooples/token-optimizer-mcp@latest\"]\n\n# Optional: keep the cache in a custom location.\n# env = { TOKEN_OPTIMIZER_CACHE_DIR = \"/absolute/path/to/cache\" }\n```\n\n### Claude Code\n\n**Install the plugin, not the bare MCP server.** The plugin is the only path that\noptimizes by default; adding the MCP server alone gives the model a set of tools\nit is free to never call.\n\n```text\n/plugin marketplace add ooples/token-optimizer-mcp\n/plugin install token-optimizer@token-optimizer\n/reload-plugins\n```\n\nThat is the whole installation. There is nothing to configure and no flag to\nturn on.\n\n#### What you get immediately\n\nFrom the first message of the next session, expensive built-in calls are\n**refused and redirected** to the optimized equivalent:\n\n| You (or the model) do this                     | What happens                                         |\n| ---------------------------------------------- | ---------------------------------------------------- |\n| `Read` a file over ~25 KB                      | Denied → `smart_read` (cached)                       |\n| `Read` **any** file already read this session  | Denied → `smart_read` (returns only the diff)        |\n| `Grep` file contents / `Glob` for files        | Denied → `smart_grep` / `smart_glob`                 |\n| `Edit` a file over ~25 KB                      | Denied → `smart_edit` (returns a diff, not the file) |\n| `cat`/`head`/`tail`/`Get-Content` a large file | Denied → `smart_read`                                |\n| `grep -r` / `rg` across the tree               | Denied → `smart_grep`                                |\n| Context fills and compaction starts            | `optimize_session` runs first                        |\n\nThe re-read case is usually the largest single win and the one most often\nmissed: a 5 KB config read fifteen times across a session costs far more than\none 200 KB file read once. Size-based rules never catch it.\n\n#### It cannot get you stuck\n\nThree properties, all tested:\n\n- **Fail-open.** Any error in the optimizer — bad payload, unreadable file,\n  unexpected exception — allows the original call through, exactly as if the\n  plugin were not installed.\n- **Loop-breaking.** A given target is refused **once**. Come back to it and it\n  is allowed. So if the MCP server is missing or misconfigured, the cost is one\n  wasted turn per file, self-healing, with no intervention.\n- **Cheap calls are left alone.** Small files, paged reads, `git log | head`,\n  and binary paths are never touched.\n\n#### Turning it down\n\nOne variable, no reinstall:\n\n```bash\nTOKEN_OPTIMIZER_MODE=advise   # nudge instead of refuse (the pre-5.2 behaviour)\nTOKEN_OPTIMIZER_MODE=off      # disable the hooks entirely\nTOKEN_OPTIMIZER_LARGE_READ_BYTES=51200   # raise the \"large file\" threshold\n```\n\n#### MCP server only (not recommended)\n\nIf you want the tools without the enforcement:\n\n```bash\nclaude mcp add --transport stdio --scope user token-optimizer -- \\\n  npx -y @ooples/token-optimizer-mcp@latest\n```\n\nVerify with `claude mcp get token-optimizer`, or `/mcp` inside Claude Code. Then\nadd the recommendations from [`integrations/AGENTS.md`](./integrations/AGENTS.md)\nto your `CLAUDE.md` — but be aware that guidance in a context file is advisory,\nand models routinely read past it.\n\nThe standalone global installer can also configure the Claude Code hooks and supported desktop clients:\n\n```bash\nnpm install -g @ooples/token-optimizer-mcp@latest\n```\n\nOn Windows, a restrictive PowerShell policy may need this user-scoped adjustment first:\n\n```powershell\nSet-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser\nnpm install -g @ooples/token-optimizer-mcp@latest\n```\n\nInteractive global installs run the hook installer; CI and local dependency installs skip it. If automatic setup is skipped, use `install-hooks.ps1` on Windows or `install-hooks.sh` on macOS/Linux. See the [Claude Code MCP guide](https://code.claude.com/docs/en/mcp) and this project's [hook installation guide](./docs/HOOKS-INSTALLATION.md).\n\n### GitHub Copilot CLI\n\n#### 1. Add the MCP server\n\nOn current Copilot CLI releases:\n\n```bash\ncopilot mcp add token-optimizer -- npx -y @ooples/token-optimizer-mcp@latest\n```\n\nIf your Copilot CLI does not expose `copilot mcp` yet, save this as `~/.copilot/mcp-config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"token-optimizer\": {\n      \"type\": \"local\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@ooples/token-optimizer-mcp@latest\"],\n      \"tools\": [\"*\"]\n    }\n  }\n}\n```\n\nA ready-made copy is available at [`integrations/copilot/mcp-config.json`](./integrations/copilot/mcp-config.json).\n\n#### 2. Verify the installation\n\n```bash\ncopilot mcp get token-optimizer\ncopilot mcp list\n```\n\nInside an interactive Copilot session, `/mcp show token-optimizer` displays the connection status and available tools.\n\n#### 3. Add optimization guidance and hooks\n\nKeep [`integrations/AGENTS.md`](./integrations/AGENTS.md) as the repository's `AGENTS.md`, or adapt the same guidance into `.github/copilot-instructions.md`.\n\nFor native lifecycle integration, copy the ready-made repository hooks into your project:\n\n```bash\nmkdir -p .github/hooks\ncp integrations/copilot/.github/hooks/token-optimizer* .github/hooks/\n```\n\n```powershell\nNew-Item -ItemType Directory -Force .github/hooks | Out-Null\nCopy-Item integrations/copilot/.github/hooks/token-optimizer* .github/hooks/\n```\n\nThe hooks inject optimization guidance at `sessionStart` and deny a large built-in `view` by default so Copilot retries with `smart_read`. Partial reads and files below 25 KB pass through unchanged, and `TOKEN_OPTIMIZER_MODE=advise` restores non-blocking guidance. Repository hooks work without overwriting user-level files; global hooks can instead be placed in `~/.copilot/hooks/` with their script paths adjusted for that directory.\n\nRestart Copilot CLI after changing hook files. See GitHub's official [MCP setup guide](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-mcp-servers) and [hooks reference](https://docs.github.com/en/copilot/reference/hooks-reference).\n\n### Gemini CLI\n\n#### 1. Add the MCP server\n\nAdd Token Optimizer directly at user scope:\n\n```bash\ngemini mcp add --scope user token-optimizer npx -y @ooples/token-optimizer-mcp@latest\n```\n\nAlternatively, install this repository as a Gemini extension so the MCP configuration and `GEMINI.md` guidance are packaged together:\n\n```bash\ngemini extensions install https://github.com/ooples/token-optimizer-mcp --auto-update\n```\n\n#### 2. Verify the installation\n\n```bash\ngemini mcp list\ngemini extensions list\n```\n\nRun `/mcp` inside Gemini CLI to inspect the connection. Restart Gemini CLI after installing or updating the extension.\n\n#### 3. Add optimization guidance and hooks\n\nDirect MCP users should copy [`GEMINI.md`](./GEMINI.md) into the project or merge its rules into an existing `GEMINI.md`. Extension users receive that context file plus native hooks automatically.\n\nThe extension's `SessionStart` hook injects optimization guidance. Its `AfterTool` hook notices full-file `read_file` results over 25 KB and suggests `smart_read`. To make Gemini automatically replace those large results with a token-optimizer tail call, configure the extension setting **Automatic large-read routing** as `true`:\n\n```bash\ngemini extensions config token-optimizer\n```\n\nAutomatic routing uses Gemini's native `tailToolCallRequest`: the `smart_read` result replaces the built-in read result before it reaches the model. Partial reads remain unchanged. Restart Gemini CLI after installing, updating, or reconfiguring the extension. See the official [Gemini MCP guide](https://geminicli.com/docs/tools/mcp-server/), [extension guide](https://geminicli.com/docs/extensions/reference/), and [hooks reference](https://geminicli.com/docs/hooks/reference/).\n\n### OpenCode\n\n#### 1. Add the MCP server\n\nCreate or update `opencode.json` in your project:\n\n```json\n{\n  \"$schema\": \"https://opencode.ai/config.json\",\n  \"mcp\": {\n    \"token-optimizer\": {\n      \"type\": \"local\",\n      \"command\": [\"npx\", \"-y\", \"@ooples/token-optimizer-mcp@latest\"],\n      \"enabled\": true\n    }\n  },\n  \"instructions\": [\"./AGENTS.md\"]\n}\n```\n\nFor a global installation, merge the same `mcp` entry into `~/.config/opencode/opencode.json`.\n\n#### 2. Verify the installation\n\n```bash\nopencode mcp list\n```\n\nThe output shows configured servers and their connection status.\n\n#### 3. Add optimization guidance and the local plugin\n\nCopy [`integrations/AGENTS.md`](./integrations/AGENTS.md) to the project as `AGENTS.md`; the `instructions` entry above loads it. Then copy the ready-made local plugin:\n\n```bash\nmkdir -p .opencode/plugins\ncp integrations/opencode/.opencode/plugins/token-optimizer.js .opencode/plugins/\n```\n\n```powershell\nNew-Item -ItemType Directory -Force .opencode/plugins | Out-Null\nCopy-Item integrations/opencode/.opencode/plugins/token-optimizer.js .opencode/plugins/\n```\n\nThe plugin preserves Token Optimizer usage state in OpenCode's compaction prompt. Its `tool.execute.before` hook rejects full-file reads over 25 KB by default and steers the agent to `smart_read`; small and partial reads pass normally. Set `TOKEN_OPTIMIZER_MODE=advise` for non-blocking guidance. Restart OpenCode after adding the plugin. See the official [OpenCode MCP guide](https://opencode.ai/docs/mcp-servers/) and [plugin hook guide](https://opencode.ai/docs/plugins/).\n\n### Generic MCP configuration\n\nAny stdio-capable MCP client can launch Token Optimizer with:\n\n```json\n{\n  \"mcpServers\": {\n    \"token-optimizer\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@ooples/token-optimizer-mcp@latest\"]\n    }\n  }\n}\n```\n\nAdditional ready-made integration files are available for [Claude Desktop](./examples/claude_desktop_config.json), [Codex](./integrations/codex/config.toml), [Gemini CLI](./integrations/gemini/), [OpenCode](./integrations/opencode/), and [GitHub Copilot](./integrations/copilot/mcp-config.json).\n\n## Use it\n\nYou normally use Token Optimizer by asking your agent in plain language:\n\n```text\nUse token-optimizer smart_read for the large server file, then use it again\nafter the edit so only the diff comes back.\n```\n\n```text\nCache this API response with optimize_text under the key customer-schema,\nthen retrieve it only if we need the full payload again.\n```\n\n```text\nShow my token savings with get_optimization_report.\n```\n\nFor clients that expose direct MCP tool calls, the core inputs are small JSON objects:\n\n```json\n{\n  \"tool\": \"smart_read\",\n  \"arguments\": {\n    \"path\": \"/absolute/path/to/large-file.ts\"\n  }\n}\n```\n\n```json\n{\n  \"tool\": \"optimize_text\",\n  \"arguments\": {\n    \"text\": \"A large response, log, document, or generated artifact...\",\n    \"key\": \"stable-reference-key\",\n    \"quality\": 11\n  }\n}\n```\n\n```json\n{\n  \"tool\": \"get_optimization_report\",\n  \"arguments\": {\n    \"topN\": 10\n  }\n}\n```\n\n## Understand the compression stats\n\n`optimize_text` returns measurements with every call. This example uses a deliberately repetitive payload to make every field easy to see; it is not a benchmark:\n\n```json\n{\n  \"success\": true,\n  \"key\": \"customer-schema\",\n  \"originalTokens\": 4180,\n  \"compressedTokens\": 72,\n  \"tokensSaved\": 4108,\n  \"percentSaved\": 99.55,\n  \"cached\": true,\n  \"compressionUsed\": true\n}\n```\n\n`get_optimization_report` applies the same versioned measurement contract as\nthe dashboard and aggregates qualifying operations into:\n\n- gross preview reduction, linked expansion debits, and net transport avoided;\n- observed returned context and the net reduction percentage;\n- verified operations tracked, with legacy and tool-reported claims excluded;\n- breakdowns by action/tool, hook phase, and MCP server;\n- optional date-range and session filters.\n\nTwo tools sound similar but serve different purposes:\n\n| Tool            | Use it for                                                  | Context-window effect                                     |\n| --------------- | ----------------------------------------------------------- | --------------------------------------------------------- |\n| `optimize_text` | Store bulky text under a key and return a compact reference | Reduces text kept in the active context                   |\n| `compress_text` | Produce Brotli/base64 data for storage or transport         | May use **more** model tokens if pasted back into context |\n\nIf your goal is a smaller prompt, prefer `optimize_text`. Use `compress_text` only when you specifically need byte compression.\n\n## What is included\n\n| Capability              | Representative tools                                                                                | What gets smaller or faster              |\n| ----------------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------- |\n| Context and compression | `optimize_text`, `get_cached`, `count_tokens`, `analyze_optimization`, `context_delta`              | Large payloads and repeated context      |\n| File and Git operations | `smart_read`, `smart_write`, `smart_edit`, `smart_grep`, `smart_glob`, `smart_diff`, `smart_status` | File contents, search results, and diffs |\n| Caching                 | `smart_cache`, `cache_warmup`, `cache_invalidation`, `cache_compression`, `predictive_cache`        | Repeated computation and retrieval       |\n| APIs and databases      | `smart_api_fetch`, `smart_sql`, `smart_graphql`, `smart_rest`, `smart_schema`                       | Responses, schemas, and query analysis   |\n| Build and system tasks  | `smart_build`, `smart_test`, `smart_lint`, `smart_logs`, `smart_processes`                          | Build logs and diagnostic output         |\n| Intelligence            | `smart-summarization`, `pattern-recognition`, `natural-language-query`, `recommendation-engine`     | Analysis and summaries                   |\n| Analytics               | `get_optimization_report`, `get_action_analytics`, `get_hook_analytics`, `export_analytics`         | Token-savings visibility                 |\n\nSee [`docs/TOOLS.md`](./docs/TOOLS.md) for detailed tool inputs and examples.\n\n## Requirements and data\n\n- Node.js 22 or newer\n- npm 9 or newer\n- An MCP client with stdio transport support\n\nDefault local data locations include:\n\n- cache: `~/.token-optimizer-cache/`\n- analytics: `~/.token-optimizer-mcp/analytics.db`\n- sessions and configuration: `~/.token-optimizer/`\n\nSet `TOKEN_OPTIMIZER_CACHE_DIR` to override the cache location.\n\n## Verify it, check it, remove it\n\nThis installs hooks that **refuse your tool calls**. That is a bigger ask than a\nnormal dependency makes, so here is everything needed to check it and undo it.\n\n**Verify the release is genuine.** The package is published from CI with npm\nprovenance, which signs an attestation binding the artifact to the workflow run\nand the commit that built it:\n\n```bash\nnpm audit signatures\n```\n\nThat verifies without trusting us. A `CHECKSUMS.sha256` is attached to each\nGitHub release for offline checking (`sha256sum -c CHECKSUMS.sha256`) — useful\nfor mirrors, but weaker: it shares a trust root with the thing it hashes.\n\n**Check it actually works.** Not that the files are in place — that it _works_:\n\n```bash\nnpm run doctor\n```\n\nThis feeds a synthetic payload to the real hook binary and asserts a large read\nis refused and a small one is not, that session-start emits the policy, that the\ngraph directory is writable, and that the MCP server starts and lists its tools.\nEvery failure names its own fix. There is also an `install_doctor` MCP tool.\n\n**Turn enforcement off, instantly.** Every refusal says this, so you never have\nto come back here to find it:\n\n```bash\nTOKEN_OPTIMIZER_MODE=off      # no enforcement, no hooks\nTOKEN_OPTIMIZER_MODE=advise   # suggestions only, nothing is ever denied\n```\n\n**Remove it.** The installer records every file it wrote, with hashes, so\nremoval is exact rather than best-effort:\n\n```bash\nnpm run uninstall-hooks              # show the plan; changes nothing\nnpm run uninstall-hooks -- --apply   # carry it out\n```\n\nIt removes only files that still match what we wrote. Anything you have edited\nsince is **left in place and named**, because removing it would destroy your\nwork and removing it silently would be worse. Hooks you added yourself are not\nin the manifest and are never touched. Config entries we added are listed for\nyou to remove — we do not rewrite your `settings.json`.\n\n## Technical reference\n\nThe detailed operational material below is intentionally retained for users who want to understand the complete tool surface, hooks pipeline, performance controls, analytics, and troubleshooting behavior.\n\nThe proposed category-level successor architecture, its 18 required\nworkstreams, and the evidence gates for claiming a universal cognitive runtime\nare documented in\n[`docs/UNIVERSAL_COGNITIVE_RUNTIME_PROGRAM.md`](docs/UNIVERSAL_COGNITIVE_RUNTIME_PROGRAM.md).\n\n### Complete Tool Reference (74 Total)\n\n#### Core Caching & Optimization (8 tools)\n\n<details>\n<summary>Click to expand</summary>\n\n- **optimize_text** - Compress and cache text (primary tool for token reduction)\n- **get_cached** - Retrieve previously cached text\n- **compress_text** - Compress text using Brotli\n- **decompress_text** - Decompress Brotli-compressed text\n- **count_tokens** - Count tokens using tiktoken (GPT-4 tokenizer)\n- **analyze_optimization** - Analyze text and get optimization recommendations\n- **get_cache_stats** - View cache hit rates and compression ratios\n- **clear_cache** - Clear all cached data\n\n**Usage Example**:\n\n```typescript\n// Cache large content to remove it from context window\noptimize_text({\n  text: 'Large API response or file content...',\n  key: 'api-response-key',\n  quality: 11,\n});\n// Result: 60-90% token reduction\n```\n\n</details>\n\n#### Smart File Operations (10 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nOptimized replacements for standard file tools with intelligent caching and diff-based updates:\n\n- **smart_read** - Read files with 80% token reduction through caching and diffs\n- **smart_write** - Write files with verification and change tracking\n- **smart_edit** - Line-based file editing with diff-only output (90% reduction)\n- **smart_grep** - Search file contents with match-only output (80% reduction)\n- **smart_glob** - File pattern matching with path-only results (75% reduction)\n- **smart_diff** - Git diffs with diff-only output (85% reduction)\n- **smart_branch** - Git branch listing with structured JSON (60% reduction)\n- **smart_log** - Git commit history with smart filtering (75% reduction)\n- **smart_merge** - Git merge management with conflict analysis (80% reduction)\n- **smart_status** - Git status with status-only output (70% reduction)\n\n**Usage Example**:\n\n```typescript\n// Read a file with automatic caching\nsmart_read({ path: '/path/to/file.ts' });\n// First read: full content\n// Subsequent reads: only diff (80% reduction)\n```\n\n</details>\n\n#### API & Database Operations (10 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nIntelligent caching and optimization for external data sources:\n\n- **smart_api_fetch** - HTTP requests with caching and retry logic (83% reduction on cache hits)\n- **smart-cache-api** - API response caching with TTL/ETag/event-based strategies\n- **smart_database** - Database queries with connection pooling and caching (83% reduction)\n- **smart_sql** - SQL query analysis with optimization suggestions (83% reduction)\n- **smart_schema** - Database schema analysis with intelligent caching\n- **smart_graphql** - GraphQL query optimization with complexity analysis (83% reduction)\n- **smart_rest** - REST API analysis with endpoint discovery (83% reduction)\n- **smart_orm** - ORM query optimization with N+1 detection (83% reduction)\n- **smart_migration** - Database migration tracking (83% reduction)\n- **smart_websocket** - WebSocket connection management with message tracking\n\n**Usage Example**:\n\n```typescript\n// Fetch API with automatic caching\nsmart_api_fetch({\n  method: 'GET',\n  url: 'https://api.example.com/data',\n  ttl: 300,\n});\n// Cached responses: 95% token reduction\n```\n\n</details>\n\n#### Build & Test Operations (10 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nDevelopment workflow optimization with intelligent caching:\n\n- **smart_build** - TypeScript builds with diff-based change detection\n- **smart_test** - Test execution with incremental test selection\n- **smart_lint** - ESLint with incremental analysis and auto-fix\n- **smart_typecheck** - TypeScript type checking with caching\n- **smart_install** - Package installation with dependency analysis\n- **smart_docker** - Docker operations with layer analysis\n- **smart_logs** - Log aggregation with pattern filtering\n- **smart_network** - Network diagnostics with anomaly detection\n- **smart_processes** - Process monitoring with resource tracking\n- **smart_system_metrics** - System resource monitoring with performance recommendations\n\n**Usage Example**:\n\n```typescript\n// Run tests with caching\nsmart_test({\n  onlyChanged: true, // Only test changed files\n  coverage: true,\n});\n```\n\n</details>\n\n#### Advanced Caching (10 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nEnterprise-grade caching strategies with 87-92% token reduction:\n\n- **smart_cache** - Multi-tier cache (L1/L2/L3) with 6 eviction strategies (90% reduction)\n- **cache_warmup** - Intelligent cache pre-warming with schedule support (87% reduction)\n- **cache_analytics** - Real-time dashboards and trend analysis (88% reduction)\n- **cache-benchmark** - Performance testing and strategy comparison (89% reduction)\n- **cache_compression** - 6 compression algorithms with adaptive selection (89% reduction)\n- **cache_invalidation** - Dependency tracking and pattern-based invalidation (88% reduction)\n- **cache_optimizer** - ML-based recommendations and bottleneck detection (89% reduction)\n- **cache_partition** - Sharding and consistent hashing (87% reduction)\n- **cache_replication** - Distributed replication with conflict resolution (88% reduction)\n- **predictive_cache** - ML-based predictive caching with ARIMA/LSTM (91% reduction)\n\n**Usage Example**:\n\n```typescript\n// Configure multi-tier cache\nsmart_cache({\n  operation: 'configure',\n  evictionStrategy: 'LRU',\n  l1MaxSize: 1000,\n  l2MaxSize: 10000,\n});\n```\n\n</details>\n\n#### Monitoring & Dashboards (7 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nComprehensive monitoring with 88-92% token reduction through intelligent caching:\n\n- **alert_manager** - Multi-channel alerting (email, Slack, webhook) with routing (89% reduction)\n- **metric_collector** - Time-series metrics with multi-source support (88% reduction)\n- **monitoring_integration** - External platform integration (Prometheus, Grafana, Datadog) (87% reduction)\n- **custom_widget** - Dashboard widgets with template caching (88% reduction)\n- **data_visualizer** - Interactive visualizations with SVG optimization (92% reduction)\n- **health_monitor** - System health checks with state compression (91% reduction)\n- **log_dashboard** - Log analysis with pattern detection (90% reduction)\n\n**Usage Example**:\n\n```typescript\n// Create an alert\nalert_manager({\n  operation: 'create-alert',\n  alertName: 'high-cpu-usage',\n  channels: ['slack', 'email'],\n  threshold: { type: 'above', value: 80 },\n});\n```\n\n</details>\n\n#### System Operations (6 tools)\n\n<details>\n<summary>Click to expand</summary>\n\nSystem-level operations with smart caching:\n\n- **smart_cron** - Scheduled task management (cron/Win",
  "bytes": 60000,
  "sha": "4bf8fe0d56e32824f110b643e8e6df4d185c4ebed23634e663fb4d0ddba97185",
  "repo_slug": "ooples/token-optimizer-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_ooples_token_optimizer_mcp_5dcf5ec5/readme"
}