Repository navigation
feat: /api/adapt/tools, never-used MCP servers, tools and skills priced per carrying request - #523
Conversation
OsherElhadad
left a comment
There was a problem hiding this comment.
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.
gofmtandgo vetare clean ondashandproxy. TheAdapt*dash tests pass, as do TestCapturedRequestRecordsItsDeclarationDigest, the apply test and the existing ToolFilter tests (theupdateRemovedrefactor 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 matchingcontext[-_]?gurunever become items. A stale basis gets 409, an unknown option 400, a missing cookie 401, and the write goes through the same auditedreg.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:
- An empty
basisskips 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 requirebasisand answer 400 without it. - 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
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at afa0dd5. (Posted as a comment: GitHub does not let the author account approve.)
- Both blockers are fixed. A missing
basisnow gets 400; with that check disabled, TestAdaptToolsApplyWritesOnlyTheReportedNames fails. Apply scopes totenant=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.
gofmtandgo vetare clean, and the dashAdapttests and proxyAdapt|ToolFilter|DeclDigesttests pass. Both commits are signed off with no AI attribution.
Approved.
OsherElhadad
left a comment
There was a problem hiding this comment.
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
statsTrustedaccepts: loopback, with no forwarded headers. With the gate disabled, TestAdaptToolsApplyOnALocalProxy fails.readJSONstill runscheckOrigin, so a browser page (cross-site POST or DNS rebinding) cannot drive the route. Hosted mode keeps the cookie path. - Concurrency.
h.staticis anatomic.Pointer; readersLoadit intenancyFor, and writes are serialised bylocalMu.Pipeline.Withbuilds 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. gofmtandgo vetare clean, and thecomponents/...tests pass. In a fullgo test ./dashrun, 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:
Pipeline.Withputs the toolfilter last. That matches the presets that end withtoolfilter, 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.- Restore on a local proxy. The
restoreoption lists the whole current removal list, including the config file's own names.updateLocalRemovednever takes those out (unionRemoveadds them back), yet the answer says "stopped filtering X". Either offer only the names apply added, or say that config-file names stay filtered. - 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.mdfor anyone running a single-tenant proxy on a shared host.
8f9a34e to
09a480b
Compare
1d03ab5 to
60e46d8
Compare
60e46d8 to
ee3050b
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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.goandPipeline.Withare gone. The only runtimeh.static.Storeis the shared helper'sreloadLocal(proxy/adaptapply.go), underadaptMu. - 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 withmcp__or the skill prefix and is not Context Guru's own. An emptybasisgets 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. withComponentkeeps a present toolfilter in place.applyNotereads the written config back, so a restore names what stays filtered. The report uses the shared report slot.gofmtandgo vetare clean.go testpasses forproxy,components/...andcmd/.... Indash, one SQLITE_BUSY flake under load passed on rerun.go test -race ./proxy -run Adaptpasses. All commits are signed off with no AI attribution.
Non-blocking:
- 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. - 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.
- The
ownDecldefence-in-depth check in apply is not pinned by a test, which is fine because the report never emits such a name.
fc269f1 to
e05cbb7
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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/adaptRevertwith 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.CacheWriteremoved, TestAdaptToolsPricesAFiveMinuteWriteAtTheWriteRate fails. The regression came in at 667d225, and my earlier approvals missed it: the earlier 1h test only exercised the 1h branch. gofmtandgo vetare clean, and the dashAdapttests and proxyAdapt|ToolFiltertests pass. All commits are signed off with no AI attribution.
Approved. Merge after #528.
8ace311 to
63dfba9
Compare
bd15bf4 to
a5e3295
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
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.
a5e3295 to
fd300e3
Compare
…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]>
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]>
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]>
Signed-off-by: Osher-Elhadad <[email protected]>
… document the local trust boundary Signed-off-by: Osher-Elhadad <[email protected]>
…mmands 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]>
Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
… tools Signed-off-by: Osher-Elhadad <[email protected]>
fd300e3 to
9b489bf
Compare
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
toolfilterentry (remove_as) and the client-side change that stops sending it. That change isclaude mcp remove,claude plugin disablefor a plugin's server or skills, disconnecting a claude.ai connector, apermissions.denyentry for a single MCP tool, orskillOverridesfor a user skill.keep,remove-sufficient,remove-unused,restore), recommendation, basis id and warnings.spend_usdis 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_usdis saved minus spend, and nothing is recommended when the rewrite outweighs the saving.requests.decl_digest(additive column): each captured request now records the digest of the declaration set it carried.usd_low/usd_highbound it.POST /api/adapt/tools/apply {option, basis}runs on the shared adapt apply helper (base branchfeat/adapt-compaction): the same identity rule, rate limit, audit row, revert and single-tenant override file as every/api/adapt/*/apply.restoretakes the entries out again;revertundoes the last adapt change.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 intoeditRemoved, 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.denyandskillOverrideschanges really removed those declarations from the next session's requests.skillOverridesdoes 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
revertrestored the starting configuration.Not done