Skip to content

fix(dash): record deferred MCP tools in the tool inventory - #728

Merged
vz-ibm merged 6 commits into
mainfrom
fix/deferred-mcp-inventory
Oct 26, 2026
Merged

vz-ibm merged 6 commits into
mainfrom
fix/deferred-mcp-inventory

Conversation

@vz-ibm

@vz-ibm vz-ibm commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Summary

/cg:insights tools reported 0 MCP servers on Claude Code 2.1.310. It also listed an unknown tool, DeferredToolPlaceholder. On the test Mac, 5 MCP servers with 39 tools are connected.

Why it happens: Claude Code now defers MCP tools. The request's tools array holds only the built-ins and a DeferredToolPlaceholder stub. The mcp__* names travel as a text list in a message:

The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded — ...
<one tool name per line>

The inventory read only the tools array, so it never saw the MCP tools.

What changed

All in dash/toolinventory.go:

  1. Read the deferred list. Each mcp__<server>__<tool> line becomes an MCP tool row with its server.
  2. Combine the lists. Each list is a delta (one session sent 2 tools, then 37). The declared set is all of them together.
  3. Cost. The list's measured tokens are split equally over its names. The MCP tools carry their shares. Before, nothing carried this cost: the placeholder had 0 tokens.
  4. No double count. A tool loaded through ToolSearch is in both the list and tools (defer_loading, 0 tokens). It keeps one row.
  5. Placeholder. DeferredToolPlaceholder is no longer a row.
  6. Fail-safe parse. A list counts only in a user or system text block, with the header at a line start and bare tool names on every line. A quoted header or a tool result declares nothing.
  7. Digest. The lists feed the declaration-set digest, with byte searches only. A request without a list keeps its old digest.

Not handled: removals. Their wording is not captured yet. A removed server stays in the set until the session ends.

Only mcp__ names are recorded. 8 other names in the list (for example ArtifactData, DesignSync) are not in builtinTools, so recording them would show them as unused client tools.

How it was tested

  • 10 new tests in dash/toolinventory_deferred_test.go, with fixtures copied byte for byte from real requests (dash/testdata/deferred/). The 7 behaviour tests failed before the fix. Each of the 3 guard tests fails when its guard is removed.
  • go build ./... and make lint: clean.
  • go test ./dash/...: all pass except TestCalculatorPricesFromTheRowsModelNotABlend. It also fails on clean main (3 of 3 runs), so it is not from this change.
  • Benchmark BenchmarkScanInventoryDeferred (new, built from the fixtures; BenchmarkScanInventory skips without /tmp/cg-runs):
Case Before After
Warm, request with the list 3.0 µs 4.2 µs
Warm, request without the list 1.35 µs 1.35 µs
Cold, new list (once per set) 6.5 µs 110 µs
  • End to end, on a real Mac (Claude Code 2.1.310 through a proxy built from this branch):
    • /api/tools shows 5 servers and 39 MCP tools: playwright 25, memory 9, context7 2, web-search 2, sequential-thinking 1. No placeholder row.
    • A session that loaded and called mcp__context7__resolve-library-id shows one row (9 tokens), calls: 1, and the context7 server row shows calls: 1.

Data dependence

  • No change to what any component or feature stores.

The inventory already stores MCP tool names, servers and token counts. This PR adds more rows of the same kind. The declaration text of a new row is the tool name itself, and it stays under the same consent gate.

What it does at each level (see docs/data-dependence.md):

  • Off: no change. No dashboard, no inventory.
  • Metadata only: works. It stores the MCP tool names, servers and token counts.
  • Everything: works. It also stores each name as the declaration text.

Open questions

  1. Removal wording: should a follow-up capture it and subtract removed tools?
  2. Side finding, for a separate PR: a server row can show calls: 0 while its tool shows a last-used time. lastUsedOf counts calls in every session in scope. Calls counts only sessions that declare the tool.

Assisted-By: Claude (Anthropic AI) [email protected]

Claude Code 2.1.310 defers MCP tools. The tools array then holds only the
built-ins and a DeferredToolPlaceholder stub. The mcp__* names arrive as a
text list in a message. The inventory read only the tools array, so
/cg:insights tools reported 0 MCP servers and listed the placeholder.

- Read every deferred-tools list in the request and record each mcp__ name
  as an MCP tool with its server. The lists are deltas, so combine them.
- Split each list's measured tokens equally over its names.
- A tool loaded through ToolSearch keeps one row, charged once.
- Skip the placeholder.
- Accept a list only in its exact shape, in a user or system text block,
  so a quoted header or a tool result declares nothing.
- Feed the lists into the declaration-set digest. A request without a list
  keeps its old digest.

Removals are not handled: their wording is not captured yet.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session fresh 1 of 2 1 of 2 f020a265374b blocking

Verdict: blocking

Findings

  1. dash/toolinventory.go:225 — the new deferred MCP rows are offered for a proxy filter that cannot remove them
    • What fails: a Claude Code 2.1.310 session with an unused deferred server, for example playwright.
      1. This PR records 25 mcp__playwright__* rows with real token shares (before: no rows).
      2. adaptToolsCandidate (dash/adapttools.go:1088-1094) turns them into one mcp_server item with RemoveAs: "mcp__playwright". finish puts it in remove-sufficient / remove-unused, and the report says "filtering them would have saved $X".
      3. The user says yes. adaptToolsApply (proxy/adapttoolsctl.go) writes mcp__playwright to the removal list.
      4. filterDeclarations (apply/toolfilter.go:128-200) reads only the tools array. The deferred names are text in a user message, so pass 1 finds no candidate and the request goes out unchanged. Saving: 0.
      5. The item then leaves the report for good: removed["mcp__"+server] excludes it (adapttools.go:1088). SavedSoFar prices filter items only on rows with filtered_decl_tokens > 0, and this filter never sets it, so it shows nothing for the item.
    • Result: the plugin says "Applied: filtered", the user pays the same tokens, and the report no longer shows the server. The same applies to the /api/tools suggestions (dash/toolsuggest.go), which also feed the proxy filter.
    • Proof: grep -rln "ToolSearch\|deferred tools" --include=*.go . finds only dash/toolinventory.go and its test. No code in apply/ touches the deferred list. Before this PR the path could not fire, because deferred tools had no rows. This PR makes it reachable. No test covers inventory → adapt for a deferred row.
    • Fix: mark a deferred row, for example a flag on Decl or a distinct marker in Server/Kind. Then, in adaptToolsCandidate and suggest, either do not offer RemoveAs (offer only the client-side claude mcp remove / permissions.deny), or count it as a client-side item. Add a test: a body with a deferred list → AdaptTools → no filter option that names a deferred-only server. The filter must not edit the user message, because that would break the cached prefix.

Non-blocking

  • hashDeferred hashes every header in the raw body, also a header in a tool result or in quoted user text. deferredDecls then returns the same rows, but under a new digest. Each such session writes one more declaration set, with the same content. A session that talks about this feature (like the one that wrote this PR) hits it. This is cheap, but it is not "a tool result declares nothing" at the digest level.
  • No removals: a server that the user removes mid-session is still charged on every later request of that session. The adapt report then overstates that server's cost. The PR says so. Please file the follow-up as an issue so it does not get lost.
  • mergeDeferred replaces a ToolSearch-loaded tool's row (Text = whole schema) with the listing row (Text = name only). With consent on, the dashboard then shows only the name, not the loaded schema. This is acceptable, but a one-line comment would help.
  • Lists that sit before an auto-compaction are gone after it. I did not verify that Claude Code sends a full list again after it compacts. If it does not, the set becomes smaller after a compaction.

