Repository navigation
Description
What are you really trying to do?
Run a Strands TemporalAgent that works with binary content: send it an image or a document ({"image": {"format": "png", "source": {"bytes": ...}}}), use a Bedrock Claude model with extended thinking (its reasoning comes back as reasoningContent.redactedContent, which is bytes), and call an MCP tool that returns an image.
Describe the bug
Strands messages and stream events carry raw bytes in image and document sources, in redactedContent, and in MCP image tool results. The plugin's payload converter is the Pydantic JSON one, which writes bytes as UTF-8 text. _InvokeModelInput.messages and the invoke_model result in python/strands_agents/src/temporalio/strands_agents/_model_activity.py are typed Any / list[StreamEvent], so nothing converts them. A plain Strands Agent hands the model the exact bytes in every case below.
- Image in the prompt. A PNG is not valid UTF-8, so encoding the
invoke_modelinput raisesPydanticSerializationError: invalid utf-8 sequenceinside the workflow. That is a workflow task failure, so the workflow task is retried until the workflow times out and no activity is ever scheduled. - Document in the prompt. ASCII-only bytes (a csv or txt document) serialize, but the model receives
strinstead ofbytes. redactedContentin the reply.invoke_modelruns the model, then fails to encode its result with the same error, on every attempt. A workflow that gets redacted thinking from the model can never finish.- MCP tool that returns an image. The
{server}-call-toolactivity runs the tool, then fails to encode thetoolResultbytes and is retried, so the tool and its side effects run again on every attempt. With a retry policy of 3 attempts the tool ran 3 times and the model never received the image.
Minimal Reproduction
Runs against main @ 5e91c26 with the plugin installed from the checkout (cd python/strands_agents && make sync, then .venv/bin/python repro_model.py). The plugin is applied on the Client, where the data converter is configured. The model is a fake that records the types it receives, so no credentials are needed.
import asyncio
import uuid
from datetime import timedelta
from typing import Any
from strands.models import Model
from temporalio import workflow
from temporalio.api.enums.v1 import EventType
from temporalio.client import Client, WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.strands_agents import StrandsPlugin, TemporalAgent
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
PNG = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" # not valid UTF-8
CSV = b"a,b\n1,2\n" # ASCII only
REDACTED = b"\xff\x00\xfe-redacted"
SEEN: list[Any] = []
class FakeModel(Model):
"""Records the bytes it is given and, for the prompt "think", answers with redactedContent."""
def update_config(self, **_: Any) -> None: ...
def get_config(self) -> dict[str, Any]:
return {}
def structured_output(self, *a: Any, **k: Any):
raise NotImplementedError
async def stream(self, messages, *_a, **_k):
for block in messages[-1]["content"]:
for kind in ("image", "document"):
if kind in block:
value = block[kind]["source"]["bytes"]
SEEN.append((kind, type(value).__name__))
yield {"messageStart": {"role": "assistant"}}
if messages[-1]["content"][0].get("text") == "think":
yield {"contentBlockDelta": {"delta": {"reasoningContent": {"redactedContent": REDACTED}}}}
yield {"contentBlockStop": {}}
yield {"contentBlockStart": {"start": {}}}
yield {"contentBlockDelta": {"delta": {"text": "ok"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
@workflow.defn
class W:
@workflow.run
async def run(self, case: str) -> str:
agent = TemporalAgent(
model="fake",
start_to_close_timeout=timedelta(seconds=10),
retry_policy=RetryPolicy(maximum_attempts=2),
)
if case == "image":
prompt = [{"text": "describe"}, {"image": {"format": "png", "source": {"bytes": PNG}}}]
elif case == "document":
prompt = [{"text": "describe"}, {"document": {"format": "csv", "name": "d", "source": {"bytes": CSV}}}]
else:
prompt = "think"
await agent.invoke_async(prompt)
return repr(agent.messages[-1]["content"])
async def main() -> None:
async with await WorkflowEnvironment.start_local() as env:
config = env.client.config()
config["plugins"] = [StrandsPlugin(models={"fake": FakeModel})]
client = Client(**config)
async with Worker(client, task_queue="q", workflows=[W]):
for case in ("image", "document", "redacted"):
SEEN.clear()
handle = await client.start_workflow(
W.run, case, id=f"wf-{uuid.uuid4()}", task_queue="q",
execution_timeout=timedelta(seconds=8),
)
try:
print(f"[{case}] result: {await handle.result()} model saw: {SEEN}")
except WorkflowFailureError as e:
print(f"[{case}] workflow failed: {type(e.cause).__name__}: {e.cause}")
async for ev in handle.fetch_history_events():
if ev.event_type == EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED:
print(f" workflow task failed: {ev.workflow_task_failed_event_attributes.failure.message}")
break
if ev.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_FAILED:
print(f" activity failed: {ev.activity_task_failed_event_attributes.failure.message}")
break
if __name__ == "__main__":
asyncio.run(main())Output on main:
[image] workflow failed: TimeoutError: Workflow timed out
workflow task failed: Error serializing to JSON: invalid utf-8 sequence of 1 bytes from index 0
ok[document] result: [{'text': 'ok'}] model saw: [('document', 'str')]
[redacted] workflow failed: ActivityError: Activity task failed
activity failed: Error serializing to JSON: invalid utf-8 sequence of 1 bytes from index 0
For the MCP case, save image_server.py next to repro_mcp.py:
import os
from mcp.server.fastmcp import FastMCP, Image
mcp = FastMCP("image-server")
@mcp.tool()
def screenshot() -> Image:
"""Return a PNG and record that the tool ran."""
with open(os.environ["CALLS_FILE"], "a") as calls:
calls.write("call\n")
return Image(data=b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", format="png")
if __name__ == "__main__":
mcp.run()import asyncio
import sys
import uuid
from datetime import timedelta
from pathlib import Path
from typing import Any
from mcp import StdioServerParameters, stdio_client
from strands.models import Model
from strands.tools.mcp import MCPClient
from temporalio import workflow
from temporalio.client import Client
from temporalio.common import RetryPolicy
from temporalio.strands_agents import StrandsPlugin, TemporalAgent, TemporalMCPClient
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
CALLS_FILE = str(Path(__file__).parent / "calls.txt")
def image_server() -> MCPClient:
return MCPClient(
lambda: stdio_client(
StdioServerParameters(
command=sys.executable,
args=[str(Path(__file__).parent / "image_server.py")],
env={"CALLS_FILE": CALLS_FILE},
)
)
)
class CallScreenshotThenAnswer(Model):
def __init__(self) -> None:
self.turn = 0
def update_config(self, **_: Any) -> None: ...
def get_config(self) -> dict[str, Any]:
return {}
def structured_output(self, *a: Any, **k: Any):
raise NotImplementedError
async def stream(self, messages, *_a, **_k):
self.turn += 1
yield {"messageStart": {"role": "assistant"}}
if self.turn == 1:
yield {"contentBlockStart": {"start": {"toolUse": {"name": "screenshot", "toolUseId": "t1"}}}}
yield {"contentBlockDelta": {"delta": {"toolUse": {"input": "{}"}}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "tool_use"}}
return
yield {"contentBlockDelta": {"delta": {"text": "ok"}}}
yield {"contentBlockStop": {}}
yield {"messageStop": {"stopReason": "end_turn"}}
@workflow.defn
class W:
@workflow.run
async def run(self) -> str:
agent = TemporalAgent(
model="m",
start_to_close_timeout=timedelta(seconds=10),
tools=[
TemporalMCPClient(
"img",
start_to_close_timeout=timedelta(seconds=10),
retry_policy=RetryPolicy(maximum_attempts=3),
)
],
)
await agent.invoke_async("take a screenshot")
return "done"
async def main() -> None:
Path(CALLS_FILE).unlink(missing_ok=True)
plugin = StrandsPlugin(models={"m": CallScreenshotThenAnswer}, mcp_clients={"img": image_server})
async with await WorkflowEnvironment.start_local() as env:
config = env.client.config()
config["plugins"] = [plugin]
client = Client(**config)
async with Worker(client, task_queue="q", workflows=[W]):
result = await client.execute_workflow(
W.run, id=f"wf-{uuid.uuid4()}", task_queue="q", execution_timeout=timedelta(seconds=20)
)
runs = len(Path(CALLS_FILE).read_text().splitlines())
print(f"workflow result: {result!r}; tool executions: {runs}")
if __name__ == "__main__":
asyncio.run(main())Output on main: workflow result: 'done'; tool executions: 3 (the activity failed with PydanticSerializationError each time, after the tool had run). Expected: 1 execution and an image in the tool result.
Environment/Versions
- OS and processor: macOS, arm64
- Temporal Version: temporalio 1.34.0 (local dev server via
WorkflowEnvironment.start_local()), temporalio-strands-agents frommain@ 5e91c26, strands-agents 1.56.0, Python 3.14.7 - Are you using Docker or Kubernetes or building Temporal from source? No
Additional context
I have a fix ready: bytes in the messages and in the returned stream events are tagged as base64 with Strands' own encode_bytes_values / decode_bytes_values at the activity boundary and restored on the other side, and the same for the MCP call-tool result. Messages without bytes encode to the same JSON as before, and a history recorded before the change replays. I will open a PR for it, as two commits (model activity, MCP result) since they are independent.
Two things I noticed and left alone: with streaming_topic set, events published to the WorkflowStream carry bytes in the same tagged form, so subscribers see {"__bytes_encoded__": true, "data": "<base64>"}; and if the plugin is only passed to Worker(plugins=...) the default JSON converter turns bytes into a list of ints instead of failing, which the fix also handles. The same class of bug was fixed for Deep Agents in #124.
Activity