Repository navigation
fix(mcp): compile tool output validators on first call, not at catalog load (#199327) - #199346
Conversation
…g load (openclaw#199327) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR defers MCP output-validator compilation until first use, while preserving eager registration of shared schema resources. Example: A session lists 200 tools whose output schemas contain no $id.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains This PR addresses a current resource-use bug, and the revised head fixes the earlier shared-schema finding without introducing another identified code defect. Priority: P2 Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe shared MCP catalog normalizer receives advertised tools and a catalog-local schema provider, then supplies tool metadata and result validators to session, native stdio, and node-host callers. flowchart TD
A[MCP tool catalog] --> B[Catalog normalizer]
B --> C[Schema snapshots and resources]
C --> D[First call validator acquisition]
D --> E[MCP request]
E --> F[Structured result validation]
F --> G[Agent tool result]
Technical reviewBest possible solution: Keep compilation demand-driven within the existing catalog owner while preserving shared-resource registration and dispatch-time result validation. Do we have a high-confidence way to reproduce the issue? Current-main source deterministically acquires every included output validator during catalog loading, and draft-2020-12 acquisition invokes compilation; this review ran no target code. Is this the best way to solve the issue? The diff fixes the existing owner directly, retains catalog-local schema semantics, and avoids the unsupported complexity of cross-runtime sharing. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8f9bd10825ff. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +19, Tests +37. Total +56 across 2 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 15, 2026, 6:10 AM ET / 11:10 UTC (Revision 2). |
…load A tool output schema that declares `$id` still compiles while the catalog loads, in catalog order, so another tool's `$ref` to it resolves whichever tool is called first. Schemas without `$id` stay lazy.
|
Head The PR body now uses the template sections and adds a live run: an isolated Gateway, a 204-tool stdio MCP server, and three agent turns covering a first call to the @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Hi @lonexreb, thanks for this fix. We run a Gateway with a ~200-tool MCP server and hit exactly this: about a 1.1 s main-thread stall every time a session starts. The only open item here was the real-model Gateway proof, and that lives in the PR description, which only you can edit. So I opened #205723 with your two commits unchanged, rebased onto current If you'd rather carry it here, copy the evidence into this PR's description and I'll close mine. Otherwise maintainers can close this one as superseded by #205723. |
One catalog covers both boundaries: unused schemas stay uncompiled at load, a shared $id resource still compiles in catalog order, and the referencing tool compiles once on its first call and validates against it.
Native HTTP calls go through the SDK's callTool, which never consults the catalog validator. With validators now compiled on first use, an uncompilable outputSchema let that call reach the server; acquiring it first keeps the failure ahead of the request, as the catalog load did before.
|
Observed proof for head |
|
Merged in eb704f5. Thanks @lonexreb for the fix, @Subseaking for the heap-snapshot report in #199327, and @brandon-julio-t for the extra evidence in #205723. Each session's MCP runtime now compiles a tool's output-schema validator the first time that tool is called instead of compiling one for every listed tool up front, which cut Gateway heap growth by about a third and validator objects from about 4,100 to about 100 in our 20-session run. Tool outputs are validated exactly as before. One visible difference: a server with one tool whose output schema can't be compiled now starts and serves its healthy tools, and calling the broken tool returns the same schema error. |
…g load (openclaw#199327) (openclaw#199346) Root cause: `src/agents/mcp-tool-metadata.ts:76-79` (on `main`) compiles an output-schema validator for every included tool inside `normalizeMcpToolCatalog`, on every `tools/list`, and keeps it for the catalog's lifetime. Each session MCP runtime normalizes its own catalog, so a ~200-tool server costs ~200 compiled TypeBox validators per session, almost all for tools that session never calls. Fixes openclaw#199327. Thanks @Subseaking for the report and heap snapshots, @lonexreb for the fix, and @brandon-julio-t for the real-model Gateway check and session-start measurements in openclaw#205723 (same two commits, rebased). ## What Problem This Solves With per-session MCP runtimes and a long `mcp.sessionIdleTtlMs`, every new session that uses a large MCP catalog compiles and retains a validator for every tool. The reporter saw Gateway heap grow from 0.73 GB to 1.05 GB in an hour and TypeBox validators from 1,461 to 5,111, with ~25 session runtimes each holding ~202 compiled validators for the same ~200-tool HTTP server. ## Why This Change Was Made - `normalizeMcpToolCatalog` now records each included tool's output schema; `validatorForCall` compiles it on that tool's first call and reuses it for the rest of the catalog's life. Each catalog still owns its validator provider: no shared or global cache, no change to refresh or TTL. - Schemas that contain an `$id` still compile at catalog load, in catalog order, because compiling registers that resource for other tools' `$ref`s (lonexreb's second commit). - Native HTTP calls go through the SDK's `client.callTool`, which never consults the catalog validator. The native bridge now acquires the validator before that call, so an uncompilable output schema still fails before any request reaches the server. Without this line the PR head let such a call through (shown below). - The two new tests are folded into one regression covering both boundaries (unused schemas stay uncompiled; a shared `$id` still compiles at load and a `$ref` to it resolves on first call). Against `main`: production +47/-26, tests +26/-0 (contributor revision: tests +37). ## User Impact - Less retained memory per MCP session runtime and less catalog work per new session (numbers below). - Output validation is unchanged: same validator, same accept/reject results, same error text, on first and later calls; tools without an output schema, `isError` results and missing structured content behave as before. - One behavior differs, only for a server that advertises an output schema that cannot compile. Before: the whole server failed to start (`bundle-mcp: failed to start server "X": Invalid MCP draft-2020-12 JSON Schema: ...`) and none of its tools were available. Now: the server starts, its healthy tools work, and calling the broken tool fails with the same `Invalid MCP ... JSON Schema: ...` message, before any `tools/call` is sent. This matches the MCP SDK's own per-tool handling of uncompilable output schemas (SEP-2106). ## Evidence Built Gateway (`pnpm build`) for `main` `fbedcc3ea078` and this head, each in a secretless `node:24.22.1` container. Local streamable-HTTP MCP server with 205 tools (200 `bulk_*` with draft 2020-12 schemas using nested objects, `$defs`/`$ref`, enums, formats and patterns, plus `good`, `bad`, `plain`, `missing`, `iserr`); the server never validates its own output. Scripted local OpenAI-compatible model, `mcp.sessionIdleTtlMs: 86400000`, `tools.toolSearch: false`. Each of 20 fresh sessions ran one turn calling `bulk_<k>` and `good`. Forced-GC `heapUsed` read in the Gateway main isolate, TypeBox `Validator` objects counted from a heap snapshot. Serial interleaved runs, base/cand alternating. Acceptance rule: win = lower forced-GC heap growth and fewer retained TypeBox validators after 20 sessions, with session start and first-turn time not worse beyond run spread; any cell more than 20% worse is a stop. Settled set: 60 s after Gateway ready, 3 runs per side (ABAB): | 20 sessions, 2 tool calls each | `main` | this PR | |---|---|---| | heapUsed growth after forced GC (median, range) | 208.1 MB (206.9–209.4) | 131.6 MB (130.4–133.8) | | per session | 10.4 MB | 6.6 MB | | TypeBox `Validator` objects in heap snapshot | 4,145 | 105 | | first session: chat.send to first model request (median) | 2,558 ms | 2,503 ms | | sessions 2–20: chat.send to first model request (median / p95, n=57) | 297 / 459 ms | 283 / 370 ms | | first turn to final (median / p95, n=60) | 384 / 577 ms | 367 / 585 ms | | Gateway `mcp-materialize` stage on the first session (median of all runs) | 153 ms (n=7) | 102 ms (n=8) | Unsettled set: first session sent as soon as the Gateway was ready, 5 runs per side (ABAB): heap growth 212.7 vs 138.9 MB, validators 4,145 vs 105, sessions 2–20 start median/p95 363/2,480 vs 335/952 ms. The first session here overlaps Gateway warm-up and swings widely (`main` 2,348–11,349 ms, this PR 3,190–10,405 ms, medians 2,776 vs 3,687 ms); the difference sits in the Gateway's `preparation`/`replyInitialization` startup stages, not the MCP stage (lower on this PR in every run), and disappears in the settled set. `main` count: 26 Gateway-internal validators + ~203 per session runtime. This PR: 26 + one per called tool per runtime + a small per-turn constant that also appears on `main`. Controls (same on both builds unless noted; observed tool results handed back to the model): | case | `main` | this PR | |---|---|---| | `good` (valid output), first and second call in one session | `structuredContent: {"ok":true}` | same | | `bad` (`{"ok":"not-a-boolean"}`), first and second call | `Structured content does not match the tool's output schema: /ok must be boolean` | same | | `missing` (schema, no structured content) | `Tool missing has an output schema but did not return structured content` | same | | `iserr` (isError result) | passed through: `P199346-ISERR tool reported a problem` | same | | `plain` (no outputSchema) | `plain text result P199346-PLAIN` | same | | same tools over stdio | good passes, bad rejected with the same text, plain unchanged | same | | repeated calls in one runtime (`good`,`bad` again): Validator delta | +2 | +2 (same per-turn constant; no recompilation) | | server `broken` with one uncompilable outputSchema | server fails to start: `failed to start server "broken": Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; 0 `tools/call` | `fine` works; `broken` call fails with `Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; server saw only `tools/call fine` | Native HTTP bridge (`createSessionMcpRuntime` + `acquireNativeMcpServer` + `view.callTool` against an HTTP server with tools `fine` and `broken`): ``` main fbedcc3: catalog fails (same Invalid MCP ... unresolved ref), server tools/call: 0 f992f15 on main: fine -> {"ok":true}; broken -> complete {"a":1}; server tools/call: fine, broken this head: fine -> {"ok":true}; broken -> rejected Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref; server tools/call: fine ``` Tests: `mcp-tool-metadata.test.ts` regression fails on `main` (`expected "getValidator" to be called 1 times, but got 3 times`) and passes here; touched-area MCP tests pass. Proof comment: openclaw#199346 (comment) ## Merge danger Two-way door: no stored state, config, schema or protocol change; a revert restores eager compilation. Blast radius: MCP tool catalogs and calls in the bundle runtime, node host and native bridge; the only visible difference is the per-tool timing of the uncompilable-schema error described above. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
…g load (#199327) (#199346) Root cause: `src/agents/mcp-tool-metadata.ts:76-79` (on `main`) compiles an output-schema validator for every included tool inside `normalizeMcpToolCatalog`, on every `tools/list`, and keeps it for the catalog's lifetime. Each session MCP runtime normalizes its own catalog, so a ~200-tool server costs ~200 compiled TypeBox validators per session, almost all for tools that session never calls. Fixes #199327. Thanks @Subseaking for the report and heap snapshots, @lonexreb for the fix, and @brandon-julio-t for the real-model Gateway check and session-start measurements in #205723 (same two commits, rebased). ## What Problem This Solves With per-session MCP runtimes and a long `mcp.sessionIdleTtlMs`, every new session that uses a large MCP catalog compiles and retains a validator for every tool. The reporter saw Gateway heap grow from 0.73 GB to 1.05 GB in an hour and TypeBox validators from 1,461 to 5,111, with ~25 session runtimes each holding ~202 compiled validators for the same ~200-tool HTTP server. ## Why This Change Was Made - `normalizeMcpToolCatalog` now records each included tool's output schema; `validatorForCall` compiles it on that tool's first call and reuses it for the rest of the catalog's life. Each catalog still owns its validator provider: no shared or global cache, no change to refresh or TTL. - Schemas that contain an `$id` still compile at catalog load, in catalog order, because compiling registers that resource for other tools' `$ref`s (lonexreb's second commit). - Native HTTP calls go through the SDK's `client.callTool`, which never consults the catalog validator. The native bridge now acquires the validator before that call, so an uncompilable output schema still fails before any request reaches the server. Without this line the PR head let such a call through (shown below). - The two new tests are folded into one regression covering both boundaries (unused schemas stay uncompiled; a shared `$id` still compiles at load and a `$ref` to it resolves on first call). Against `main`: production +47/-26, tests +26/-0 (contributor revision: tests +37). ## User Impact - Less retained memory per MCP session runtime and less catalog work per new session (numbers below). - Output validation is unchanged: same validator, same accept/reject results, same error text, on first and later calls; tools without an output schema, `isError` results and missing structured content behave as before. - One behavior differs, only for a server that advertises an output schema that cannot compile. Before: the whole server failed to start (`bundle-mcp: failed to start server "X": Invalid MCP draft-2020-12 JSON Schema: ...`) and none of its tools were available. Now: the server starts, its healthy tools work, and calling the broken tool fails with the same `Invalid MCP ... JSON Schema: ...` message, before any `tools/call` is sent. This matches the MCP SDK's own per-tool handling of uncompilable output schemas (SEP-2106). ## Evidence Built Gateway (`pnpm build`) for `main` `40f3903e6e2b` and this head, each in a secretless `node:24.22.1` container. Local streamable-HTTP MCP server with 205 tools (200 `bulk_*` with draft 2020-12 schemas using nested objects, `$defs`/`$ref`, enums, formats and patterns, plus `good`, `bad`, `plain`, `missing`, `iserr`); the server never validates its own output. Scripted local OpenAI-compatible model, `mcp.sessionIdleTtlMs: 86400000`, `tools.toolSearch: false`. Each of 20 fresh sessions ran one turn calling `bulk_<k>` and `good`. Forced-GC `heapUsed` read in the Gateway main isolate, TypeBox `Validator` objects counted from a heap snapshot. Serial interleaved runs, base/cand alternating. Acceptance rule: win = lower forced-GC heap growth and fewer retained TypeBox validators after 20 sessions, with session start and first-turn time not worse beyond run spread; any cell more than 20% worse is a stop. Settled set: 60 s after Gateway ready, 3 runs per side (ABAB): | 20 sessions, 2 tool calls each | `main` | this PR | |---|---|---| | heapUsed growth after forced GC (median, range) | 208.1 MB (206.9–209.4) | 131.6 MB (130.4–133.8) | | per session | 10.4 MB | 6.6 MB | | TypeBox `Validator` objects in heap snapshot | 4,145 | 105 | | first session: chat.send to first model request (median) | 2,558 ms | 2,503 ms | | sessions 2–20: chat.send to first model request (median / p95, n=57) | 297 / 459 ms | 283 / 370 ms | | first turn to final (median / p95, n=60) | 384 / 577 ms | 367 / 585 ms | | Gateway `mcp-materialize` stage on the first session (median of all runs) | 153 ms (n=7) | 102 ms (n=8) | Unsettled set: first session sent as soon as the Gateway was ready, 5 runs per side (ABAB): heap growth 212.7 vs 138.9 MB, validators 4,145 vs 105, sessions 2–20 start median/p95 363/2,480 vs 335/952 ms. The first session here overlaps Gateway warm-up and swings widely (`main` 2,348–11,349 ms, this PR 3,190–10,405 ms, medians 2,776 vs 3,687 ms); the difference sits in the Gateway's `preparation`/`replyInitialization` startup stages, not the MCP stage (lower on this PR in every run), and disappears in the settled set. `main` count: 26 Gateway-internal validators + ~203 per session runtime. This PR: 26 + one per called tool per runtime + a small per-turn constant that also appears on `main`. Controls (same on both builds unless noted; observed tool results handed back to the model): | case | `main` | this PR | |---|---|---| | `good` (valid output), first and second call in one session | `structuredContent: {"ok":true}` | same | | `bad` (`{"ok":"not-a-boolean"}`), first and second call | `Structured content does not match the tool's output schema: /ok must be boolean` | same | | `missing` (schema, no structured content) | `Tool missing has an output schema but did not return structured content` | same | | `iserr` (isError result) | passed through: `P199346-ISERR tool reported a problem` | same | | `plain` (no outputSchema) | `plain text result P199346-PLAIN` | same | | same tools over stdio | good passes, bad rejected with the same text, plain unchanged | same | | repeated calls in one runtime (`good`,`bad` again): Validator delta | +2 | +2 (same per-turn constant; no recompilation) | | server `broken` with one uncompilable outputSchema | server fails to start: `failed to start server "broken": Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; 0 `tools/call` | `fine` works; `broken` call fails with `Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; server saw only `tools/call fine` | Native HTTP bridge (`createSessionMcpRuntime` + `acquireNativeMcpServer` + `view.callTool` against an HTTP server with tools `fine` and `broken`): ``` main 40f3903: catalog fails (same Invalid MCP ... unresolved ref), server tools/call: 0 f992f15 on main: fine -> {"ok":true}; broken -> complete {"a":1}; server tools/call: fine, broken this head: fine -> {"ok":true}; broken -> rejected Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref; server tools/call: fine ``` Tests: `mcp-tool-metadata.test.ts` regression fails on `main` (`expected "getValidator" to be called 1 times, but got 3 times`) and passes here; touched-area MCP tests pass. Proof comment: #199346 (comment) ## Merge danger Two-way door: no stored state, config, schema or protocol change; a revert restores eager compilation. Blast radius: MCP tool catalogs and calls in the bundle runtime, node host and native bridge; the only visible difference is the per-tool timing of the uncompilable-schema error described above. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit eb704f5)
…g load (#199327) (#199346) Root cause: `src/agents/mcp-tool-metadata.ts:76-79` (on `main`) compiles an output-schema validator for every included tool inside `normalizeMcpToolCatalog`, on every `tools/list`, and keeps it for the catalog's lifetime. Each session MCP runtime normalizes its own catalog, so a ~200-tool server costs ~200 compiled TypeBox validators per session, almost all for tools that session never calls. Fixes #199327. Thanks @Subseaking for the report and heap snapshots, @lonexreb for the fix, and @brandon-julio-t for the real-model Gateway check and session-start measurements in #205723 (same two commits, rebased). ## What Problem This Solves With per-session MCP runtimes and a long `mcp.sessionIdleTtlMs`, every new session that uses a large MCP catalog compiles and retains a validator for every tool. The reporter saw Gateway heap grow from 0.73 GB to 1.05 GB in an hour and TypeBox validators from 1,461 to 5,111, with ~25 session runtimes each holding ~202 compiled validators for the same ~200-tool HTTP server. ## Why This Change Was Made - `normalizeMcpToolCatalog` now records each included tool's output schema; `validatorForCall` compiles it on that tool's first call and reuses it for the rest of the catalog's life. Each catalog still owns its validator provider: no shared or global cache, no change to refresh or TTL. - Schemas that contain an `$id` still compile at catalog load, in catalog order, because compiling registers that resource for other tools' `$ref`s (lonexreb's second commit). - Native HTTP calls go through the SDK's `client.callTool`, which never consults the catalog validator. The native bridge now acquires the validator before that call, so an uncompilable output schema still fails before any request reaches the server. Without this line the PR head let such a call through (shown below). - The two new tests are folded into one regression covering both boundaries (unused schemas stay uncompiled; a shared `$id` still compiles at load and a `$ref` to it resolves on first call). Against `main`: production +47/-26, tests +26/-0 (contributor revision: tests +37). ## User Impact - Less retained memory per MCP session runtime and less catalog work per new session (numbers below). - Output validation is unchanged: same validator, same accept/reject results, same error text, on first and later calls; tools without an output schema, `isError` results and missing structured content behave as before. - One behavior differs, only for a server that advertises an output schema that cannot compile. Before: the whole server failed to start (`bundle-mcp: failed to start server "X": Invalid MCP draft-2020-12 JSON Schema: ...`) and none of its tools were available. Now: the server starts, its healthy tools work, and calling the broken tool fails with the same `Invalid MCP ... JSON Schema: ...` message, before any `tools/call` is sent. This matches the MCP SDK's own per-tool handling of uncompilable output schemas (SEP-2106). ## Evidence Built Gateway (`pnpm build`) for `main` `40f3903e6e2b` and this head, each in a secretless `node:24.22.1` container. Local streamable-HTTP MCP server with 205 tools (200 `bulk_*` with draft 2020-12 schemas using nested objects, `$defs`/`$ref`, enums, formats and patterns, plus `good`, `bad`, `plain`, `missing`, `iserr`); the server never validates its own output. Scripted local OpenAI-compatible model, `mcp.sessionIdleTtlMs: 86400000`, `tools.toolSearch: false`. Each of 20 fresh sessions ran one turn calling `bulk_<k>` and `good`. Forced-GC `heapUsed` read in the Gateway main isolate, TypeBox `Validator` objects counted from a heap snapshot. Serial interleaved runs, base/cand alternating. Acceptance rule: win = lower forced-GC heap growth and fewer retained TypeBox validators after 20 sessions, with session start and first-turn time not worse beyond run spread; any cell more than 20% worse is a stop. Settled set: 60 s after Gateway ready, 3 runs per side (ABAB): | 20 sessions, 2 tool calls each | `main` | this PR | |---|---|---| | heapUsed growth after forced GC (median, range) | 208.1 MB (206.9–209.4) | 131.6 MB (130.4–133.8) | | per session | 10.4 MB | 6.6 MB | | TypeBox `Validator` objects in heap snapshot | 4,145 | 105 | | first session: chat.send to first model request (median) | 2,558 ms | 2,503 ms | | sessions 2–20: chat.send to first model request (median / p95, n=57) | 297 / 459 ms | 283 / 370 ms | | first turn to final (median / p95, n=60) | 384 / 577 ms | 367 / 585 ms | | Gateway `mcp-materialize` stage on the first session (median of all runs) | 153 ms (n=7) | 102 ms (n=8) | Unsettled set: first session sent as soon as the Gateway was ready, 5 runs per side (ABAB): heap growth 212.7 vs 138.9 MB, validators 4,145 vs 105, sessions 2–20 start median/p95 363/2,480 vs 335/952 ms. The first session here overlaps Gateway warm-up and swings widely (`main` 2,348–11,349 ms, this PR 3,190–10,405 ms, medians 2,776 vs 3,687 ms); the difference sits in the Gateway's `preparation`/`replyInitialization` startup stages, not the MCP stage (lower on this PR in every run), and disappears in the settled set. `main` count: 26 Gateway-internal validators + ~203 per session runtime. This PR: 26 + one per called tool per runtime + a small per-turn constant that also appears on `main`. Controls (same on both builds unless noted; observed tool results handed back to the model): | case | `main` | this PR | |---|---|---| | `good` (valid output), first and second call in one session | `structuredContent: {"ok":true}` | same | | `bad` (`{"ok":"not-a-boolean"}`), first and second call | `Structured content does not match the tool's output schema: /ok must be boolean` | same | | `missing` (schema, no structured content) | `Tool missing has an output schema but did not return structured content` | same | | `iserr` (isError result) | passed through: `P199346-ISERR tool reported a problem` | same | | `plain` (no outputSchema) | `plain text result P199346-PLAIN` | same | | same tools over stdio | good passes, bad rejected with the same text, plain unchanged | same | | repeated calls in one runtime (`good`,`bad` again): Validator delta | +2 | +2 (same per-turn constant; no recompilation) | | server `broken` with one uncompilable outputSchema | server fails to start: `failed to start server "broken": Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; 0 `tools/call` | `fine` works; `broken` call fails with `Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref`; server saw only `tools/call fine` | Native HTTP bridge (`createSessionMcpRuntime` + `acquireNativeMcpServer` + `view.callTool` against an HTTP server with tools `fine` and `broken`): ``` main 40f3903: catalog fails (same Invalid MCP ... unresolved ref), server tools/call: 0 f992f15 on main: fine -> {"ok":true}; broken -> complete {"a":1}; server tools/call: fine, broken this head: fine -> {"ok":true}; broken -> rejected Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref; server tools/call: fine ``` Tests: `mcp-tool-metadata.test.ts` regression fails on `main` (`expected "getValidator" to be called 1 times, but got 3 times`) and passes here; touched-area MCP tests pass. Proof comment: #199346 (comment) ## Merge danger Two-way door: no stored state, config, schema or protocol change; a revert restores eager compilation. Blast radius: MCP tool catalogs and calls in the bundle runtime, node host and native bridge; the only visible difference is the per-tool timing of the uncompilable-schema error described above. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit eb704f5) Companion audit: #208033 covers broader concurrent-run allocations; lazy output validator compilation does not depend on it. Co-authored-by: RomneyDa <[email protected]>
Root cause:
src/agents/mcp-tool-metadata.ts:76-79(onmain) compiles an output-schema validator for every included tool insidenormalizeMcpToolCatalog, on everytools/list, and keeps it for the catalog's lifetime. Each session MCP runtime normalizes its own catalog, so a ~200-tool server costs ~200 compiled TypeBox validators per session, almost all for tools that session never calls.Fixes #199327. Thanks @Subseaking for the report and heap snapshots, @lonexreb for the fix, and @brandon-julio-t for the real-model Gateway check and session-start measurements in #205723 (same two commits, rebased).
What Problem This Solves
With per-session MCP runtimes and a long
mcp.sessionIdleTtlMs, every new session that uses a large MCP catalog compiles and retains a validator for every tool. The reporter saw Gateway heap grow from 0.73 GB to 1.05 GB in an hour and TypeBox validators from 1,461 to 5,111, with ~25 session runtimes each holding ~202 compiled validators for the same ~200-tool HTTP server.Why This Change Was Made
normalizeMcpToolCatalognow records each included tool's output schema;validatorForCallcompiles it on that tool's first call and reuses it for the rest of the catalog's life. Each catalog still owns its validator provider: no shared or global cache, no change to refresh or TTL.$idstill compile at catalog load, in catalog order, because compiling registers that resource for other tools'$refs (lonexreb's second commit).client.callTool, which never consults the catalog validator. The native bridge now acquires the validator before that call, so an uncompilable output schema still fails before any request reaches the server. Without this line the PR head let such a call through (shown below).$idstill compiles at load and a$refto it resolves on first call). Againstmain: production +47/-26, tests +26/-0 (contributor revision: tests +37).User Impact
isErrorresults and missing structured content behave as before.bundle-mcp: failed to start server "X": Invalid MCP draft-2020-12 JSON Schema: ...) and none of its tools were available. Now: the server starts, its healthy tools work, and calling the broken tool fails with the sameInvalid MCP ... JSON Schema: ...message, before anytools/callis sent. This matches the MCP SDK's own per-tool handling of uncompilable output schemas (SEP-2106).Evidence
Built Gateway (
pnpm build) formain40f3903e6e2band this head, each in a secretlessnode:24.22.1container. Local streamable-HTTP MCP server with 205 tools (200bulk_*with draft 2020-12 schemas using nested objects,$defs/$ref, enums, formats and patterns, plusgood,bad,plain,missing,iserr); the server never validates its own output. Scripted local OpenAI-compatible model,mcp.sessionIdleTtlMs: 86400000,tools.toolSearch: false. Each of 20 fresh sessions ran one turn callingbulk_<k>andgood. Forced-GCheapUsedread in the Gateway main isolate, TypeBoxValidatorobjects counted from a heap snapshot. Serial interleaved runs, base/cand alternating.Acceptance rule: win = lower forced-GC heap growth and fewer retained TypeBox validators after 20 sessions, with session start and first-turn time not worse beyond run spread; any cell more than 20% worse is a stop.
Settled set: 60 s after Gateway ready, 3 runs per side (ABAB):
mainValidatorobjects in heap snapshotmcp-materializestage on the first session (median of all runs)Unsettled set: first session sent as soon as the Gateway was ready, 5 runs per side (ABAB): heap growth 212.7 vs 138.9 MB, validators 4,145 vs 105, sessions 2–20 start median/p95 363/2,480 vs 335/952 ms. The first session here overlaps Gateway warm-up and swings widely (
main2,348–11,349 ms, this PR 3,190–10,405 ms, medians 2,776 vs 3,687 ms); the difference sits in the Gateway'spreparation/replyInitializationstartup stages, not the MCP stage (lower on this PR in every run), and disappears in the settled set.maincount: 26 Gateway-internal validators + ~203 per session runtime. This PR: 26 + one per called tool per runtime + a small per-turn constant that also appears onmain.Controls (same on both builds unless noted; observed tool results handed back to the model):
maingood(valid output), first and second call in one sessionstructuredContent: {"ok":true}bad({"ok":"not-a-boolean"}), first and second callStructured content does not match the tool's output schema: /ok must be booleanmissing(schema, no structured content)Tool missing has an output schema but did not return structured contentiserr(isError result)P199346-ISERR tool reported a problemplain(no outputSchema)plain text result P199346-PLAINgood,badagain): Validator deltabrokenwith one uncompilable outputSchemafailed to start server "broken": Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref; 0tools/callfineworks;brokencall fails withInvalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref; server saw onlytools/call fineNative HTTP bridge (
createSessionMcpRuntime+acquireNativeMcpServer+view.callToolagainst an HTTP server with toolsfineandbroken):Tests:
mcp-tool-metadata.test.tsregression fails onmain(expected "getValidator" to be called 1 times, but got 3 times) and passes here; touched-area MCP tests pass.Proof comment: #199346 (comment)
Merge danger
Two-way door: no stored state, config, schema or protocol change; a revert restores eager compilation. Blast radius: MCP tool catalogs and calls in the bundle runtime, node host and native bridge; the only visible difference is the per-tool timing of the uncompilable-schema error described above.