Send `ToolReturn.content` as part of the tool result

DO
5h ago
+33221-155569
  • Closes #12391
  • Closes #15002
  • Supersedes #14327 (credit: @dsfaccini, co-author of the main commit)
  • Stacked on #14376 (its C1 route matrix drops two expected failures here)
  • Next: #14450 (a tool return's files apart from its output)

A tool's ToolReturn.content is now part of the tool's result, as #12391 decided:

  • It's stored on the call's own ToolReturnPart, in a new attachments field: a list of ToolResultAttachment(content, tool_call_id, tool_name, capability_id=None), one per item, each naming the call that produced it.
  • Model.prepare_messages sends the attachments in one pass, after the request's tool results, as data framed on the user channel: one frame per call, behind a note naming the producing tool (<tool_content tool_name="...">), or the capability that contributed it (<capability_content>, byte for byte what a capability at 'none' sent before).
  • Its authority is fixed at data by kind. Nothing on an attachment is read to decide how it's sent, so an attachment from stored history, a client, a DeferredToolResults body or a hook can at most name the wrong tool; it never speaks as the user or the application.
  • That rule is about who produced the content: content from a tool this run executed is data; content supplied with deferred tool results keeps the user's voice. A ToolReturn in DeferredToolResults (the application's, or the user's answer through a UI) wasn't produced by a tool in the run, so its content still becomes a sibling UserPromptPart after the tool results, held to the owning capability's ceiling, exactly as on main. A client can already send user text, so nothing is raised.
  • Content a tool wants the model to read at a different authority (as the user's message, or the application's instruction) is what it should ctx.enqueue, where the capability's authority ceiling applies.

Tools that run other tools keep the producer of each nested call's content:

  • Code Mode (run_nested_call), IPython Code Mode and ToolBridge put each nested call's ToolReturn.content on the outer result's attachments, with the nested call's tool_call_id, tool_name and capability_id, taken from the nested ToolManager that ran the call. They pass it through a new ToolReturn.attachments field, which is ahead of the tool's own content on the result. A hook that replaces the outer ToolReturn (or its content) yields content attributed to the outer call: still data.
  • BackgroundTools no longer folds ToolReturn.content into its <tool_result> frame: it delivers it after the frame as the same data parts a direct call's attachments are sent as.
  • ToolOutputLimits reduces each text item in ToolReturn.attachments on its own, with the same bands as return_value and content, keeping each item's attribution; files and StructuredContent pass through, and a spilled attachment's handle goes in metadata['overflow_attachment_handles']. This comes from #15046 by @KundanDhage (folded in with co-author credit).
  • This fixes C1's _CONTENT (#14327) and _BACKGROUND_NAME findings, so their KNOWN entries are removed. The C1 comparison now includes a carrier's attachments, as the parts they're sent as.

Durable runs: ToolReturn.attachments and ToolReturnPart.attachments are typed dataclass fields, so they survive the Temporal/DBOS journal and ModelMessagesTypeAdapter (tested). Both are left out of a dump when empty, so a result or history without any is stored byte for byte as before.

UI adapters: VercelAIAdapter and AGUIAdapter dump_messages/load_messages carry a tool result's attachments in the call's existing metadata channel (the AI SDK's callProviderMetadata.pydantic_ai, AG-UI's namespaced encrypted_value), so a client-held history keeps the content and the next turn sends it to the model as the turn that produced it did (tested end to end, and in a new tests/ui_roundtrip tool_return_content scenario against the real AI SDK and @ag-ui/client). Below AG-UI 0.1.11, which has no encrypted_value, they dump as the user message they used to be. An attachment's capability_id is left out of what the adapters send the client, since for an MCP(url=...) without an id it's the server's hostname, and load_messages ignores one the client sends back. So an attachment from a capability, round-tripped through a client, is introduced to the model as content from the tool it names rather than from the capability. A history rebuilt from the stream doesn't carry them, as it never carried the sibling user prompt either: neither stream has a metadata slot on a tool result (recorded as a known ui_roundtrip gap).

