Skip to content

fix(mcp): #226 review findings — typed tool results (security + correctness) - #230

Merged
JAORMX merged 1 commit into
feat/mcp-typed-tool-results-223from
review/mcp-226-fixes
Jul 3, 2026
Merged

JAORMX merged 1 commit into
feat/mcp-typed-tool-results-223from
review/mcp-226-fixes

Conversation

@jhrozek

@jhrozek jhrozek commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Review fixes for #226 (typed MCP tool results)

Stacked on #226 — base is feat/mcp-typed-tool-results-223, so the diff here is just this fix commit. GitHub will retarget this PR to main automatically once #226 merges.

These are the findings from a multi-pass review of #226 (per-layer correctness → cross-layer system interactions → adversarial red-team), reproduced with a standalone hostile MCP server and offline end-to-end tests. Eleven items across security, correctness, and coverage.

Security

  • jq single-value OOM (CWE-770/400). jq.Run's output cap only fires after each value is materialized, so a filter that builds one huge value ([range(1e9)]) allocated ~1 GiB before the 5 s deadline — enough to OOM a constrained pod. Added a heap-growth watchdog that cancels the run past a 256 MiB budget (gojq honours ctx cancellation mid-construction).
  • NAT64 SSRF (CWE-918). The egress guard didn't screen the RFC 6052 well-known prefix 64:ff9b::/96, so https://[64:ff9b::a9fe:a9fe]/ could smuggle 169.254.169.254 past it on NAT64/DNS64 clusters. Now screened + the embedded IPv4 re-validated (well-known prefix only; NSPs documented as out of scope).
  • Guardrail blind to Parts (CWE-345 / OWASP LLM01). The PostToolUse hook inspected only ToolResult.Content, so prompt injection in a resource_link Title (which lives only in Parts) reached the model uninspected. The hook now inspects the model-facing session.ToolBlockText projection.