What I checked

  • The full diff of dash/toolinventory.go (+202), all 10 tests in dash/toolinventory_deferred_test.go, and the 4 fixtures in dash/testdata/deferred/.
  • hashDeferred / stringEnd: the escaped-quote parity and the \n\n end in the raw JSON, the maxListing budget, and that the digest does not change without a header (TestNoDeferredReminderKeepsTheDigest).
  • appendDeferred: the line-start rule, the void-on-bad-line rule, the </system-reminder> end, the token split (share/extra), and the dedupe through seen.
  • deferredDecls: only user/system roles and only text blocks. tool_result blocks are skipped.
  • declsFrom: the placeholder skip needs both the name and defer_loading.
  • Consumers of KindMCPTool rows: dash/adapttools.go (candidate, finish, saved), dash/toolsuggest.go, dash/toolremoval.go, proxy/adapttoolsctl.go, and apply/toolfilter.go (pass 1 and pass 2).
  • Data dependence: the new rows hold only names, servers and token counts, and Text is the name. I agree with "no change". The package doc now says that the inventory reads a user-role block, and why.
  • Fail open: all new code reads only, has no panic path that I can see (all slice bounds checked), and does not change the request.
  • I did not run Go builds or tests. Live tests were not approved.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session fresh 2 of 2 1 of 2 f020a265374b blocking

Verdict: blocking