Client input: what a client sends back goes through sanitize_messages, which checks attachment files like any other client file (URL schemes, force_download, uploaded files) and strips TextContent.metadata. A forged attachment still reaches the model as data (a capability it claims is ignored), and malformed ones are dropped. A DeferredToolResults body is tested to reach the model no higher than the user: its content in the user's voice, its forged attachments as data.

AskUser: the user's notes on an answer are their own words and keep the user's voice. When the answer arrives during the run (an answerer, or a HandleDeferredToolCalls handler), AskUser takes them off the result in an after_tool_execute hook and ctx.enqueues them right after the answer; an answer passed in DeferredToolResults to a later run is supplied from outside the run, so its content keeps the user's voice by the rule above. Both paths store the same sibling UserPromptPart as before.

Other places that read tool results now see the attachments: OTel message conversion (as the data parts the model is sent), Pydantic AI Harness's tool_return_text (compaction summaries, conversation search), ToolOutputLimits (preserves them), and instrumentation's binary redaction. A realtime session still sends the content as the user content it did; rendering it as data on the live channel is the realtime follow-up.

The multimodal tool_return_content cassettes are re-recorded, so their request bodies show the framed attachments in main's current wire format (the xAI ones on grok-4.3, which serves the retired grok-4-1-fast-non-reasoning slug, so the configured and recorded model match), except where the recording can't be redone: OpenAI Chat/Responses (gpt-5-mini is now deprecated, which the suite turns into an error), Groq (llama-4-maverick is retired) and most uploaded_file cases (their provider file ids have expired). Those still replay the old request shape; the assertions on the history pass either way.

Old histories keep the sibling UserPromptPart / _CapabilityContentPart parts they were stored with, and are sent as they were: nothing is reclassified on load.

[!WARNING]
Compatibility impact: ToolReturn(content=...) from a plain tool, or from a capability at 'operator' or 'user' authority, used to reach the model as a plain user message (a sibling UserPromptPart in history). It now reaches the model as data framed after the tool result, with a note naming the tool or capability, and history keeps it on the call's ToolReturnPart.attachments instead of a sibling UserPromptPart. A capability at 'none' sends the same bytes as before, but history stores the content on the return part instead of a sibling <capability_content> part. Code that reads the sibling part from history (or FunctionModel code that reads the request) needs updating, and a prompt that relied on the content being read as the user's words will see the model treat it as tool output. BackgroundTools sends ToolReturn.content after its <tool_result> frame rather than inside it. Code Mode's and IPython Code Mode's run_code and ToolBridge's tool_call return the nested calls' content in ToolReturn.attachments, not ToolReturn.content, so a hook on them that edited content now sees it in attachments. Likewise, FunctionToolResultEvent.content carries only the tool's own ToolReturn.content, so a stream consumer reading it for these tools now sees None: read event.part.attachments for the content that reaches the model with the result. The rule is: content from a tool this run executed is data; content supplied with deferred tool results keeps the user's voice. So a ToolReturn passed in DeferredToolResults behaves as before, and AskUser answer notes keep the user's voice on both paths. Client-held UI histories (dump_messages/load_messages) keep the content, now on the tool result.

Why this can ship in a minor release: it's the fix #12391 decided for tool content reaching the model as if the user had written it, and the history change is an added optional field on an existing message part, which the version policy allows in a minor release.

Migration: read a tool's content from ToolReturnPart.attachments ([attachment.content for attachment in part.attachments]). To have the model read text as the user's message or the application's instruction, enqueue it from the tool with ctx.enqueue instead of returning it as ToolReturn.content: a UserPromptPart for the user's words, or an InstructionCapabilityPart kind for the application's; from a capability's tool, the capability's authority ceiling applies.

