Repository navigation
fix(mcp): #226 review findings — typed tool results (security + correctness) - #230
Merged
Merged
Conversation
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 tomainautomatically 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.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).64:ff9b::/96, sohttps://[64:ff9b::a9fe:a9fe]/could smuggle169.254.169.254past it on NAT64/DNS64 clusters. Now screened + the embedded IPv4 re-validated (well-known prefix only; NSPs documented as out of scope).Parts(CWE-345 / OWASP LLM01). The PostToolUse hook inspected onlyToolResult.Content, so prompt injection in aresource_linkTitle (which lives only inParts) reached the model uninspected. The hook now inspects the model-facingsession.ToolBlockTextprojection.Correctness
CallMcpWithQuerytruncated an oversized filtered JSON result into an unparseable blob; it now fail-closes with an actionable "narrow the filter" error (ADR 0063).StructuredContentre-marshal.RouteToolResultPartsnow fails closed (defaultcase) on an unknownBlockKindinstead of passing it ungated.Parts.truncateToolBodyrebuilt tool results viaNewToolResult(nil Parts), silently destroying typed blocks; now preservesParts+IsError(shared helper, so cascade's Tier-2 is covered too).png/jpeg/gif/webp), degrading others (e.g.image/svg+xml) to a text note instead of triggering an Anthropic HTTP 400.Cleanup & coverage
toolBlockTextfrom the OpenAI/Anthropic adapters intosession.ToolBlockText(Added, minor —engine/CHANGELOG.md+engine/api/session.txtupdated).fetchmcpresource.go.mapContentedge/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-standaloneGOWORK=off, api-compat) pass.🤖 Generated with Claude Code