Skip to content

fix: a tool description is the last thing dropped, not the first (#726) - #727

Merged
EtanHey merged 2 commits into
mainfrom
fix/726-tool-descriptions-survive-the-wire
Aug 20, 2026
Merged

EtanHey merged 2 commits into
mainfrom
fix/726-tool-descriptions-survive-the-wire

Conversation

@EtanHey

@EtanHey EtanHey commented Aug 19, 2026 •

Copy link
Copy Markdown
Owner

Fixes #726.

The defect (Part A)

BrainBarServer.encodeRawJSONResponse stripped every tool description as soon as a raw
newline-framed tools/list crossed 8192 bytes (Claude Desktop's MCPB chunk limit). Core fit, so
core kept its descriptions — but calling expand_palette pushed the response over the limit and
came back with 0/17 descriptions. Expanding the palette downgraded the contract, silently.

AGENTS.md: "The rules for agents USING it live in the tool descriptions — keep those true." A
description is the last thing to drop, not the first.

The compaction ladder

encodeRawJSONResponse is now a ladder, and description survives every rung it can:

Rung Drops Why
0 nothing payload already fits
1 annotations + inputSchema property prose an agent needs neither to pick nor to call a tool
2 shortens descriptions, never removes them binary-searches the largest per-tool budget that fits

Rung 2 marks each shortened description …[truncated] and attaches an explicit
result._meta["brainlayer/descriptionsTruncated"] notice naming every affected tool, the byte
limit, the char budget, and where the full text is available. If even the 48-char floor does not
fit, the response goes out over the limit with its contract intact and logs why — a silent
contract-free response is the worse failure.

Fixing this by shortening alone (Part B) was explicitly rejected: a future tool addition must not
silently re-break it.

Tests run on the wire, not at router.handle()

Unit tests one layer above the stripping stayed green while the wire was wrong twice in this lane.
The new tests drive a real Unix socket, across the full matrix (SocketIntegrationTests):

  • testEveryToolCarriesADescriptionOnEveryProfileAndFraming — core / expanded / full × newline /
    Content-Length; every tool must carry a non-empty description.
  • testRawLineToolsListStaysUnderTheChunkLimitOnEveryProfile
  • testBrainStoreIsInTheDefaultPaletteWithItsDescriptionOnBoot — Etan's expectation, verified on
    the wire in both framings: brain_store is in the boot palette and its outcome contract is
    present with no expand_palette call.
  • testShippedPalettesFitWithoutAnyDescriptionTruncation — the shipped palette must fit rung 1.
    A new tool that pushes it into rung 2 fails loudly here instead of quietly shipping
    shortened contracts.
  • testOversizedRawToolsListTruncatesDescriptionsWithAnExplicitNotice — exercises rung 2 on a
    40-tool payload.

The rewrite (Part B)

Per skillCreator's doctrine — ~/Gits/skill-creator/docs.local/doctrine/tool-description-house-style.md,
measured across 86 golems skills: median 125 chars, p90 263, max 475 — and Etan, 2026-08-19:
"the tool descriptions should be extremely short. Just tell them what to do with it."

Shape, in priority order: (a) what it does as a verb phrase, (b) the words a user actually says,
(c) a one-clause not-for only where a sibling is genuinely confusable. Cut: parameter prose,
rationale, history, examples, reassurance.

PR #725's outcome contract is kept, compressed:

status STORED|DUPLICATE|MERGED|DEFERRED = success, do NOT re-store; REJECTED|ERROR = nothing stored, no chunk_id.

Its enforcement is the write-time dedupe, not the sentence. Descriptions state; they do not
enforce (measured: send_to's length warning was correct, prominent, and ignored by two leads
hours apart — the fix there was a PreToolUse gate).

Numbers — response bytes on the wire

profile × framing before after Part A after Part B
core × Content-Length 1641 1641 1641
core × newline 1642 1642 1642
expanded × Content-Length 12385 12385 10775
full × Content-Length 12385 12385 10775
expanded × newline 4083 (0/17 descriptions) 7939 (17/17) 6329 (17/17)
full × newline 4083 (0/17 descriptions) 7939 (17/17) 6329 (17/17)

Part A alone restored 17/17 descriptions with only 253 bytes of headroom under the 8192 limit.
Part B widened that to 1863 bytes (~23%). Shortening buys headroom; the ladder removes the cliff.

Description lengths vs the measured norm

skillCreator measured the golems skill library (86 skills, check-skill-library.mjs):
median 125 · p90 263 · max 475. BrainBar's palette before this PR:

before after norm
median 89 94 125
p90 337 212 263
max 1158 (brain_store) 293 475
total (17 tools) 3576 1957 —

The median barely moves — most tools were already terse. What was broken was the tail:
brain_store alone was an 8x outlier, and the p90 sat above the library max. Python surface
(10 rewritten tools): 7563 -> 1500 chars.

(brain_expand / brain_tags are deprecated on the Python path and left alone.)

Test gate change (lead ruling, 2026-08-19)

tests/test_tool_description_quality.py's blanket requirement that all 6 active tools contain
"Use when:" and "Don't use when:" (origin R79, PRs #212/#223) is replaced. That gate forced
prose onto tools with no confusable neighbour and pushed the palette 8× over the measured norm —
which is what made the 8192-byte strip bite. Now:

  • <1024 hard cap kept;
  • budget assertions in the median/p90 spirit (per-tool ≤320, median ≤175);
  • a not-for clause required only for tools in an explicitly-named confusable set.

Mirrored in Swift as ToolDescriptionHouseStyleTests.

Not claimed

cmux #121's controlled tool-routing eval found no wording effect (100% accuracy across
control / verbatim / rewrite). This PR does not claim better tool selection. It restores a contract
that was missing entirely, and cuts the boot payload.

Verification

  • swift test — 888 tests, 0 failures, 0 compile errors (BrainBar, final wording)
  • pytest — 4264 passed, 3 failed; all three are pre-existing or environmental, none from
    this PR:
    • test_think_recall_integration.py::TestSessionsReal::test_sessions_returns_data
    • test_think_recall_integration.py::TestSessionsReal::test_sessions_golems_project
      — both fail identically on unmodified origin/main, verified by running them in a clean
      throwaway worktree checked out at c9a4d28d. They are real-DB tests.
    • test_mcp_lazy_startup.py::test_handshake_fast_under_db_write_lock — a latency assertion under
      a DB write lock; timing-sensitive under full-suite load, passes in isolation on this branch
      (3 passed).
    • test_eval_baselines.py + test_search_validation.py (31 errors) are real-DB suites that
      error the same way on origin/main; excluded from the final run for that reason.
  • ruff check src/ tests/ — clean

Two truths my first compression pass dropped were caught by the existing suites and restored
inline, because each is something an agent acts on rather than prose: DEFERRED is queued and
will be stored (which is exactly why re-storing it is wrong), and brain_digest enriches and
connects extracted entities into the knowledge graph. A third — REJECTED/ERROR carry no status
(PR #725 review, MUST-FIX 2) — was caught by StoreResponseClarityTests.


Note

Medium Risk
Changes MCP wire behavior for Claude Desktop raw newline clients and agent-facing tool contracts; logic is well-tested on real sockets but mis-tuned truncation or budgets could still confuse agents or break chunk parsing at the limit.

Overview
Fixes #726: expanded palettes on raw newline MCP no longer ship 0/17 tool descriptions when tools/list exceeds Claude Desktop’s 8192-byte chunk limit.

Raw-line compaction (BrainBarServer) — Rung 1 still drops annotations and inputSchema prose but keeps top-level tool description (previously removed here). If still over budget, rung 2 binary-searches a per-tool char budget, shortens descriptions with …[truncated], and sets result._meta["brainlayer/descriptionsTruncated"] (affected tools, limits, pointer to Content-Length for full text). Payloads that cannot fit even at the 48-char floor go out over-limit with contracts intact rather than silent stripping.

Tool copy — Swift MCPRouter and Python _full_tool_definitions() descriptions are rewritten to short “house style”; compactCoreToolDefinition now requires a non-empty description (canonical or core override). Quality gates drop blanket "Use when:" / "Don't use when:" in favor of length budgets and not-for clauses only for named confusable siblings; brain_store must still list all six outcomes and “do NOT re-store”.

Tests — New socket integration coverage across core/expanded/full × newline/Content-Length (descriptions present, raw line under 8192, shipped palette avoids rung 2, ladder behavior on synthetic oversized payloads), plus ToolDescriptionHouseStyleTests / updated test_tool_description_quality.py.

Reviewed by Cursor Bugbot for commit 49ef4f5. Bugbot is set up for automated code reviews on this repo. Configure here.

Note

Keep top-level tool descriptions in raw-line tools/list by truncating instead of dropping them

  • Fixes the compaction order in BrainBarServer.encodeRawJSONResponse: when a raw-line payload exceeds the 8192-byte chunk limit, annotations and schema prose are dropped first, then descriptions are shortened (never removed), and a result._meta.brainlayer/descriptionsTruncated notice is appended naming the affected tools.
  • Adds a binary-search helper (truncatedRawJSONResponse) that finds the largest per-tool description budget that fits, falling back to a 48-character floor; if even that exceeds the limit, the payload is returned as-is with a notice listing zero truncated tools.
  • compactRawJSONResponseIfNeeded no longer strips the top-level description field, and MCPRouter.compactCoreToolDefinition now guarantees a non-empty description, trapping via preconditionFailure in debug when none exists.
  • Rewords tool descriptions to a concise house style across Swift (MCPRouter.toolDefinitions) and Python (mcp._full_tool_definitions).
  • Behavioral Change: compactCoreToolDefinition will preconditionFailure in debug builds if a core tool definition has no usable description; raw-line responses now carry truncated descriptions with an explicit _meta notice instead of silently removing the field.

Macroscope summarized 49ef4f5.

BrainBarServer.encodeRawJSONResponse stripped EVERY tool description as soon as
a raw newline-framed tools/list crossed 8192 bytes. Core fit, so core kept its
descriptions -- but expand_palette pushed the response over and came back with
0/17 descriptions. Expanding the palette silently downgraded the contract.
AGENTS.md: "The rules for agents USING it live in the tool descriptions."

Part A -- the compaction is now a ladder. Rung 1 drops annotations and
inputSchema prose (an agent needs neither to pick nor to call a tool). Rung 2,
only if that still does not fit, SHORTENS descriptions to the largest
binary-searched budget that does, marks each shortened one "…[truncated]", and
attaches an explicit result._meta["brainlayer/descriptionsTruncated"] notice
naming every affected tool and why. Descriptions are never removed; if even the
48-char floor does not fit, the response goes out over the limit with its
contract intact and logs the reason. Fixing this by shortening alone was
rejected on purpose: a future tool addition must not silently re-break it.

The tests run against a real Unix socket, across profile x framing (core /
expanded / full x newline / Content-Length). Unit tests at router.handle() sit
one layer above the stripping and stayed green while the wire was wrong twice in
this lane. testShippedPalettesFitWithoutAnyDescriptionTruncation fails loudly if
a new tool ever pushes the shipped palette into rung 2.

Part B -- every description rewritten to skillCreator's measured house style
(docs.local/doctrine/tool-description-house-style.md: median 125 chars, p90 263,
max 475 across 86 golems skills). Shape: what it does as a verb phrase, the
words a user actually says, and a not-for clause only where a sibling is
genuinely confusable. PR #725's outcome contract is kept, compressed -- its
enforcement is the write-time dedupe, not the sentence. Three truths the first
compression pass dropped are restored inline, because each is something an agent
acts on: REJECTED/ERROR return no `status` (PR725 review MUST-FIX 2), DEFERRED is
queued and WILL be stored (which is why re-storing is wrong), and brain_digest
enriches and connects entities into the knowledge graph.

tests/test_tool_description_quality.py's blanket "Use when:" AND
"Don't use when:" requirement (R79, PRs #212/#223) is replaced per the lead
ruling of 2026-08-19. That gate forced prose onto tools with no confusable
neighbour and pushed the palette 8x over the measured norm, which is what made
the 8192-byte strip bite. It becomes: the <1024 hard cap, a median/p90 budget,
and a not-for clause required only for an explicitly-named confusable set.
Mirrored in Swift as ToolDescriptionHouseStyleTests.

Response bytes on the wire, expanded/full profile:
  newline:        4083 (0/17 descriptions) -> 6329 (17/17), 1863 B under the limit
  Content-Length: 12385 -> 10775
core is unchanged at 1641/1642 and still boots brain_store with its contract.
Swift description lengths: total 3576 -> 1957, p90 337 -> 212, max 1158 -> 293.

Not claimed: cmux #121's controlled tool-routing eval found no wording effect.
This restores a contract that was missing entirely, and cuts the boot payload.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ee6e844a-370e-4f31-96c4-22590145d3cb


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

@cursor

cursor Bot commented Aug 19, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_f55e7513-e32d-4b42-a767-5f6eddeb08c1)

Comment on lines +838 to +853
var low = minimumRawToolDescriptionLength
var high = longest
var best: Data?
while low <= high {
let budget = (low + high) / 2
guard let candidate = try? MCPFraming.encodeJSONResponse(
responseTruncatingDescriptions(response, result: result, tools: tools, budget: budget)
) else {
break
}
if candidate.count < claudeExtensionRawChunkLimit {
best = candidate
low = budget + 1
} else {
high = budget - 1
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High BrainBar/BrainBarServer.swift:838

truncatedRawJSONResponse can return an unnecessarily shortened or still-over-limit payload for mixed description lengths, causing raw tools/list clients to reject the response. The binary search assumes encoded size always increases with budget, but responseTruncatingDescriptions removes entries from _meta["brainlayer/descriptionsTruncated"] as descriptions stop being shortened, so a higher budget can produce a smaller response. Search budgets in descending order (or otherwise account for these discontinuities) instead of using this monotonic binary search.

-        var low = minimumRawToolDescriptionLength
-        var high = longest
         var best: Data?
-        while low <= high {
-            let budget = (low + high) / 2
+        for budget in stride(from: longest, through: minimumRawToolDescriptionLength, by: -1) {
             guard let candidate = try? MCPFraming.encodeJSONResponse(
                 responseTruncatingDescriptions(response, result: result, tools: tools, budget: budget)
             ) else {
                 break
             }
             if candidate.count < claudeExtensionRawChunkLimit {
                 best = candidate
-                low = budget + 1
-            } else {
-                high = budget - 1
+                break
             }
         }
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @brain-bar/Sources/BrainBar/BrainBarServer.swift around lines 838-853:

`truncatedRawJSONResponse` can return an unnecessarily shortened or still-over-limit payload for mixed description lengths, causing raw `tools/list` clients to reject the response. The binary search assumes encoded size always increases with `budget`, but `responseTruncatingDescriptions` removes entries from `_meta["brainlayer/descriptionsTruncated"]` as descriptions stop being shortened, so a higher budget can produce a smaller response. Search budgets in descending order (or otherwise account for these discontinuities) instead of using this monotonic binary search.

FIX 1: compactCoreToolDefinition assigned coreToolDescriptions[name] directly;
Swift removes the key on nil, so a core tool without an entry shipped with no
description at all — silently, on the default palette every agent boots into.
Now falls back to the canonical definition and fails loudly if neither exists.
Asserted over the CORE-compacted palette, which no test covered before.

FIX 2: the floor path returned nil at the minimum-length guard and shipped
over-limit with no log and no _meta notice, contradicting the shipped contract.
It now emits the notice on that path too.

Found by the lead-routed pair review (wire-verified against a real socket).
Implemented by brainlayerCodex-c1a1569c; committed by the lead because that
seat could not write .git (EPERM on a read-only mount).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@cursor

cursor Bot commented Aug 20, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_60ced0d8-6716-4d32-910f-39dd1e9c12e4)

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BrainBar strips ALL tool descriptions over 8192 bytes on newline framing — expand_palette/full profile serve brain_store with NO description

1 participant