Durable execution, rolling deploys: a worker on an earlier release drops a non-empty attachments field it receives from a newer one, so a model request it makes in that window goes out without that tool content. Finish the deploy before relying on it, or drain in-flight runs first.

Supersedes #14327, by @dsfaccini, whose analysis, nested-call fixes and tests this builds on (co-authored). That PR carried the nested content's capabilities in a private list subclass, which comes back as a plain list across the durable journal; here the producer is a typed field on the result, and authority isn't carried at all. Also folds in its RetryFeedbackPart docstring fix (OpenAIDecisionsModel sends retry feedback as a developer message).

Follow-ups (not in this PR):

  • Send attachments inside the provider's tool result where it supports that content (#12391's first choice), per adapter, probe-backed.
  • Realtime: render attachments as data on the live channel.
  • UI streams: a history the client rebuilds from the stream doesn't carry attachments (neither stream has a slot for them); recorded as a ui_roundtrip known gap.
  • The files field (storing multimodal files of the return value apart from it), with its own design review.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.

THREAT_MODEL.md changes

  • "The ceiling covers a capability's instructions and what it enqueues mid-conversation" (was "what it sends mid-conversation, including its tools' ToolReturn.content"): narrows. ToolReturn.content now goes out inside the tool result, so the authority ceiling no longer claims to cover it. Consistent with 685 B: it only removes a claim from the existing voice paragraph and adds none.

🤖 Generated with Claude Code


Summary by cubic

A tool's ToolReturn.content now reaches the model as part of the tool result instead of as a sibling user message read in the user's voice.

  • Content is kept on ToolReturnPart.attachments as ToolResultAttachment items (content, tool call id, tool name, capability id) and sent as framed data after the request's tool results, at fixed data authority.
  • Code Mode, IPython Code Mode, ToolBridge and BackgroundTools keep each nested call's producer identity on the outer result; BackgroundTools no longer folds content into its <tool_result> frame.
  • A ToolReturn supplied in DeferredToolResults keeps the user's voice: its content still becomes a user message, and its attachments join it in the user-channel part, so AskUser answer notes stay in the user's voice on both paths.
  • Empty attachments are left out of dumps, so existing journals and histories stay byte-identical; the durable journal's raw-content variant carries them too, excluded when empty.
  • ToolResultAttachment is exported from pydantic_ai; Vercel AI and AG-UI dump_messages/load_messages carry attachments in the call's metadata channel (below AG-UI 0.1.11 they dump as the user message they used to be), client-supplied attachments go through sanitize_messages, capability_id stays out of what UI adapters send the client, and AG-UI omits an UploadedFile attachment unless preserve_file_data is set.
  • Attachment content is validated like UserPromptPart content; telemetry redaction sweeps attachments a call returns directly, ones relayed through a carrier, and ones a tool return part keeps in a tool's metadata, masking URL-derived MCP capability IDs and redacting binary content.
  • Guardrails scan attachment text: PromptInjectionDefender and for_tool_result_text scan ToolReturn.attachments with each call's run on its own, and a rejected result drops the attachments.
  • A realtime session's FunctionToolResultEvent.content carries only the tool's own ToolReturn.content; ToolOutputLimits reduces attachments per item with the same bands, and a spill note lands on that attachment.
  • The C1 route matrix now also compares parts it doesn't know by type (as PlanMode puts an InstructionDeltaPart in history), and its _CONTENT and _BACKGROUND_NAME gaps are removed.

Compatibility impact

  • Plain tools and capabilities at 'operator' or 'user' authority used to send ToolReturn.content as a user message; it is now data. To have the model read text as the user, enqueue it from the tool with ctx.enqueue.
  • Read a tool's content from ToolReturnPart.attachments ([attachment.content for attachment in part.attachments]); hooks on Code Mode's and IPython Code Mode's run_code and ToolBridge's tool_call now see nested content in attachments, not content.