Skip to content

Studio: render image content returned by MCP tools - #7081

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
NilayYadav:fix-mcp-image-content-blocks
Jul 14, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
NilayYadav:fix-mcp-image-content-blocks

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Render ImageContent blocks returned by MCP tools in chat tool results.

  • Extract image blocks from MCP responses
  • Display returned images in the tool-result UI
  • Keep base64 image payloads out of follow-up model context
  • Add coverage for text, image, error, and oversized-image results

Merge only after #7080, which keeps stateful stdio MCP sessions alive across tool calls.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces support for extracting, transmitting, and rendering images returned by Model Context Protocol (MCP) tools. On the backend, _flatten_result is updated to extract image blocks, enforce a size budget, append summary notes, and serialize the images with a __MCP_IMAGES__: sentinel. The frontend is updated to parse this sentinel, strip it from model context and search indexing, and render the base64 images inline within the tool fallback results. Comprehensive unit tests have also been added to verify the backend behavior. I have no feedback to provide as there are no review comments.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@danielhanchen

Copy link
Copy Markdown
Member

Validated the MCP image rendering in Studio end to end. The same MCP screenshot tool result was driven through the real chat UI on main and on this PR.

Before / after

before and after

On main the returned image is dropped and only the text survives the flatten. With this PR the image renders in the tool result card.

After, live:

after

Also confirmed:

  • Studio backend, frontend, and UI CI green on Linux, Windows, and macOS.
  • The base64 payload stays out of the follow-up model context and the chat search index.
  • The image renders and a returned SVG stays inert with no script execution in Chromium, Firefox, and WebKit.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 2cd2cee7cc

ℹ️ 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".

if getattr(result, "is_error", False):
# "Error: " prefix triggers tool_call_parser's TOOL_ERROR_PREFIXES nudge.
return f"Error: {body}" if body else "Error: tool returned no content"
body = f"Error: {body}" if body else "Error: tool returned no content"

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 Preserve MCP error results before flattening images

When an MCP server returns an isError result that includes image content, this new error/image formatting is bypassed in the real call path because call_tool_sync invokes FastMCP client.call_tool with its default raise_on_error=True; FastMCP raises before returning the CallToolResult, so the generic exception handler emits only text and drops the image payload. This affects the error-image cases covered by the new _flatten_result tests unless the MCP call is made with error raising disabled so this branch can actually see the result.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 765a31b: call_tool_sync now passes raise_on_error=False so an is_error result keeps its image content and reaches _flatten_result, instead of FastMCP raising ToolError and dropping the image. Added a regression test that pins the real call path.

FastMCP client.call_tool raises ToolError by default on an is_error
result, so it never reaches _flatten_result and any returned image is
dropped. Pass raise_on_error=False so error results flow through
_flatten_result and keep their images. Transport failures still raise
and hit the existing handler. Add a regression test for the real path.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@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: 1ed6f9afbf

ℹ️ 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".

# image content) is returned to _flatten_result instead of FastMCP
# raising ToolError, which would drop the images. Transport/connection
# failures still raise and are handled by the caller's except below.
return await client.call_tool(name, args, raise_on_error = False)

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 Preserve call_tool compatibility in MCP tests

When CI runs the existing stdio MCP execution tests, _RecordingClient.call_tool in studio/backend/tests/test_mcp_stdio_pr5863.py still accepts only (name, args). This new keyword raises TypeError, which call_tool_sync catches and turns into an error string, so the enabled execute_tool("mcp__stdio1__list_directory", ...) path no longer returns called list_directory. Update the existing fake clients to accept the new keyword (or otherwise guard this call) so the MCP test suite remains green.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in b58194c: updated the fake MCP clients (_RecordingClient in test_mcp_stdio_pr5863.py and the two _StubClient mocks in test_mcp_servers.py) to accept the raise_on_error keyword, so call_tool_sync's new kwarg no longer trips TypeError. Full MCP test suite green.

The call_tool_sync fix passes raise_on_error=False to client.call_tool.
Update the fake MCP clients patched into mcp_client._client so their
call_tool signatures accept the keyword, keeping the stdio/servers MCP
test suites green.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 95f8400f5b

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d803d02f02

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@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: 8a2e05073f

ℹ️ 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 +3263 to +3266
const images = JSON.parse(
rawResult.slice(mcpImgIdx + mcpImgMarker.length),
) as McpImageToolResult["images"];
parsedResult = { text, images };

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 Validate MCP image envelopes before parsing

When a tool result merely contains the marker followed by valid JSON that is not the backend image envelope (for example documentation/log output like \n__MCP_IMAGES__:["not image"]), this branch still coerces it into { text, images } because the as McpImageToolResult["images"] cast does not validate at runtime. That corrupts the displayed result and later replay serializes a different JSON object instead of the original tool text; mirror the backend/search-index shape checks before assigning parsedResult.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in d3102f1: the adapter now validates the parsed suffix with isMcpImageToolResult before treating it as an image envelope, so tool text that merely contains the marker followed by non-image JSON round-trips unchanged for both display and replay.

const images = JSON.parse(
rawResult.slice(mcpImgIdx + mcpImgMarker.length),
) as McpImageToolResult["images"];
parsedResult = { text, images };

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 Strip MCP image payloads from conversation exports

When a chat containing an MCP image result is exported from the prompt/conversation dialog, this stores the base64 images array on the persisted tool-call result, but the exporter serializes non-string tool results with JSON.stringify(p.result). That makes OpenAI/JSON/Markdown exports include up to 12 MB of base64 per image instead of the sanitized text used for chat replay, which can bloat or corrupt fine-tuning datasets; reuse the same text-only serialization for export paths or keep the image payload outside result.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in d3102f1: the OpenAI export now serializes MCP image results as their text (matching serializeToolResultPart used for chat replay) instead of JSON.stringify, so the base64 payload stays out of exported fine-tuning datasets.

@danielhanchen

Copy link
Copy Markdown
Member

@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: d3102f13c7

ℹ️ 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 +309 to +310
: isMcpImageToolResult(p.result)
? p.result.text

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 Strip MCP image payloads from every export format

This only sanitizes MCP image results for the OpenAI/ChatML export path, but the ShareGPT and CSV export paths still go through contentBlocksToText, which serializes tool-call result with JSON.stringify({ ..., result: p.result }). For conversations containing an MCP image result, choosing those formats will dump the full base64 images array into the exported dataset/file, defeating the stated goal of keeping image payloads out of exports and potentially creating huge exports.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 7406bc4: contentBlocksToText (the ShareGPT and CSV export path) now also uses the MCP result text, so base64 stays out of every export format, not just OpenAI/ChatML.

Comment on lines +3270 to +3272
parsedResult = isMcpImageToolResult(candidate)
? candidate
: rawResult;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Preserve sandbox images after invalid MCP markers

When a tool result contains a literal \n__MCP_IMAGES__: that is not a valid envelope and also has the existing \n__IMAGES__: suffix (for example a Python run prints that marker while saving a plot), this branch assigns rawResult and skips the __IMAGES__ parser below. That regresses those sandbox images from rendered images to raw suffix text; only consume the MCP branch after validation succeeds, or fall through to the existing image parser when validation fails.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 7406bc4: the MCP branch now only wins when the envelope validates; an invalid marker falls through to the existing IMAGES parser, so sandbox images still render.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7406bc40ce

ℹ️ 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".

@danielhanchen
danielhanchen merged commit fea7d9b into unslothai:main Jul 14, 2026
36 checks passed
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