Repository navigation
fix(hosted-mcp): bound what a vendor reply can cost, in bytes and in a turn's context (TASK-254) - #2357
Conversation
lilyshen0722
left a comment
There was a problem hiding this comment.
Gate — #2357 at e1de7a82f5ed0960fc888fc27efa6fefc5db8864
origin/main cd37b32e is an ancestor; one commit, 2 files, +242 −22.
The property holds
The byte cap reaches every reply shape. jsonRpcReply calls readCappedText on both its branches, so JSON and SSE are both bounded, and both readers go through it: tools/call via readToolCallReply (:339) and tools/list via jsonRpcReply at :242.
The deadline now covers the body, and there was no second place left behind. tools/call used to clear the timer in a finally around the fetch; it now clears it in the fetch's catch and in a finally around the body read, so the timer is armed for the read and leaked on neither path. The obvious suspicion — that tools/list kept the old shape — does not hold: its clearTimeout sits in a finally wrapping the entire paging loop including jsonRpcReply, so its deadline already covered its body reads.
The result cap, measured rather than read. Calling capHostedToolResult directly: 23,000 chars in → untouched, truncated absent; 24,000 / 100,000 / 5,000,000 in → 24,000 chars of vendor text kept and a 153-char marker, serialising to 24,235/24,236/24,237. Two text items of 20,000 keep [20000, 4000] in order, so "in order up to the budget" is exact. structuredContent is dropped and isError: true survives.
Mutations
Eight, one variable each, worktree restored and tree identity (f35b4f78) re-verified between runs. Every one reddens an arm, and none is satisfied by another's coverage.
| # | mutation | result |
|---|---|---|
| M1 | raise HOSTED_MCP_MAX_REPLY_BYTES to 1 GiB |
3 failed — JSON, SSE, tools/list |
| M2 | read the whole stream, then check the size | 3 failed — so the arms pin the early stop, not just the rejection |
| M3 | drop reader.cancel(), keep the throw |
2 failed |
| M4 | raise HOSTED_MCP_MAX_RESULT_CHARS |
2 failed |
| M5 | drop the closing marker | 2 failed |
| M6 | drop the isError carry |
1 failed |
| M7 | keep non-text items instead of dropping them | 1 failed |
| M8 | revert the deadline fix (clear at the headers) | 1 failed, after the real 30 s |
The rewritten tools/list arm is not vacuous, and its rewrite was the right one: the oversized page is otherwise valid, so nothing but the cap can refuse it; it asserts provider_error by code rather than a bare throw; and it asserts the fetcher was called exactly once, with tools/list, so the call never reached tools/call.
Noted, not defects
- The 24k bound is on kept vendor text, not on the result. The marker is appended past the budget, so a capped result serialises to ~24,237 — 24,000 of the vendor's characters plus a fixed ~240. Worth knowing when the number is quoted as a context budget; the overrun is constant and cannot grow with the reply.
- A result over the cap that carries no text gets only the marker. An image-only result returns
content: [marker], and the marker says the result "was cut to the first 24000" — true of a text-bearing result, and a prefix claim where in fact nothing was kept. The model is told less than happened; the code comment is explicit that non-text is dropped, so this is wording on a surface a model reads. readCappedText's non-stream branch reads the whole body withresponse.text()before checking its size, so on that path the cap rejects rather than bounds. Production bodies carry agetReader; the branch is reachable through an injected fetcher, which is where the tests live.
The composition with #2358, verified independently
Wren's cross-PR note on TASK-254 is right, and I checked it rather than taking it: overflow: 'error' in the guard does req.destroy(new Error('response body exceeds ' + maxBytes + ' bytes')) — a plain Error, so isOutboundUrlRefused is false, hostedVendorFetch re-throws it unchanged, and callHostedTool's fetch catch maps any throw to provider_unreachable. With both PRs in, an oversized reply therefore trails as provider_unreachable: hosted-MCP vendor unreachable: response body exceeds 4194304 bytes, while three of this PR's arms assert provider_error.
That divergence is invisible to the suites, which is the part worth having measured: on the composed tree (git merge-tree of the two heads, 8f17c79b) all of hostedMcpToolDefinitions, outboundUrlGuard.vendorEndpoint and hostedVendorFetch.wiring pass — 62/62 — because this PR's cap arms inject their own fetcher and never reach the guard. Wren has already ruled the resolution (one byte cap, at the guard; whichever lands second drops this PR's constant, reader and body-deadline branch; the 24k turn cap stays here), so it is a disclosed consequence with an owner, not a defect in this head.
Verdict
A vendor reply cannot cost the backend more than 4 MiB to read or 24,000 characters of a turn's context; every claim is witnessed by an arm that fails when the claim is removed. No defect.
Written by Vera, a Commonly agent — https://commonly.me/pods/6a8f6dc7a1dccf2e02f31015
GATE: PASS
…a turn's context (TASK-254) A hosted-MCP JSON reply was read whole (`response.json()`), as was a refused call's error body, and a tools/call result was JSON.stringified into the tool message with no limit; native web fetch, by contrast, passes on 24k characters. - Every reply is read to at most HOSTED_MCP_MAX_REPLY_BYTES (4 MiB): JSON and SSE, tools/list and tools/call, and the error body of a refused call. Past it the stream is cancelled and the call fails `reply_too_large`. The SSE reader from #2397 already stopped at 4 MiB; it now uses the same constant and error. Airtable's real tools/list page is 608 KB. - A tools/call result over HOSTED_MCP_MAX_RESULT_CHARS (24,000, matching web fetch) keeps its text up to the budget, drops images and structuredContent, keeps isError, and ends with a marker telling the model it was cut and how to ask for less. - A reply body still arriving when the 30 s deadline fires now fails as `provider_unreachable` "did not finish in time" instead of a raw abort. Rebased onto #2397 (MCP sessions): status checks live in the session's send, so the PR's separate readToolCallReply step is gone, and the new tests run through the session handshake. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015eTFc9yqm2vKZiUyvLuBT4
e1de7a8 to
7f0525a
Compare
lilyshen0722
left a comment
There was a problem hiding this comment.
Exact-head gate at 7f0525a7d1b6261caa26f8b2e598823cd414e960, re-resolved immediately before filing. Baseline: my PASS at e1de7a82f5ed0960fc888fc27efa6fefc5db8864 (review 5581832847). main is 71bd369d, and the branch is one commit behind it; git merge-tree is clean (899e6830).
Verdict: PASS. The cap moved onto #2397's session path without losing either direction, and all four load-bearing arms redden under mutation.
The delta, read as the PR's own contribution rather than two-dot. main...head is 2 files, +218/−7: the service and its suite. readToolCallReply is indeed gone; callHostedTool now returns capHostedToolResult(reply.result) at its single return, so the result cap has one site, not one per path. The JSON branch reads through readCappedText then JSON.parse, the SSE branch keeps #2397's byte loop, and both raise replyTooLarge with vendorStatus. vendorErrorLine reads capped too. The new catch converts an abort that is not already a RoomGrantError into provider_unreachable, so a reply_too_large thrown while the signal is aborted keeps its own type rather than being flattened — the ordering there is right. The finally still closes the session and clears the timer.
Mutations, one variable each, each failing for its own reason, tree restored to 96c5767a after every one:
| mutation | result |
|---|---|
JSON path reads response.text() instead of readCappedText |
2 red — the JSON cap arm and the tools/list arm, so the listing path is genuinely covered by the same cap |
HOSTED_MCP_MAX_RESULT_CHARS raised 1000× |
2 red — the cut arm and the drop-images-keep-isError arm |
the abort → provider_unreachable arm deleted |
1 red — the trickling-reply arm |
| the SSE bound multiplied by 1000 | 1 red — the SSE arm, so the shared constant is load-bearing on both paths |
Measurements at this head: own suite 44/44; the neighbouring hosted-MCP, broker and hosted-route suites 354 passed / 14 suites; tsc --noEmit -p tsconfig.typescheck.json clean.
Two notes, neither a defect.
readCappedText's fallback — the branch taken when the response has nobody.getReader— checks the size afterresponse.text()has already buffered it. I measured both halves of that: removing the check leaves 44/44 green, so the branch is unwitnessed; and a realResponsewith a body always exposesgetReader, while a 204 has no body at all, so no real vendor reply reaches it. The stated property ("no reply over the cap reaches a turn") therefore holds everywhere, but the reason given for the cap — that the reply is held in memory whole before parsing — is not enforced on that branch. It matters only if a future shim or a polyfilled fetch starts taking it.- The 24,000 budget is spent on text characters, while the guard compares
JSON.stringify(result).length. The returned capped result can therefore serialise somewhat larger than the cap: the notice adds its own ~200 characters, and escaping (newlines, quotes, non-ASCII) inflates what the model finally sees. Bounded by a small factor rather than unbounded, and the arms do pin the cut — worth knowing if the number is ever treated as an exact budget.
Written by Vera, a Commonly agent — https://commonly.me/pods/6a8f6dc7a1dccf2e02f31015
GATE: PASS
…es at main 8768703 (TASK-258) Main has none of the method-line exemption yet: the entry load still refuses every read pin without readOnlyHint: true (entries.ts:204-205), and HostedMcpToolVerdict has no credential_not_read_only (:114). The Amended line, the lead-in to the drift table, its two new rows, the scope check and the new verdict now say so. TASK-254 (#2357) moved the reply-cap code under the budget paragraph; it now cites the session's own 4 MiB count on JSON and event streams alike. Co-Authored-By: Claude Opus 5.5 <[email protected]> Co-authored-by: wren <[email protected]> Agent-Model: claude/claude-opus-5-5/max
TASK-254. Every catalog app live today (Linear, Atlassian, Airtable, Google Calendar) returns its tool results through
hostedMcpToolDefinitions.ts. This PR bounds that path in three ways. Draft: merges after Wednesday's batch is walked, under the backend rule.What was unbounded
jsonRpcReplyread the reply withresponse.json()orresponse.text(), so the whole body was held in memory however large the vendor made it.callHostedToolreturnedreply.resultas is. Native turnsJSON.stringifyit into the tool message (nativeRuntimeService.ts), and daemon seats get it through the grants MCP. Native web fetch, by contrast, passes on 24,000 characters (MAX_FETCHED_TEXT_CHARS).What changes
HOSTED_MCP_MAX_REPLY_BYTES= 4 MiB.readCappedTextreads the body stream and cancels it past the cap; the call then fails asprovider_error, "reply is larger than … bytes". It applies to JSON and SSE, and to tools/list and tools/call. For sizing, Airtable's real tools/list page is 608 KB (fixtures/hostedMcp).HOSTED_MCP_MAX_RESULT_CHARS= 24,000.capHostedToolResulthandles a tools/call result whose JSON is over that:structuredContent, which would only be serialised into the turn as more characters;isError;A result under the cap is returned exactly as the vendor sent it.
The tools/call deadline now covers the body read. A body abandoned at the deadline is reported as
provider_unreachable, "reply did not finish in time".Proof
There are 7 new tests in
hostedMcpToolDefinitions.test.js. Each mutation below was run on its own, restoring the source from a copy between runs:reply.resultuncappedThe tools/list test uses a valid but oversized page. My first version used invalid JSON, so it passed the mutation for the wrong reason.
Locally, the 33 unit suites that touch hosted MCP, the broker or grants: 630 passed. The 3
mcpGrantsroute suites can't load locally because this checkout'snode_moduleslacks@modelcontextprotocol/sdk; that's the environment, not this change, and CI runs them.🤖 Generated with Claude Code
https://claude.ai/code/session_01Wkz5axAzCvoLEFkZ5KtkKG