Correctness

  • Recovery re-truncation. CallMcpWithQuery truncated an oversized filtered JSON result into an unparseable blob; it now fail-closes with an actionable "narrow the filter" error (ADR 0063).
  • Copy-before-gate. The 20 MiB input gate now runs before the redundant content copy / StructuredContent re-marshal.
  • Fail-open router. RouteToolResultParts now fails closed (default case) on an unknown BlockKind instead of passing it ungated.
  • Compaction dropped Parts. truncateToolBody rebuilt tool results via NewToolResult (nil Parts), silently destroying typed blocks; now preserves Parts + IsError (shared helper, so cascade's Tier-2 is covered too).
  • Image MIME → provider 400. MCP-result image blocks are now allowlisted to provider-renderable types (png/jpeg/gif/webp), degrading others (e.g. image/svg+xml) to a text note instead of triggering an Anthropic HTTP 400.

Cleanup & coverage

  • Extracted the byte-identical toolBlockText from the OpenAI/Anthropic adapters into session.ToolBlockText (Added, minor — engine/CHANGELOG.md + engine/api/session.txt updated).
  • Corrected a stale transport comment in fetchmcpresource.go.
  • Added coverage for mapContent edge/error branches, the jq memory budget, ValidateResolvedIP(nil), plus offline hostile-findings and positive typed-result e2e tests.

Validation

task lint + task test (both modules, -race, engine-standalone GOWORK=off, api-compat) pass.

🤖 Generated with Claude Code

Review of the typed-MCP-tool-results work surfaced 11 findings across
security, correctness, and coverage:

- jq OOM (CWE-770/400): a heap-growth watchdog cancels a filter run once
  it grows past a 256 MiB budget; previously only the 5s deadline bounded
  allocation, so a memory-amplifying filter (e.g. `[range(1e9)]`) could
  allocate ~1 GiB before it tripped — enough to OOM a constrained pod.
- NAT64 SSRF (CWE-918): screen the RFC 6052 well-known prefix
  64:ff9b::/96 and re-validate the embedded IPv4, so a literal like
  [64:ff9b::a9fe:a9fe] can no longer smuggle 169.254.169.254 past the
  egress guard on NAT64/DNS64 clusters.
- Guardrail blind to Parts (CWE-345 / OWASP LLM01): the PostToolUse hook
  now inspects the model-facing session.ToolBlockText projection, so
  prompt injection carried in a resource_link Title (which lives only in
  Parts, not Content) is no longer invisible to guardrails.
- CallMcpWithQuery recovery now fail-closes on an oversized filtered JSON
  result instead of truncating it into an unparseable blob (ADR 0063).
- CallMcpWithQuery applies the 20 MiB input gate before the redundant
  content copy / StructuredContent re-marshal.
- RouteToolResultParts fails closed (default case) on an unknown
  BlockKind rather than passing it to the provider ungated.
- Compaction preserves typed Parts (and IsError) when truncating a tool
  body instead of silently dropping them; the fix is in the shared
  truncateToolBody, so it covers cascade's Tier-2 strip too.
- MCP-result image blocks are allowlisted to provider-renderable types
  (png/jpeg/gif/webp), degrading others to a text note so an unsupported
  MIME (e.g. image/svg+xml) can no longer cause a provider HTTP 400.
- Extract the byte-identical toolBlockText from the OpenAI and Anthropic
  adapters into session.ToolBlockText (Added, minor — engine/CHANGELOG.md
  + engine/api/session.txt regenerated).
- Fix a stale transport comment in fetchmcpresource.go (it described
  ForceClose but the field set is ForceAttemptHTTP2).
- Add coverage: mapContent edge/error branches (audio, invalid
  image/audio, nil/empty embedded resource, unknown kind), the jq memory
  budget, ValidateResolvedIP(nil), plus end-to-end hostile-findings and
  positive typed-result tests.

task lint and task test (both modules, -race, engine-standalone,
api-compat) pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@JAORMX
JAORMX merged commit 7ee17e7 into feat/mcp-typed-tool-results-223 Jul 3, 2026
13 checks passed
JAORMX pushed a commit that referenced this pull request Jul 3, 2026
Review of the typed-MCP-tool-results work surfaced 11 findings across
security, correctness, and coverage:

- jq OOM (CWE-770/400): a heap-growth watchdog cancels a filter run once
  it grows past a 256 MiB budget; previously only the 5s deadline bounded
  allocation, so a memory-amplifying filter (e.g. `[range(1e9)]`) could
  allocate ~1 GiB before it tripped — enough to OOM a constrained pod.
- NAT64 SSRF (CWE-918): screen the RFC 6052 well-known prefix
  64:ff9b::/96 and re-validate the embedded IPv4, so a literal like
  [64:ff9b::a9fe:a9fe] can no longer smuggle 169.254.169.254 past the
  egress guard on NAT64/DNS64 clusters.
- Guardrail blind to Parts (CWE-345 / OWASP LLM01): the PostToolUse hook
  now inspects the model-facing session.ToolBlockText projection, so
  prompt injection carried in a resource_link Title (which lives only in
  Parts, not Content) is no longer invisible to guardrails.
- CallMcpWithQuery recovery now fail-closes on an oversized filtered JSON
  result instead of truncating it into an unparseable blob (ADR 0063).
- CallMcpWithQuery applies the 20 MiB input gate before the redundant
  content copy / StructuredContent re-marshal.
- RouteToolResultParts fails closed (default case) on an unknown
  BlockKind rather than passing it to the provider ungated.
- Compaction preserves typed Parts (and IsError) when truncating a tool
  body instead of silently dropping them; the fix is in the shared
  truncateToolBody, so it covers cascade's Tier-2 strip too.
- MCP-result image blocks are allowlisted to provider-renderable types
  (png/jpeg/gif/webp), degrading others to a text note so an unsupported
  MIME (e.g. image/svg+xml) can no longer cause a provider HTTP 400.
- Extract the byte-identical toolBlockText from the OpenAI and Anthropic
  adapters into session.ToolBlockText (Added, minor — engine/CHANGELOG.md
  + engine/api/session.txt regenerated).
- Fix a stale transport comment in fetchmcpresource.go (it described
  ForceClose but the field set is ForceAttemptHTTP2).
- Add coverage: mapContent edge/error branches (audio, invalid
  image/audio, nil/empty embedded resource, unknown kind), the jq memory
  budget, ValidateResolvedIP(nil), plus end-to-end hostile-findings and
  positive typed-result tests.

task lint and task test (both modules, -race, engine-standalone,
api-compat) pass.

Co-authored-by: Claude Opus 4.8 <[email protected]>
JAORMX added a commit that referenced this pull request Jul 3, 2026
…allMcpWithQuery jq filter (#226)

* feat(mcp): preserve typed content blocks, structured content, and resource links in tool results (#223)

mecatl's MCP client adapter collapsed every MCP CallToolResult.content[] to a
single string (flattenContent), discarding ResourceLink metadata, EmbeddedResource
bodies, Image/Audio data, StructuredContent, and outputSchema. When an MCP tool
(e.g. github MCP get_file) returned a resource, the model got a bare placeholder
and the user saw nothing. This preserves typed content end-to-end per the MCP
2025-06-18 spec.

Domain (engine/session, additive, Added/minor):
- ToolResult.Parts []Content — typed content blocks; zero-value = string-only
  legacy (backward-compat: old sessions Load/Fold with nil Parts).
- Content generalized with a BlockKind discriminator + block variants
  (BlockText/BlockImage/BlockAudio/BlockResourceLink/BlockEmbeddedResource/
  BlockStructuredContent) + fields (Text/Name/Title/Description/Size/Audience/
  Priority/LastModified). NewResourceLinkBlock/NewEmbeddedResourceBlock/
  NewStructuredContentBlock/NewTextBlock constructors. ValidateToolResultParts
  (per-block + total byte caps, CWE-770). NewToolResultWithParts builder.
  NewToolResult/NewToolError stay 2-arg (~200 call sites untouched).
- ValidateResolvedIP — the dial-layer SSRF predicate (CWE-918) reused by the
  fetch tool; shares the isGlobalUnicast definition with ValidateMediaURL.

MCP adapter (internal/adapter/mcp/tool.go):
- mapContent replaces flattenContent: mcpsdk.Content -> session.Content (neutral,
  no mcpsdk.* in engine/). TextContent verbatim; Image/Audio via NewImageContent/
  NewAudioContent (no second validation path); ResourceLink as a reference (URI+
  name+desc+MIME, audience carried through — advisory-only, CWE-345, NEVER
  suppresses model content); EmbeddedResource inline (text verbatim, binary
  summarized); StructuredContent as a BlockStructuredContent + the spec-SHOULD
  TextContent mirror. outputSchema captured; optional jsonschema-go defense-in-
  depth validation (never session.ValidateJSON — fail-open subset validator).
- toolkit.Truncate(MaxOutputBytes) applied to MCP results (closes #178).

Routing (engine/port.RouteToolResultParts): a pure read-only capability-gated
projection — image iff caps.Image, audio iff caps.Audio, text/resource-link/
embedded-resource always pass, audience never filters, nil -> degrade to string.
Placed in engine/port (the one layer both providers and composition import) so
providers call it without inverting layering. Never mutates recorded history
(effective-payload guarantee intact).

Providers (openai, anthropic): consume ToolResult.Parts when capability-routed
(WithProviderCapabilities adapter Option, re-minted per-session — NOT an
LLMRequest field, neutrality holds). Byte-identical legacy path when Parts empty.

FetchMcpResource tool (internal/adapter/tools): https-only fetch of resource_link
URIs via ValidateMediaURL (SSRF IP-deny) + CheckRedirect URL re-validation +
ssrfGuardedDialContext (ValidateResolvedIP on each resolved IP — closes the
DNS-rebinding window at the dial layer). Non-https schemes guide to ReadMcpResource
against the owning server. Per-call http.Client (no outlives-a-call resource).
ScopeBuiltinDefault floor-Allow; guardrail default block set (post-only).

Proto + relay: additive ToolResult.blocks + structured_content; new ContentBlock
message. Relay mappers (blocksToProto/blocksFromProto). Fold reconstructs typed
blocks for free (rides EvToolResult.ToolResult) — no sidecar.

TUI: tool card surfaces resource-link/image blocks distinctly; existing goldens
byte-unchanged, new tool_mcp_card_blocks.golden.

Tests: TestMcpperfRoundTripResourceLinkPreserved (e2e: mecatl's own mcpperf
server -> mecatl client renders the user-audience resource_link — the broken
round-trip fixed); TestLoopEmitsToolResultWithParts (full loop);
TestFetchMcpResourceRedirectToInternalRejected + TestFetchMcpResourceDialLayer
RejectsInternalIP (SSRF); TestValidateResolvedIP; provider byte-identical-legacy
tests; TestFoldReconstructsTypedToolResult.

Docs: ADR 0059 (the contract); CLOUD-NATIVE.md re-audit (no new List 1/List 2
row — value-object widening; FetchMcpResource http.Client is per-call);
IMPLEMENTATION-NOTES.md, architecture.md, usage/mecated.md; perf-mcp-
interpretation skill updated (resource_link now surfaces as a typed block,
fetchable via FetchMcpResource for https). engine/CHANGELOG.md Added entries.

Verified: task lint (0 issues), task test (full suite green, -race), task
api:check (Added/minor), task docs:check (0 broken links/anchors), go run
./cmd/mecademo (full offline session).

Closes #223. Refs #178.

* feat(mcp): fail-closed on structured truncation + CallMcpWithQuery jq filter (#223)

Truncating a structured (JSON) MCP tool result at MaxOutputBytes makes it
unparseable and unusable — the model gets a partial JSON blob it can't reason
over. Other harnesses persist big results to a file and let the model jq/grep
it, but mecatl runs cloud-native (mecak8s is storage-free, no PVC — ADR 0048),
so local-disk persistence is NOT a portable option. This implements the
agreed two-tier, environment-agnostic (no local-disk) design.

Fail-closed on structured-over-cap (internal/adapter/mcp/tool.go):
- remoteTool.Execute now returns an actionable tool ERROR (not a truncated
  blob) when a structured result exceeds MaxOutputBytes. The error names the
  two portable escape hatches: (1) narrow/paginate the remote call using the
  tool's own filter/pagination params, (2) call it through CallMcpWithQuery
  with a jq filter. Three detection signals (OR): outputSchema advertised,
  StructuredContent present, or a content block that is JSON by MIME
  (application/json / +json) or text-parse (starts with {/[ and json.Unmarshals).
  Unstructured text still truncates with a marker (text tolerates it). Error
  payloads short-circuit before the check (errors stay string-only, truncated).
  Closes the operator's "unparseable JSON" concern.

CallMcpWithQuery meta-tool (internal/adapter/mcp/callmcpwithquery.go):
- Calls a remote MCP tool AND filters its JSON result through jq in memory
  (no disk), so the big JSON never enters conversation history — only the
  filtered subset does. Works in FS + no-FS/cloud-native environments.
- JSON-input precedence: StructuredContent (if present) → first
  JSON-parseable text block → loud error. Remote IsError → surface the error
  text pre-filter (no jq). Input ≤ jq.MaxInputBytes (20 MiB); output
  truncated to MaxOutputBytes. Registered when MCP tools exist (global, FS +
  no-FS, including the no-FS child catalog — no dead-end). Floor-Allow
  (config-overridable); guardrail default block (pre+post, mirrors mcp__*).
- Args: server, tool (remote name, not mcp__-prefixed), args (verbatim),
  jq_filter (required).

gojq wrapper (internal/adapter/mcp/jq/jq.go):
- github.com/itchyny/gojq (pure Go, MIT, root-module only — engine closure
  untouched). Sandboxed by construction: gojq.New without WithModuleLoader /
  WithInputIter / WithEnvironLoader — the filter cannot read files, env, or
  stdin. ctx-deadline-bounded via RunWithContext (gojq is ctx-aware). Input ≤
  20 MiB, output ≤ ~100 KiB (loud errors on oversize). Multi-output → array-
  wrapped; zero → null; single string → JSON-quoted.

Provider.CallTool + CallResult (internal/adapter/mcp/calltool.go):
- Widens the internal adapter Provider interface with CallTool returning a
  new adapter CallResult value object (Content + StructuredContent + IsError),
  BEFORE model-facing truncation — so CallMcpWithQuery filters the raw result.
  No mcpsdk types leak to internal/app (CallResult is adapter-only). No
  engine/ exported API change (internal adapter widening only).

Tests: TestCallMcpWithQueryE2EFailClosedThenRecovery (real Service e2e —
fail-closed error on the direct call, filtered subset on CallMcpWithQuery);
Signal-1-only / EmbeddedResource-MIME / JSON-as-TextContent fail-close cases;
gojq sandbox isolation (no input/inputs/import/include/env leak); output
truncation; remote-IsError pre-filter; no-FS child catalog presence.

Docs: ADR 0063 (the contract); IMPLEMENTATION-NOTES.md; usage/mecated.md;
perf-mcp-interpretation skill; llms.txt regenerated.

Verified: task lint (0 issues), task test (full suite green, -race),
task api:check (no engine API change), task docs:check (0 broken links),
go run ./cmd/mecademo (full offline session).

Refs #223. Cloud-native: no local-disk dependency anywhere.

* fix(mcp): address PR #226 review findings (typed tool results) (#230)

Review of the typed-MCP-tool-results work surfaced 11 findings across
security, correctness, and coverage:

- jq OOM (CWE-770/400): a heap-growth watchdog cancels a filter run once
  it grows past a 256 MiB budget; previously only the 5s deadline bounded
  allocation, so a memory-amplifying filter (e.g. `[range(1e9)]`) could
  allocate ~1 GiB before it tripped — enough to OOM a constrained pod.
- NAT64 SSRF (CWE-918): screen the RFC 6052 well-known prefix
  64:ff9b::/96 and re-validate the embedded IPv4, so a literal like
  [64:ff9b::a9fe:a9fe] can no longer smuggle 169.254.169.254 past the
  egress guard on NAT64/DNS64 clusters.
- Guardrail blind to Parts (CWE-345 / OWASP LLM01): the PostToolUse hook
  now inspects the model-facing session.ToolBlockText projection, so
  prompt injection carried in a resource_link Title (which lives only in
  Parts, not Content) is no longer invisible to guardrails.
- CallMcpWithQuery recovery now fail-closes on an oversized filtered JSON
  result instead of truncating it into an unparseable blob (ADR 0063).
- CallMcpWithQuery applies the 20 MiB input gate before the redundant
  content copy / StructuredContent re-marshal.
- RouteToolResultParts fails closed (default case) on an unknown
  BlockKind rather than passing it to the provider ungated.
- Compaction preserves typed Parts (and IsError) when truncating a tool
  body instead of silently dropping them; the fix is in the shared
  truncateToolBody, so it covers cascade's Tier-2 strip too.
- MCP-result image blocks are allowlisted to provider-renderable types
  (png/jpeg/gif/webp), degrading others to a text note so an unsupported
  MIME (e.g. image/svg+xml) can no longer cause a provider HTTP 400.
- Extract the byte-identical toolBlockText from the OpenAI and Anthropic
  adapters into session.ToolBlockText (Added, minor — engine/CHANGELOG.md
  + engine/api/session.txt regenerated).
- Fix a stale transport comment in fetchmcpresource.go (it described
  ForceClose but the field set is ForceAttemptHTTP2).
- Add coverage: mapContent edge/error branches (audio, invalid
  image/audio, nil/empty embedded resource, unknown kind), the jq memory
  budget, ValidateResolvedIP(nil), plus end-to-end hostile-findings and
  positive typed-result tests.

task lint and task test (both modules, -race, engine-standalone,
api-compat) pass.

Co-authored-by: Claude Opus 4.8 <[email protected]>

* chore: regenerate llms.txt after rebase onto main

---------

Co-authored-by: Jakub Hrozek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
JAORMX pushed a commit that referenced this pull request Jul 28, 2026
Review of the typed-MCP-tool-results work surfaced 11 findings across
security, correctness, and coverage:

- jq OOM (CWE-770/400): a heap-growth watchdog cancels a filter run once
  it grows past a 256 MiB budget; previously only the 5s deadline bounded
  allocation, so a memory-amplifying filter (e.g. `[range(1e9)]`) could
  allocate ~1 GiB before it tripped — enough to OOM a constrained pod.
- NAT64 SSRF (CWE-918): screen the RFC 6052 well-known prefix
  64:ff9b::/96 and re-validate the embedded IPv4, so a literal like
  [64:ff9b::a9fe:a9fe] can no longer smuggle 169.254.169.254 past the
  egress guard on NAT64/DNS64 clusters.
- Guardrail blind to Parts (CWE-345 / OWASP LLM01): the PostToolUse hook
  now inspects the model-facing session.ToolBlockText projection, so
  prompt injection carried in a resource_link Title (which lives only in
  Parts, not Content) is no longer invisible to guardrails.
- CallMcpWithQuery recovery now fail-closes on an oversized filtered JSON
  result instead of truncating it into an unparseable blob (ADR 0063).
- CallMcpWithQuery applies the 20 MiB input gate before the redundant
  content copy / StructuredContent re-marshal.
- RouteToolResultParts fails closed (default case) on an unknown
  BlockKind rather than passing it to the provider ungated.
- Compaction preserves typed Parts (and IsError) when truncating a tool
  body instead of silently dropping them; the fix is in the shared
  truncateToolBody, so it covers cascade's Tier-2 strip too.
- MCP-result image blocks are allowlisted to provider-renderable types
  (png/jpeg/gif/webp), degrading others to a text note so an unsupported
  MIME (e.g. image/svg+xml) can no longer cause a provider HTTP 400.
- Extract the byte-identical toolBlockText from the OpenAI and Anthropic
  adapters into session.ToolBlockText (Added, minor — engine/CHANGELOG.md
  + engine/api/session.txt regenerated).
- Fix a stale transport comment in fetchmcpresource.go (it described
  ForceClose but the field set is ForceAttemptHTTP2).
- Add coverage: mapContent edge/error branches (audio, invalid
  image/audio, nil/empty embedded resource, unknown kind), the jq memory
  budget, ValidateResolvedIP(nil), plus end-to-end hostile-findings and
  positive typed-result tests.

task lint and task test (both modules, -race, engine-standalone,
api-compat) pass.

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants