Skip to content

feat(mcp): typed tool results + fail-closed structured truncation + CallMcpWithQuery jq filter - #226

Merged
JAORMX merged 4 commits into
mainfrom
feat/mcp-typed-tool-results-223
Jul 3, 2026
Merged

JAORMX merged 4 commits into
mainfrom
feat/mcp-typed-tool-results-223

Conversation

@JAORMX

@JAORMX JAORMX commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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. the github MCP's get_file) returned a resource, the model got a bare [resource link: <uri>] placeholder and the user saw nothing. This PR preserves typed content blocks end-to-end per the MCP 2025-06-18 spec, AND adds a fail-closed policy + a jq-filtering tool so large structured results don't get truncated into unparseable blobs.

Closes #223. Closes #178.

Design: ADR 0059 (typed results) + ADR 0063 (fail-closed + CallMcpWithQuery).

Commits

  1. feat(mcp): preserve typed content blocks, structured content, and resource links in tool results — the typed-blocks foundation.
  2. feat(mcp): fail-closed on structured truncation + CallMcpWithQuery jq filter — the large-JSON handling, additive on top.

Commit 1 — typed content blocks (the foundation)

Domain (engine/session, additive → Added/minor):

  • ToolResult.Parts []Content — typed content blocks; zero-value = string-only legacy (backward-compat: old persisted sessions Load/Fold with nil Parts).
  • Content generalized with a BlockKind discriminator + block variants (BlockText/BlockImage/BlockAudio/BlockResourceLink/BlockEmbeddedResource/BlockStructuredContent) + fields. Constructors; ValidateToolResultParts (per-block + total byte caps, CWE-770). NewToolResultWithParts builder. NewToolResult/NewToolError stay 2-arg.
  • ValidateResolvedIP — the dial-layer SSRF predicate (CWE-918).

