Skip to content

fix: keep text and image together in MCP tool results - #29332

Merged
ibetitsmike merged 16 commits into
mainfrom
mike/mcp-multipart-tool-results
Sep 17, 2026
Merged

ibetitsmike merged 16 commits into
mainfrom
mike/mcp-multipart-tool-results

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

MCP tool results that mix text and an image (Playwright's default browser_take_screenshot returns [text, image]) were reduced to text only in both MCP conversion paths, so screenshots never reached the model. The generic tool renderer also showed media results as a JSON dump of base64.

Fix

  • mcpclient and chattool: keep all text plus the first usable binary item. Error flags survive empty and MIME-less results. Only one binary payload is represented; additional images are still dropped.
  • chatloop: at execution time, cap tool media at the 10 MiB attachment limit and correct or reject declared image types by byte signature (sniffing, not decoding).
  • chatd prompt build and chatprovider: at generation and compaction, replace media the destination provider cannot accept with the text plus an omission note (Anthropic/Bedrock: JPEG, PNG, GIF, WebP under the inline cap; OpenAI/Azure and Google: their image allowlists, applying the configured vendor's rules behind openai-compat). Persisted history is unchanged, so the UI keeps the payload and provider switches keep working.
  • site: results flagged is_media render through ToolResultMedia (image with the existing lightbox, or a short notice for non-image media, plus the text). Unflagged media-shaped JSON stays in the JSON viewer.
  • go.mod: pin coder/fantasy 9a3598480a71, main's a511353f83eb plus the batch-order fix 460d4fdd113b (Chat Completions and compatible transports emit every tool result before synthetic user images). The fix lives on mike/mcp-tool-media-batch-order; no upstream PR yet.

Validation

Round 3 dogfood UAT on this head, 522bd76a58a: PASS (chat, real Playwright MCP, Claude Haiku 4.5 and GPT-4o mini through the AI gateway). Verified in the UI and on the wire: image plus text render together, the lightbox opens and closes, both survive a reload; audio shows a notice instead of base64; media-shaped JSON stays in the JSON viewer; BMP on OpenAI Responses and Chat Completions reaches the model as text plus an omission note; SVG and PNG histories switch from Anthropic to OpenAI; cross-provider compaction through the organization override works; a result over 10 MiB persists only text plus a note, and a 5.5 MiB PNG is substituted for Anthropic yet still renders in the UI. Google is not routable on the dogfood gateway (404), so it was not exercised. The remote agent's own FAIL was a probe artifact (the code viewer renders in a shadow root) and was overturned on its screenshots by the independent runner. Rounds 1 and 2 (65db84a, 5001de7) covered the same API surface earlier.

Known limits: signature sniffing does not catch a truncated PNG with a valid header (providers return 400 for it), and only the first binary item of a result is kept. Pre-existing and out of scope: chatd opens a new MCP session per generation action, so Playwright's default per-session browser loses page state between steps (UAT used --cdp-endpoint).

Reviews:

Review Head Outcome
Codex 1 to 5 472914f to bcf4c72 16 findings (empty binary promoted over text, no provider caps, SVG on Anthropic, provider-switch gap, Bedrock labels, unbounded media, unvalidated bytes, renderer gating, lightbox test), all fixed
Codex 6, 7 8a9a9e0, 5001de7 no major issues; one Responses audio concern refuted with a live probe
Codex 83e1a10 two P2s refuted with serializer captures (MIME, advisor); reassessment clean
Codex 522bd76 no major issues on the rewritten tests
@DanielleMaywood 472914f, 5001de7 renderer restructure and explicit audio mapping done; lazy slice cloning removed; two threads left open for her re-check

Local pre-push hooks were skipped per Mike's instruction; CI is the gate.

Xum acted on Mike's (@ibetitsmike) behalf to create this PR.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T11:34:19.133999Z 522bd76 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 472914f967

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
@ibetitsmike
ibetitsmike marked this pull request as ready for review September 15, 2026 08:52
Comment thread coderd/x/chatd/chattool/mcpworkspace.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 472914f967

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 588402d336

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
Comment thread coderd/x/chatd/chatloop/chatloop.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 36c480b5ae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/generation_preparer.go Resolved
Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bcf4c7218f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/compaction_sanitize.go Resolved
Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 8a9a9e06d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Please review exact head 5001de7c11f4b9353b251885cd3cf87b2c0fdc12, including the pinned Fantasy tool-result ordering fix.

Xum requested this review on Mike’s (@ibetitsmike) behalf.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5001de7c11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Please reassess exact head 5001de7c11f4b9353b251885cd3cf87b2c0fdc12 after the evidence-backed resolution. The reported Responses audio rejection was not reproduced: the actual pinned ToolResultOutputContentMedia serializer substitutes text for non-images, independently of user FilePart admission. A live Responses request with WAV/MPEG/PDF/octet-stream tool results returned HTTP 200, with no binary content in the captured request. No code change was made.

Xum requested reassessment on Mike’s (@ibetitsmike) behalf.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 5001de7c11

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +259 to +272
export const parseMediaToolResult = (
result: unknown,
): MediaToolResult | null => {
const rec = asRecord(result);
if (
!rec ||
typeof rec.data !== "string" ||
typeof rec.mime_type !== "string"
) {
return null;
}
const mimeType = rec.mime_type.split(";")[0].trim().toLowerCase();
return { data: rec.data, mimeType, text: asString(rec.text) };
};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I still wish we had a better way of doing this, lol. This isn't me asking for it right now though!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Noted. I left the parser unchanged in this pass.

Xum acted on Mike's (@ibetitsmike) behalf.

Comment on lines +17 to +67
func replaceUnsupportedToolMedia(
ctx context.Context,
logger slog.Logger,
messages []fantasy.Message,
model chatprovider.Model,
configuredProvider string,
) []fantasy.Message {
replaced := 0
provider := model.Provider()
out := messages
for i, msg := range messages {
var parts []fantasy.MessagePart
for j, part := range msg.Content {
result, ok := part.(fantasy.ToolResultPart)
if !ok {
continue
}
media, ok := fantasy.AsToolResultOutputType[fantasy.ToolResultOutputContentMedia](result.Output)
if !ok {
continue
}
note, omit := chatprovider.ToolResultMediaOmission(provider, configuredProvider, media.MediaType, base64DecodedLen(media.Data))
if !omit {
continue
}
if replaced == 0 {
out = slices.Clone(messages)
}
if parts == nil {
parts = slices.Clone(msg.Content)
}
replaced++
text := media.Text
if text != "" {
text += "\n"
}
result.Output = fantasy.ToolResultOutputContentText{Text: text + note}
parts[j] = result
}
if parts != nil {
out[i].Content = parts
}
}
if replaced > 0 {
logger.Debug(ctx, "replaced unsupported tool result media in prompt",
slog.F("provider", provider),
slog.F("replaced_parts", replaced),
)
}
return out
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

what the heck are we doing here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This keeps persisted tool media replayable when the chat or compaction model changes. Some provider serializers turn every media result into an image, so audio, unsupported image formats, or oversized images can make the request fail. The helper substitutes the accompanying text plus an omission note without changing stored history.

The lazy copy-on-write bookkeeping was unnecessary. 83e1a1094bf replaces it with the same fresh-slice loop as the neighboring sanitizers. Provider policy and the input-immutability assertions are unchanged.

Xum acted on Mike's (@ibetitsmike) behalf.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Sadly. We do a similar thing for compaction too.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Xum acted on Mike's (@ibetitsmike) behalf.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 83e1a1094b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/mcpclient/mcpclient.go Resolved
Comment thread coderd/x/chatd/generation_preparer.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Please reassess unchanged head 83e1a1094bf8f6d1f775a77f19be332cbdbab86c, including the executable evidence in both review replies:

  • Malformed MIME: actual chatd routing and pinned serializers produce text fallbacks. The converter/persistence/replay/serializer matrix captured 1,600 requests with no caption loss or unrepaired malformed payload transmitted. Native Google is not the configured Google chat transport.
  • Advisor override: BuildAdvisorMessages already textualizes tool results. The actual override resolver and Anthropic serializer emitted no structured media; removing that existing call caused the probe to fail.

Both probes intercepted HTTP requests; neither is live-provider UAT. No code was changed for these findings. Current-head CI passes; remaining live UAT acceptance and human re-review are separate, still-open gates.

Xum acted on Mike's (@ibetitsmike) behalf.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 83e1a1094b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Pull coder/fantasy#58 so the Google provider sends media tool results
as a text function response plus a sibling inline data part instead of
dropping them. Without it, keeping both the text and the image of a
mixed MCP tool result would leave Gemini with an unpaired function
call.
Workspace-hosted MCP tools go through convertMCPToolResponse, which
had the same text-first rule as mcpclient: any text block hid the
image block. Return the first binary block with the joined text as
its Content so both reach the model. Audio blocks are mapped to the
"media" response type because the chat loop only recognizes "image"
and "media".
convertCallResult now ignores image, audio, and blob items with no
payload so accompanying text is not replaced by an empty media
response. executeSingleTool keeps only the text plus an omission note
when a tool image reaches the provider's inline image cap, because the
image would fail the next request and every later turn once persisted.
Propagate is_media from tool result parts through message parsing and
stream state into Tool so GenericToolRenderer only renders an image
when the server persisted a media result, not whenever a JSON result
happens to carry data and an image mime type. Add stories for the open
lightbox and for a media-shaped text result.
fantasy renders Anthropic and Bedrock tool result media as image blocks,
so audio or blob results from an MCP tool would fail the next request
and every later turn once persisted. Add
chatprovider.AcceptsToolResultMediaType and fold it into the chatloop
text fallback alongside the inline image cap. Make the workspace MCP
audio-to-media mapping explicit.
parseMediaToolResult owns the {data, mime_type, text} shape and
ToolResultMedia renders it, showing the text plus a short notice for
non-image media instead of falling through to the JSON viewer with the
raw base64 payload.
…build

Move the provider media gate from tool execution to prompt preparation.
Every generation action and compaction rebuilds the prompt from the
persisted rows, so replacing media there with the accompanying text plus
an omission note covers history recorded under another provider and
keeps the payload persisted for the UI. chatprovider.ToolResultMediaOmission
limits Anthropic and Bedrock to the JPEG, PNG, GIF, and WebP formats the
Messages API accepts under the inline image cap and labels the note with
the configured provider, so Bedrock users no longer read "Anthropic".
The chatloop write-time gate is removed.
Bedrock routes non-Anthropic models through the OpenAI transport, so the
media gate now decides on model.Provider() and only labels the note with
the configured provider. MCP converters no longer promote binary items
that lack a MIME type, since the prompt reader cannot rebuild them as
media and would replay the raw base64 as text.
Tools may report image types with parameters or mixed case; the parser
now lowercases the base type so ToolResultMedia recognizes them.
Tool media is now checked once at execution, the single chokepoint for
MCP, workspace MCP, and computer-use results: payloads over the chat
attachment cap and image types whose bytes are not an image fall back
to the accompanying text plus a note, and a declared image type is
replaced by the detected one. Provider-specific rules stay at prompt
build. The compaction sanitizer now labels omission notes with the
configured provider instead of the routed transport.
Rewrite the closure-style media tests as table tests, compare whole
fantasy.ToolResponse values instead of field by field, and drop cases that
duplicated the provider matrix already covered by TestToolResultMediaOmission
or exercised trivial branches. The compaction and generation wiring tests
keep one native and one bridged provider case each.
@ibetitsmike
ibetitsmike force-pushed the mike/mcp-multipart-tool-results branch from 83e1a10 to 522bd76 Compare September 17, 2026 07:30
@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Head 522bd76a58a is a rebase onto main plus a test-only commit that rewrites the media tests as table tests; production code is unchanged since your last pass on 83e1a1094bf.

Xum posted this on Mike's (@ibetitsmike) behalf.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 522bd76a58

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +41 to +42
{Role: fantasy.MessageRoleTool, Content: []fantasy.MessagePart{fantasy.ToolResultPart{
ToolCallID: "call-1",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep coverage for multiple media results

Every table row now builds a tool message containing exactly one ToolResultPart, removing the previous case that supplied two unsupported media results and verified that both were converted while the input remained unchanged. replaceUnsupportedToolMedia is explicitly a loop over every part, so a regression that stops or mutates after sanitizing the first result would now pass this test and leave a later unsupported result to be submitted to the provider. Retain a case with multiple media result parts in the same message.

Useful? React with 👍 / 👎.

@ibetitsmike

Copy link
Copy Markdown
Collaborator Author

@codex review

Xum posted this on Mike's (@ibetitsmike) behalf. The previous request on this head completed without a posted result.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 522bd76a58

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike
ibetitsmike merged commit 8397680 into main Sep 17, 2026
36 checks passed
@ibetitsmike
ibetitsmike deleted the mike/mcp-multipart-tool-results branch September 17, 2026 13:09
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 17, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants