Metadata-Version: 2.4
Name: temporalio-strands-agents
Version: 1.0.0
Summary: Temporal integration for strands agents
Author: Temporal Technologies Inc
Author-email: Temporal Technologies Inc <sdk@temporal.io>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 5 - Production/Stable
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: temporalio>=1.36.0,<2
Requires-Dist: strands-agents>=1.63.0
Requires-Dist: botocore>=1.34.0,<2
Requires-Dist: mcp>=1.23,<3
Requires-Dist: mcp>=2,<3 ; extra == 'mcp'
Requires-Dist: mcp-types>=2,<3 ; extra == 'mcp'
Requires-Dist: temporalio-mcp>=0.4.0,<0.5 ; extra == 'mcp'
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/temporalio/ai-integrations/tree/main/python/strands_agents
Project-URL: Repository, https://github.com/temporalio/ai-integrations
Project-URL: Documentation, https://docs.temporal.io/develop/python/integrations/strands-agents
Provides-Extra: mcp
Description-Content-Type: text/markdown

# Strands Agents

> Release stage: [Generally Available](https://docs.temporal.io/develop/python/integrations/strands-agents).

This Temporal [Plugin](https://docs.temporal.io/develop/plugins-guide) allows you to run [Strands Agents](https://strandsagents.com/) inside Temporal Workflows, routing model invocations, tool calls, and MCP tool calls through Temporal Activities for durable execution, Temporal-managed retries, and timeouts.

## Installation

```sh
uv add temporalio-strands-agents
```

## Quickstart

`workflow.py` defines the workflow and runs the worker:

```python
import asyncio
from datetime import timedelta

from temporalio import workflow
from temporalio.client import Client
from temporalio.strands_agents import StrandsPlugin, TemporalAgent
from temporalio.worker import Worker


@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        self.agent = TemporalAgent(start_to_close_timeout=timedelta(seconds=60))

    @workflow.run
    async def run(self, prompt: str) -> str:
        result = await self.agent.invoke_async(prompt)
        return str(result)


async def main() -> None:
    client = await Client.connect("localhost:7233")
    worker = Worker(
        client,
        task_queue="strands",
        workflows=[MyWorkflow],
        plugins=[StrandsPlugin()],
    )
    await worker.run()


if __name__ == "__main__":
    asyncio.run(main())
```

`client.py` starts the workflow:

```python
import asyncio

from temporalio.client import Client

from workflow import MyWorkflow


async def main() -> None:
    client = await Client.connect("localhost:7233")
    result = await client.execute_workflow(
        MyWorkflow.run,
        "Hello",
        id="strands-quickstart",
        task_queue="strands",
    )
    print(result)


if __name__ == "__main__":
    asyncio.run(main())
```

Note: Use `agent.invoke_async(message)` instead of `agent(message)`. Strands runs its synchronous calls on a new thread, outside the workflow sandbox and off the workflow event loop, where their model calls and other I/O would not be recorded. So in workflow code these raise `RestrictedWorkflowAccessError`: calling an `Agent`, `A2AAgent`, `Graph` or `Swarm`, `agent.structured_output()`, direct tool calls such as `agent.tool.name()`, and Strands features that make such calls themselves, such as `SummarizingConversationManager`, `SnapshotSessionManager`, and, in recent Strands versions, leaving `with agent:` when the agent has a `memory_manager`. Building agents, graphs and swarms still works, and calls made while they are built are not checked. Call agents that do their own I/O, such as an `A2AAgent`, from an activity, for example with `activity_as_tool`.

The error fails the workflow task, so the run stays open until you deploy a fix, unless the worker or workflow lists `NondeterminismError` in its failure exception types, which fails the run instead. Inside a tool, Strands catches it and gives the model an error tool result instead. Under the default sandboxed runner, a synchronous call in a workflow module's top-level code also stops the worker from starting, and fails every replay of that workflow. A run that made a synchronous call before you deploy this version no longer replays as recorded; if it caught the error, it now takes its error branch. Let those runs finish first, or use Worker Versioning.

## Models

`StrandsPlugin(models=...)` takes a mapping of `name → factory`. Each factory is called lazily on first use (on the worker, outside the workflow sandbox) and the constructed model is cached for the worker's lifetime. `TemporalAgent(model="name", ...)` selects which factory to invoke and carries the activity options for that agent's model calls. If `models` is omitted, the plugin registers a single `BedrockModel` factory under the name `"bedrock"` with Botocore retries disabled so Temporal owns retries.

```python
from botocore.config import Config as BotocoreConfig
from strands.models.anthropic import AnthropicModel
from strands.models.bedrock import BedrockModel

# workflow
@workflow.defn
class MultiModelWorkflow:
    def __init__(self) -> None:
        self.agent_a = TemporalAgent(
            model="claude",
            start_to_close_timeout=timedelta(seconds=60),
        )
        self.agent_b = TemporalAgent(
            model="bedrock",
            start_to_close_timeout=timedelta(seconds=60),
        )

# worker
Worker(..., plugins=[StrandsPlugin(models={
    "claude": lambda: AnthropicModel(client_args={"api_key": "..."}),
    "bedrock": lambda: BedrockModel(
        boto_client_config=BotocoreConfig(retries={"max_attempts": 0})
    ),
})])
```

Each `TemporalAgent` carries its own activity options (timeouts, retry policy, task queue, streaming topic) and dispatches to the shared model activity, which resolves the model name against the registered factories at runtime. A name not present in `models` raises `ValueError` inside the activity.

`heartbeat_timeout` defaults to 10 seconds. The model activities heartbeat on a timer, so a cancel reaches a running model call and a lost worker is noticed before the start-to-close timeout. Pass `heartbeat_timeout=None` to turn heartbeats off. The timer runs on the worker's event loop, so a model factory or model call that blocks that loop for longer than the timeout fails with a heartbeat timeout on a healthy worker. In Strands 1.56.0, `SageMakerAIModel` and `LlamaAPIModel` call their synchronous clients on the loop: pass `heartbeat_timeout=None` (or a longer timeout) for them. A factory slower than the timeout logs a warning on the worker.

Before its first invocation in a workflow, each `TemporalAgent` reads the worker model's `model_id` and `context_window_limit` with the `strands_get_model_config` activity, using the agent's activity options. `agent.model.get_config()` returns them, so proactive compression, `context_manager="auto"` and Strands' tracing use the real model's window and id, as they do natively. No other part of the model's config is sent to the workflow. The read is a new activity, so a run whose agent ran before you deploy this version fails to replay on it: let those runs finish first, or use Worker Versioning.

If you scaled `compression_threshold` by the model's window divided by 200,000 to work around the missing limit, remove that scaling: the threshold now applies to the model's own window.

A worker model that keeps the conversation server-side, such as `OpenAIResponsesModel(stateful=True)`, works as it does natively: each model call gets the agent's model state, such as the last response id, and the agent clears its messages after each turn. As in Strands, such an agent cannot use a `conversation_manager` or `context_manager`; because `TemporalAgent` learns that the model is stateful when it reads the config, it raises `ValueError` at the agent's first invocation instead of at construction. Remove the manager from those agents.

Stateful model calls run as their own activities, `strands_invoke_stateful_model` and `strands_invoke_stateful_model_streaming`. While you roll out this version, a worker running an earlier version does not register them, so it fails such a call (`NotFoundError`) and Temporal retries it until an upgraded worker takes it. Upgrade every worker on the task queue before a `retry_policy` with a low `maximum_attempts` runs out, or route upgraded workflows to upgraded workers with Worker Versioning.

A run that continues as new starts with no messages when its model is stateful, so it needs the model state it carries. If that run's workers do not have this version, or its config activity runs on a worker that does not, it treats the model as stateless, ignores the carried response id and starts the model's conversation over. Keep such runs on upgraded workers, and do not roll workers back to an earlier version while they continue as new.

A model call that fails with a context window overflow raises `ContextWindowOverflowException` in the workflow, so Strands reduces the conversation and calls the model again, as it does natively. Releases before 1.0 let the overflow reach the workflow as an `ActivityError`, and later builds of `main` gated the change with a patch marker, which this version no longer reads. So a run that hit an overflow before you deploy this version fails to replay on it with `[TMPRL1100]`, and a run that hits one on this version fails to replay on an earlier version. Let those runs finish on their original workers before you upgrade, or keep them there with Worker Versioning, and do not roll workers back to an earlier version while runs that hit an overflow on this version are open.

## Retries

`TemporalAgent` disables Strands' built-in `ModelRetryStrategy` so retries are handled exclusively by Temporal. The plugin's default Bedrock model also disables Botocore retries. When supplying your own model factory, disable that provider client's retries as shown in the Bedrock example above.

Configure retries via `retry_policy` on `TemporalAgent`, and on the activity options accepted by `workflow.activity_as_tool`, `workflow.activity_as_hook`, and `TemporalMCPClient`:

```python
from temporalio.common import RetryPolicy

TemporalAgent(
    start_to_close_timeout=timedelta(seconds=60),
    retry_policy=RetryPolicy(maximum_attempts=3),
)
```

Passing `retry_strategy=...` to `TemporalAgent(...)` raises `ValueError`; remove the argument (or pass `retry_strategy=None`) and put the retry config on the activity options instead.

## Snapshots

`TemporalAgent.take_snapshot()` and `TemporalAgent.load_snapshot()` raise `NotImplementedError`. Temporal's event history already persists workflow state durably at a finer granularity than Strands snapshots, so calling either inside a workflow is redundant.

## Structured Output

Like Strands `Agent`, `TemporalAgent` supports structured output with `structured_output_model`. The plugin defaults to [`pydantic_data_converter`](https://github.com/temporalio/sdk-python/blob/1.36.0/temporalio/contrib/pydantic.py), so Pydantic types easily serialize across the activity and workflow boundary.

```python
from pydantic import BaseModel

class PersonInfo(BaseModel):
    name: str
    age: int

@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        self.agent = TemporalAgent(
            start_to_close_timeout=timedelta(seconds=60),
            structured_output_model=PersonInfo,
        )

    @workflow.run
    async def run(self, prompt: str) -> PersonInfo:
        result = await self.agent.invoke_async(prompt)
        return result.structured_output
```

## Streaming

To forward model chunks to external consumers, pass `streaming_topic="..."` to `TemporalAgent` and host a `WorkflowStream` on the workflow. Each `StreamEvent` is published on the named topic from inside the model activity; subscribers read via `WorkflowStreamClient`. Chunks are batched on `streaming_batch_interval` (default 100ms).

```python
# workflow
@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        self.stream = WorkflowStream()
        self.agent = TemporalAgent(streaming_topic="events")

# client
async for item in WorkflowStreamClient.create(client, workflow_id).subscribe(
    ["events"], result_type=StreamEvent,
):
    print(item.data)
```

Events are published as your data converter writes them, so a `StreamEvent`-typed subscriber receives `bytes` fields such as `redactedContent` as `bytes`. If the model emits `redactedContent` that is not valid UTF-8 and the data converter is the Pydantic one (the plugin's default), which cannot write it, subscribers receive the event with `redactedContent` empty (`b""`) and the model activity does not fail. The workflow itself always gets the real bytes, and the default converter carries any bytes to subscribers.

## Sandboxes

`TemporalSandbox` implements Strands' sandbox API by scheduling every command,
code, and filesystem operation as a Temporal Activity. Register the real
worker-side sandbox under a name, then select that name in workflow code:

```python
from strands.sandbox.docker import DockerSandbox
from temporalio.strands_agents import (
    SandboxWorkflowContext,
    StrandsPlugin,
    TemporalAgent,
    TemporalSandbox,
)

async def build_sandbox(context: SandboxWorkflowContext) -> DockerSandbox:
    # Application-specific and idempotent: return the existing container when
    # another activity worker has already provisioned this Workflow's sandbox.
    container = await get_or_create_build_container(
        context.chain.first_execution_run_id
    )
    return DockerSandbox(container.name)

# workflow
agent = TemporalAgent(
    sandbox=TemporalSandbox(
        "build",
        start_to_close_timeout=timedelta(minutes=5),
    ),
)

# worker
Worker(
    ...,
    plugins=[StrandsPlugin(sandboxes={
        "build": build_sandbox,
    })],
)
```

The plugin registers one shared set of sandbox activities regardless of how
many factories are configured. Each operation carries the selected sandbox
name in its activity input so the worker can dispatch it to the matching
factory.

The factory is called for every sandbox Activity with a `SandboxWorkflowContext`
containing the current `run_id` and a `chain` identity with the Workflow's
namespace, Workflow ID, and first execution Run ID. Use the chain identity to
find or recreate the same backing environment across Activity retries, Worker
restarts, Continue-As-New, Reset, and Cron runs. Unrelated Workflow chains
should not share an environment unless the application explicitly intends that.

The first execution Run ID is supplied by workflow code because Activity
metadata only identifies the current run. Treat sandbox activities as trusted
worker endpoints: workflow code with access to their task queue can call them
directly and choose this value. Do not share the task queue between mutually
untrusted workflows. If Workflow IDs can be reused, the backing environment
lookup must also prevent a new execution from reconnecting to an old execution's
environment, for example by expiring old environments before ID reuse.

Factories may be synchronous or asynchronous. Synchronous factories must only
construct a lightweight adapter and must not block the activity event loop;
use an asynchronous factory for remote lookup or provisioning. Calls may run
concurrently or on different workers, so lookup and provisioning must be
idempotent. Strands' `DockerSandbox` only connects to an already-running
container; it does not create one.

The plugin does not cache adapters. If constructing an adapter is expensive,
cache it in the factory along with any backend-specific liveness and recovery
logic. The cache remains an optimization: every worker process must still be
able to reconnect to the same Workflow-scoped backing environment. Protect
in-process cache misses when concurrent Activities could otherwise provision
the same environment twice.

Return an async context manager from the factory when an adapter owns clients,
sockets, subprocess handles, tunnels, or leases that should be scoped to one
Activity. Its exit method runs after that Activity finishes:

```python
from contextlib import asynccontextmanager

@asynccontextmanager
async def build_managed_sandbox(context: SandboxWorkflowContext):
    adapter = await connect_to_sandbox(context)
    try:
        yield adapter
    finally:
        await adapter.aclose()
```

In either case, provisioning, teardown, and cleanup of orphaned backing
environments remain the application's responsibility; use a backend TTL or
reaper for workflows that are terminated before normal cleanup.

Successive sandbox Activities from one Workflow are routed independently across
the task queue. With more than one worker on the queue, a `write-file` can land
on one worker and the following `read-file` on another. The context factory must
therefore reconnect every worker to the same Workflow-scoped backing environment
rather than relying on per-process state. A single worker on the queue also
satisfies this.

Reset does not roll back commands or filesystem mutations already performed in
the external sandbox, just as it does not roll back other Activity side effects.
Account for that when resetting a Workflow that uses a sandbox.

`SandboxTimeoutError` is serialized as an Activity failure and retried under the
`retry_policy` you pass to `TemporalSandbox`. If retries are exhausted, it is
reconstructed inside the workflow with the sandbox's own message. Any
`FileNotFoundError` raised by a sandbox filesystem operation — including its
`SandboxPathNotFoundError` subclass — is non-retryable because the requested path
is absent, and is reconstructed in the same way. Factory failures and other
sandbox failures, including the `OSError` that Strands documents for a failed
`write_file`, are also retryable.

Like all Temporal Activities, sandbox operations have at-least-once execution
semantics. A worker can finish a command or filesystem mutation and fail before
recording its result, causing a retry to perform the operation again. Use a
bounded `retry_policy`, and make commands and mutations idempotent when repeated
execution would be unsafe.

By default, `TemporalSandbox.get_tools()` vends `sandbox_shell`, `sandbox_read`,
`sandbox_write`, and `sandbox_edit`. The file tools use Strands' focused read,
write, and edit implementations: read returns numbered text with optional paging
or image/document content, write creates or overwrites a text file, and edit
replaces an exact, unique string. They require absolute paths. These tools replace
the deprecated `sandbox_file_editor`. A tool passed explicitly through
`TemporalAgent(tools=...)` with the same name takes precedence, following Strands'
normal sandbox-tool override behavior.

Execution output is always buffered into the activity result so workflow replay
observes the same ordered `StreamChunk` and `ExecutionResult` values. For live,
observer-facing output, set `streaming_topic` and host a `WorkflowStream` on the
workflow. The activity publishes each `StreamChunk` as it arrives; the final
`ExecutionResult` is returned only through the buffered activity result:

```python
from datetime import timedelta

from temporalio.strands_agents import SandboxStreamEvent, TemporalSandbox
from temporalio.contrib.workflow_streams import WorkflowStream, WorkflowStreamClient

# workflow __init__
self.stream = WorkflowStream()
self.sandbox = TemporalSandbox(
    "build",
    start_to_close_timeout=timedelta(minutes=5),
    streaming_topic="sandbox-events",
)

# external client
async for item in WorkflowStreamClient.create(client, workflow_id).subscribe(
    ["sandbox-events"], result_type=SandboxStreamEvent
):
    event = item.data
    print(event.execution_id, event.sequence, event.chunk.data)
```

Each `SandboxStreamEvent` includes the sandbox name, an execution ID composed of
the Workflow Run ID and Activity ID, the Activity attempt, chunk sequence, and
`StreamChunk`. Events from concurrent executions may interleave on a shared
topic; group them by `execution_id` and `attempt`, then order them by `sequence`.
Workflow code still receives the correctly separated, complete buffered result
for each call. Because publications are observer-facing side effects of an
Activity attempt, a failed attempt may leave chunks in the topic before a retry
publishes its own output.

Streaming is disabled by default. When `streaming_topic=None`, sandbox
activities do not construct a `WorkflowStreamClient` and the workflow does not
need to host a `WorkflowStream`.

All sandbox Activity arguments and results are serialized into workflow history.
Keep command output and files within the server's configured payload size limits;
use external storage for large artifacts.
`sandbox_read` and `sandbox_edit` record the entire file in a read-file Activity
result, even when the read tool requests only a page of text. `sandbox_write`
and `sandbox_edit` record the written content in a write-file Activity input.

Do not put secret values directly in `env`, because those values are serialized
into workflow history. Use `temporal_worker_env_ref()` to serialize only the
name of a worker environment variable, then allow that name on every worker that
runs the sandbox activities:

```python
from temporalio.strands_agents import temporal_worker_env_ref

# workflow
await sandbox.execute(
    "build",
    env={"API_KEY": temporal_worker_env_ref("BUILD_API_KEY")},
)

# worker
plugin = StrandsPlugin(
    sandboxes={"build": build_sandbox},
    resolvable_worker_env_vars=["BUILD_API_KEY"],
)
```

Names are matched exactly. A reference to a name the worker does not allow is
passed to the sandbox unchanged; an allowed but unset variable resolves to an
empty string. `AllowAllWorkerEnvVars()` permits any name, but should only be used
when all workflow code on the task queue is trusted to read every environment
variable available to that worker.

## Tools

Decorate non-deterministic tools with `@activity.defn`, or if you're importing tools from `strands_tools`, wrap them in a thin async function. Then, register the activity on the worker via `Worker(activities=[...])` and pass it to the agent with `workflow.activity_as_tool(activity, **options)` along with any activity options (e.g. `start_to_close_timeout`):

```python
from strands_tools import shell
from temporalio.strands_agents import workflow as strands_workflow

@activity.defn
async def fetch_user(user_id: str) -> dict:
    ...

@activity.defn(name="shell")
async def shell_activity(command: str) -> dict:
    return shell.shell(command=command, non_interactive=True)

# workflow
agent = TemporalAgent(
    start_to_close_timeout=timedelta(seconds=60),
    tools=[
        strands_workflow.activity_as_tool(fetch_user, start_to_close_timeout=timedelta(seconds=30)),
        strands_workflow.activity_as_tool(shell_activity, start_to_close_timeout=timedelta(seconds=15)),
    ],
)

# worker
Worker(
    ...,
    activities=[fetch_user, shell_activity],
    plugins=[StrandsPlugin(models=MODELS)],
)
```

`activity_as_tool` also takes a method passed as `Class.method`, with the bound method registered on the worker, and a callable-class activity passed as its class, with an instance registered. The tool offers the parameters the activity is called with: a method's without `self`, and a class's `__call__` parameters. An instance, or a `__call__` that takes `*args`, keyword-only arguments or `**kwargs`, raises `ValueError`, and parameters named `agent` or `cls` are not offered, as in Strands' own tools. Runs from versions before this behavior whose model called a method tool, a class tool whose constructor parameters differ from `__call__`'s, or a function tool with a positional-only parameter, fail replay with it: let them finish before upgrading, or use Worker Versioning.

If a tool's activity fails, the agent receives a failed tool result containing
the activity's error message, and `AfterToolCallEvent.exception` contains the
underlying exception. This also applies when an MCP tool's call-tool activity
fails.

When a workflow or tool task is cancelled, cancellation of its activity or MCP
call propagates as `asyncio.CancelledError` instead of a failed tool result, so
cancelling the workflow ends it as `CANCELED`. The tool's `cancellation_type`
controls whether it waits for activity cleanup. An activity that reports
cancellation independently still produces a failed tool result for the agent.

**Breaking change:** histories that previously processed a cancelled tool as an
error result can fail replay on this version. Keep those runs on their original
workers with Worker Versioning. To recover a run stuck during tool cancellation,
reset it to before the affected tool call and run it on upgraded workers.

Other tools run directly in the workflow, so they must be deterministic, like
workflow code. Sync tools run there too, not in a separate thread as they do
outside Temporal. They run again on every replay. Their combined work in one
Workflow Task can trigger deadlock detection (two seconds by default), even if
each tool takes less than two seconds. Tools from packages the plugin passes
through the sandbox, such as `strands_tools`, are not checked by it; wrap them
as activities as described above.

**Breaking change:** a run recorded on an earlier version whose sync tool got
an error can fail replay on this version: if the workflow then acted on what
the tool now does, if the tool issues commands itself or takes more than two
seconds, or if a `Swarm` agent handed off. Let runs that called a sync tool
finish on their original workers first, or keep them there with Worker
Versioning.

## Hooks

Strands' [hook system](https://strandsagents.com/) (`strands.hooks`) lets you subscribe callbacks to events in the agent lifecycle — invocation start/end, model call before/after, tool call before/after, message added. Pass `hooks=[MyHookProvider()]` to `TemporalAgent`: every single-agent hook event fires in workflow context, so deterministic callbacks just work.

```python
from strands.hooks import HookProvider, HookRegistry
from strands.hooks.events import AfterToolCallEvent

class AuditHook(HookProvider):
    def register_hooks(self, registry: HookRegistry) -> None:
        registry.add_callback(AfterToolCallEvent, self._on_tool_call)

    def _on_tool_call(self, event: AfterToolCallEvent) -> None:
        # Pure local state - deterministic across replay.
        workflow.logger.info(f"tool {event.tool_use['name']} finished")

agent = TemporalAgent(start_to_close_timeout=..., hooks=[AuditHook()])
```

Callbacks run in workflow context, so they must be deterministic: no `time.time()`, `uuid.uuid4()`, or I/O — same rules as workflow code. For callbacks that need I/O (audit logging, metrics, alerting), use `workflow.activity_as_hook()` to dispatch the work as a Temporal activity:

```python
from temporalio.strands_agents.workflow import activity_as_hook

@activity.defn
async def persist_tool_call(tool_name: str) -> None:
    # I/O safely in an activity.
    ...

class AuditHook(HookProvider):
    def register_hooks(self, registry: HookRegistry) -> None:
        registry.add_callback(
            AfterToolCallEvent,
            activity_as_hook(
                persist_tool_call,
                activity_input=lambda event: event.tool_use["name"],
                start_to_close_timeout=timedelta(seconds=10),
            ),
        )
```

`activity_input` extracts serializable values from the event to pass as the activity's input. Use a dataclass or Pydantic model for multiple values. This is needed because events hold references to the `Agent`, `AgentTool` instances, etc., none of which cross the activity boundary.

## Human-in-the-loop interrupts

Strands offers two HITL surfaces; both work with the plugin. In each case, `agent.invoke_async()` returns `AgentResult(stop_reason="interrupt", interrupts=[...])` instead of raising. Pair this with a signal handler that supplies responses, then resume by calling `agent.invoke_async(responses)`.

### Hook-based interrupts

A hook on an interruptible event (e.g. `BeforeToolCallEvent`) can pause the agent by calling `event.interrupt(name, reason=...)`. The hook runs in workflow context, so it must be deterministic — no I/O.

```python
from strands.hooks import HookProvider, HookRegistry
from strands.hooks.events import BeforeToolCallEvent

class ApprovalHook(HookProvider):
    def register_hooks(self, registry: HookRegistry) -> None:
        registry.add_callback(BeforeToolCallEvent, self._gate)

    def _gate(self, event: BeforeToolCallEvent) -> None:
        if event.interrupt("approval", reason="confirm delete") != "approve":
            event.cancel_tool = "denied"

@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        self.agent = TemporalAgent(
            start_to_close_timeout=timedelta(seconds=60),
            tools=[delete_thing],
            hooks=[ApprovalHook()],
        )
        self._approval: str | None = None

    @workflow.signal
    def approve(self, response: str) -> None:
        self._approval = response

    @workflow.run
    async def run(self, prompt: str) -> str:
        result = await self.agent.invoke_async(prompt)
        if result.stop_reason == "interrupt":
            await workflow.wait_condition(lambda: self._approval is not None)
            result = await self.agent.invoke_async([
                {"interruptResponse": {"interruptId": result.interrupts[0].id, "response": self._approval}}
            ])
        return str(result)
```

### Tool-body interrupts

A `@strands.tool(context=True)` function can call `tool_context.interrupt(name, reason=...)`. The agent stops with the interrupt, and the workflow handles the resume the same way as for hooks. On resume, Strands runs the tool again, and the call returns the response instead of raising.

```python
from strands import tool
from strands.types.tools import ToolContext

@tool(context=True)
def delete_thing(name: str, tool_context: ToolContext) -> str:
    if tool_context.interrupt("approval", reason=f"delete {name}?") != "approve":
        return f"kept {name}"
    return f"deleted {name}"
```

An `activity_as_tool`-wrapped activity has no `tool_context`, so it raises `InterruptException(Interrupt(...))` instead. The plugin's failure converter preserves the `Interrupt` payload across the activity boundary, so `AgentResult.interrupts` is populated just like the in-workflow case:

```python
from strands.interrupt import Interrupt, InterruptException
from temporalio.strands_agents.workflow import activity_as_tool

@activity.defn
async def delete_thing(name: str) -> str:
    if not await policy.is_authorized(name):
        raise InterruptException(
            Interrupt(id=f"delete:{name}", name="approval", reason=f"delete {name}?")
        )
    await storage.delete(name)
    return f"deleted {name}"

@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        self.agent = TemporalAgent(
            start_to_close_timeout=timedelta(seconds=60),
            tools=[activity_as_tool(delete_thing, start_to_close_timeout=timedelta(seconds=10))],
        )
```

This relies on the plugin's failure converter, which is installed via the client's data converter. **Attach `StrandsPlugin` to the client** (not just the worker) for activity-tool interrupts to work — workers built from that client pick up the plugin automatically. If your data converter uses the default payload converter with `DefaultFailureConverterWithEncodedAttributes` or a subclass of it, the plugin replaces it with its own failure converter but keeps the encoding, so failure messages and stack traces still go through your codec. Methods your class overrides are not used. A data converter with a non-default payload converter, such as `pydantic_data_converter`, keeps that payload converter and its own failure converter: the plugin adds the Strands exception handling on top, and your `from_failure` still decodes recorded failures. A failure converter that does not subclass `DefaultFailureConverter` is kept unchanged, without the Strands handling.

```python
client = await Client.connect("localhost:7233", plugins=[StrandsPlugin(models=MODELS)])
Worker(client, task_queue="strands", workflows=[MyWorkflow], activities=[delete_thing])
```

## Continue-as-new

A chat-style workflow accumulates history with every turn and will eventually hit Temporal's per-workflow history limit. `workflow.info().is_continue_as_new_suggested()` flips true once the server decides history has grown large enough; check it after each turn and hand off to a fresh run, carrying `agent.messages` and `agent.model_state` as input. A stateful model clears the messages after each turn and keeps its context in the model state, such as the last response id; a run that carries only the messages starts the model's conversation over:

```python
from dataclasses import dataclass, field
from typing import Any
from strands.types.content import Messages

@dataclass
class ChatInput:
    messages: Messages = field(default_factory=list)
    model_state: dict[str, Any] = field(default_factory=dict)

@workflow.defn
class ChatWorkflow:
    def __init__(self) -> None:
        self._pending: list[str] = []
        self._done = False

    @workflow.signal
    def user_says(self, prompt: str) -> None:
        self._pending.append(prompt)

    @workflow.signal
    def end_chat(self) -> None:
        self._done = True

    @workflow.run
    async def run(self, input: ChatInput) -> None:
        agent = TemporalAgent(
            start_to_close_timeout=timedelta(seconds=60),
            messages=list(input.messages),
            model_state=input.model_state,
        )
        while True:
            await workflow.wait_condition(lambda: self._pending or self._done)
            if self._done:
                return
            await agent.invoke_async(self._pending.pop(0))
            if workflow.info().is_continue_as_new_suggested():
                workflow.continue_as_new(
                    ChatInput(messages=agent.messages, model_state=agent.model_state)
                )
```

## MCP

MCP support runs on [`temporalio-mcp`](https://github.com/temporalio/ai-integrations/tree/main/python/mcp) and the MCP Python SDK v2. Install it with the `mcp` extra:

```bash
uv add "temporalio-strands-agents[mcp]"
```

`StrandsPlugin(mcp_clients=...)` takes a mapping of `name → mcp.Client factory`. The worker calls a factory each time it opens a connection, so return a new `mcp.Client` and transport from every call, and do not cache it. The plugin registers the `temporalio-mcp` activities for each server, such as `temporalio.mcp.{name}.list-tools` and `temporalio.mcp.{name}.call-tool`. Workflow-side, `TemporalMCPClient(server="name")` is a pure handle: it references the server by name, discovers tools by running `list-tools`, and carries the per-call activity options.

These are the activities that `temporalio.mcp.MCPPlugin` registers, so `temporalio.mcp.TemporalMCPClient` can also use these servers, for prompts and resources for example, as long as it passes no `factory_argument`. Don't register the same server name through `MCPPlugin` or `OpenAIAgentsPlugin` on the same worker: Temporal rejects the duplicate activity types.

```python
from mcp import Client, StdioServerParameters, stdio_client
from temporalio.strands_agents import TemporalMCPClient

# workflow
@workflow.defn
class MyWorkflow:
    def __init__(self) -> None:
        echo = TemporalMCPClient(server="echo", start_to_close_timeout=timedelta(seconds=30))
        self.agent = TemporalAgent(
            start_to_close_timeout=timedelta(seconds=60),
            tools=[echo],
        )

# worker
Worker(
    ...,
    plugins=[StrandsPlugin(
        mcp_clients={
            "echo": lambda: Client(
                stdio_client(StdioServerParameters(command="...", args=[...])),
            ),
        },
    )],
)
```

Connection options such as `elicitation_callback` or `read_timeout_seconds` go on the `mcp.Client`. A tool call that needs several rounds (`InputRequiredResult`) runs all of them inside one call-tool activity, through the `mcp.Client`'s callbacks.

`TemporalMCPClient` takes `prefix` and `tool_filters`, which work as on Strands' `MCPClient`: the agent sees `{prefix}_{name}`, and filters match the server's tool name. A callable filter receives the workflow-side `TemporalMCPTool`, a Strands `MCPAgentTool` whose `mcp_client` is the durable client, and runs in the workflow, so it must be deterministic:

```python
github = TemporalMCPClient(
    server="github",
    prefix="gh",
    tool_filters={"allowed": ["search_issues", re.compile("get_.*")]},
    start_to_close_timeout=timedelta(seconds=30),
)
```

A tool that reports an error returns a failed tool result to the agent. Errors a retry cannot fix reach the agent at once as a failed tool result, without a retry. These include an unknown tool, invalid arguments, a malformed result that the MCP client cannot parse, such as one whose `content` is not a list, and a result that does not match the tool's output schema. Internal server errors, timeouts and lost connections fail the attempt and are retried under the activity's `retry_policy`. See the [`temporalio-mcp` README](https://github.com/temporalio/ai-integrations/tree/main/python/mcp#errors-and-retries) for which errors are retried.

Without `start_to_close_timeout` or `schedule_to_close_timeout`, the MCP activities get a one-minute `start_to_close_timeout`. The default retry policy retries without limit, so an agent turn waits while its MCP server is down. To give up instead, bound the retries:

```python
echo = TemporalMCPClient(
    server="echo",
    start_to_close_timeout=timedelta(seconds=30),
    retry_policy=RetryPolicy(maximum_attempts=3),
)
```

A call-tool activity that runs out of attempts returns a failed tool result to the agent, which can go on without the tool. A list-tools activity that runs out of attempts does not reach the agent. It runs before every model call, and the result depends on which Strands event-loop cycle makes that call, not on how many model calls came before it. In the first cycle of an `invoke_async()` that starts with a model call, the `ActivityError` propagates from the call and, if the workflow does not catch it, fails the workflow. That covers the first model call of every such invocation, including one on an agent whose earlier invocations completed, and a model call that an `AfterModelCallEvent` hook repeats in that cycle by setting `retry = True`. An invocation that resumes a tool interrupt runs the approved tools first, so its first model call is in a later cycle. Strands starts a new cycle after the agent runs tools, and when it asks the model again for a `structured_output_model` result that the model answered in plain text, so no tool needs to have run. In such a cycle, including a model call a hook repeats there, Strands wraps the `ActivityError` in an `EventLoopException`: the workflow task fails on every retry, and the workflow stays open until it is reset or terminated. With `cache_tools=True`, a `TemporalMCPClient` stops listing after its first successful listing, so only that first listing can fail.

Tool names must be unique on one agent. Two tools may not have the same name, or names that differ only by `-` or `_`: for example two servers that both list `search`, a server that lists a name twice, or a server tool named like a tool in `tools=[...]`, a `TemporalSandbox` tool or a tool a Signal handler adds while the servers list. `TemporalAgent` learns its MCP tools only when it lists them, so the model call after that listing raises `MCPToolNameConflictError`, a `ValueError` and a non-retryable `ApplicationError`: the first one, or, with `cache_tools=False`, a later one if a server starts listing such a name. It is raised again at every later model call while the duplicate lasts; between `cache_tools=True` listings, that is the rest of the run. This holds for an agent built before or after its clients listed. Give one `TemporalMCPClient` a different `prefix`, or drop the tool with its `tool_filters`. While a server lists a name, the name is the server's: a tool you put under it is replaced at the next model call, and a tool you remove comes back, also with `cache_tools=True`. A `structured_output_model` named like an MCP tool the agent already has gets Strands' own `ValueError` when the call starts, as in Strands.

The error fails the Workflow when it escapes the Workflow's run method or a Signal handler, with `StrandsPlugin` on the client or only on the Worker, because replay would raise it again. Escaping an Update handler, it fails only that Update, and the run stays open. Strands' `Swarm` records it as a failed node, and an agent used as a tool returns it as an error result, so neither fails the Workflow. If Workflow code catches it, or an Update failed, and calls the agent again, first remove the messages that Strands added to `agent.messages` during that call (the prompt, and any tool calls and results), as for any error during an agent call. A new `prefix` renames that server's tools, and new `tool_filters` can drop some, in every replay: an open run fails to replay if its model called a renamed or dropped tool, if its Workflow code acted on one among the agent's tools (for example on `'x' in agent.tool_names`), or if it met the error and went on, since the refused turn now proceeds. So deploy such a change with Worker Versioning. To recover a run that met the error, reset it to before the first listing that returned a tool the change renames or drops. A later reset point, such as just before the first refused listing, recovers it only if the run had not met the error before that point and neither the model nor Workflow code used those tools before it.

Earlier versions let the later tool replace the earlier one in most of these cases. A run that started before you deploy this version can fail to replay on it if one of its agents met such a duplicate, including two handles of one server and names that differ only by `-` or `_`. It can also fail if a server's tools changed during the run: a tool that moves from one server to another in one turn now stays, where earlier versions could lose it, and an agent that shares an uncached client with another agent now drops the tools the server stopped listing, where earlier versions kept them. And an agent built after another agent listed a client they share has none of that client's tools until its first model call, where earlier versions gave it the last listing at construction. A call to one of them that its initial `messages` end with, which Strands runs before that model call, now finds no such tool, and Workflow code that reads its `tool_names` or `tool_registry` before then can take another path, though no names clashed and the servers kept their tools. So can Strands' estimate of that model call's input tokens, which now leaves those tools out, so proactive context compression can run at a different model call. An agent that shares a `cache_tools=True` client with another agent and was built before that agent's first listing now gets the client's tools at its first model call; earlier versions never gave it those tools. Workflow code that reads its tools can take another path, and runs in which it calls them fail to replay on earlier versions. An agent whose `cache_tools=True` client's tool Workflow code replaced or removed now gets the server's tool back at the next model call; earlier versions kept the change. Last, an agent now applies a turn's listings together, once every server due that turn has listed, where earlier versions added each server's tools as soon as it listed. Until then the agent's tools stay as they were before that turn, and they stay so if a listing fails. Workflow code that reads the agent's tools before the turn's listings are applied can take another path, though no names clashed and the servers kept their tools: for example a Signal or Update handler that runs while a later server lists, even if every listing then succeeds, or code that catches a failed listing. Let those runs finish first, or use Worker Versioning.

By default, `TemporalMCPClient` re-lists the server's tools (via `list-tools`) on every agent turn, so an MCP server that is restarted mid-workflow — with tools added, removed, or renamed — is picked up. To list the tools just once at the beginning of the workflow and reuse that schema for the workflow's lifetime (one fewer activity per turn), set `cache_tools=True`:

```python
echo = TemporalMCPClient(server="echo", cache_tools=True, start_to_close_timeout=timedelta(seconds=30))
```

Each listing records the server's full tool list in the workflow history, before `tool_filters` apply. For a server with many tools, use `cache_tools=True` so the list is recorded once. Call-tool results are also recorded as the server returns them, including content the agent does not receive, such as audio; a result over Temporal's payload size limit fails the activity.

To amortize connection setup, the MCP activities share a worker-process connection that is opened lazily and reused across calls. Only servers that negotiate the modern MCP protocol share a connection; a server on an older protocol, such as one built with MCP Python SDK 1.x, gets a new connection for every activity (a new process for stdio). The connection is disconnected after it sits idle for `mcp_connection_idle_timeout` (default 5 minutes); the timer resets on every reuse. `None` keeps connections until the worker shuts down, and `timedelta(0)` closes them as soon as they are idle:

```python
StrandsPlugin(
    mcp_clients={"echo": lambda: Client(...)},
    mcp_connection_idle_timeout=timedelta(seconds=30),
)
```

Earlier versions used Strands' `MCPClient` factories and the `{name}-list-tools` and `{name}-call-tool` activities. To upgrade:

- Return an `mcp.Client` from each factory, and move `prefix` and `tool_filters` from the factory to `TemporalMCPClient`. Pass the `mcp.Client` the transport itself, a `StdioServerParameters` or a URL, not a function that returns the transport as Strands' `MCPClient` took. `mcp.Client` doesn't take `prefix` or `tool_filters`: a factory that still passes `prefix=` fails every MCP activity with a `TypeError`, which is retried. A factory that returns the wrong client type, such as Strands' `MCPClient`, now fails the Activity without retries with type `MCPServerFactoryTypeError`. An `mcp.Client` built on a function fails without retries with type `MCPServerFactoryTransportError`. A client passed in place of its factory, or any other value that isn't callable, makes `StrandsPlugin(...)` raise `TypeError`, so the worker doesn't start. Fix these factories before upgrading: these errors used to retry, but deploying a corrected worker no longer resumes an Activity that has already failed. Without distinct prefixes, same-named tools from different servers are refused (see above).
- Callable `tool_filters` now run in the workflow, so they must be deterministic.
- Set connection options on `mcp.Client`. Strands `MCPClient` options and subclass overrides, such as `map_mcp_content_to_tool_result_content`, do not apply; tool results are mapped as Strands' default `MCPClient` maps them.
- A call-tool failure that a retry can fix (a lost connection, an internal server error, a timeout) used to give the model `Tool execution failed` at once; it is now retried under `retry_policy`, without limit by default. `mcp_connection_idle_timeout=None` used to mean five minutes; it now keeps connections until the worker shuts down. A server on an older MCP protocol now gets a new connection, a new process for stdio, for every activity.
- Workflows started on earlier versions that use MCP tools must finish on workers running them before those workers are upgraded.

## Observability

Strands' agent cycle, tool, and trace durations use Temporal's Workflow
clock inside Workflows, so replay reconstructs the original elapsed time. These
durations include Activity scheduling, retries, and waits; provider-reported
latency and token usage still come from the recorded model response. Activities
and ordinary Strands calls outside Workflows keep their native clocks.

Graph and Swarm orchestration-level `execution_time` and `execution_timeout`
still use native wall clocks and are not replay-safe. Their agents' cycle and
tool metrics use the Workflow clock as described above.

This changes the values returned by earlier versions, which measured replay
execution time after a cache eviction or Worker restart. It can break replay if
Workflow code uses those durations to choose what to do next. Let existing runs
finish on their original Workers, or use Worker Versioning to keep them there
before deploying this change.

`StrandsPlugin` composes cleanly with [`OpenTelemetryPlugin`](https://github.com/temporalio/sdk-python/tree/1.36.0/temporalio/contrib/opentelemetry). Register `OpenTelemetryPlugin` on the client (workers built from that client pick it up automatically) and `StrandsPlugin` on the worker. You'll get OTel spans around the model, tool, and MCP activities the plugin schedules, plus any spans Strands itself emits inside `invoke_async`:

```python
import opentelemetry.trace
from temporalio.contrib.opentelemetry import OpenTelemetryPlugin, create_tracer_provider

opentelemetry.trace.set_tracer_provider(create_tracer_provider())

client = await Client.connect("localhost:7233", plugins=[OpenTelemetryPlugin()])

Worker(
    client,
    task_queue="strands",
    workflows=[MyWorkflow],
    plugins=[StrandsPlugin(models=MODELS)],
)
```

Set the tracer provider before connecting the client. See the [OpenTelemetry plugin README](https://github.com/temporalio/sdk-python/tree/1.36.0/temporalio/contrib/opentelemetry) for exporter setup.