MCP adapter (internal/adapter/mcp/tool.go):

  • mapContent replaces flattenContent: mcpsdk.Content → session.Content (neutral — no mcpsdk.* in engine/). TextContent verbatim; Image/Audio via validating constructors; 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.
  • toolkit.Truncate(MaxOutputBytes) applied to MCP results (closes MCP tool results are not truncated to MaxOutputBytes (unlike every built-in tool) #178).

Routing (engine/port.RouteToolResultParts): pure read-only capability-gated projection (image/audio gated; text/resource-link always pass; audience never filters; nil → degrade to string). Never mutates recorded history.

Providers (openai, anthropic): consume ToolResult.Parts when capability-routed (WithProviderCapabilities adapter Option; NOT an LLMRequest field). Byte-identical legacy path when Parts empty.

FetchMcpResource tool: https-only fetch of resource_link URIs via ValidateMediaURL + CheckRedirect re-validation + ssrfGuardedDialContext (ValidateResolvedIP — closes the DNS-rebinding window). Per-call http.Client.

Proto + relay + TUI: additive ToolResult.blocks + structured_content; new ContentBlock message. Fold reconstructs typed blocks for free (rides EvToolResult) — no sidecar. TUI surfaces resource-link/image blocks distinctly.


Commit 2 — fail-closed structured truncation + CallMcpWithQuery jq filter

The problem. Truncating a structured (JSON) MCP result at MaxOutputBytes makes it unparseable and unusable. 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.

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 the cap. The error names two portable escape hatches: (1) narrow/paginate the remote call, (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/text-parse. Unstructured text still truncates with a marker. Error payloads short-circuit (stay string-only).

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. JSON-input precedence: StructuredContent → first JSON-parseable text block → loud error. Remote IsError → surface error pre-filter. Registered when MCP tools exist (global, FS + no-FS, including the no-FS child catalog — no dead-end). Floor-Allow; guardrail default block (pre+post).

gojq wrapper (internal/adapter/mcp/jq/jq.go): github.com/itchyny/gojq (pure Go, MIT, root-module only — engine closure untouched). Sandboxed by construction: no WithModuleLoader/WithInputIter/WithEnvironLoader — the filter cannot read files, env, or stdin. RunWithContext (ctx-aware) bounds pathological compute. Input ≤ 20 MiB, output ≤ ~100 KiB.

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 truncation — so CallMcpWithQuery filters the raw result. No mcpsdk types leak to internal/app. No engine/ exported API change.


Key invariants respected

  • No mcpsdk.* in engine/ — typed blocks are the domain's own neutral session.Content; CallResult is adapter-only.
  • port.LLMRequest neutrality — capabilities thread via adapter Options; CallMcpWithQuery is a tool, not a request field.
  • Loop stays storage-agnostic — typed blocks ride EvToolResult; no port.EventLog/Append in the new paths.
  • audience advisory-only (CWE-345) — never suppresses model content.
  • Never auto-dereference URIs (CWE-918) — FetchMcpResource is https-only through ValidateMediaURL + dial-layer ValidateResolvedIP.
  • Cloud-native portability — no local-disk dependency anywhere (fail-closed is a string; jq runs in memory; CallMcpWithQuery fetches via the MCP session). mecak8s/no-FS safe.
  • Size bound (MCP tool results are not truncated to MaxOutputBytes (unlike every built-in tool) #178) — MaxOutputBytes applied; fail-closed for structured; jq input/output caps.
  • api-compat — Added/minor (commit 1); no engine API change (commit 2).
  • No stdio MCP / no spawn — gojq is a pure-Go library.

Tests

  • TestMcpperfRoundTripResourceLinkPreserved — e2e: our own mcpperf server consumed by our client renders the resource_link (broken round-trip fixed).
  • TestLoopEmitsToolResultWithParts — full loop wiring.
  • TestCallMcpWithQueryE2EFailClosedThenRecovery — e2e: fail-closed error on the direct >25KiB JSON call, filtered subset (.items | length → 1100) on CallMcpWithQuery.
  • SSRF suite (redirect + DNS-rebinding dial layer); provider byte-identical-legacy; TestFoldReconstructsTypedToolResult.
  • Fail-closed: Signal-1-only (outputSchema), EmbeddedResource-MIME, JSON-as-TextContent, unstructured-truncates, error-not-fail-closed.
  • gojq sandbox: no input/inputs/import/include/env leak; deadline on def f: f; f; oversize input/output.
  • CallMcpWithQuery: subset filter, StructuredContent precedence, non-JSON loud error, parse error, remote-IsError pre-filter, output truncation.

Verification

  • task lint — 0 issues
  • task test — full suite green (-race, root + engine + GOWORK=off standalone)
  • task api:check — Added/minor (commit 1); no change (commit 2)
  • task docs:check — 0 broken links/anchors/orphans/unreachable/ambiguous
  • go run ./cmd/mecademo — full offline session

Review context

Both commits went through a dev pipeline: architect plan → delegated implementations → a multi-reviewer panel (spec / standards / secure-code-reviewer / software-architect / devops / QA) → an iteration fixing confirmed findings (the DNS-rebinding dial guard; the redirect-rejection test; the full-loop test; the no-FS-child CallMcpWithQuery dead-end; the Signal-1-only and EmbeddedResource-MIME test gaps; the gojq isolation tests). Panels found no Critical/High.

Docs

ADR 0059 + ADR 0063 (the contracts); docs/adr/0027-cloud-native.md re-audit; docs/design/IMPLEMENTATION-NOTES.md; docs/architecture.md; docs/usage/mecated.md; engine/CHANGELOG.md; the perf-mcp-interpretation skill.

@JAORMX
JAORMX force-pushed the feat/mcp-typed-tool-results-223 branch 2 times, most recently from 87485c0 to 009464e Compare July 1, 2026 07:07
@JAORMX JAORMX changed the title feat/mcp typed tool results 223 feat(mcp): preserve typed content blocks, structured content, and resource links in tool results Jul 1, 2026
@JAORMX JAORMX added the e2e-live Run the live e2e suite on this PR label Jul 1, 2026
@JAORMX JAORMX changed the title feat(mcp): preserve typed content blocks, structured content, and resource links in tool results feat(mcp): typed tool results + fail-closed structured truncation + CallMcpWithQuery jq filter Jul 1, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — typed MCP tool results + fail-closed + CallMcpWithQuery

Reviewed across three passes (per-layer correctness → cross-layer system interactions → adversarial red-team + skeptical verification of each finding). Overall this is a solid, well-tested change — the outward data flow is architecturally sound and several security-critical seams were proven not exploitable (see bottom). Inline comments below are the findings that survived adversarial verification, ranked. Nothing is a hard correctness blocker; the two items I'd resolve before merge are cloud-deployment security issues (jq OOM, NAT64 SSRF).

Two root-cause themes (most inline findings collapse into these)

  • A — the guardrail/redaction boundary is blind to ToolResult.Parts. The PostToolUse hook inspects only .Content; content that lives only in Parts (resource-link Title/Description, image/audio Data) reaches the model and the client wire uninspected. One fix: route a Parts-flattened projection through the hook input.
  • B — size limits fire after allocation, or disagree across layers. jq's output cap is post-materialization (OOM), CallMcpWithQuery re-marshals the full result before the 20 MiB gate, and the recovery path re-truncates at 25 KB despite jq's 100 KB cap. One fix: one coherent cap ladder (25 KB terminal · 20 MiB jq input), enforced before/incrementally, with a memory budget on jq.

Findings that could not be anchored inline (unchanged files / cross-file)

  • Low/Med — compaction silently drops Parts. engine/agent/compaction.go truncateToolBody rebuilds an over-budget tool message via NewToolResult → Parts:nil, keyed on text length (400 chars), with only a text-byte elision marker — no signal the typed blocks vanished. Same defect in cascade.go. Because compaction ReplaceHistorys, the loss is durable. Conditional (needs compaction to fire + a Parts-bearing tail result + Content > 400). Fix: NewToolResultWithParts in the truncation branch, or only truncate when Parts is empty.
  • Medium — provider-400 via valid-but-unsupported image MIME. session.NewImageContent only checks the image/ prefix, so image/svg+xml / image/tiff route to Anthropic as a base64 image → HTTP 400 → session failed each turn (recoverable via Recover, but a reliable per-turn availability hit from a hostile server). Fix: allowlist provider-accepted image MIMEs at the block boundary, or degrade unsupported types to a text placeholder.
  • Low — cross-provider duplication. toolBlockText is duplicated verbatim in internal/adapter/openai/request.go and internal/adapter/anthropic/request.go (pure domain projection — belongs beside RouteToolResultParts or on session.Content); the openai free-vs-method buildParams also duplicates the params-struct assembly (drift risk).
  • Low — test-coverage gaps. mapContent's AudioContent branch has no test; the error/edge branches (invalid image/audio, nil/empty embedded resource, unknown-kind default) and ValidateResolvedIP(nil) are untested — regression risk on the fail-closed paths.

Investigated and dismissed

  • CallMcpWithQuery dodging the mcp__* guardrail glob — NOT an issue: internal/app/guardrails.go:191 already adds an explicit {Match: "CallMcpWithQuery", pre+post, block} entry to the default set. (FetchMcpResource is likewise covered at :187.)
  • A "fail-closed → recovery dead loop" via a schema-lying server is bounded by MaxTurns/MaxToolCalls/MaxRunTokens and has an off-ramp — a wasteful edge case, not a hang.

Proven NOT exploitable (confidence-builders)

ValidateToolResultParts (no int overflow; unknown kind fails closed; BlockKind is adapter-set) · the SSRF dial-selection logic + all internal ranges except NAT64 + octal/hex/userinfo/zone-id URL tricks + redirect re-validation + no second egress · Gauntlet-#7 child isolation (children string-render; no NewToolResultWithParts on any child→parent path) · wire version-skew both directions · snapshot↔event-fold convergence · capability-neutrality (single composition-computed intersection, no LLMRequest widening).

Process note

The branch is behind main (forked before #222 rebindable-keys merged). Rebase before merge — harness.pb.go and llms.txt will conflict, and the raw two-dot diff shows a phantom revert of rebindable-keys (GitHub's three-dot view is already correct).

Severity legend: High = resolve before merge; Medium = strong fast-follow; Low/Trivial = opportunistic.

return "", fmt.Errorf("jq output could not be JSON-encoded: %w", err)
}
accumulated += len(enc)
if accumulated > MaxOutputBytes {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High — jq output cap is post-materialization → single-value OOM. This 100 KB cap is only checked after iter.Next() (line 92) has fully built each yielded value. A filter that yields one huge value ([range(1e8)], [.[]*100000]) materializes the entire slice inside gojq before this check ever runs — bounded only by the 5 s deadline (line 69), during which gojq can allocate hundreds of MB–GB and OOM the process (acute on a memory-constrained mecak8s pod). A hostile MCP server can shape its JSON so an obvious model-chosen filter explodes. Consider a memory/cardinality budget on the run, not just a wall-clock deadline. (CWE-770/400)

Comment thread engine/session/content.go
// otherwise. Re-exported as the single dial-layer IP predicate so the fetch path
// and the URL-string path share ONE screening definition.
func ValidateResolvedIP(ip net.IP) error {
if !isGlobalUnicast(ip) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (High on IPv6/NAT64 egress) — NAT64 prefix not screened. isGlobalUnicast covers loopback/RFC1918/CGNAT/link-local/ULA/IPv4-mapped etc., but not the RFC 6052 well-known prefix 64:ff9b::/96. A literal https://[64:ff9b::a9fe:a9fe]/ embeds 169.254.169.254 and passes both ValidateMediaURL and this dial-time ValidateResolvedIP — no DNS rebinding needed; a hostile MCP server just hands the model the URI. On IPv6-only clusters with NAT64/DNS64 on egress (GKE/EKS) it reaches the metadata service. Fix: in isGlobalUnicast, detect 64:ff9b::/96 and re-check the embedded low-32-bit IPv4 before the fall-through to IsGlobalUnicast(). (CWE-918)

// carried through for operator/model visibility, NEVER enforced here.
audience := audienceFrom(c.Annotations)
blocks = append(blocks, session.NewResourceLinkBlock(
c.URI, c.Name, c.Title, c.Description, c.MIMEType, derefSize(c.Size), audience))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — resource_link Title/Description bypass the PostToolUse guardrail. They ride only in Parts (this NewResourceLinkBlock); the model-facing string (line 295) carries only URI+Name. The guardrail/redaction hook input marshals only ToolResult.Content (engine/agent/dispatch.go ~1210), never Parts — yet both providers render Title to the model (toolBlockText) and the wire mapper projects it to the client unredacted. So a hostile server can put prompt-injection in resource_link.title and it reaches the model/client uninspected; same class applies to image/audio base64 Data. Caveats: the guardrail is opt-in (needs a configured checker) and a mutation-style hook drops Parts (sanitizes by accident) — the bypass is real for inspect/flag/string-redaction hooks. Fix: feed a Parts-flattened projection (incl. Title/Description) into the hook input. (CWE-345 / OWASP LLM01)

return session.NewToolError(in.ID, fmt.Sprintf("CallMcpWithQuery: %v", err)), nil
}

return session.NewToolResult(in.ID, toolkit.Truncate(filtered, toolkit.MaxOutputBytes)), nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — recovery path re-truncates JSON into an unparseable blob. jq.Run caps output at 100 KB but this then toolkit.Truncates at toolkit.MaxOutputBytes (25 KB) on a rune boundary (not JSON-aware) with no fail-closed re-check. A 25–100 KB filtered result is cut mid-token — reintroducing on the recovery path the exact hazard remoteTool.Execute (~tool.go:201) fail-closes on the primary path, undercutting ADR 0063's "the model never receives truncated JSON." Mitigated by the visible truncation marker (the model is told and can narrow the filter), so it's degraded-UX rather than silent corruption. Fix: align jq.MaxOutputBytes to toolkit.MaxOutputBytes, or apply the same structured fail-closed error on the filtered output.

// noisy error — the Content blocks still carry the data.
if raw, ok := res.StructuredContent.(json.RawMessage); ok {
structured = raw
} else if b, mErr := json.Marshal(res.StructuredContent); mErr == nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium — full untruncated result is copied + re-marshaled before the size gate. callResultContent(res.Content) (line 85) and this json.Marshal(res.StructuredContent) build the whole payload in memory here, but the 20 MiB cap isn't applied until callmcpwithquery.go:141 — downstream of peak allocation (SDK-parsed + copied + re-marshaled ≈ 3× the response), and read-parallel calls compound it. A hostile MCP server can force large per-call allocation before rejection. Fix: bound the raw MCP-response read upstream of the copy/marshal. (CWE-770/400)

Comment on lines +65 to +66
case session.BlockText, session.BlockResourceLink, session.BlockEmbeddedResource, session.BlockStructuredContent:
// Text-summarised blocks always survive — no modality gate.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (defense-in-depth) — no default case → fail-open on an unknown BlockKind. A future/unknown kind matches none of the cases and falls through to out = append(out, b) (line 68), passing ungated — the opposite of the fail-closed posture the doc-comment implies. Mitigated today because the only production Parts producer runs ValidateToolResultParts (which rejects unknown kinds) upstream, so this is a second-line guard. Note the inconsistency: here "" is dropped while ValidateToolResultParts counts its bytes — same illegal state, two behaviours.

Suggested change
case session.BlockText, session.BlockResourceLink, session.BlockEmbeddedResource, session.BlockStructuredContent:
// Text-summarised blocks always survive — no modality gate.
case session.BlockText, session.BlockResourceLink, session.BlockEmbeddedResource, session.BlockStructuredContent:
// Text-summarised blocks always survive — no modality gate.
default:
// Unknown/future BlockKind: fail closed rather than pass ungated.
continue

DialContext: ssrfGuardedDialContext,
// ForceClose avoids reuse of the per-call connection pool so a
// one-shot fetch does not leak idle conns across the tool boundary.
ForceAttemptHTTP2: true,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trivial — stale comment. The comment says ForceClose avoids reuse of the per-call connection pool ... does not leak idle conns, but the field set is ForceAttemptHTTP2: true (re-enables HTTP/2 that a custom DialContext otherwise disables) — unrelated to closing connections, and there's no DisableKeepAlives/CloseIdleConnections, so per-call idle conns actually linger ~IdleConnTimeout. Fix the comment to match, and add DisableKeepAlives: true (or defer transport.CloseIdleConnections()) if leak-prevention was the intent.

@jhrozek

jhrozek commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Reviewed this PR in depth — three passes (per-layer correctness → cross-layer system interactions → adversarial red-team), plus reproduction with a standalone hostile MCP server and offline end-to-end tests.

Given the size of both this PR and the resulting fix set, I've put the fixes in a stacked PR — #230 — rather than force-pushing here, so this PR's history and review threads stay intact. #230 is based on this branch and will retarget to main automatically once this merges.

#230 addresses 11 findings. The two I'd treat as merge-gaters are both fixed there:

  • jq single-value OOM (CWE-770/400) — a filter like [range(1e9)] materializes one huge value before the output cap fires, allocating ~1 GiB before the deadline; enough to OOM a constrained pod. Fixed with a heap-growth watchdog.
  • NAT64 SSRF (CWE-918) — https://[64:ff9b::a9fe:a9fe]/ smuggles 169.254.169.254 past the egress guard on NAT64/DNS64 clusters. Now screened.

Plus: a PostToolUse guardrail blind to resource_link Title injection in Parts (CWE-345), the CallMcpWithQuery recovery path re-truncating JSON into an unparseable blob, an image-MIME provider-400 (image/svg+xml), compaction silently dropping typed Parts, a fail-open block router, and cleanup/coverage. task lint + task test (both modules, -race, engine-standalone, api-compat) pass. Full details and per-finding rationale are on #230.

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 and others added 3 commits July 3, 2026 12:38
…ource 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.
… 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.
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 force-pushed the feat/mcp-typed-tool-results-223 branch from 7ee17e7 to 8e41654 Compare July 3, 2026 09:44
@JAORMX
JAORMX force-pushed the feat/mcp-typed-tool-results-223 branch from 8e41654 to 9bad309 Compare July 3, 2026 09:54
@JAORMX
JAORMX merged commit 5fdc891 into main Jul 3, 2026
13 checks passed
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

e2e-live Run the live e2e suite on this PR

Projects

None yet

2 participants