Findings

  1. dash/toolinventory.go:582 — the new deferred MCP rows make /api/adapt/tools offer a proxy filter that cannot remove them
    • What fails: a Claude Code 2.1.310 session declares 5 deferred MCP servers and calls none of them. After this PR, tool_declarations holds 39 mcp_tool rows with token shares. adaptToolsCandidate (dash/adapttools.go:1088-1094) turns each unused server into an item with RemoveAs: "mcp__<server>". finish (dash/adapttools.go:784-792) offers "Filter the N unused items" with a SavedUSD. The user says yes, and adaptToolsApply (proxy/adapttoolsctl.go:55-66) writes mcp__playwright and the others into the toolfilter list. Then filterDeclarationsWithAdapter (apply/toolfilter.go:128-150) looks only in the tools array. The deferred tools are not there: they are names in a user-message text block. So any stays false, the body goes out unchanged, and the listing lines still go to the model on every request. The report promised a saving, and the apply saved 0 tokens. filtered_decl_tokens stays 0, so the "what your earlier removals saved" part also shows nothing. The tools also stay callable through ToolSearch.
    • Proof: before this PR, deferred MCP tools had no rows, so the adapt report could not offer them. The new rows come from appendDeferred (dash/toolinventory.go:582) with Kind: KindMCPTool, which is the exact kind adaptToolsCandidate treats as removable by the proxy filter. No code in apply/ reads the deferred-tools list (grep -i 'deferred\|ToolSearch' apply/*.go finds nothing relevant). So the inventory now reports a declaration that the filter, the only actor of the "Apply it?" step, cannot act on.
    • Fix: pick one. (a) Mark deferred rows so the adapt report does not offer them as proxy-filter items, and offer only the client change (claude mcp remove <server>) for them. A distinct marker, for example Server plus a flag or a separate kind, would also let the Inventory tab show them. (b) Teach apply/toolfilter.go to cut the named lines out of the deferred list, with the same prose and pending-call gates. Option (b) changes the cached prefix, so (a) is the smaller change for this PR. Add a test: a body with only deferred MCP tools gives an adapt report with no filter option for them (or, for (b), a filter that removes the lines).

Non-blocking

  • appendDeferred accepts a list in a user-role text block. A user who types the header line, then bare mcp__x__y lines, then a blank line, declares those tools. The impact is small (identifier rows only, and a quoted header with prose is rejected, as the test shows). The doc comment says this. It may still be worth a sentence in the PR under "Open questions".
  • hashDeferred searches the whole raw body, tool results included. A tool result that holds the header (for example cat of a fixture) changes the digest, but deferredDecls ignores it. The result is one extra declaration set per such session, with the same rows. This is harmless, but the comment "writes every deferred list" can mislead a reader.
  • Removals are not handled, as the PR says. A removed server stays in the set and so keeps looking "unused" with a cost. With finding 1 fixed, this matters less, because nothing will be filtered on it.
  • The list cost includes the header and the built-in names, but only the MCP names carry shares. So the sum of the rows is less than the list's measured cost (39/60 of it in the fixture). This is a fair choice, but the Inventory tab total for "what this session carries" now under-counts the listing. A marker row like skill_listing would keep the total honest.

What I checked

  • Read the full diff: dash/toolinventory.go, dash/toolinventory_deferred_test.go and the 4 fixtures.
  • Read the code around each change: ScanInventory, declsFrom, skillRegion, skillDecls, usedFrom, the cache (declCache, declBytes) and the writer.
  • Traced hashDeferred and stringEnd: each loop step moves forward (the header has no " and no \n\n), so there is no infinite loop. The budget bounds the bytes hashed. A body without the header writes nothing, so the old digest holds (the test confirms it).
  • Traced appendDeferred: line start check, reminderEnd stop, blank-line stop, name charset, share and remainder split, dedup with seen across lists, identName on name and server.
  • Traced mergeDeferred: it drops only a 0-token mcp_tool row whose name is in the list, so a loaded tool keeps one row with a share.
  • Traced the consumers of KindMCPTool rows: dash/adapttools.go (carriedCost, adaptToolsCandidate, finish, the saved part), proxy/adapttoolsctl.go and apply/toolfilter.go. This is where finding 1 comes from.
  • Fail open: the new code adds no panic path I could find (gjson on bad input gives empty results, slices stay in range). ScanInventory runs on the capture path, not on the forward path.
  • Data dependence: the new rows are names and token counts, the same kind as before, and Text is the name only, under the same consent gate. I agree with "No change".
  • Did not run Go builds or tests (not approved; Go is not installed).

Review round 1 on #728: the proxy filter removes only `tools` elements. A
deferred MCP tool is a name in a message, so the filter cannot remove it.
The adapt report, the filter suggestions and the Inventory switch offered
it anyway: the user saw "Applied", saved nothing, and the item left the
report.

- Mark deferred rows: Decl.Deferred, stored in a new
  tool_declarations.deferred column (old rows read 0).
- /api/adapt/tools: a deferred item keeps its client command
  (claude mcp remove <server>), has no remove_as, and is in no filter
  option.
- /api/toolfilter suggestions: a deferred tool stays a suggestion, so the
  insights verdict still works, but names no filter entry.
- /api/tools rows carry `deferred`; the Inventory switch is disabled for
  them, with the reason.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>
@vz-ibm

vz-ibm commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

Reply to review round 1

Both reviewers found the same blocking finding. Fixed in 5128788.

Finding 1: the proxy filter is offered for deferred MCP tools it cannot remove

Fixed. The user chose option (a): mark deferred rows, and offer only the client change.

  • Decl.Deferred marks a row from the deferred list. A new column tool_declarations.deferred stores it (old rows read 0).
  • /api/adapt/tools: a deferred item keeps its cost and its client command (claude mcp remove <server>). It has remove_as: "", client_only: true, and it is in no filter option. One deferred tool makes its whole server item client-only.
  • /api/toolfilter suggestions: a deferred tool stays a suggestion, so the insights remove verdict still works. It names no filter entry (remove_as: "", client_only: true).
  • /api/tools rows carry deferred. The Inventory switch is disabled for them, with the reason, like the skill switch.
  • The deferred lookup is its own small query (deferredNames). The report's inventory read keeps its covering index, idx_tooldecl_inventory.

Tests (dash/toolfilter_deferred_test.go, each failed first for the intended reason):

  1. The writer stores deferred = 1 for a deferred row and 0 for a tools row.
  2. AdaptTools: the deferred server is listed with claude mcp remove dfr, and no option names it. The tools-array server keeps its filter option.
  3. ToolFilterDocFor: the deferred suggestion is kept, with no remove_as.
  4. ToolReportFor: rows carry the flag.

Live check (Claude Code 2.1.310 through a proxy built from 5128788): playwright is listed as client_only with claude mcp remove playwright. The remove-unused option holds no MCP name. All 39 MCP rows on /api/tools have deferred: true.

Not tested automatically: the Inventory switch. TestUISmokeEveryTab skips on macOS (it looks for chrome-linux64).

Non-blocking notes

  • Digest counts a header in a tool result or quoted text (both reviewers). True, and accepted. The cost is one extra declaration set, with the same rows, for such a session. I made no change: making the hot-path byte search role-aware costs more than the duplicate set.
  • Removals not handled (both). Accepted. I will open an issue after this PR, as asked.
  • mergeDeferred keeps the name, not the loaded schema, as Text (reviewer 1). Accepted as is. The flag now marks the row as deferred, so the reason is visible in the data.
  • Compaction may drop earlier lists (reviewer 1). Not verified. A compacted session that loses the lists would show a smaller set, never a wrong filter offer. It is in the follow-up issue.
  • A typed header plus bare names declares tools (reviewer 2). Accepted. The impact is identifier rows only, and the filter is no longer offered for them.
  • The list's header and built-in names carry no share (reviewer 2). This is on purpose: removing an MCP tool gives back only its own line. The total under-counts the listing by that amount. A listing marker row can follow if wanted.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 2 of 2 2 of 2 512878873b77 blocking

Verdict: blocking

Earlier findings

  • Reviewer 1, finding 1, and reviewer 2, finding 1 (the same defect): mostly fixed. /api/adapt/tools, the /api/toolfilter suggestions and the per-row Inventory switch no longer offer the filter for a deferred tool. One path is still open: the server group switch on the Inventory tab. See finding 1 below.

Findings

  1. dash/ui/tools.js:932-936 — the Inventory tab's server switch still writes a deferred server to the proxy filter
    • What fails: a deferred server with more than one tool, for example playwright (25 tools, not plugin-bundled).
      1. groupRemovable (tools.js:646-650) groups its rows under sub = 'MCP server', because each row's removal has kind: 'mcp_tool' and the command claude mcp remove playwright (dash/toolremoval.go:134-137). This PR does not change that.
      2. removalGroup (tools.js:932-933) builds a new object for the group switch: { kind: 'mcp_server', name: '', server: g.label, tokens: g.tokens }. It has no deferred field.
      3. excludeToggle (tools.js:1445) reads t.deferred on that object. The value is undefined, so fixed is false and the switch is enabled.
      4. The user ticks it. toggleExcluded posts {kind: 'mcp_server', server: 'playwright', action: 'exclude'} to POST /api/toolfilter. ctlToolFilter (proxy/toolfilterctl.go:110-139) resolves it to mcp__playwright and writes it. Nothing on the server side checks for a deferred server.
      5. The result is the same as the round-1 defect. filterDeclarations finds no tools element for playwright and saves 0 tokens. isExcluded then shows the switch as on. adaptToolsCandidate drops the server from /api/adapt/tools, because removed["mcp__playwright"] is now true (adapttools.go:1104).
    • Proof: the trace above, from the lines named. The per-tool switches in the same group are disabled, because they get the real row with deferred: true. The group switch above them is enabled. The reply on the PR says the Inventory switch was not tested automatically (TestUISmokeEveryTab skips on macOS), so no test covers this.
    • Fix: in removalGroup, set deferred: g.items.some((t) => t.deferred) on the srv object, so excludeToggle disables it with DEFERRED_SWITCH_REASON. As defence in depth, consider a refusal in ctlToolFilter for a name that deferredNames returns. Then a hand-made POST or another client also cannot write it.

Non-blocking

  • deferredNames (dash/toolapi.go) filters on d.deferred = 1, and no index covers that column. It runs on every /api/tools, /api/adapt/tools and /api/insights request. For each session in scope, SQLite can use idx_tooldecl_session, but it must then read each row from the table to test deferred. On a broad scope this reads most of the 695 MB table. dash/api.go:77 and :888 record earlier 503 outages on these same routes. I did not measure it. A partial index, CREATE INDEX ... ON tool_declarations(session_id) WHERE deferred = 1, makes it nearly free, because almost no rows match. Please measure it, or add the index.
  • deferredNames is keyed on the tool name only. If a tool is deferred in one session and in tools in another, the item becomes client-only for all sessions. That is the safe direction, so I accept it.
  • The author's replies to my round-1 non-blocking points are reasonable. I accept each one.

What I checked

  • Last review: round 1, f020a26, 2026-10-26T07:45:22Z
  • New commits read: 1 (5128788 fix(dash): never offer the proxy filter for a deferred MCP tool)
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Commit 5128788: read the full diff of all 7 files and the code around it. Finding 1 comes from it.
    • Comment by vz-ibm at 2026-10-26T08:02:56Z ("Reply to review round 1"): checked each claim against the code. The adapt, suggestion and per-row switch fixes are as described. The group switch is not covered (finding 1). I accept the replies to the non-blocking points.
  • dash/adapttools.go: ClientOnly is set under metaMu for any deferred tool of an item, RemoveAs is cleared, and finish skips client-only items for all filter options. The item still keeps Suggest and its cost.
  • dash/toolsuggest.go: a deferred suggestion keeps its row for the insights qualified set (dash/insightsapi.go:73-77), with remove_as empty. insights.py:963 falls back to the name when remove_as is empty, so it prints no wrong filter entry.
  • dash/toolinventory.go and dash/schema.go: the new column is additive with DEFAULT 0. The insert writes d.Deferred, and false for the system-prompt row. The primary key does not change, so a set already stored keeps its old row (ON CONFLICT DO NOTHING). That only affects sets written before the upgrade, which is acceptable.
  • dash/toolapi.go: deferredNames uses the same where/args and the same tenant scope as scopedUses. The query uses bound parameters only.
  • dash/ui/tools.js: traced every caller of excludeToggle (lines 936, 1023, 1380). The per-row and skill callers pass the real row. The group caller at 936 passes a new object (finding 1).
  • dash/toolfilter_deferred_test.go: 4 tests. They check the stored flag, the adapt item and options, the suggestion, and the /api/tools flag. They use specific values. No test covers the UI.
  • Data dependence: the new column is a flag, so it is metadata. I agree with "No change".
  • Fail open: the change is on the read and report side only. It does not change the request.
  • I did not run Go builds or tests. Live tests were not approved.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 1 of 2 2 of 2 512878873b77 blocking

Verdict: blocking

Earlier findings

  • Reviewer 1, finding 1, and reviewer 2, finding 1 (the same defect: the filter is offered for deferred tools): fixed for /api/adapt/tools, /api/toolfilter and the per-tool Inventory switch. I checked adaptToolsCandidate + deferredNames, finish, suggest, excludeToggle and the 4 new tests. One path is still open: the server-level switch in the Inventory tab. See new finding 1.
  • Non-blocking notes from both reviewers: the author accepted each one with a reason. I agree with each reason.

Findings

  1. dash/ui/tools.js:933 — the server-level Inventory switch still writes a deferred server to the filter

    • What fails: Claude Code 2.1.310, unused deferred server playwright (25 tools).
      1. renderUnused groups the 25 rows into one "MCP server" card. removalGroup builds srv = { kind: 'mcp_server', name: '', server: g.label, tokens: g.tokens } (lines 931-932). It does not copy deferred.
      2. excludeToggle(srv) computes fixed = ... || t.deferred (line 1445). srv.deferred is undefined, so the switch is live.
      3. The user turns it off. The page posts an mcp_server exclusion. proxy/toolfilterctl.go:237 accepts it and stores mcp__playwright.
      4. apply/toolfilter.go finds no tools element for it. Saving: 0. This is the exact defect of round 1, through the one switch that the fix did not reach.
    • Proof: the new commit changes only excludeToggle and adds DEFERRED_SWITCH_REASON. The per-tool rows get t.deferred from /api/tools, but the synthetic srv object at line 932 has no such field. The commit message says "the Inventory switch is disabled for them". That is true only for the per-tool switch. The author notes that the UI smoke test skips on macOS, so no test covers this.
    • Fix: deferred: g.items.some((t) => t.deferred) on srv. For defence in depth, the server side can refuse a mcp_server / mcp_tool exclusion whose name is only in deferredNames.
  2. dash/adapttools.go:831 — the summary says "everything was used" while it lists unused deferred servers

    • What fails: on Claude Code 2.1.310 every MCP tool is deferred. A user with 5 unused MCP servers and no unused skill gets len(all) == 0, because finish now skips every ClientOnly item (line 787). So Summary = "Every MCP server, MCP tool and skill you declared was used in this window." The same doc then has 5 items, and cg.py render_kind prints the summary and then "Never used in this window:" with those 5 servers. The two lines contradict each other. This is now the normal case, not an edge case.
    • Proof: finish lines 787-789 continue before all is appended. Line 831 case len(all) == 0: sets the "every ... was used" text. TestAdaptToolsNeverOffersTheFilterForADeferredServer seeds a filterable server too, so all is not empty there, and no test checks Summary with only deferred items.
    • Fix: count the client-only items apart. When len(out.Items) > 0 and len(all) == 0, say for example "N declared items were unused from A to B ($X). Claude Code sends them as deferred tools, which the proxy cannot filter: remove them in the client with the command on each item." Add a test with only deferred items that checks the summary.

Non-blocking

  • cg.py render_kind prints a client-only item with its name and cost, but not its remove command. The user sees a cost and no action. The summary fix above can name the action, or the table can show remove for a client_only item.
  • deferredNames keys on the tool name for the whole scope. If one session carries a tool as deferred and another carries it in tools, the tool is client-only everywhere. This is the safe direction. A short comment would help.

What I checked

  • Last review: round 1, f020a26, 2026-10-26T07:38:56Z
  • New commits read: 1 — 51287887 fix(dash): never offer the proxy filter for a deferred MCP tool
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 2's round-1 review (07:45:22Z): read in full. Its finding 1 is the same as mine and is handled above. I checked its 4 non-blocking points against the author's replies.
    • The author's reply comment (08:02:56Z): read in full. I checked each claim against the code. The claim "the Inventory switch is disabled for them" is only true for the per-tool switch (new finding 1).
  • The full diff f020a265..512878873b77 (7 files, +222/-9): adapttools.go, schema.go, toolapi.go, toolfilter_deferred_test.go, toolinventory.go, toolsuggest.go, ui/tools.js.
  • Code around each change: AdaptTools, finish (options, summary, recommendation), adaptToolsCandidate, scopedUses (same scope shape as deferredNames), toolReportFor errgroup, suggest, the writer's two declStmt.Exec calls (10 binds for 10 columns), additiveColumns and addColumns.
  • OpenReadOnly's temp view shims only requests. A read-only handle on an old file would fail on d.deferred. The only caller (cmd/cg-cache-campaign) calls only KVCacheDataset, so it does not reach deferredNames. No defect today.
  • Consumers of remove_as: insights.py falls back to the name when it is empty (line 963). The /api/toolfilter suggestion set in insights.py keys on (kind, name), so the remove verdict still works, as the author says.
  • UI: excludeToggle call sites at lines 936, 1023 and 1380. Lines 1023 and 1380 pass an API row, which has deferred. Line 936 passes the synthetic srv (finding 1).
  • Fail open: the new code is read-side and writer-side only. It does not change the request.
  • Data dependence: the new column is a flag (metadata). I agree with "no change".
  • I did not run Go builds or tests. Live tests were not approved.

… tools

Review round 2 on #728:

- The Inventory tab's server-group switch was built from a new object
  without `deferred`, so it stayed live and wrote mcp__<server> to the
  filter. It now carries `deferred` from its tools.
- POST /api/toolfilter refuses an exclusion of a deferred tool or server
  (409), and fails closed when it cannot check. An include is never
  refused. New DB.IsDeferredDecl does the per-tenant lookup.
- /api/adapt/tools no longer says "every item was used" when the only
  unused items are deferred. It names them and points to the client
  command.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>
@vz-ibm

vz-ibm commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

Reply to review round 2

Both findings are real. Fixed in 290749a.

Finding 1 (both reviewers): the server-group switch still wrote a deferred server to the filter

Fixed, in two places:

  1. UI. removalGroup now sets deferred: g.items.some((t) => t.deferred) on the srv object. excludeToggle then disables it with DEFERRED_SWITCH_REASON. This is the only mcp_server switch object in the UI.
  2. Server (defence in depth). POST /api/toolfilter now refuses an exclude of a deferred tool or a deferred server with 409. A new DB.IsDeferredDecl(tenant, name) does the lookup per tenant, with no window. It accepts both mcp__<server>__<tool> and the whole-server form mcp__<server>. If the lookup fails, the write fails closed (503). An include is never refused.

Tests:

  • TestIsDeferredDecl (dash): exact tool, whole server, a tools-array server, another tenant, and a non-MCP name.
  • TestToolFilterRefusesADeferredTool (proxy): 409 for the deferred server and tool. 200 for a tools-array server and for an include.

Both failed first for the intended reason (the stub returned false, and the POST returned 200).

Finding 2 (reviewer 1): the summary said "every item was used" while it listed deferred items

Fixed. finish counts client-only items apart. When none of the items is filterable and some are client-only, the summary says: "N declared items were unused from A to B ($X). Claude Code sends them as deferred tools, which the proxy cannot filter: remove them in the client with the command on each item." There is still no filter option and no recommendation.

Test: TestAdaptToolsSummaryWhenOnlyDeferredItemsAreUnused. It failed first with the exact text from the review.

Checks

  • go build ./... and make lint: clean.
  • go test ./dash/... ./proxy/...: all pass except TestCalculatorPricesFromTheRowsModelNotABlend, which also fails on clean main.
  • Live: on a single-user local proxy, POST /api/toolfilter is 405 (no per-account config), so the switch is off there anyway. The guard matters on a hosted proxy, which the proxy test covers.

Not tested automatically: the UI switch. TestUISmokeEveryTab skips on macOS.

The round budget (2) is used. More rounds are the user's decision.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 1 of 2 3 of 3 290749a004d3 approve

Verdict: approve

Earlier findings

  • Round 1, finding 1 (both reviewers): fixed. The filter is not offered for a deferred tool in /api/adapt/tools, /api/toolfilter or the per-tool switch.
  • Round 2, finding 1 (both reviewers), the server switch: fixed.
    • removalGroup sets deferred: g.items.some((t) => t.deferred) on srv (tools.js:934-935). excludeToggle then disables it.
    • ctlToolFilter refuses an exclude with 409 when IsDeferredDecl is true. It fails closed with 503 when the lookup fails. An include is never refused.
    • TestToolFilterRefusesADeferredTool covers both forms (server and tool), a tools-array server, and an include.
  • Round 2, finding 2 (reviewer 1), the summary: fixed. finish counts client-only items apart. A new case before len(all) == 0 names them and the client command. TestAdaptToolsSummaryWhenOnlyDeferredItemsAreUnused checks the text, Best == "keep", no recommendation, and one option.
  • Round 2 non-blocking points: the deferredNames name key is the safe direction (both reviewers accepted it). The cg.py table point is now covered by the summary text.

Findings

None.

Non-blocking

  • Reviewer 2's round-2 index point has no reply. deferredNames filters on d.deferred = 1, and no index covers that column. The author's round-2 reply does not mention it. I agree with reviewer 2 that it is worth measuring, or worth a partial index ON tool_declarations(session_id) WHERE deferred = 1. IsDeferredDecl has the same shape: it uses idx_tooldecl_tenant and then reads the tenant's rows until it finds a match. For a name that is not deferred (the common case) it reads all of them. It runs only on a switch POST, so it is rare, but the same partial index, keyed (tenant_id, name) or (tenant_id, server), makes it a lookup.
  • adaptToolsApply (proxy/adapttoolsctl.go) does not call IsDeferredDecl. Today this is safe: it writes only the names of a report option, and finish keeps client-only items out of every option. A one-line check there would make the guard the same for both write paths.
  • IsDeferredDecl has no time window. A server that was deferred once, and is later sent in tools (for example, a Claude Code version without deferral), stays refused for that tenant. This is the safe direction. A comment would help.

What I checked

  • Last review: round 2, 5128788, 2026-10-26T08:07:26Z
  • New commits read: 1 — 290749a0 fix(dash,proxy): close the server switch and the summary for deferred tools
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 2's round-2 review (08:06:48Z): read in full. Its finding 1 is the same as my round-2 finding 1, and it is fixed. Its index point has no reply (see non-blocking).
    • The author's reply comment (08:17:39Z): read in full. I checked each claim against the code: the srv flag, the 409 / 503 guard, the include path, IsDeferredDecl and its two forms, the summary case and its test. All match.
    • Commit 290749a0: read the full diff of all 6 files (+150/-2).
  • IsDeferredDecl: SplitMCPName picks the tool form. Otherwise it strips mcp__ and refuses a non-MCP name or an empty server. The query is parameterised and scoped by tenant_id. The tenant id on capture is e.TenantID (proxy/dashcapture.go:643), and the guard uses t.ID of the same account.
  • ctlToolFilter: the guard runs after declConfigName resolves the name and after the built-in check. So {"kind":"mcp_server","server":"dfr"} resolves to mcp__dfr before the lookup. h.rec == nil skips the guard; then there is no inventory, so nothing is deferred.
  • finish: the new case comes before the "every item was used" case. A report with both filterable and client-only items keeps the old summaries. Those count only filterable items, which is correct for the filter options they describe.
  • dash/ui/tools.js: srv is the only synthetic mcp_server object passed to excludeToggle (lines 936, 1023, 1380).
  • Tests: the proxy test polls with a deadline (no fixed sleep). The dash test adds a t2 row to prove the tenant scope.
  • Fail open: no change to the request path.
  • Data dependence: no change. The new code only reads the existing deferred flag.
  • I did not run Go builds or tests. Live tests were not approved.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 2 of 2 3 of 3 290749a004d3 blocking

Verdict: blocking

Earlier findings

  • Round 1, finding 1 (both reviewers), the filter is offered for deferred tools: fixed in round 2.
  • Round 2, finding 1 (both reviewers), the server switch still writes a deferred server: fixed. removalGroup now sets deferred from its tools (dash/ui/tools.js:934-935). ctlToolFilter refuses an exclusion with 409, and returns 503 when the check fails (proxy/toolfilterctl.go:139-153). An include is never refused. TestToolFilterRefusesADeferredTool covers both forms, a tools-array server and an include.
  • Round 2, reviewer 1, finding 2, the summary said "everything was used": fixed in /api/adapt/tools. The new text has a gap in the plugin. See finding 1 below.

Findings

  1. dash/adapttools.go:836 — the new summary tells the user to run "the command on each item", but /cg:remove-mcp-and-skills shows no command
    • What fails: Claude Code 2.1.310, 5 unused deferred MCP servers, no unused skill. This is now the normal case, as reviewer 1 showed in round 2.
      1. finish sets Summary = "5 declared items were unused from A to B ($X). … remove them in the client with the command on each item."
      2. render_kind (context-guru-plugin/scripts/cg.py:1143) prints that summary.
      3. It then prints "Never used in this window:" (cg.py:1156-1162). Each line has only the kind, the name, the cost and a bar. It never reads remove or suggest. No other line in cg.py reads either field.
      4. The skill rules (remove-mcp-and-skills/SKILL.md:32) say "Do not … add advice the output does not contain". So the model may not add claude mcp remove playwright on its own.
    • Result: the one command that this PR made the only way to act is not shown. The user reads "use the command on each item" and sees no command. Before round 3, this was reviewer 1's non-blocking point. The new summary text makes it a wrong instruction. The author's round-2 reply does not answer that point.
    • Proof: the lines above. grep -n 'suggest\|"remove"' context-guru-plugin/scripts/cg.py finds no read of an item's command. No golden file in context-guru-plugin/testdata/cg/ has a client_only item.
    • Fix: in render_kind, add the item's remove text when client_only is true (for example, one more column or a line under the item). Add a golden case with one client-only item. Another fix is to change the summary to name the command for each item. The plugin change is smaller and also helps the dashboard reader.

Non-blocking

  • My round-2 point on deferredNames has no reply. It filters on d.deferred = 1 with no index on that column. It runs on every /api/tools, /api/adapt/tools and /api/insights request. Please measure it on a broad scope, or add a partial index on (session_id) WHERE deferred = 1.
  • IsDeferredDecl with the whole-server form queries tenant_id = ? AND deferred = 1 AND server = ?. No index covers server, so it scans the tenant's rows. It runs once per POST, so the cost is small. The same partial index (with tenant_id, server) would cover it.
  • IsDeferredDecl has no time window. A server that was deferred once stays refused even if a later Claude Code version sends it in tools again. That is the safe direction, and the 409 text says what to do, so I accept it.

What I checked

  • Last review: round 2, 5128788, 2026-10-26T08:06:48Z
  • New commits read: 1 (290749a fix(dash,proxy): close the server switch and the summary for deferred tools)
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 1's round-2 review (08:07:26Z): read in full. Its finding 1 is the same as my round-2 finding 1. Its finding 2 (summary) I checked: real, and fixed in the API. Its non-blocking point on render_kind I checked and raise as finding 1, with the new summary text as new proof.
    • The author's reply (08:17:39Z, "Reply to review round 2"): read in full. I checked each claim against the code: the UI flag, the 409 and 503, IsDeferredDecl and its two forms, the per-tenant scope, the new summary and the 3 tests. Each claim is true. The reply does not answer reviewer 1's render_kind point or my deferredNames index point.
    • Commit 290749a: read the full diff of all 6 files and the code around it.
  • proxy/toolfilterctl.go: the check runs after declConfigName and the built-in check, on the resolved name. h.rec.DB() never returns nil for a live recorder (dash/capture.go:232), and WithContext is nil-safe. Fail closed on a lookup error, as the global rules ask.
  • dash/toolapi.go IsDeferredDecl: bound parameters only. A non-MCP name returns false with no query. mcp__ alone returns false.
  • dash/adapttools.go finish: client-only items keep their Remove and Basis, and add to the count and the cost. With no filterable item there is one option ("keep") and no recommendation, as the test checks.
  • dash/toolfilter_deferred_test.go: the new t2 row checks the tenant scope. The summary test checks specific text.
  • Fail open: all changes are on the report and control side. The request path does not change.
  • Data dependence: no change. The new code reads only the flag, names and servers.
  • I did not run Go builds or tests. Live tests were not approved.

Review round 3 on #728: the adapt summary sends the reader to "the
command on each item" for deferred MCP servers, but render_kind printed
only kind, name, cost and a bar. The skill may not add advice the output
does not contain, so the one way to act was not shown.

render_kind now prints a "run: <command>" line under each client_only
item. Filterable items keep their plain row. The Codex copy of cg.py is
synced.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>
Review round 3 on #728 (both reviewers, non-blocking): deferredNames runs
on every inventory read and filtered on tool_declarations.deferred with
no index, so it scanned the table. IsDeferredDecl did the same per tenant.

Add a partial index on (tenant_id, server, name, session_id) WHERE
deferred = 1, in additiveDDL2 because it names a column addColumns adds.
EXPLAIN QUERY PLAN: all three lookups now search the covering index. The
index holds only deferred rows, so it is empty on older databases.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>
@vz-ibm

vz-ibm commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

Reply to review round 3

Reviewer 1: approve. Reviewer 2: one blocking finding. Fixed in 9252634. I also added the index that both reviewers asked for, in dd7f8ed.

Finding 1 (reviewer 2): the summary points to "the command on each item", but /cg:remove-mcp-and-skills showed no command

Fixed. render_kind (cg.py) now prints a run: <command> line under each client_only item. Filterable items keep their plain row. The Codex copy of cg.py is synced (TestCGScriptsAreVendoredIntoCodex passes).

Test: TestCGRemoveShowsTheClientCommandForAClientOnlyItem. A fixture has one client-only server and one filterable skill. The command is shown for the server only. The test failed first for the intended reason.

Non-blocking

  • No index for deferred = 1 (both reviewers). Done, in dd7f8ed. It is a partial index ON tool_declarations(tenant_id, server, name, session_id) WHERE deferred = 1, in additiveDDL2, because it names a column that addColumns adds. EXPLAIN QUERY PLAN before: SCAN d USING INDEX idx_tooldecl_name. After: all three lookups (deferredNames, and IsDeferredDecl by name and by server) use SEARCH d USING COVERING INDEX idx_tooldecl_deferred. The index holds only deferred rows.
  • adaptToolsApply has no deferred check (reviewer 1). Not added, on purpose. It writes only names from a report option, and finish keeps client-only items out of every option, so the check would guard a state that cannot occur. ctlToolFilter is the path that takes a free name, and it has the guard.
  • IsDeferredDecl has no time window (both). Accepted as is. Both reviewers agree it fails in the safe direction, and the 409 text says what to do.

Checks

  • go build ./... and make lint: clean.
  • go test ./dash/... ./proxy/...: all pass except 2 tests that also fail on clean main (56f59a7) on this Mac:
    • TestCalculatorPricesFromTheRowsModelNotABlend: 3 of 3 runs.
    • TestALateFirstByteOnTheRealTransportNeverReachesTheClient: a 5 ms timing test. 7 of 10 runs fail on this branch, and 8 of 10 on main.
  • go test ./context-guru-plugin/: the new test, the vendoring test and all goldens pass once the host's ANTHROPIC_DEFAULT_*_MODEL variables are unset. With them set, main also fails the settings-card goldens. 15 install and settings tests also fail on main on this Mac: they find the real ~/.local/bin/context-guru-proxy, or they compare /var with /private/var. CI on Linux is the real check for these.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 2 of 2 4 of 4 dd7f8edfb9ca approve

Verdict: approve

Earlier findings

  • Round 1, finding 1 (both reviewers), the filter is offered for deferred tools: fixed in round 2.
  • Round 2, finding 1 (both reviewers), the server switch: fixed in round 3.
  • Round 2, finding 2 (reviewer 1), the summary text: fixed in round 3.
  • Round 3, finding 1 (reviewer 2), no command shown for a client-only item: fixed in 9252634. render_kind prints run: <command> under each client_only item. A filterable item keeps its plain row. TestCGRemoveShowsTheClientCommandForAClientOnlyItem checks both cases.
  • Non-blocking, no index for deferred = 1 (both reviewers): fixed in dd7f8ed with a partial index.
  • Non-blocking, adaptToolsApply has no deferred check (reviewer 1): rejected by the author. The reason is right: that path writes only names from a report option, and finish keeps client-only items out of every option. I accept it.
  • Non-blocking, IsDeferredDecl has no time window (both): accepted as is by the author. It fails in the safe direction. I accept it.

Findings

None.

Non-blocking

  • Without --details, render_kind shows only the first 8 items. A client-only item after the 8th has no run: line on screen, while the summary still says "the command on each item". --details shows all of them. This is minor, because the list is sorted by cost.

What I checked

  • Last review: round 3, 290749a, 2026-10-26T08:20:39Z
  • New commits read: 2 (9252634 fix(plugin): show the client command for a deferred MCP item; dd7f8ed perf(dash): index the deferred MCP rows)
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 1's round-3 review (08:20:03Z, approve): read in full. Its 3 non-blocking points are handled in the author's reply. I checked each reply (see "Earlier findings").
    • The author's reply (08:45:04Z, "Reply to review round 3"): read in full. I checked the render_kind change, the new test, the Codex copy and the index against the code. All claims match. The test failures named there also fail on main, as the author says. I could not check that, because live tests were not approved.
    • Commit 9252634: read the full diff of 3 files.
    • Commit dd7f8ed: read the full diff of dash/schema.go.
  • cg.py: T.cols (tvlib.py:198-209) returns one line for each input row, in order, so zip(shown, rows) pairs each item with its own line. The command comes from remove, else suggest. Both are built from names that pass adaptToolsSafe (adapttools.go), so no unsafe text reaches the screen.
  • The Codex copy is the same file: diff context-guru-plugin/scripts/cg.py codex-marketplace/plugins/context-guru/scripts/cg.py prints nothing.
  • The new test uses a fixture and checks specific text in both directions: the command is shown for the client-only server, and is not shown for the filterable skill.
  • idx_tooldecl_deferred in additiveDDL2: migrate runs additiveDDL (which creates tool_declarations), then addColumns (which adds deferred), then additiveDDL2, on both a fresh and an existing database (schema.go:853-888). So the column always exists before the index is created. The index columns (tenant_id, server, name, session_id) cover IsDeferredDecl (both forms) and deferredNames. The author's EXPLAIN QUERY PLAN result agrees with that.
  • Fail open: no change to the request path.
  • Data dependence: no change. The index and the plugin line use only names and the existing flag.
  • I did not run Go builds or tests. Live tests were not approved.

@vz-ibm vz-ibm 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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @vz-ibm) Claude Code 2.1.310 offload-review skill, @vz-ibm's session resumed 1 of 2 4 of 4 dd7f8edfb9ca approve

Verdict: approve

Earlier findings

  • Round 1 and round 2 findings (both reviewers): fixed in earlier rounds. Nothing in the new commits undoes them.
  • Round 3, reviewer 2, finding 1 (the summary names a command that the plugin does not show): fixed in 92526345. render_kind prints run: <remove or suggest> under each client_only item. A filterable item keeps its plain row. TestCGRemoveShowsTheClientCommandForAClientOnlyItem checks both. The Codex copy of cg.py is the same file (diff is empty).
  • Round 3, the index (both reviewers, non-blocking): done in dd7f8edf. See "What I checked" for the migration order.
  • Round 3, reviewer 1, no deferred check in adaptToolsApply: the author declined. The reason is right: that path writes only names from a report option, and finish keeps every client-only item out of every option. I accept it.
  • Round 3, no time window on IsDeferredDecl (both): accepted as is by everyone.

Findings

None.

Non-blocking

  • The run: line also shows suggest text that is not a command. For example, suggestServer gives "disconnect the X connector in claude.ai settings" for a claude_ai_ server, and "claude plugin disable P (the plugin that provides this server)" for a plugin server. A user who pastes the second one into a shell gets an error from the text in parentheses. A neutral word, such as do: or fix:, would fit all three forms.

What I checked

  • Last review: round 3, 290749a, 2026-10-26T08:20:03Z
  • New commits read: 2 — 92526345 fix(plugin): show the client command for a deferred MCP item; dd7f8edf perf(dash): index the deferred MCP rows
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 2's round-3 review (08:20:39Z): read in full. Its finding 1 (render_kind shows no command) is real. I checked cg.py at the old head, and it is fixed now. Its index points are fixed by dd7f8edf.
    • The author's reply (08:45:04Z, "Reply to review round 3"): read in full. I checked each claim against the code: the run: line, the test, the synced Codex copy, the index columns and where the index is created, and the reason for not guarding adaptToolsApply. The EXPLAIN QUERY PLAN result is plausible, because the index starts with tenant_id and then server and name. I did not run it.
    • Commits 92526345 and dd7f8edf: read the full diff (4 files, +50/-6).
  • cg.py render_kind: T.cols returns one line per input row, in order (tvlib.py:198-209), so zip(shown, rows) pairs each item with its own line. The extra line is not passed through T.cols, so the column widths do not change. Names and servers in suggest pass adaptToolsSafe first (adapttools.go:1106).
  • Index migration order: tool_declarations is created in additiveDDL (schema.go:467). migrate runs additiveDDL, then addColumns (adds deferred), then additiveDDL2 (creates the index), on both the fresh path and the already-at-version path (schema.go:853-888). So the column always exists before the index is created.
  • The index is partial (WHERE deferred = 1). The queries in deferredNames and IsDeferredDecl have d.deferred = 1 as a literal term, so SQLite can use the partial index.
  • Fail open: no change to the request path.
  • Data dependence: no change.
  • I did not run Go builds or tests. Live tests were not approved.

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review (automated, run with Claude Code). I built and tested the PR head on Linux.

Tests

  • go build ./... and go vet ./dash/... ./proxy/...: clean.
  • go test ./dash/...: pass.
  • go test -race -count=3 on the new deferred and inventory tests in dash and proxy: pass.
  • go test ./proxy/...: TestDashboardUnderConcurrentTraffic failed once (1 insert errors, dash_test.go:650) and passed on reruns. It looks flaky and unrelated to this PR. I did not check it on main.
  • TestCalculatorPricesFromTheRowsModelNotABlend passes here, on both this branch and main.
  • Plugin package (ANTHROPIC_DEFAULT_*_MODEL unset): only TestSaveMoreDefaultIncludesTheSettingsCard fails, and it fails the same way on main. TestCGRemoveShowsTheClientCommandForAClientOnlyItem passes. The two cg.py copies are byte-identical.
  • BenchmarkScanInventoryDeferred: warm 1.9 µs without the list and 5.8 µs with it, cold about 200 µs with the list (about 1000 allocs). Your table says 110 µs cold. The difference is down to the machine, and it is fine for a cost paid once per declaration set.

Findings (details inline)

  1. Issue: the hashDeferred region can run past the list into unrelated text, so the digest churns.
  2. Issue: the deferred flag is checked against every row the tenant ever had, so it never clears.
  3. Issue (known gap): removals and compaction. A removed server stays in the set and is suggested for claude mcp remove after it is already gone. If the client ever stops resending an old delta (compaction), the set shrinks and the digest flips. Please add a test, or at least a tracked follow-up, for both.
  4. Nit: with \r\n line endings the whole list is silently dropped.
  5. Nit: the token split is rough. The header (about 50 tokens) and the built-in names' shares are spread equally over the names, and the built-in shares are then dropped. Fine if that is deliberate, but the per-tool numbers are approximate.

Verified OK

  • Migration: deferred INTEGER NOT NULL DEFAULT 0 is added through addColumns, and the partial index lives in additiveDDL2, which runs after it. I tested only on fresh DBs; a test on an existing DB would be worth adding.
  • The proxy filter only removes tools elements, so deferred names and the placeholder are never rewritten.
  • The /api/tools/filter deferred check fails closed (503) and returns 409 for deferred tools.
  • finish keeps client-only items out of the apply options, so an empty RemoveAs cannot reach withDecl.
  • An assistant-role message that carries the header is correctly ignored.

Suggested extra tests: a list followed directly by other text in the same string (finding 1), a migration on an existing DB, and a list in an assistant message.

Comment thread dash/toolinventory.go Outdated
}
rest = rest[i:]
end := len(rest)
if j := bytes.Index(rest, []byte(`\n\n`)); j >= 0 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Issue: the digest can cover text after the list. The region ends at the first \n\n or at the end of the JSON string. appendDeferred also stops at a </system-reminder> line, and TestDeferredReminderInsideSystemReminderTag shows the closing tag can come right after the last name. When it does, and other text follows in the same string, that text goes into the digest too.

Repro, from a probe test: wrap the list in <system-reminder> with no blank line, then add <system-reminder>Today's date is …</system-reminder> in the same text block. Changing only the date changed the digest (682506… → ac8f1a…). Each change means a cold parse and tokenize (about 200 µs), a new declCache entry, and a new tool_declarations digest set for the session.

Suggested fix: also end the region at \n</system-reminder> (it appears literally in the escaped body), so the hash bounds match the parser's. Add a test where the text after the closing tag changes and the digest stays the same.

I can't confirm whether Claude Code actually sends it this way. The fixtures end with a blank line, but the parser already handles the tag form, so it seems worth matching.

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.

Fixed in 006da4e. Your repro was right, and it found a second spelling.

  • hashDeferred now also ends the region at a newline followed by </system-reminder>, so the hash bounds match the parser's.
  • Both JSON spellings. Claude Code writes the tag literally (I checked real request bodies). Go's encoder writes </system-reminder>, which is why my first version of the fix missed your repro: the test helper uses json.Marshal. Both are now matched (deferredTagEnds).
  • Tests: TestDeferredDigestStopsAtTheClosingTag (escaped form) and TestDeferredDigestStopsAtALiteralClosingTag (literal form, built as raw JSON, as a client sends it). In each, only the date after the tag changes, and the digest stays the same. Both failed first. The literal one also fails if I remove only the literal spelling.

Comment thread dash/toolapi.go
// (Decl.Deferred). Its own query, so the report's inventory read keeps its covering index
// (idx_tooldecl_inventory); only deferred rows match, so it is empty on older data.
func (d *DB) deferredNames(f Filter, where string, args []any) (map[string]bool, error) {
q := `SELECT DISTINCT d.name FROM tool_declarations d WHERE d.deferred = 1 AND d.session_id IN

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Issue: the deferred flag never clears. deferredNames here, and IsDeferredDecl (used by the proxy's 409), match any row of the tenant with deferred = 1, with no time bound. A tool that was deferred once stays marked as client-only forever, and the filter cannot exclude it. That stays true when the same tenant runs an older Claude Code, or a client that sends the tool in tools, where the filter would work.

Also, for the whole-server form mcp__<server>, IsDeferredDecl refuses as soon as any one tool of the server was deferred. The filter could still honour that exclusion in part.

Suggestion: limit both checks to recent rows, or better, to rows where the tool was not also seen as a real tools element. If you keep it as is, please document the limit.

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.

Fixed in 006da4e, with your "better" option.

A tool is now deferred only while the tenant's newest row for it is deferred. A NOT EXISTS subquery (newerPlainRow) skips a deferred row when a newer deferred = 0 row exists for the same tenant and name. So the flag follows the client the tenant uses now, with no time window to guess, and it clears as soon as a client sends the tool in tools. A loaded deferred tool stays deferred: mergeDeferred keeps its list row and drops its 0-token tools row, so it writes no plain row.

  • It applies to both deferredNames and IsDeferredDecl.
  • Query plan: the outer lookup still uses idx_tooldecl_deferred. The subquery uses idx_tooldecl_name (SEARCH p USING INDEX idx_tooldecl_name (name=?)).
  • Test: TestTheDeferredFlagClearsWhenTheToolIsSentInToolsAgain. Tool a is deferred in an old session and sent in tools in a newer one. Tool b stays deferred. Both lookups now say a is not deferred, while b and the mcp__srv form still are. It failed first (IsDeferredDecl(mcp__srv__a) = true).

Whole-server form, kept as is and documented: mcp__<server> is refused while any of its tools is still deferred. The filter cannot remove that tool, so a whole-server exclusion would save only part of the server while it hides the whole server from the report. Honouring it in part would change the filter's behaviour, so I left it out of this PR.

Comment thread dash/toolinventory.go
if k := strings.IndexByte(line, '\n'); k >= 0 {
line, next = line[:k], pos+k+1
}
if line == "" || line == reminderEnd {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: if a client sends \r\n line endings, every name line ends in \r, so isToolName fails and the whole list is dropped with no signal. Claude Code doesn't seem to send \r\n today, but strings.TrimSuffix(line, "\r") here costs nothing. A debug counter for voided lists would also make a future format change visible instead of showing up as "0 MCP servers" again.

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.

Fixed in 006da4e.

  • Each name line is trimmed of a trailing \r, so a CRLF list parses.
  • The hash region also ends at a CRLF blank line (\r\n\r\n), so the bounds stay the same.
  • Debug signal: a voided list now logs dash: ignored a deferred-tools list that did not parse at debug level. It logs counts only (names_before_bad_line, bad_line), never the text, because a voided list can be a user quoting the header. It fires on a digest miss only, so it adds nothing per request.
  • Test: TestDeferredListWithCRLFLineEndings. It failed first with servers = map[].

Teammate review on #728:

- The digest region ran past the list into later text when the closing
  </system-reminder> came right after the last name, so a changed date
  meant a new digest, a cold parse and a new declaration set. The region
  now also ends at that tag, in both JSON spellings (literal, as Claude
  Code sends it, and <...>, as Go's encoder writes it).
- The deferred flag never cleared: any deferred row ever seen kept a tool
  client-only. A tool is now deferred only while its newest row for the
  tenant is deferred, so it is filterable again once a client sends it in
  `tools`. A loaded deferred tool writes no plain row, so it stays
  deferred. The new NOT EXISTS uses idx_tooldecl_name.
- A CRLF client voided the whole list (every name ended in \r). Names are
  trimmed, and a CRLF blank line ends the hash region. A voided list now
  logs at debug level, counts only, never its text.
- The equal token split is documented as approximate on purpose.

New tests: the digest ignores text after the tag (both spellings), the
flag clears, CRLF parses, an assistant message declares nothing, and an
existing database gains the column and the index. A known gap is pinned:
removals are not subtracted yet.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Vitaly Zabershinsky <[email protected]>
@vz-ibm

vz-ibm commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator Author

Reply to @OsherElhadad's review

Thank you for the Linux run. All findings are addressed in 006da4e. The details are in each inline thread.

# Finding Status
1 The digest covers text after the list Fixed. The region ends at </system-reminder>, in both JSON spellings.
2 The deferred flag never clears Fixed. A tool is deferred only while its newest row is deferred.
3 Removals and compaction Pinned with a test. Follow-up below.
4 \r\n drops the whole list Fixed, plus a debug log (counts only) for a voided list.
5 The token split is rough Documented as approximate on purpose.

3. Removals and compaction

  • Removals: not subtracted yet. Claude Code's removal wording is not captured, and the user chose to ship additions only. TestDeferredRemovalIsNotYetSubtracted now pins today's behaviour: a server removed mid-session stays declared until the session ends. Its comment says to change it once the wording is captured. This is a known gap, not correct behaviour.
  • Compaction: if a client stops resending an old list, the set shrinks and the digest changes. That is a correct new declaration set, not churn, and it only ever under-reports. From one compacted session's transcript, Claude Code appears to send a fresh list on each change (deferred_tools_delta) rather than replay old ones, but one session does not prove it.

Both stay as a tracked follow-up. Capturing the removal wording needs a manual claude mcp remove on a real install.

Your suggested tests, all added

  • A list followed by other text: the two digest tests for finding 1.
  • A migration on an existing database: TestAnExistingDatabaseGainsTheDeferredColumn. An existing table without the column gains it on open, old rows read 0, and the partial index is created. It fails if the column is left out of additiveColumns, because the database then does not open.
  • A list in an assistant message: TestDeferredListInAnAssistantMessageIsIgnored. It fails if the role check is removed: all 39 tools would be declared.

Checks

  • go build ./... and make lint: clean.
  • go test ./dash/... ./proxy/...: all pass, except TestCalculatorPricesFromTheRowsModelNotABlend on this Mac. Your run shows it passes on Linux.
  • go test -timeout 20m ./context-guru-plugin/ (the whole package, with ANTHROPIC_DEFAULT_*_MODEL unset): all pass except
    • 10 that also fail on clean main on this Mac: install and setup tests that find this host's real proxy binary, or compare /var with /private/var.
    • 1 flaky one: TestRejectingAValueDoesNotEatTheNextFlag, "the proxy did not come up" under load. It passed 3 times out of 3 alone. This PR changes only dash/.
  • TestDashboardUnderConcurrentTraffic (your flaky one): it passed in my proxy run.

Benchmark note

Your cold figure (about 200 µs) and mine (110 µs) differ by machine. The cost is paid once per declaration set, so I agree it is fine.

@vz-ibm
vz-ibm merged commit f831e7e into main Oct 26, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 26, 2026
@vz-ibm vz-ibm mentioned this pull request Oct 26, 2026
1 task done
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