Skip to content

fix(mcp): compile tool output validators on first call, not at catalog load (#199327) - #199346

Merged
obviyus merged 5 commits into
openclaw:mainfrom
lonexreb:fix/199327-lazy-mcp-output-validators
Nov 26, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
lonexreb:fix/199327-lazy-mcp-output-validators

Conversation

@lonexreb

@lonexreb lonexreb commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

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' $refs (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 40f3903e6e2b:      catalog fails (same Invalid MCP ... unresolved ref), server tools/call: 0
f992f15609 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.

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Nov 15, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This 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.

  • Before: Catalog loading acquires 200 output validators, including validators for unused tools.
  • After: Catalog loading acquires none; the first tool call acquires its validator and later calls reuse it.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, useful implementation with the earlier correctness finding resolved and limited remaining validation confidence.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Sessions connected to large MCP catalogs retain compiled validators for tools they never call.
Reason: Removing unused compilation has concrete resource value; optional cross-runtime sharing is unnecessary to solve the central problem.

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
Reviewed head: f992f15609f468873c6c41431c11cae2b795af7b

Before merge

  • Add real behavior proof - Current-head CLI/Gateway logs exercise the production MCP path and demonstrate preserved validation, but the provider is explicitly scripted rather than a real model as required by AGENTS.md:83; the earlier HTTP measurements provide supporting performance evidence. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Provide current-head Gateway evidence using a real model for first-call shared-reference validation and valid/invalid structured results, with credentials, IPs, phone numbers, and non-public endpoints redacted.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still performs eager compilation: Current main acquires and retains an output validator for every included tool during normalization; the affected files are unchanged from the PR merge base. (src/agents/mcp-tool-metadata.ts:61, 8f9bd10825ff)
  • Earlier shared-resource finding resolved: The revised head eagerly acquires schemas containing $id in catalog order and adds a regression that calls a referencing tool before its schema-providing tool. (src/agents/mcp-tool-metadata.ts:98, f992f15609f4)
  • Dispatch-time validation preserved: Session and node-host calls capture the validator before sending tools/call; native stdio does the same before entering its continuation flow, preserving validation against the dispatched catalog. (src/agents/agent-bundle-mcp-runtime.ts:758, f992f15609f4)
  • Original ownership and purpose: The creation patch introduced createMcpToolCatalogMetadata to preserve validation across paginated discovery; the later normalizeMcpToolCatalog refactor preserved dispatch-time validation and excluded-tool filtering. The relevant patches are readable; git log --follow stops at an unavailable older object. (src/agents/mcp-tool-metadata.ts:23, 1cf8ea446df4)
  • Supplied behavior evidence: The full PR body records current-head Gateway CLI turns covering a first-call cross-tool reference, valid output, and rejected invalid output using a scripted loopback provider; it separately identifies the earlier revision used for heap measurements. (f992f15609f4)
  • Applicable behavior-proof requirement: Root policy explicitly requires an isolated Gateway with a real agent and model for user-visible behavior and says mocks do not replace that proof; root and agent-scoped policies were read and applied. (AGENTS.md:83, f992f15609f4)

Likely related people:

  • Peter Steinberger: Raw commit 407c8cd adds src/agents/mcp-tool-metadata.ts:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 407c8cdb3440; files: src/agents/mcp-tool-metadata.ts)
  • Ayaan Zaidi: Raw commit d4f6966 adds src/agents/mcp-tool-metadata.ts:41 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d4f6966dbf3b; files: src/agents/mcp-tool-metadata.ts)

PR surface

Source +19, Tests +37. Total +56 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 45 26 +19
Tests 1 37 0 +37
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 82 26 +56

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Large MCP catalogs incur avoidable compilation and retained memory per session, without evidence here of unbounded retention or an urgent availability failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-15T01:07:57.318Z sha f138672 :: needs real behavior proof before merge. :: [P2] Preserve registered schema resources before compiling on demand

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.
@lonexreb

Copy link
Copy Markdown
Contributor Author

Head f992f15609f addresses the P2: a tool output schema that contains an $id still compiles at catalog load, in catalog order, so another tool's $ref to it resolves whichever tool is called first. Schemas without $id stay lazy. New regression: resolves a reference to another tool's schema whichever tool is called first (fails on f1386727098).

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 $ref tool, a valid result, and a rejected invalid result. It used a scripted loopback provider, not a real model.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 15, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Nov 15, 2026
@brandon-julio-t

Copy link
Copy Markdown
Contributor

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 main and keeping your authorship. That PR adds a real-model (openai/gpt-5.6-luna) isolated-Gateway run of the derived/good/bad cases and a per-session catalog benchmark: 142 ms → 22 ms on first load, 8.3 MB → 1.3 MB retained per catalog.

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.
@obviyus

