Skip to content

feat: /api/adapt/tools, never-used MCP servers, tools and skills priced per carrying request - #523

Merged
amiddavid merged 16 commits into
mainfrom
feat/adapt-tools
Oct 15, 2026
Merged

amiddavid merged 16 commits into
mainfrom
feat/adapt-tools

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Adds the analysis and apply endpoints behind /context-guru:adapt tools: the MCP servers, MCP tools and skills an account declared and never used, what carrying each one cost, and how to stop sending it.

What

  • GET /api/adapt/tools (dash, tenant-scoped). Returns a closed list of never-used items:
    • mcp_server: no tool of the server was ever called.
    • mcp_tool: an unused tool of a server that is otherwise used.
    • skill.
      Each item has its dollar cost, its toolfilter entry (remove_as) and the client-side change that stops sending it. That change is claude mcp remove, claude plugin disable for a plugin's server or skills, disconnecting a claude.ai connector, a permissions.deny entry for a single MCP tool, or skillOverrides for a user skill.
    • The response uses the shared adapt report shape: summary, options (keep, remove-sufficient, remove-unused, restore), recommendation, basis id and warnings.
    • Only items that pass the filter's existing evidence bar are recommended (5 sessions over 7 days).
    • Every item states the observed window it was unused in. Each option's spend_usd is the one-off cost of the change: the next request re-writes the cached prefix, priced on the latest request at write minus read. net_usd is saved minus spend, and nothing is recommended when the rewrite outweighs the saving.
    • Coverage reports how many requests had more than one candidate declaration set.
    • Context Guru's own tools and skills, built-ins and server tools are never listed.
  • Pricing: each request is priced on the declaration set it actually carried, at its own model and cache tier.
    • The tier is cache read if the prefix was read, cache write if it was rewritten (1h writes at 2x), and input otherwise.
    • The existing inventory page prices a declaration on every request of every session that declared it, at the session's first model. Sessions hold several declaration sets (subagents, servers added mid-session), so that over-counts.
  • requests.decl_digest (additive column): each captured request now records the digest of the declaration set it carried.
    • Older rows are matched by tool count.
    • Where that match is ambiguous, usd_low/usd_high bound it.
  • POST /api/adapt/tools/apply {option, basis} runs on the shared adapt apply helper (base branch feat/adapt-compaction): the same identity rule, rate limit, audit row, revert and single-tenant override file as every /api/adapt/*/apply.
    • The report's options are offered for 30 minutes; apply takes one of exactly those by id. The basis is required. restore takes the entries out again; revert undoes the last adapt change.
    • Writes only mcp__* / skill__* entries, never Context Guru's own (checked again at apply). A manager's report and apply act on their own account.
    • ctlToolFilter's list edit is factored into editRemoved, shared by the Inventory switch and adapt.

Checked

  • Unit tests: set mapping (a subagent set without the server is not billed), per-request model and tier pricing including 1h writes, digest-exact vs guessed requests and their bounds, own-plugin exclusion, the envelope, and the apply route end to end (stale basis, unknown option, no cookie, apply, undo).

  • An experimental proxy run on copies of real dashboard data, against an independent recompute.

  • A real Claude Code session with the plugin, through an experimental proxy. Its requests recorded their digests, the plugin's own skills were declared but not listed, and the suggested permissions.deny and skillOverrides changes really removed those declarations from the next session's requests.

    • skillOverrides does not reach plugin skills, so for those the suggestion is disabling the plugin, or the proxy filter.
  • A real Claude Code session through a local proxy: apply took effect on the very next request (the filtered declaration tokens are recorded on the row) and revert restored the starting configuration.

Not done

  • The existing inventory page still uses its own per-session pricing.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: REQUEST CHANGES at 0ccb51a (two small items). (Posted as a comment: GitHub does not let the author account request changes.)

Verified:

  • The branch is up to date with main. All 6 commits are by Osher-Elhadad and signed off, with no AI attribution.
  • gofmt and go vet are clean on dash and proxy. The Adapt* dash tests pass, as do TestCapturedRequestRecordsItsDeclarationDigest, the apply test and the existing ToolFilter tests (the updateRemoved refactor keeps their behaviour).
  • Pricing. Each request is assigned one tier, which is right, because tool declarations lead the prefix. If any of the prefix was read, the declarations were read; otherwise they were written. With the 1h blend replaced by the flat 5m write rate, TestAdaptToolsPricesEachRequestAtTheSetItCarried fails.
  • Set mapping. It uses the exact digest when one was recorded. Otherwise it takes the latest set with the same tool count that was first seen at or before the request, else the earliest one. Requests with more than one candidate set are counted, and both bounds take the least and most each item weighs across the candidates (0 where a candidate lacks it).
  • Apply only writes names from the report. The report emits only mcp__<server>, mcp__… tool names and skill-prefixed entries. Built-ins, server tools and anything matching context[-_]?guru never become items. A stale basis gets 409, an unknown option 400, a missing cookie 401, and the write goes through the same audited reg.Update.
  • Capture path and schema. The capture path gains one field assignment (a digest, not content). The schema change is one additive column in the existing migration list and one more insert parameter.

Blocking:

  1. An empty basis skips the stale check (if in.Basis != "" && ...). A client that omits it applies whatever the report says now, which may not be what the user saw. The route's contract is "decide on the report you read", so require basis and answer 400 without it.
  2. Scoping the apply to the caller's own report is untested. With own.URL.RawQuery = "tenant=me" removed, TestAdaptToolsApplyWritesOnlyTheReportedNames still passes. For a manager whose default view covers other accounts, that line is what keeps other accounts' tool names out of the manager's own removal list. Add a manager case: another tenant's unused server must not be written.

Non-blocking:
3. The 1h write blend under-prices declarations. A 1h breakpoint must come before every 5m breakpoint, so whenever cache_write_1h is at least the declarations' tokens, the declarations sit entirely in the 1h part. Blending by the request-level share moves them part-way to the 5m rate. Consider pricing at the 1h rate when cache_write_1h > 0, or at least when it covers the set's tokens.
4. usd_high is not an upper bound. A request with no digest and no set of its tool count is skipped (st == nil), so it is in neither bound. Either count those requests in the coverage warning or say that the bounds cover mapped requests only.
5. RewriteUSD in a fleet view. It is taken from the single latest request in scope. In a manager's fleet view the savings sum over every account, but the spend is one request. It is correct for the apply path, which always uses the caller's own scope, so the GET view could label it, or only compute net_usd for one tenant.
6. The suggestions build shell commands from declared names (claude mcp remove <server>, claude plugin disable <plugin>). MCP names are restricted by the API, but skill and plugin names are less so. If a client ever runs these commands, quote them or check them against ^[A-Za-z0-9_.:-]+$.
7. Cheap defence in depth in apply. Assert that every name starts with mcp__ or the skill prefix and is not dash.IsBuiltinTool, so a future change to the report cannot widen what the write accepts.
8. Size. The core logic is reasonable for what it does. PerMonthUSD, the Current/Default/Best trio and Tools/mcpN are the parts nothing reads yet (the envelope's consumer aside). Keep them only if the plugin renderer uses them.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at afa0dd5. (Posted as a comment: GitHub does not let the author account approve.)

  • Both blockers are fixed. A missing basis now gets 400; with that check disabled, TestAdaptToolsApplyWritesOnlyTheReportedNames fails. Apply scopes to tenant=me; with that line removed, the new TestAdaptToolsApplyForAManagerWritesOnlyTheirOwn fails.
  • The GET report now defaults to the caller's own account, and ?tenant= still widens it.
  • A request that wrote any 1h tokens prices its declarations at the 1h rate, because a 1h breakpoint precedes every 5m one. Unmapped requests are now named in a warning. Suggested commands are only built from names matching ^[A-Za-z0-9_.:@-]+$. Apply also checks every name's prefix and refuses Context Guru's own entries.
  • The basis now hashes the sorted name lists, so new traffic that only moves dollars no longer makes an apply stale. The undo carries the basis of the report after the write.
  • In single-tenant mode, apply answers 501 with a JSON reason before any auth or write.
  • gofmt and go vet are clean, and the dash Adapt tests and proxy Adapt|ToolFilter|DeclDigest tests pass. Both commits are signed off with no AI attribution.

Approved.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at 8f9a34e (adds local apply). (Posted as a comment: GitHub does not let the author account approve.)

Verified:

  • The write gate. On a single-tenant proxy, apply writes only for a caller that statsTrusted accepts: loopback, with no forwarded headers. With the gate disabled, TestAdaptToolsApplyOnALocalProxy fails. readJSON still runs checkOrigin, so a browser page (cross-site POST or DNS rebinding) cannot drive the route. Hosted mode keeps the cookie path.
  • Concurrency. h.static is an atomic.Pointer; readers Load it in tenancyFor, and writes are serialised by localMu. Pipeline.With builds a fresh pipeline and copies every field (comps, emitter, fixedRestore), so a request in flight keeps a complete pipeline. go test -race ./proxy -run 'Adapt|ToolFilter|Thread' passes.
  • Validation. The runtime list goes through reformat.NewToolfilter, the same validation as the config path, and the saved file is reloaded through it. A bad file fails open with a warning. The file is written with mode 0600 as a temp file and renamed.
  • gofmt and go vet are clean, and the components/... tests pass. In a full go test ./dash run, 4 tests failed with SQLITE_BUSY under host load; they pass when rerun alone. Both new commits are signed off with no AI attribution.

Non-blocking:

  1. Pipeline.With puts the toolfilter last. That matches the presets that end with toolfilter, but a config that lists it earlier would have its order changed silently on the first apply. Replace it in place when it is already present.
  2. Restore on a local proxy. The restore option lists the whole current removal list, including the config file's own names. updateLocalRemoved never takes those out (unionRemove adds them back), yet the answer says "stopped filtering X". Either offer only the names apply added, or say that config-file names stay filtered.
  3. The loopback gate trusts every local user and process. That is fine for the per-project plugin proxy, and worth one sentence in docs/components/reformat.md for anyone running a single-tenant proxy on a shared host.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at ee3050b (tools apply on the shared adapt helper). (Posted as a comment: GitHub does not let the author account approve.)

  • One swap path. localfilter.go and Pipeline.With are gone. The only runtime h.static.Store is the shared helper's reloadLocal (proxy/adaptapply.go), under adaptMu.
  • Apply writes only names the server offered. It writes only AdaptOffer("tools", who.TenantID, basis, option) names, from that account's latest report and within 30 minutes. It then checks every name starts with mcp__ or the skill prefix and is not Context Guru's own. An empty basis gets 400: with that check disabled, TestAdaptToolsApplyWritesOnlyTheReportedNames fails.
  • The report is scoped to the caller. The GET report defaults to tenant=me. With that default removed, the restored TestAdaptToolsApplyForAManagerWritesOnlyTheirOwn fails, because the manager's report lists the other account's server.
  • withComponent keeps a present toolfilter in place. applyNote reads the written config back, so a restore names what stays filtered. The report uses the shared report slot.
  • gofmt and go vet are clean. go test passes for proxy, components/... and cmd/.... In dash, one SQLITE_BUSY flake under load passed on rerun. go test -race ./proxy -run Adapt passes. All commits are signed off with no AI attribution.

Non-blocking:

  1. This branch is based on 1521573, not #528's head 9b6a830. So it lacks the actor match in adaptRevert, the fix for "a manager's adapt apply on the account's behalf must not be revertible by the account token". Merging #528 first brings it in. Rebase before this merges so the tested tree is the merged one.
  2. The tools revert is not tools-only. It undoes the caller's latest adapt change of any kind (see the #528 note), and the answer says so ("whatever made it"). Matching the kind would make "revert tools" mean what it says.
  3. The ownDecl defence-in-depth check in apply is not pinned by a test, which is fine because the report never emits such a name.

@OsherElhadad
OsherElhadad force-pushed the feat/adapt-tools branch 2 times, most recently from fc269f1 to e05cbb7 Compare October 13, 2026 21:10

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: APPROVE at bd15bf4. (Posted as a comment: GitHub does not let the author account approve.)

  • The branch is rebased on #528's d6b3147 (per-kind revert). Tools uses adaptWrite/adaptRevert with kind "tools", so a tools revert cannot undo a compaction apply. The new test pins apply's refusal of own and non-MCP names.
  • Pricing fix. A 5-minute write is priced at the write rate again. With rate = p.CacheWrite removed, TestAdaptToolsPricesAFiveMinuteWriteAtTheWriteRate fails. The regression came in at 667d225, and my earlier approvals missed it: the earlier 1h test only exercised the 1h branch.
  • gofmt and go vet are clean, and the dash Adapt tests and proxy Adapt|ToolFilter tests pass. All commits are signed off with no AI attribution.

Approved. Merge after #528.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-confirm: APPROVE at a5e3295 (rebased onto #528's 9496607; was bd15bf4). git range-diff d6b3147c..e925f27d 9496607d..d592326a shows 21 of 22 commits identical. The only changed patch is 352d2b7 → 5cdab08, and its sole difference is context lines in cmd/context-guru-proxy/main.go from the squashed base; no code change. CI is green. This approval covers a5e3295.

@amiddavid
amiddavid changed the base branch from feat/adapt-compaction to main October 15, 2026 10:07
Osher-Elhadad added 8 commits October 15, 2026 13:37
…kills priced per carrying request

Record each request's declaration-set digest so a declaration is priced
on exactly the requests that carried it; older rows fall back to the
tool-count match and report a low/high bound.

Signed-off-by: Osher-Elhadad <[email protected]>
…kills suggest disabling the plugin

Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Options keep / remove-sufficient / remove-unused / restore, a basis id
the apply must match, warnings, and one-hour cache writes priced at 2x.

Signed-off-by: Osher-Elhadad <[email protected]>
…d dates every item's window

Signed-off-by: Osher-Elhadad <[email protected]>
…er apply with a JSON reason

Signed-off-by: Osher-Elhadad <[email protected]>
…r's own account

One-hour writes price the declarations at 2x outright, the undo carries a
basis, apply refuses anything but MCP and skill entries, and names that
are not plain identifiers are never offered in a command.

Signed-off-by: Osher-Elhadad <[email protected]>
Osher-Elhadad added 8 commits October 15, 2026 13:38
One override file and one revert for every adapt command: the report's
options are offered for a short time and apply takes one of exactly
those; locally the helper rebuilds the running pipeline. editRemoved is
the one toolfilter list edit for the Inventory switch and adapt.

Signed-off-by: Osher-Elhadad <[email protected]>
… document the local trust boundary

Signed-off-by: Osher-Elhadad <[email protected]>
…anager scoping test

Tests wait for the inventory on the database rather than polling the
report route, which now allows one running report per account.

Signed-off-by: Osher-Elhadad <[email protected]>
@amiddavid
amiddavid merged commit a8f6484 into main Oct 15, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants