Skip to content

Carry image, document and redacted reasoning bytes across the Strands model and MCP activities - #150

Merged
brianstrauch merged 6 commits into
temporalio:mainfrom
avanish-garg:fix/strands-bytes-model-activity
Oct 28, 2026
Merged

brianstrauch merged 6 commits into
temporalio:mainfrom
avanish-garg:fix/strands-bytes-model-activity

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

What was changed

  • _InvokeModelInput tags every bytes value in messages as base64 with Strands' encode_bytes_values when it is built (__post_init__, so the streaming subclass gets it too), and ModelActivity restores them before calling Model.stream.
  • invoke_model and invoke_model_streaming return their stream events in the same tagged form, TemporalModel.stream restores them, and the streaming activity publishes the tagged events to the WorkflowStream topic. The activities' return type is now list[dict[str, Any]] instead of list[StreamEvent]: the JSON on the wire is unchanged, but the tagged form would not validate as a StreamEvent (redactedContent is bytes).
  • Second commit: the {server}-call-tool activity tags the bytes in the MCP tool result (images) and TemporalMCPTool restores them before handing the result to Strands.
  • Messages and events without bytes encode to the same JSON as before; nothing changes in the public API, activity names or options. The agent's own message history is never modified (the encoding builds new containers).

Why?

A prompt with an image failed the workflow task on every attempt, an ASCII-only document reached the model as str, a redactedContent block in the reply made invoke_model fail on every attempt, and an MCP tool that returns an image was re-run on every retry because its result could not be recorded. Details and a repro in the issue.

Checklist

  1. Closes [Bug] strands_agents: images, documents and redactedContent bytes cannot cross the model activity, and an MCP image result re-runs the tool on every retry #149

  2. How was this tested:
    New tests in tests/test_model_bytes.py and tests/test_mcp_image.py. Round trips through the plugin's payload converter and a real ModelActivity run for an image block, a document block (ASCII bytes, which used to come back as str) and redactedContent as input, and for redactedContent in the activity result; text-only messages encode to the same JSON as before; the caller's messages are not modified. Workflow tests send an image and a document, get redactedContent back, and send the whole history back on a second turn (the model sees the same bytes, the workflow holds bytes), with and without streaming_topic (subscribers get the tagged events), each replayed with Replayer. One workflow test runs an MCP image tool with the plugin on the Client and a 3-attempt retry policy: the tool runs once, and the workflow and the model both get the PNG. On main (install rebuilt with make sync and checked against the source) 9 of the 10 new tests fail (the 10th checks that text-only messages are unchanged) and the MCP tool runs 3 times; with the change make lint is clean and make test passes (62, 10 of them new). A workflow history recorded on main with an ASCII csv document replays on the new code. Not run against a real Bedrock or vision model.

  3. Any docs updates needed?
    No. The README does not mention image or document content.

… model activity

Strands content blocks hold raw bytes in image and document sources and in reasoningContent.redactedContent. The JSON payload converter fails on non-UTF-8 bytes and turns ASCII bytes into str, so a prompt with an image never reached the model and a redacted reasoning block made invoke_model fail on every attempt.

The activity input tags bytes in the messages as base64 with Strands' encode_bytes_values and the worker restores them before calling the model. Stream events are returned and published in the same form and restored in TemporalModel.stream. Messages without bytes encode to the same JSON as before.
An MCP tool that returns an image produces a ToolResult holding raw bytes, which the call-tool activity could not serialize. The activity failed after the tool had run, so every retry ran the tool again. The result is tagged as base64 in the activity and restored in TemporalMCPTool.
@avanish-garg
avanish-garg requested a review from a team as a code owner October 23, 2026 09:57

@brianstrauch brianstrauch left a comment

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.

Two correctness issues reproduced during review. make lint passes and all 62 existing tests pass; the inline comments describe cases outside that coverage.


def decode_event(event: dict[str, Any]) -> StreamEvent:
"""Restore the ``bytes`` that ``invoke_model`` tagged in a returned stream event."""
return decode_bytes_values(event) # type: ignore[no-any-return]

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.

[P1] Preserve decoding of previously recorded reasoning bytes

Changing the activity return type from list[StreamEvent] to list[dict[str, Any]] changes how existing activity results decode. On the base commit, UTF-8 redactedContent bytes serialize as JSON strings and the StreamEvent type hint restores them to bytes. With this change, those old untagged values remain strings, and decode_bytes_values leaves them unchanged. I recorded a successful workflow on base commit 5e91c26 with redactedContent=b"ASCII-redacted": its history replays successfully on the base version but fails on this PR with TypeError: can't concat str to bytes in Strands' handle_content_block_delta. Existing workflows with such results will fail workflow tasks after upgrading. Please preserve legacy redactedContent decoding after restoring tagged values and add a replay regression using a history recorded before this change.

def _stream(model: Model, input: _InvokeModelInput) -> AsyncIterable[StreamEvent]:
return model.stream(
input.messages,
decode_bytes_values(input.messages),

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.

[P2] Avoid interpreting ordinary tool JSON as encoded bytes

decode_bytes_values interprets any dictionary containing __bytes_encoded__: true and data as binary, including arbitrary JSON under toolUse.input or toolResult.content[].json. encode_bytes_values does not escape ordinary dictionaries with those keys, so this is not a lossless round trip. Through the plugin converter and a real ModelActivity, I verified that {"__bytes_encoded__": true, "data": "SGVsbG8=", "other": "retained"} reaches the model as b"Hello", discarding the other field; making data a JSON object instead raises TypeError before the model runs. The new decoder in TemporalMCPTool.stream has the same problem for MCP structured content and metadata. Please escape colliding dictionaries or restrict decoding to binary content fields, with coverage for ordinary JSON matching the marker.

…alues

The previous change walked every dict with Strands' decode_bytes_values, so ordinary JSON shaped like its marker (a tool input, a tool result json block, MCP structured content or metadata) was turned into bytes, lost its other keys, or raised on a non-string data value. Bytes are now tagged and restored only at the fields Strands types as bytes: the source of image, document, video and audio blocks, tool result content, and reasoningContent.redactedContent. Everything else reaches the model and the agent unchanged. The model activity input, its stream events, the streaming topic and the MCP call-tool result all use the same helpers in _bytes_values.

Changing invoke_model to return plain dicts also stopped the StreamEvent type hint from restoring redactedContent in results recorded before the change, so replaying them raised TypeError in Strands. A value in a bytes field that is a string (pydantic converter) or a list of ints (default converter) now decodes to bytes, which is what the type hint did. The same applies to image bytes in recorded MCP results.

Tests replay four histories recorded on 5e91c26, cover marker-shaped JSON in the model input, the stream events and an MCP result, and check each bytes field round trips.

@brianstrauch brianstrauch left a comment

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.

The two earlier findings are addressed. One remaining streaming issue reproduced with both supported data converters; make lint and all 101 PR tests pass.

Comment on lines +114 to +116
encoded = encode_event(event)
events.append(encoded)
topic.publish(encoded)

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.

[P2] Preserve typed stream subscriptions

Publishing the tagged event breaks the README's WorkflowStreamClient.subscribe(..., result_type=StreamEvent) when a model emits redactedContent: StreamEvent requires bytes | None there, but now receives a marker dictionary. I reproduced this against a local Temporal server by running the new streaming-bytes test with result_type=StreamEvent: the default converter raises TypeError, and the plugin's Pydantic converter raises ValidationError, so the subscription stops before receiving the remaining events. The new test uses dict[str, Any], which bypasses this failure. Please preserve decoding for typed stream subscribers and add coverage using the documented subscription type.

…bscribers read

The streaming activity published the base64-tagged event, which a subscriber typed with StreamEvent, as the README documents, cannot validate: redactedContent must be bytes and arrived as a marker dictionary, so the default converter raised TypeError and the Pydantic converter ValidationError, and the subscription ended before the remaining events. The topic now carries the event as the payload converter writes it, as it did before the tagging, so typed and untyped subscribers see what they saw then. The activity result the workflow decodes stays tagged.

bytes that the converter cannot write (non-UTF-8 under the Pydantic converter, which a StreamEvent subscriber could not read back either) are published as b"" in redactedContent instead of failing the activity or ending the subscription. The default converter carries any bytes, so its subscribers get them intact. The README says so.

Tests subscribe with result_type=StreamEvent, dict[str, Any] and no type under both converters, for UTF-8 and non-UTF-8 redactedContent and for events without bytes.

@brianstrauch brianstrauch left a comment

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.

Thank you!

@brianstrauch
brianstrauch enabled auto-merge (squash) October 28, 2026 15:50
@brianstrauch
brianstrauch merged commit e883430 into temporalio:main Oct 28, 2026
25 of 27 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

2 participants