obviyus commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Observed proof for head 660acbb1571a vs main 40f3903e6e2b (built Gateways in secretless node:24.22.1 containers, local streamable-HTTP + stdio MCP fixtures, scripted local model):

# #199346 (fixes #199327) proof — base main 40f3903e6e2b, candidate 660acbb1571a (contributor f13867270985 + f992f15609f4, merge of main, + e9f391196563 test fold, + 660acbb1571a native HTTP acquire)
# Builds: build.sh <label> <sha> -> secretless node:24.22.1, pnpm install --frozen-lockfile && pnpm build, volumes bugloop-199346-{base,cand}
# Gateway runs: run.sh <label> <name> perf|control (205-tool streamable-HTTP MCP fixture, scripted local model, mcp.sessionIdleTtlMs=86400000, 20 sessions x 2 tool calls)

## perf, unsettled (ABAB x5): side run heapUsedDeltaMB validators firstStartMs warmStartMedianMs load
base perf-base-1-20261126-102037 201.01 4145 11349 2316 2.05
base perf-base-2-20261126-102349 215.88 4145 2348 308 3.16
base perf-base-3-20261126-102517 210 4145 2842 353 2.80
base perf-base-4-20261126-102634 216.85 4145 2545 359 1.62
base perf-base-5-20261126-102758 212.67 4145 2776 347 1.89
cand perf-cand-1-20261126-102224 133.02 105 10405 275 1.37
cand perf-cand-2-20261126-102431 138.92 105 3190 395 2.87
cand perf-cand-3-20261126-102556 139.44 105 3743 308 2.12
cand perf-cand-4-20261126-102717 140.06 105 3343 348 1.92
cand perf-cand-5-20261126-102843 136.2 105 3687 332 1.58
{"side":"base","heapDeltaMB":{"median":212.67,"min":201.01,"max":216.85},"validators":{"median":4145,"min":4145,"max":4145},"coldFirstStartMs":{"median":2776,"max":11349},"warmStartMs":{"n":95,"median":363,"p95":2480,"max":5150},"firstTurnMs":{"n":100,"median":496.5,"p95":3047}}
{"side":"cand","heapDeltaMB":{"median":138.92,"min":133.02,"max":140.06},"validators":{"median":105,"min":105,"max":105},"coldFirstStartMs":{"median":3687,"max":10405},"warmStartMs":{"n":95,"median":335,"p95":952,"max":2803},"firstTurnMs":{"n":100,"median":442.5,"p95":2907}}

## perf, settled 60s after ready (SETTLE=60, ABAB x3)
base perf-base-s1-20261126-103020 209.39 4145 2558 301 0.93
base perf-base-s2-20261126-103347 208.14 4145 2492 294 1.52
base perf-base-s3-20261126-103700 206.9 4145 2562 298 1.26
cand perf-cand-s1-20261126-103210 133.78 105 2534 293 1.26
cand perf-cand-s2-20261126-103526 130.36 105 2503 283 1.37
cand perf-cand-s3-20261126-103840 131.63 105 2320 264 1.31
{"side":"base","heapDeltaMB":{"median":208.14,"min":206.9,"max":209.39},"validators":{"median":4145,"min":4145,"max":4145},"coldFirstStartMs":{"median":2558,"max":2562},"warmStartMs":{"n":57,"median":297,"p95":459,"max":483},"firstTurnMs":{"n":60,"median":383.5,"p95":577}}
{"side":"cand","heapDeltaMB":{"median":131.63,"min":130.36,"max":133.78},"validators":{"median":105,"min":105,"max":105},"coldFirstStartMs":{"median":2503,"max":2534},"warmStartMs":{"n":57,"median":283,"p95":370,"max":483},"firstTurnMs":{"n":60,"median":366.5,"p95":585}}

## first-session Gateway mcp-materialize stage (ms, all perf runs)
base:  148 151 153 153 162 179 192
cand: 104 108 117 174 86 95 96 99

## control base (runs/control-base-1-20261126-101829)
{"validators":{"c1":439,"c1r":441,"start":26},"mcp":{"mcp-broken.jsonl":{"initialize":4,"toolsList":4,"toolsCall":{}},"mcp-http.jsonl":{"initialize":3,"toolsList":3,"toolsCall":{"good":2,"bad":2,"plain":1,"missing":1,"iserr":1}},"mcp-stdio.jsonl":{"initialize":3,"toolsList":3,"toolsCall":{"good":1,"bad":1,"plain":1}}}}
C1 final proof__good,proof__bad,proof__plain,proof__missing,proof__iserr
  structuredContent: {"ok":true}
  proof__bad error: Structured content does not match the tool's output schema: /ok must be boolean
  plain text result P199346-PLAIN
  proof__missing error: Tool missing has an output schema but did not return structured content
  P199346-ISERR tool reported a problem
C1R final proof__good,proof__bad
  structuredContent: {"ok":true}
  proof__bad error: Structured content does not match the tool's output schema: /ok must be boolean
C2 final proofstdio__good,proofstdio__bad,proofstdio__plain
  structuredContent: {"ok":true}
  proofstdio__bad error: Structured content does not match the tool's output schema: /ok must be boolean
  plain text result P199346-PLAIN
C3 final broken__fine,broken__broken
  
2026-11-26T04:48:59.288+00:00 [bundle-mcp] failed to start server "broken" (http://127.0.0.1:39401/mcp): Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref

## control cand (runs/control-cand-1-20261126-101916)
{"validators":{"c1":35,"c1r":37,"start":26},"mcp":{"mcp-broken.jsonl":{"initialize":3,"toolsList":3,"toolsCall":{"fine":1}},"mcp-http.jsonl":{"initialize":3,"toolsList":3,"toolsCall":{"good":2,"bad":2,"plain":1,"missing":1,"iserr":1}},"mcp-stdio.jsonl":{"initialize":3,"toolsList":3,"toolsCall":{"good":1,"bad":1,"plain":1}}}}
C1 final proof__good,proof__bad,proof__plain,proof__missing,proof__iserr
  structuredContent: {"ok":true}
  proof__bad error: Structured content does not match the tool's output schema: /ok must be boolean
  plain text result P199346-PLAIN
  proof__missing error: Tool missing has an output schema but did not return structured content
  P199346-ISERR tool reported a problem
C1R final proof__good,proof__bad
  structuredContent: {"ok":true}
  proof__bad error: Structured content does not match the tool's output schema: /ok must be boolean
C2 final proofstdio__good,proofstdio__bad,proofstdio__plain
  structuredContent: {"ok":true}
  proofstdio__bad error: Structured content does not match the tool's output schema: /ok must be boolean
  plain text result P199346-PLAIN
C3 final broken__fine,broken__broken
  structuredContent: {"ok":true}
  broken__broken error: Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref

## native HTTP bridge (native-http-check.mts, createSessionMcpRuntime + acquireNativeMcpServer + view.callTool)
-- native/base-40f3903e6e2b.txt
catalog tools: (none)
native acquire failed: bundle-mcp server "broken" is not connected
server tools/call: 0 
-- native/pr-head-e9f391196563.txt
catalog tools: broken,fine
native view.callTool fine: complete {"ok":true}
native view.callTool broken: complete {"a":1}
server tools/call: 2 "tool":"fine" "tool":"broken" 
-- native/cand-660acbb1571a.txt
catalog tools: broken,fine
native view.callTool fine: complete {"ok":true}
native view.callTool broken: rejected Invalid MCP draft-2020-12 JSON Schema: <schema>.properties.a.$ref: unresolved ref
server tools/call: 1 "tool":"fine" 

## regression red on base (cand test file over base tree)
 �[31m�[39m �[30m�[45m agents-core �[49m�[39m src/agents/mcp-tool-metadata.test.ts�[2m > �[22mcompiles output schemas on first call, except shared $id resources (#199327)�[32m 4�[2mms�[22m�[39m
�[31m⎯⎯⎯⎯⎯⎯⎯�[39m�[1m�[41m Failed Tests 1 �[49m�[22m�[31m⎯⎯⎯⎯⎯⎯⎯�[39m
�[31m�[1mAssertionError�[22m: expected "getValidator" to be called 1 times, but got 3 times�[39m
�[2m      Tests �[22m �[1m�[31m1 failed�[39m�[22m�[2m | �[22m�[1m�[32m15 passed�[39m�[22m�[90m (16)�[39m

## pre-push tests (cand tree, Docker): src/agents/mcp-tool-metadata.test.ts src/agents/tool-search-catalog-reuse.test.ts src/agents/native-mcp-runtime.http.test.ts src/agents/native-mcp-runtime.test.ts src/agents/agent-bundle-mcp-runtime.test.ts src/agents/agent-bundle-mcp-schema.test.ts src/agents/mcp-json-schema-validator.test.ts src/node-host/mcp-elicitation.integration.test.ts src/node-host/mcp.cancellation.integration.test.ts 
�[2m Test Files �[22m �[1m�[32m4 passed�[39m�[22m�[90m (4)�[39m
�[2m      Tests �[22m �[1m�[32m103 passed�[39m�[22m�[90m (103)�[39m
[test] passed 4 Vitest shards in 102.96s

@obviyus
obviyus merged commit eb704f5 into openclaw:main Nov 26, 2026
125 of 126 checks passed
@obviyus

obviyus commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
…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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
…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)
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Every session MCP runtime eagerly compiles an output-schema validator for every tool (~15–20 MB per runtime, nothing shared)

3 participants