Skip to content

agents generated API reference

agents

Python port of the Cloudflare Agents SDK.

DEFAULT_MAX_CHUNK_BYTES = 1048576 module-attribute

The default limit on one serialized chunk (1 MiB).

__title__ = 'agents' module-attribute

__version__ = '0.3.0' module-attribute

__license__ = 'MIT OR Apache 2.0' module-attribute

__author__ = 'justanotherbyte' module-attribute

__all__ = ('DEFAULT_MAX_CHUNK_BYTES', 'AIChatAgent', 'AIChatAgentOptions', 'Agent', 'AgentOptions', 'AgentPathStep', 'AgentRoute', 'AgentStub', 'AgentsException', 'AnyToolPart', 'AppendEvent', 'AppendResult', 'Approval', 'CallableMetadata', 'CancelledRun', 'ChatMessage', 'ChatMessageOptions', 'ChatResponseResult', 'ChatStreamError', 'ChunkEvent', 'ClearEvent', 'ClientToolSchema', 'CompletedRun', 'Completion', 'CompletionEvent', 'Connection', 'ConnectionContext', 'ConnectionStateTooLargeError', 'ContentPart', 'CurrentAgent', 'DataPart', 'Debounce', 'DeleteEvent', 'Disposable', 'DuplicateConnectionIdError', 'DuplicateTaskStepError', 'Duration', 'DynamicAgents', 'FailedRun', 'FiberAborted', 'FiberCompleted', 'FiberConflictError', 'FiberContext', 'FiberErrored', 'FiberInspection', 'FiberInterrupted', 'FiberNotFoundError', 'FiberRecoveryContext', 'FiberRecoveryResult', 'FiberStatus', 'Fibers', 'FileInput', 'FilePart', 'FunctionCall', 'FunctionSchema', 'Harness', 'HarnessEvent', 'HarnessInput', 'HarnessSession', 'HarnessSessions', 'ImageContentPart', 'ImageURL', 'InputPart', 'InvalidCronExpressionError', 'JSONValue', 'JobContext', 'JobOutcome', 'KeepAlive', 'Lifecycle', 'LifecycleCapability', 'LifecycleEvent', 'LifecycleJob', 'LifecycleJobs', 'LifecycleRoutes', 'LifecycleServices', 'LifecycleStatus', 'LoggingObservability', 'MCPNotEnabledError', 'MCPOptions', 'MemoryLimitContext', 'MessageConcurrency', 'MessageEvent', 'MissingTaskDefinitionError', 'NonRetryableError', 'Observability', 'ObservabilityEvent', 'OperationEvent', 'OperationNotFoundError', 'OperationResult', 'OperationStatus', 'PendingOperation', 'PendingRun', 'Queue', 'QueueItem', 'ReadonlyConnectionError', 'ReasoningDelta', 'ReasoningPart', 'Receipt', 'RecentHistoryResult', 'Replay', 'Reschedule', 'ResetEvent', 'RetryOptions', 'RouteAddress', 'RouteContext', 'RoutingRetryEvent', 'RoutingRetryOptions', 'RunEndEvent', 'RunSnapshot', 'RunStartEvent', 'RunningRun', 'SaveMessagesResult', 'Schedule', 'ScheduleType', 'Scheduler', 'Session', 'SessionBusyError', 'SessionChangeEvent', 'SessionChangeListener', 'SessionInfo', 'SessionMessage', 'SessionNotFoundError', 'SessionRowStat', 'SessionSnapshot', 'Sessions', 'Source', 'SourceDocumentPart', 'SourceUrlPart', 'Sql', 'SqlError', 'SqlValue', 'StartFiberResult', 'State', 'StateSource', 'StepInterruption', 'StepRetries', 'StepStartPart', 'StepTimeoutError', 'StreamChunk', 'StreamClosedError', 'StreamNotFoundError', 'StreamSerializationError', 'StreamState', 'StreamStatus', 'StreamWriter', 'StreamingResponse', 'Streams', 'SubAgentAbortedError', 'SubAgentInfo', 'TaskError', 'TaskHandle', 'TaskReceipt', 'TaskReplayDivergedError', 'TaskRun', 'TaskRunState', 'TaskSerializationError', 'TaskStep', 'TaskStepAttempt', 'Tasks', 'TextContentPart', 'TextDelta', 'TextInput', 'TextPart', 'ToolAnswer', 'ToolApproval', 'ToolApprovalRequestedPart', 'ToolApprovalRespondedPart', 'ToolCall', 'ToolCallDelta', 'ToolCallPayload', 'ToolInputAvailablePart', 'ToolInputStreamingPart', 'ToolOutput', 'ToolOutputAvailablePart', 'ToolOutputDeniedPart', 'ToolOutputErrorPart', 'ToolPart', 'ToolRequest', 'ToolSchema', 'ToolSpec', 'ToolState', 'Turn', 'TurnResult', 'UIMessage', 'UIMessagePart', 'UnknownPart', 'UpdateEvent', 'Usage', 'WaitingRun', 'WebSocketHandlers', 'WebSockets', 'WhenBusy', 'WorkersAIModel', 'build_agent_path', 'build_agent_url', 'callable', 'get_agent_by_name', 'get_current_agent', 'get_sub_agent_by_name', 'retry', 'route_agent_request', 'route_sub_agent_request', 'subscribe', 'task', 'tool') module-attribute

AnyToolPart = ToolInputStreamingPart | ToolInputAvailablePart | ToolApprovalRequestedPart | ToolApprovalRespondedPart | ToolOutputAvailablePart | ToolOutputErrorPart | ToolOutputDeniedPart

Every tool state, for an exhaustive match.

ToolState = Literal['input-streaming', 'input-available', 'approval-requested', 'approval-responded', 'output-available', 'output-error', 'output-denied']

UIMessagePart = TextPart | ReasoningPart | AnyToolPart | FilePart | SourceUrlPart | SourceDocumentPart | StepStartPart | DataPart | UnknownPart

One part of a message.

MessageConcurrency = Literal['queue', 'latest', 'merge', 'drop'] | Debounce

What a user's send does while another turn is running or queued.

  • "queue": run every send, in order.
  • "latest": only the newest overlapping send runs; the others still save their user messages.
  • "merge": overlapping sends' user messages become one user message, answered once.
  • "drop": overlapping sends are rejected (the client rolls them back).
  • Debounce(seconds): like "latest", after a quiet window.

Regenerations and programmatic turns (save_messages) always queue.

Duration = timedelta | float

A length of time: a timedelta, or a number of seconds.

JSONValue = bool | int | float | str | list[JSONValue] | dict[str, JSONValue] | None

A value JSON can represent.

SqlValue = int | float | str | bytes | None

A value SQLite accepts as a parameter.

FiberRecoveryResult = FiberCompleted | FiberErrored | FiberAborted | FiberInterrupted

How a recovery hook settles a managed fiber; None leaves it interrupted.

FiberStatus = Literal['pending', 'running', 'completed', 'aborted', 'interrupted', 'error']

A managed fiber's status. pending and running are live; the rest are terminal (interrupted: the isolate died mid-run and recovery found it).

HarnessEvent = SessionSnapshot | OperationEvent | RunStartEvent | RunEndEvent | ChunkEvent | MessageEvent | ResetEvent

What watch yields.

HarnessInput = str | Sequence[InputPart] | Sequence[ToolAnswer]

What an operation carries: a user message (text, or parts), or answers to tool requests.

InputPart = TextInput | FileInput

One part of a user message.

OperationStatus = Literal['queued', 'running', 'done', 'needs_input', 'unanswered', 'aborted']

queued and running are open; the rest are settled. needs_input means the turn stopped on tool calls the client must answer with new operations.

Replay = Literal['safe', 'unsafe']

Whether a tool may run again after a crash interrupted it.

ToolAnswer = Approval | ToolOutput

An answer to one of a needs_input result's requests.

WhenBusy = Literal['queue', 'reject']

What submit does when the session has open work: queue behind it, or raise SessionBusyError.

JobOutcome = Reschedule | Literal['yield'] | None

What an owner returns after running a job.

None completes (deletes) it, Reschedule suspends it until a later time, and "yield" leaves it due so it runs again on the next wake. A same-id push or reschedule made during dispatch wins over the returned outcome.

LifecycleStatus = Literal['zero', 'starting', 'started']

"zero" before startup, "starting" while it runs, "started" after.

CompletionEvent = TextDelta | ReasoningDelta | ToolCallDelta | Usage

What WorkersAIModel.stream yields; Usage counts the whole request.

ContentPart = TextContentPart | ImageContentPart

One part of a user message's content list.

ScheduleType = Literal['scheduled', 'delayed', 'cron', 'interval']

"scheduled" runs once at a time, "delayed" once after a delay, "cron" on a cron expression, "interval" at a fixed interval.

SessionChangeEvent = AppendEvent | UpdateEvent | DeleteEvent | ClearEvent

What the change feed delivers, after the write has committed.

SessionChangeListener = Callable[[SessionChangeEvent], Awaitable[None] | None]

A change-feed listener, sync or async.

Source = Literal['server', 'client']

Who a write came from; "client" writes lose the reserved metadata keys.

StateSource = Connection | Literal['server']

Where a change came from: "server" for host code, or the connection a client's change arrived on.

StreamState = Literal['streaming', 'completed', 'errored']

streaming from open() until the producer settles it; both terminal states keep the chunk log readable.

TaskRun = PendingRun | RunningRun | WaitingRun | CompletedRun[Out] | FailedRun | CancelledRun

A snapshot of one run; narrow it with match or isinstance.

TaskRunState = Literal['pending', 'running', 'waiting', 'completed', 'failed', 'cancelled']

pending (accepted), running (an attempt is executing), waiting (parked on a sleep or retry deadline), then completed, failed, or cancelled.

Agent

Bases: Generic[S], DurableObject

A Durable Object with state, client connections, RPC, and a queue.

Subclass it, override the on_* hooks you need, and mark methods clients may call with @callable. Extra capabilities are installed in __init__ with use.

Class attributes

initial_state The state seeded the first time nothing is stored (each agent gets its own copy). options Per-class settings (AgentOptions). observability Where events go (default: JSON lines on agents.events at DEBUG); None disables them.

initial_state = None class-attribute instance-attribute

options = AgentOptions() class-attribute instance-attribute

observability = LoggingObservability() class-attribute instance-attribute

tasks = Tasks(target=self, on_error=self._callback_failed) instance-attribute

Durable, replayable background work (@task methods and more).

name property

The instance name (idFromName / getByName).

parent_path property

The agents above this one, root first (empty on a top-level agent).

self_path property

The path from the root to this agent, root first.

dynamic_agents property

The agent's sub-agents (facets): get, abort, delete, ...

lifecycle property

The Lifecycle the agent's capabilities are installed on.

websockets property

The installed WebSockets capability serving the agent's connections.

Components that share the agent's sockets add their handlers with websockets.use(...); they run before on_message and can claim a frame.

session_affinity property

A stable, unique key for this instance (e.g. for Workers AI).

sql property

Typed SQL over the agent's database.

state property

The current state (treat it as read-only; change it with set_state).

mcp property

The MCP client: servers, their catalog, and calls.

Raises:

Type Description
MCPNotEnabledError

If the agent's options don't turn MCP on.

__init__(ctx, env)

__init_subclass__(**kwargs)

Wrap a subclass's public methods so they run as the current agent.

parent_agent(cls) async

Return a stub for this sub-agent's direct parent.

Raises:

Type Description
RuntimeError

If this agent isn't a sub-agent.

TypeError

If cls isn't the parent's class.

use(capability)

Install a capability (before startup) and return it.

on_start() async

Run once per wake, after capabilities start and before any event.

on_request(request) async

Handle an HTTP request no capability claimed (default: 404).

on_connect(connection, ctx) async

Handle a new connection (after its protocol frames were sent).

on_message(connection, message) async

Handle a frame the SDK didn't consume.

on_close(connection, code, reason, was_clean) async

Handle a client closing its connection.

on_error(connection, error) async

Handle an error from a hook or a connection (default: re-raise).

connection is set only for a connection's own error event. Returning normally handles the error: a failed request gets a 500, a failed connect or message leaves the connection open. Some errors are reported here without being handled (on_start, on_state_changed, queued callbacks); raising then changes nothing.

on_before_sub_agent(request, child) async

Gate a request to a sub-agent (/sub/{class}/{name}/...).

Return a Response to answer it instead (e.g. 404), a Request to forward that instead (its headers and body; the sub-agent's path stays the tail), or None to forward it. Default: allow.

on_alarm() async

Run on every alarm, after due jobs (rarely needed: use the queue).

on_fiber_recovered(ctx) async

Recover a fiber whose isolate died mid-run (default: log a warning).

Runs on the next wake, before on_start. ctx.snapshot is the fiber's last stash(). For a managed fiber, return a result to settle its record; None leaves it interrupted. Raising keeps a plain fiber for a later retry (until fiber_recovery_max_age) and marks a managed one error.

get_connection_tags(connection, ctx) async

Return the tags to accept a new connection under (at most 9).

should_connection_be_readonly(connection, ctx) async

Decide whether a new connection may change the state.

should_send_protocol_messages(connection, ctx) async

Decide whether a new connection gets protocol frames at all.

validate_state_change(next_state, source)

Raise to reject a state change (synchronous; default: accept).

on_state_changed(state, source) async

Run after a state change is saved and broadcast.

set_state(state)

Replace the state: validate, save, broadcast, then on_state_changed.

Raises:

Type Description
ReadonlyConnectionError

If called while serving a readonly connection.

Exception

Whatever validate_state_change raises, rejecting the change.

get_connections(tag=None)

Yield the open connections, optionally only those with tag.

get_connection(id)

Return the open connection with id, or None.

Raises:

Type Description
DuplicateConnectionIdError

If more than one open connection has that id.

broadcast(message, *, exclude=())

Send message to every open connection, except exclude.

An id excludes every connection with that id; a Connection excludes exactly that one.

get_callable_methods()

Return the @callable methods clients may call, by name.

schedule(when, callback, payload=None, *, retry=None, idempotent=None) async

Schedule callback(payload, schedule).

Parameters:

Name Type Description Default
when datetime | timedelta | float | str

A datetime runs it once then; a timedelta or number of seconds once after that delay; a str on that cron expression (UTC).

required
callback str | Callable[..., Any]

A method of this agent, or its name.

required
payload JSONValue

JSON data passed to the callback.

None
retry RetryOptions | None

Overrides options.retry for this schedule.

None
idempotent bool | None

Reuse a matching existing schedule instead of adding another (default: yes for cron, no for one-shots).

None

schedule_every(interval, callback, payload=None, *, retry=None, idempotent=None) async

Run callback(payload, schedule) every interval (at most 30 days).

A run still in progress when the next is due is skipped, unless it's older than options.hung_schedule_timeout.

get_schedule_by_id(id) async

Return one schedule, or None.

list_schedules(*, id=None, type=None, start=None, end=None) async

Return schedules, optionally filtered by id, type, or next run time.

cancel_schedule(id) async

Cancel one schedule; return whether it existed.

queue(callback, payload=None, *, retry=None, id=None) async

Queue callback(payload, item) to run soon, in order; return the id.

Parameters:

Name Type Description Default
callback str | Callable[..., Any]

A method of this agent, or its name.

required
payload JSONValue

JSON data passed to the callback.

None
retry RetryOptions | None

Overrides options.retry for this item.

None
id str | None

A stable id; pushing it again replaces the pending item.

None

dequeue(id) async

Cancel one queued item; return whether it existed.

dequeue_all() async

Cancel every queued item; return how many.

dequeue_all_by_callback(callback) async

Cancel every queued item for callback; return how many.

get_queue(id) async

Return one queued item, or None.

queue_items(callback=None) async

Return the queued items in order, optionally for one callback.

run_fiber(name, fn) async

Run fn as a fiber: if the isolate dies, it's recovered on wake.

fn gets a FiberContext; checkpoint with ctx.stash(data) (or stash), and on_fiber_recovered receives the last one. The agent stays in memory while it runs. Errors propagate; there are no retries.

stash(data)

Checkpoint the current fiber, replacing its previous snapshot.

data must be JSON-serializable; it's saved before this returns.

Raises:

Type Description
RuntimeError

If called outside a fiber.

start_fiber(name, fn, *, fiber_id=None, idempotency_key=None, metadata=None, wait_for_completion=False) async

Start a managed fiber: a fiber with a record you can inspect.

A fiber_id or idempotency_key that matches an existing fiber returns it with accepted=False instead of starting another. The body runs in the background (its return value is discarded); with wait_for_completion, this returns once the fiber has finished.

Raises:

Type Description
ValueError

If fiber_id or idempotency_key is blank.

FiberConflictError

If they name different existing fibers.

FiberNotFoundError

If the fiber is deleted while waiting for it.

inspect_fiber(fiber_id) async

Return a managed fiber's record, or None.

inspect_fiber_by_key(idempotency_key) async

Return the managed fiber with idempotency_key, or None.

list_fibers(*, status=None, name=None, limit=None) async

Return managed fibers, newest first (default 50, at most 100).

cancel_fiber(fiber_id, reason=None) async

Abort a live managed fiber; False if it's unknown or finished.

Its record turns aborted; a body running here gets CancelledError at its next await.

cancel_fiber_by_key(idempotency_key, reason=None) async

cancel_fiber the managed fiber with idempotency_key.

resolve_fiber(fiber_id, result) async

Settle an interrupted managed fiber; False for any other.

delete_fibers(*, status=None, settled_before=None, limit=None) async

Delete finished managed-fiber records and return how many.

By default completed, error, and aborted ones (at most 100); interrupted records are deleted only when asked for.

add_mcp_server(name, url, *, id=None, headers=None, transport='auto', callback_host=None, callback_path=None, agents_prefix='agents', retry=None) async

Register an MCP server, connect to it and load its catalog.

Idempotent: the same name and URL return the existing server. When the server needs OAuth, the result is authenticating with the URL to send the user to; the callback finishes the connection.

Parameters:

Name Type Description Default
name str

A display name.

required
url str

The server's Streamable HTTP endpoint.

required
id str | None

A stable id (normalized); by default a random one.

None
headers Mapping[str, str] | None

Sent on every request (bearer tokens, Cloudflare Access), and stored with the server.

None
transport TransportType

auto or streamable-http.

'auto'
callback_host str | None

The OAuth callback's origin; by default the current request's or connection's.

None
callback_path str | None

The callback's path instead of /{agents_prefix}/{agent}/{name}/callback. Required with send_identity_on_connect=False and a callback_host.

None
agents_prefix str

The routing prefix in the default callback path.

'agents'
retry RetryOptions | None

Connection retries when the server is restored.

None

Raises:

Type Description
ValueError

If callback_path is required and missing.

MCPNotEnabledError

If MCP isn't on.

(MCPServerIdConflictError, MCPBlockedUrlError, MCPConnectionError)

As MCPClientManager.add_server.

remove_mcp_server(id) async

Close an MCP server's connection and delete it and its OAuth state.

Raises:

Type Description
MCPNotEnabledError

If MCP isn't on.

get_mcp_servers()

Return what the cf_agent_mcp_servers frame carries.

Raises:

Type Description
MCPNotEnabledError

If MCP isn't on.

create_mcp_oauth_provider(callback_url)

Return the OAuth provider for an MCP server's callback URL.

Override for pre-registered client credentials or another flow. The default registers dynamically and keeps tokens in the agent's storage.

on_mcp_oauth_callback(result, request) async

Handle the end of an MCP OAuth callback (after every one).

Return a Response to replace the default redirect. result.error can contain text from the OAuth provider: escape it before showing it.

keep_alive() async

Keep the agent in memory until the returned handle is disposed.

The alarm fires every keep_alive_interval meanwhile (on a sub-agent, the root's alarm). Prefer keep_alive_while.

keep_alive_while(fn) async

Run fn keeping the agent in memory, however fn ends.

destroy() async

Delete the agent: its storage, alarm, and connections.

The object resets right after this returns; don't use it again. A teardown cut short is finished on the next wake. On a sub-agent, the root deletes it, which may abort this call (fire-and-forget).

__fetch(request) async

__alarm(*_args) async

__websocket_message(ws, message) async

__websocket_close(ws, code, reason, was_clean) async

__websocket_error(ws, error) async

__ensure_initialized() async

MCPNotEnabledError

Bases: AgentsException

An MCP member was used on an agent without AgentOptions(mcp=...).

__init__()

ReadonlyConnectionError

Bases: AgentsException

set_state was called while serving a readonly connection.

__init__()

AgentOptions dataclass

Per-class settings for an agent (options = AgentOptions(...)).

Frozen, because one instance is shared by every agent of the class. A subclass's options replaces its parent's; extend them with dataclasses.replace(Parent.options, ...). Durations are a timedelta or a number of seconds.

Parameters:

Name Type Description Default
send_identity_on_connect bool

Send the cf_agent_identity frame (with the instance name) when a client connects.

True
hung_schedule_timeout Duration

When a running interval schedule counts as hung and is reset.

30
keep_alive_interval Duration

The keep_alive() heartbeat interval.

30
retry RetryOptions

Default retries for queued and scheduled callbacks.

RetryOptions()
fiber_recovery_hook_timeout Duration

Timeout for framework fiber-recovery hooks.

10
fiber_recovery_scan_deadline Duration

Soft deadline for one fiber-recovery scan.

10
fiber_recovery_max_age Duration | None

When to give up on an interrupted fiber whose recovery keeps failing (None keeps trying forever).

timedelta(hours=24)
max_alarm_memory_limit_strikes int

Alarm memory-limit resets tolerated before recovery work is sealed.

3
expose_error_details bool

Send an unhandled error's traceback to the client (local development only: tracebacks can reveal code and data).

False
mcp MCPOptions | None

Installs the MCP client (self.mcp, add_mcp_server). None leaves it out; an agent with stored servers needs it to restore them.

None

send_identity_on_connect = True class-attribute instance-attribute

hung_schedule_timeout = 30 class-attribute instance-attribute

keep_alive_interval = 30 class-attribute instance-attribute

retry = field(default_factory=RetryOptions) class-attribute instance-attribute

fiber_recovery_hook_timeout = 10 class-attribute instance-attribute

fiber_recovery_scan_deadline = 10 class-attribute instance-attribute

fiber_recovery_max_age = timedelta(hours=24) class-attribute instance-attribute

max_alarm_memory_limit_strikes = 3 class-attribute instance-attribute

expose_error_details = False class-attribute instance-attribute

mcp = None class-attribute instance-attribute

__init__(*, send_identity_on_connect=True, hung_schedule_timeout=30, keep_alive_interval=30, retry=RetryOptions(), fiber_recovery_hook_timeout=10, fiber_recovery_scan_deadline=10, fiber_recovery_max_age=timedelta(hours=24), max_alarm_memory_limit_strikes=3, expose_error_details=False, mcp=None)

CurrentAgent dataclass

Bases: Generic[A]

The agent the running code belongs to, and what it's running for.

Parameters:

Name Type Description Default
agent A

The agent.

required
connection Connection | None

The client connection being served, if any.

None
request Request | None

The HTTP request (or WebSocket upgrade) being served, if any.

None

agent instance-attribute

connection = None class-attribute instance-attribute

request = None class-attribute instance-attribute

__init__(*, agent, connection=None, request=None)

MCPOptions dataclass

Turns on the MCP client (AgentOptions(mcp=MCPOptions())).

Parameters:

Name Type Description Default
client_name str | None

Sent to servers as the client's name. None uses the agent's class name.

None
client_version str | None

Sent to servers as the client's version. None uses the cf-agents version.

None
discovery_timeout Duration

How long listing a server's tools, prompts and resources may take after it connects.

15
oauth_success_redirect str | None

Where the OAuth callback redirects after a successful authorization, resolved against the request's origin.

None
oauth_error_redirect str | None

Where it redirects after a failed one, with ?error=<message>.

None

client_name = None class-attribute instance-attribute

client_version = None class-attribute instance-attribute

discovery_timeout = 15 class-attribute instance-attribute

oauth_success_redirect = None class-attribute instance-attribute

oauth_error_redirect = None class-attribute instance-attribute

__init__(*, client_name=None, client_version=None, discovery_timeout=15, oauth_success_redirect=None, oauth_error_redirect=None)

RoutingRetryEvent dataclass

Passed to RoutingRetryOptions.on_retry before each backoff.

error instance-attribute

attempt instance-attribute

max_attempts instance-attribute

delay instance-attribute

name instance-attribute

class_name instance-attribute

None from get_agent_by_name, as upstream.

__init__(*, error, attempt, max_attempts, delay, name, class_name)

RoutingRetryOptions dataclass

Retries for reaching an agent, on errors the platform marks transient.

Parameters:

Name Type Description Default
max_attempts int

Total attempts, including the first.

3
base_delay Duration

The backoff's base delay.

0.1
max_delay Duration

The longest wait between attempts.

0.8
on_retry Callable[[RoutingRetryEvent], Awaitable[None]] | None

Called before each backoff; a failure is logged and ignored.

None

max_attempts = 3 class-attribute instance-attribute

base_delay = 0.1 class-attribute instance-attribute

max_delay = 0.8 class-attribute instance-attribute

on_retry = None class-attribute instance-attribute

__init__(*, max_attempts=3, base_delay=0.1, max_delay=0.8, on_retry=None)

AIChatAgent

Bases: Agent[S]

An agent that answers chat messages, streaming its replies to clients.

Override on_chat_message to produce each reply. The transcript is self.messages; change it with persist_messages, save_messages, and delete_messages. Settings go in options (AIChatAgentOptions).

Attributes:

Name Type Description
sessions

The Sessions the transcript is stored in (the default session).

streams

The Streams each turn's output is stored in.

options = AIChatAgentOptions() class-attribute instance-attribute

sessions = self.use(Sessions()) instance-attribute

streams = self.use(create_chat_streams()) instance-attribute

messages property

The conversation, oldest first (read-only).

After a wake it holds the newest stored messages that fit options.hydration_byte_budget. Don't mutate the messages: change the transcript with persist_messages, save_messages, or delete_messages.

__init__(ctx, env)

on_chat_message(options)

Produce the reply to the conversation in self.messages.

Write it as an async generator yielding chunks (agents.chat.chunks) or plain str text, not both. The SDK sends Start and Finish if the stream doesn't. A delta or end chunk must follow its start (TextStart, ReasoningStart, ToolInputStart with the same id), or the turn fails with TypeError: clients reject it. An Error chunk or an exception ends the turn as failed. A cancelled turn gets CancelledError at its next await. An async def returning an async iterator also works.

on_chat_response(result) async

Run after a turn's message is saved (any outcome but skipped).

The turn queue is free by then, so this may call save_messages; turns started from here don't call it again.

sanitize_message_for_persistence(message)

Return message as it should be stored (default: unchanged).

Runs after the SDK's own cleanup, on every message saved.

repair_interrupted_tool_part(part)

Return what replaces a tool call left without a result.

Before each turn, a tool call that never settled (its turn was interrupted) is replaced, so the model isn't sent a call without a result. Default: an output-error part saying it was interrupted. Calls still waiting on the client are left alone.

persist_messages(messages, *, exclude=()) async

Store messages as the transcript, without starting a turn.

messages is the intended transcript (typically [*self.messages, new]). It's reconciled with what's stored, only changed messages are written, and stored messages left out aren't deleted. Every client but exclude is sent the result. May be overridden (call super()).

save_messages(messages) async

Store messages, then run a turn to answer them.

Waits for any running turn. messages may be an async def given the current messages when the turn starts. The turn uses the last request's client tools and body. Cancelling the caller stops the turn (its partial reply is still saved) and raises CancelledError.

continue_last_turn(*, body=None) async

Run a turn that continues the last assistant message.

on_chat_message gets continuation=True and its output is appended to that message. body replaces the last request's body for this turn. skipped if there's no assistant message. Cancelling the caller stops the turn, as for save_messages.

delete_messages(message_ids, *, exclude=()) async

Delete messages by id and send clients the result (unknown ids are ignored).

Doesn't wait for a running turn; deleting the message a turn is still streaming has no lasting effect (stop the turn first).

abort_request(request_id)

Stop a running turn, as a client's stop would (no-op if not running).

The turn ends as aborted; its partial reply is saved.

abort_all_requests()

Stop every running turn (queued turns still run).

reset_turn_state()

Stop the running turn and drop queued ones (done on a chat clear).

ChatStreamError

Bases: AgentsException

A turn's stream reported an error (an Error chunk), ending the turn.

on_error receives it for a turn that failed that way; error_text is what the client was sent.

error_text = error_text instance-attribute

__init__(error_text)

ChatMessageOptions dataclass

What on_chat_message gets about the turn it answers.

Parameters:

Name Type Description Default
request_id str

The turn's request id.

required
client_tools Sequence[ClientToolSchema]

Tools the browser runs; a call to one is sent back to the client.

()
body dict[str, JSONValue] | None

Extra fields from the client's request body.

None
continuation bool

True when the turn continues the last assistant message rather than answering a new user message (after a client tool result or approval, continue_last_turn, or recovery).

False

request_id instance-attribute

client_tools = () class-attribute instance-attribute

body = None class-attribute instance-attribute

continuation = False class-attribute instance-attribute

__init__(*, request_id, client_tools=(), body=None, continuation=False)

ClientToolSchema dataclass

A tool the browser runs, as its client sent it (JSON Schema parameters).

name instance-attribute

description = None class-attribute instance-attribute

parameters = None class-attribute instance-attribute

__init__(*, name, description=None, parameters=None)

DataPart dataclass

App data; its wire type is data-{name}.

name instance-attribute

data instance-attribute

id = None class-attribute instance-attribute

__init__(*, name, data, id=None)

FilePart dataclass

A file (url may be a data: URL).

type = 'file' class-attribute

url instance-attribute

media_type = wire('mediaType') class-attribute instance-attribute

filename = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, url, media_type=wire('mediaType'), filename=None, provider_metadata=wire('providerMetadata', None))

ReasoningPart dataclass

The model's reasoning.

type = 'reasoning' class-attribute

text instance-attribute

id = None class-attribute instance-attribute

state = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, text, id=None, state=None, provider_metadata=wire('providerMetadata', None))

SourceDocumentPart dataclass

A cited document.

type = 'source-document' class-attribute

source_id = wire('sourceId') class-attribute instance-attribute

media_type = wire('mediaType') class-attribute instance-attribute

title instance-attribute

filename = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, source_id=wire('sourceId'), media_type=wire('mediaType'), title, filename=None, provider_metadata=wire('providerMetadata', None))

SourceUrlPart dataclass

A cited web source.

type = 'source-url' class-attribute

source_id = wire('sourceId') class-attribute instance-attribute

url instance-attribute

title = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, source_id=wire('sourceId'), url, title=None, provider_metadata=wire('providerMetadata', None))

StepStartPart dataclass

The start of a model step.

type = 'step-start' class-attribute

__init__()

TextPart dataclass

Text in a message.

type = 'text' class-attribute

text instance-attribute

state = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, text, state=None, provider_metadata=wire('providerMetadata', None))

ToolApproval dataclass

A tool call's approval: approved is None until answered.

id instance-attribute

approved = None class-attribute instance-attribute

reason = None class-attribute instance-attribute

descriptor = None class-attribute instance-attribute

signature = None class-attribute instance-attribute

input_schema_input = wire('inputSchemaInput', None) class-attribute instance-attribute

__init__(*, id, approved=None, reason=None, descriptor=None, signature=None, input_schema_input=wire('inputSchemaInput', None))

ToolApprovalRequestedPart dataclass

Bases: ToolPart

The tool call waits for the user's approval.

state = 'approval-requested' class-attribute

input instance-attribute

approval instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input, approval)

ToolApprovalRespondedPart dataclass

Bases: ToolPart

The user approved or denied the tool call; it hasn't finished.

state = 'approval-responded' class-attribute

input instance-attribute

approval instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input, approval)

ToolInputAvailablePart dataclass

Bases: ToolPart

The tool call's input is complete; it hasn't run yet.

state = 'input-available' class-attribute

input instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input)

ToolInputStreamingPart dataclass

Bases: ToolPart

The tool call's input is still streaming.

state = 'input-streaming' class-attribute

input = None class-attribute instance-attribute

The partial input parsed so far.

raw_input = wire('rawInput', None) class-attribute instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input=None, raw_input=wire('rawInput', None))

ToolOutputAvailablePart dataclass

Bases: ToolPart

The tool call finished with output.

state = 'output-available' class-attribute

input instance-attribute

output instance-attribute

result_provider_metadata = wire('resultProviderMetadata', None) class-attribute instance-attribute

preliminary = None class-attribute instance-attribute

approval = None class-attribute instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input, output, result_provider_metadata=wire('resultProviderMetadata', None), preliminary=None, approval=None)

ToolOutputDeniedPart dataclass

Bases: ToolPart

The user denied the tool call.

state = 'output-denied' class-attribute

input instance-attribute

approval instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input, approval)

ToolOutputErrorPart dataclass

Bases: ToolPart

The tool call failed.

state = 'output-error' class-attribute

input = None class-attribute instance-attribute

raw_input = wire('rawInput', None) class-attribute instance-attribute

error_text = wire('errorText') class-attribute instance-attribute

result_provider_metadata = wire('resultProviderMetadata', None) class-attribute instance-attribute

approval = None class-attribute instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None), input=None, raw_input=wire('rawInput', None), error_text=wire('errorText'), result_provider_metadata=wire('resultProviderMetadata', None), approval=None)

ToolPart dataclass

Fields every tool part has; isinstance(part, ToolPart) means "a tool".

The wire type is tool-{tool_name}, or dynamic-tool when dynamic; each subclass is one state.

state class-attribute

tool_name = wire('toolName') class-attribute instance-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

dynamic = False class-attribute instance-attribute

title = None class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

tool_metadata = wire('toolMetadata', None) class-attribute instance-attribute

call_provider_metadata = wire('callProviderMetadata', None) class-attribute instance-attribute

__init__(*, tool_name=wire('toolName'), tool_call_id=wire('toolCallId'), dynamic=False, title=None, provider_executed=wire('providerExecuted', None), tool_metadata=wire('toolMetadata', None), call_provider_metadata=wire('callProviderMetadata', None))

UIMessage dataclass

A chat message (the AI SDK's UIMessage).

id instance-attribute

role instance-attribute

parts = field(default_factory=list) class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, id, role, parts=list(), metadata=None)

UnknownPart dataclass

A part the models don't know, kept exactly as stored.

A newer AI SDK's part type, or a known one missing a required field. It's saved back unchanged.

fields instance-attribute

type property

The part's wire type, if it has one.

__init__(*, fields)

AIChatAgentOptions dataclass

Bases: AgentOptions

Per-class settings for a chat agent (options = AIChatAgentOptions(...)).

Extends AgentOptions; see it for the agent-wide settings.

Parameters:

Name Type Description Default
message_concurrency MessageConcurrency

What a send does while another turn is running (MessageConcurrency).

'queue'
max_persisted_messages int | None

Keep at most this many stored messages, deleting the oldest after each save (None: no limit). Storage only: what the model sees is up to on_chat_message.

None
hydration_byte_budget int | None

How many bytes of the newest stored messages self.messages holds after a wake (None: all of them). The full history stays stored and is what get-messages serves.

32 * 1024 * 1024
wait_for_mcp_connections bool | Duration

Before each on_chat_message, wait for MCP servers that are still connecting after a wake: True waits as long as it takes, a duration bounds the wait. Needs mcp=MCPOptions().

False

message_concurrency = 'queue' class-attribute instance-attribute

max_persisted_messages = None class-attribute instance-attribute

hydration_byte_budget = 32 * 1024 * 1024 class-attribute instance-attribute

wait_for_mcp_connections = False class-attribute instance-attribute

__init__(*, send_identity_on_connect=True, hung_schedule_timeout=30, keep_alive_interval=30, retry=RetryOptions(), fiber_recovery_hook_timeout=10, fiber_recovery_scan_deadline=10, fiber_recovery_max_age=timedelta(hours=24), max_alarm_memory_limit_strikes=3, expose_error_details=False, mcp=None, message_concurrency='queue', max_persisted_messages=None, hydration_byte_budget=32 * 1024 * 1024, wait_for_mcp_connections=False)

ChatResponseResult dataclass

A finished turn, as on_chat_response receives it.

Parameters:

Name Type Description Default
message UIMessage

The assistant message the turn produced (as saved).

required
request_id str

The turn's request id.

required
continuation bool

Whether the turn continued the previous assistant message.

required
status Literal['completed', 'error', 'aborted']

How it ended.

required
error str | None

The error's message, when status is error.

None

message instance-attribute

request_id instance-attribute

continuation instance-attribute

status instance-attribute

error = None class-attribute instance-attribute

__init__(*, message, request_id, continuation, status, error=None)

Debounce dataclass

Run only the newest of overlapping sends, once none came for seconds.

Raises:

Type Description
ValueError

If seconds is negative or not finite.

seconds = 0.75 class-attribute instance-attribute

__post_init__()

__init__(seconds=0.75)

SaveMessagesResult dataclass

How a turn started by save_messages or continue_last_turn ended.

skipped: the chat was cleared before it ran (or, for continue_last_turn, there was no assistant message). error carries the error's message.

request_id instance-attribute

status instance-attribute

error = None class-attribute instance-attribute

__init__(*, request_id, status, error=None)

AgentsException

Bases: Exception

Base class for every exception the SDK raises on purpose.

SqlError

Bases: AgentsException

A SQL statement failed.

Port of upstream sql-error.ts.

Parameters:

Name Type Description Default
query str

The statement that failed.

required
message str

SQLite's error message.

required

query = query instance-attribute

__init__(query, message)

Disposable

A handle that releases one resource. Calling dispose() again does nothing.

__slots__ = ('_release',) class-attribute instance-attribute

__init__(release)

dispose()

Release the resource; calls after the first do nothing.

Sql

Run SQL statements against one Durable Object's SQLite database.

Parameters:

Name Type Description Default
storage Any

The Durable Object's ctx.storage, wrapped by the Workers SDK or raw.

required

Examples:

>>> rows = sql("SELECT id, age FROM users WHERE id = ?", user_id)
>>> users = sql("SELECT id, age FROM users WHERE id = ?", user_id, row=User)

__slots__ = ('_exec',) class-attribute instance-attribute

__init__(storage)

__call__(query, *params, row=None)

__call__(query: LiteralString, *params: SqlValue) -> Sequence[dict[str, Any]]
__call__(query: LiteralString, *params: SqlValue, row: type[R]) -> Sequence[R]

Run query and return its rows.

Parameters:

Name Type Description Default
query LiteralString

A literal SQL statement, with ? placeholders for values.

required
*params SqlValue

One value per placeholder.

()
row type[Mapping[str, Any]] | None

The type to annotate each row with, e.g. a TypedDict. Static only: rows aren't validated.

None

Returns:

Type Description
list

One dict per row; BLOB columns as bytes. Empty for statements that return no rows.

Raises:

Type Description
SqlError

If SQLite rejects the statement.

TypeError

If a parameter isn't a SqlValue.

ValueError

If an integer parameter is outside SQLite's safe range (±2**53).

RetryOptions dataclass

How many times to try an operation, and how long to wait between tries.

The wait before each retry is random, up to min(2 ** attempt * base_delay, max_delay) ("full jitter").

Parameters:

Name Type Description Default
max_attempts int

Total attempts, including the first.

3
base_delay Duration

The backoff's base delay.

0.1
max_delay Duration

The longest wait between attempts.

3.0

max_attempts = 3 class-attribute instance-attribute

base_delay = 0.1 class-attribute instance-attribute

max_delay = 3.0 class-attribute instance-attribute

__init__(*, max_attempts=3, base_delay=0.1, max_delay=3.0)

DynamicAgents

An agent's sub-agents: children with their own isolate and SQLite.

A sub-agent runs on the same machine as its parent, which supervises it. The class must be exported from the Worker module under its own name; it needs no binding or migration.

Parameters:

Name Type Description Default
engine SubAgentsEngine

The agent's sub-agents engine.

required

__slots__ = ('_engine',) class-attribute instance-attribute

__init__(engine)

get(cls, name) async

Return sub-agent cls/name, creating it on first use.

Its on_start runs the first time. Returns a stub: await stub.method(...).

Raises:

Type Description
ValueError

If the class isn't exported from the Worker, is named so it kebab-cases to sub, or the name contains NUL.

abort(cls, name, reason=None)

Stop a sub-agent now; pending calls get reason.

It restarts on the next get, with its storage. Its own sub-agents stop too. The default reason is a SubAgentAbortedError.

delete(cls, name) async

Delete a sub-agent and its storage, and its own sub-agents.

Its clients are disconnected, and its routed schedules, queue items, and task runs are cancelled. Deleting a sub-agent that doesn't exist does nothing.

has(cls, name)

Return whether this agent created sub-agent cls/name.

list(cls=None)

Return the sub-agents this agent created, oldest first.

SubAgentAbortedError

Bases: AgentsException

A sub-agent was aborted (dynamic_agents.abort) while a call was pending.

The default reason abort raises in pending callers.

AgentStub

A stub for one agent; every attribute is an async RPC method.

Parameters:

Name Type Description Default
stub Any

The runtime's stub (a facet or a Durable Object stub).

required

__slots__ = ('_stub',) class-attribute instance-attribute

__init__(stub)

__getattr__(method)

Return an async function calling method on the agent.

fetch(request) async

Send an HTTP request to the agent's fetch.

AgentPathStep

Bases: NamedTuple

One agent in a path from the root: its class name and instance name.

class_name instance-attribute

name instance-attribute

AgentRoute

Bases: NamedTuple

Which agent instance a request is for.

class_name instance-attribute

The class name: the env binding name from route_agent_request, the sub-agent's class for on_before_sub_agent.

name instance-attribute

The instance name.

SubAgentInfo dataclass

A sub-agent a parent has created (from its registry).

class_name instance-attribute

name instance-attribute

created_at instance-attribute

__init__(*, class_name, name, created_at)

FiberConflictError

Bases: AgentsException

fiber_id and idempotency_key name different existing fibers.

fiber_id = fiber_id instance-attribute

idempotency_key = idempotency_key instance-attribute

__init__(fiber_id, idempotency_key)

FiberNotFoundError

Bases: AgentsException

A fiber was deleted while start_fiber waited for it to finish.

fiber_id = fiber_id instance-attribute

__init__(fiber_id)

Fibers

Bases: LifecycleCapability

Fibers and managed fibers, with recovery of interrupted ones.

Parameters:

Name Type Description Default
keep_alive KeepAlive

The lease every running fiber holds, so the object stays in memory.

required
on_recovered FiberRecoveryHandler

The recovery hook, run in the host context; for a managed fiber, a returned result settles its record.

required
internal_recovery InternalFiberRecoveryHandler | None

A framework hook that runs first, under hook_timeout; returning True skips on_recovered.

None
hook_timeout Duration

The time limit for internal_recovery (0 or less: none).

10
scan_deadline Duration

A soft limit on one recovery scan; the rest waits for the next.

10
max_age Duration | None

How long recovery retries a plain fiber whose hook keeps failing (None: forever).

timedelta(hours=24)
housekeeping_interval Duration

How often the root checks pending recovery and its facets' fibers.

30

__init__(keep_alive, *, on_recovered, internal_recovery=None, hook_timeout=10, scan_deadline=10, max_age=timedelta(hours=24), housekeeping_interval=30)

run(name, fn) async

Run fn as a fiber and return its result (errors propagate).

run_with_stash_wrapper(name, fn, wrap) async

Run a fiber whose snapshots are wrap(data), starting at wrap(None).

For chat turns, whose recovery snapshot wraps the user's.

start(name, fn, *, fiber_id=None, idempotency_key=None, metadata=None, wait_for_completion=False) async

Accept a managed fiber, or return the existing one it matches.

Raises:

Type Description
ValueError

If fiber_id or idempotency_key is blank.

FiberConflictError

If they name different existing fibers.

FiberNotFoundError

If the fiber is deleted while waiting for it.

inspect(fiber_id)

Return a managed fiber's record, or None.

inspect_by_key(idempotency_key)

Return the managed fiber with idempotency_key, or None.

list(*, status=None, name=None, limit=None)

Return managed fibers, newest first (default 50, at most 100).

cancel(fiber_id, reason=None)

Abort a live managed fiber; False if it's unknown or finished.

The record turns aborted and waiters are released; a fiber running here gets CancelledError at its next await.

cancel_by_key(idempotency_key, reason=None)

cancel the managed fiber with idempotency_key.

resolve(fiber_id, result)

Settle an interrupted managed fiber; False for any other.

delete(*, status=None, settled_before=None, limit=None)

Delete finished records (default: completed, error, aborted).

interrupted records are kept unless asked for. Returns how many were deleted (default at most 100, at most 500).

recover() async

Recover interrupted fibers: hand each one to the recovery hook.

One scan runs at a time; a second call while one runs returns at once.

recover_on_wake() async

Recover what a dead isolate left, then arm housekeeping.

The host calls this once per wake, after every capability has started and before its own startup code (Agent does it before on_start, as upstream), so the recovery hook can use any capability.

on_start() async

Create the tables once.

Recovery waits for recover_on_wake: the hook may use capabilities installed after this one, which haven't started yet.

on_job(context) async

Housekeeping: recover here, then visit facets with indexed fibers.

on_route(context) async

Index a facet's fiber (root), or recover on the root's request (facet).

KeepAlive

Bases: LifecycleCapability

Reference-counted heartbeats that keep the object from going idle.

Parameters:

Name Type Description Default
interval Duration

How often the heartbeat alarm fires while a lease is held.

30

active property

Whether any lease is held here (facet leases included, on the root).

__init__(*, interval=30)

acquire() async

Take a lease; dispose it when the work is done (idempotent).

keep_alive_while(fn) async

Run fn holding a lease, releasing it however fn ends.

on_start() async

Drop leases left by a previous isolate: the work holding them died.

Here that's a stale heartbeat; on a facet, the leases the root still holds for the facet's previous isolate.

on_job(context) async

Beat again while leases are held; otherwise let the job go.

on_route(context) async

Hold or release leases on behalf of facets (root only).

dispose() async

Forget every lease (the object is being destroyed).

FiberAborted dataclass

Recovery result: mark the managed fiber aborted.

reason = None class-attribute instance-attribute

snapshot = None class-attribute instance-attribute

__init__(*, reason=None, snapshot=None)

FiberCompleted dataclass

Recovery result: mark the managed fiber completed.

snapshot = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, snapshot=None, metadata=None)

FiberContext dataclass

What a fiber body receives.

Parameters:

Name Type Description Default
id str

The fiber's id (the managed fiber's fiber_id).

required
stash Callable[[Any], None]

Save a checkpoint (JSON-serializable), replacing the previous one. It's written before stash returns, and recovery receives it.

required

id instance-attribute

stash instance-attribute

__init__(*, id, stash)

FiberErrored dataclass

Recovery result: mark the managed fiber error.

error = None class-attribute instance-attribute

snapshot = None class-attribute instance-attribute

__init__(*, error=None, snapshot=None)

FiberInspection dataclass

A snapshot of one managed fiber's record.

fiber_id instance-attribute

name instance-attribute

status instance-attribute

created_at instance-attribute

idempotency_key = None class-attribute instance-attribute

snapshot = None class-attribute instance-attribute

error = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

started_at = None class-attribute instance-attribute

settled_at = None class-attribute instance-attribute

__init__(*, fiber_id, name, status, created_at, idempotency_key=None, snapshot=None, error=None, metadata=None, started_at=None, settled_at=None)

FiberInterrupted dataclass

Recovery result: leave the managed fiber interrupted, with a reason.

reason = None class-attribute instance-attribute

snapshot = None class-attribute instance-attribute

__init__(*, reason=None, snapshot=None)

FiberRecoveryContext dataclass

An interrupted fiber, as on_fiber_recovered sees it.

Parameters:

Name Type Description Default
id str

The fiber's id.

required
name str

The name it was started with.

required
snapshot Any

The last stash(), or None.

required
created_at datetime

When the fiber started.

required
recovery_reason Literal['interrupted']

Why it's being recovered (always "interrupted").

'interrupted'
status FiberStatus | None

Managed fibers only: the record's status ("interrupted").

None
idempotency_key str | None

Managed fibers only.

None
metadata dict[str, JSONValue] | None

Managed fibers only.

None

id instance-attribute

name instance-attribute

snapshot instance-attribute

created_at instance-attribute

recovery_reason = 'interrupted' class-attribute instance-attribute

status = None class-attribute instance-attribute

idempotency_key = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, id, name, snapshot, created_at, recovery_reason='interrupted', status=None, idempotency_key=None, metadata=None)

StartFiberResult dataclass

Bases: FiberInspection

The result of start_fiber.

accepted is False when an existing fiber matched the fiber_id or idempotency_key (not an error).

accepted instance-attribute

__init__(*, fiber_id, name, status, created_at, idempotency_key=None, snapshot=None, error=None, metadata=None, started_at=None, settled_at=None, accepted)

OperationNotFoundError

Bases: AgentsException

No operation in the session has this id.

session = session instance-attribute

operation_id = operation_id instance-attribute

__init__(session, operation_id)

SessionBusyError

Bases: AgentsException

A session has open work and the call refuses to queue behind it.

session = session instance-attribute

__init__(session)

SessionNotFoundError

Bases: AgentsException

No session has this id.

session = session instance-attribute

__init__(session)

Harness

Bases: LifecycleCapability

Runs an agent loop in a Durable Object, one turn at a time per session.

Install it like any capability: Lifecycle(self).use(harness) on a plain Durable Object (forward alarm to the Lifecycle), or self.use(harness) on an Agent. The base class stores sessions, operations, and each session's transcript, queues and dedupes submissions, publishes events, and resumes turns a crash interrupted. Subclasses implement run_turn.

Parameters:

Name Type Description Default
id str

The capability id; also keys this harness's rows, so two harnesses on one object need different ids.

required
target object | None

The object whose @tool methods are the tools (usually the host).

None
max_restarts int

How many times a crash-interrupted turn is resumed before its operation settles unanswered with reason "interrupted".

5
heartbeat Duration

How often a session with open work is checked; the longest a turn waits to resume after a crash when no request wakes the object.

30

Raises:

Type Description
ValueError

If max_restarts is negative or heartbeat isn't positive.

target = target instance-attribute

The object the tools were collected from.

sessions = HarnessSessions(self) instance-attribute

Creating, forking, and listing sessions.

tools property

The target's @tool methods, bound.

__init__(id, *, target=None, max_restarts=5, heartbeat=30)

run_turn(turn) async

Run one turn and return the session's new history and the reply.

Call turn.save after each step, with the reply's parts so far, so a resumed turn (checkpoint set) can skip finished work and an interrupted turn keeps its partial reply; call turn.emit with a ChunkEvent for each streamed piece of the reply. Raising settles the operation unanswered with the error as reason.

reset_history(handoff)

Return the history a session starts from after reset.

The default is an empty history. Override to carry the handoff note into the model's new context; the base class adds the note to the transcript as a system message either way.

session(id=_ROOT)

Return a handle on one session (default: the root session).

prompt(input) async

Submit to the root session and wait for the result.

on_start() async

Create the tables once, and wake every session with open work.

on_job(context) async

Run a session's wake job: resume its open work, or complete.

on_memory_limit(context) async

Settle running turns once the breaker seals; they'd only run out again.

dispose() async

Stop the drives; their turns resume on the next wake.

HarnessSession

One conversation: its history and its operations. No I/O until called.

Parameters:

Name Type Description Default
harness Harness

The owning harness.

required
id str

The session id ("" is the root session).

required

__slots__ = ('_harness', 'id') class-attribute instance-attribute

id = id instance-attribute

__init__(harness, id)

__repr__()

submit(input, *, operation_id=None, message_id=None, participant=None, when_busy='queue') async

Durably queue a user message or tool answers; returns before the turn runs.

Parameters:

Name Type Description Default
input HarnessInput

A prompt, message parts, or answers to a needs_input result's requests. Answers may arrive over several operations; the turn continues once every request has one, and the first answer to a request wins.

required
operation_id str | None

Dedupes retries: submitting an existing id stores nothing new and returns a receipt with accepted=False. Generated when omitted.

None
message_id str | None

The id of the user message this places in the transcript; the operation id when omitted.

None
participant str | None

Who sent it. The client tool calls of a turn belong to the participant who started it: a ToolOutput from anyone else settles unanswered with reason "not-owner".

None
when_busy WhenBusy

"queue" behind open work, or "reject" it.

'queue'

Raises:

Type Description
SessionBusyError

If when_busy="reject" and the session has open work.

TypeError

If input mixes message parts and tool answers.

ValueError

If input is an empty sequence.

wait(operation_id) async

Wait for an operation to settle and return its result.

Raises:

Type Description
OperationNotFoundError

If the session has no such operation.

prompt(input, *, operation_id=None) async

Submit and wait for the result.

pending() async

Return the open operations, oldest first.

abort(operation_id=None) async

Stop one open operation, or all of them; queued work behind runs.

retry(operation_id) async

Run an unanswered operation again, from its last checkpoint.

Raises:

Type Description
OperationNotFoundError

If the session has no such operation.

ValueError

If the operation isn't unanswered, or a later one has run.

reset(handoff=None) async

Start the session over: clear its history and transcript.

Watchers get a ResetEvent. A handoff note becomes the new transcript's first message (a system message), and Harness.reset_history decides the new history.

Raises:

Type Description
SessionBusyError

If the session has open work.

watch() async

Yield a SessionSnapshot, then every event, in order.

Cancel the iterating task, or close the iterator, to stop watching.

stream(input, *, operation_id=None) async

Submit, then yield this operation's events until it settles.

Resubmitting an operation_id that already settled yields nothing; call wait for its result.

HarnessSessions

Creating, forking, and listing a harness's sessions.

__slots__ = ('_harness',) class-attribute instance-attribute

__init__(harness)

create() async

Create an empty session.

fork(id) async

Create a session with a copy of session id's history and transcript.

Raises:

Type Description
SessionNotFoundError

If session id doesn't exist.

list() async

Return every session, oldest first.

Approval dataclass

The client's decision on a tool call that needs approval.

id instance-attribute

approved instance-attribute

message = None class-attribute instance-attribute

__init__(*, id, approved, message=None)

ChunkEvent dataclass

A streamed piece of the in-flight reply. Part ids are unique per run.

operation_id instance-attribute

chunk instance-attribute

type = 'chunk' class-attribute instance-attribute

__init__(*, operation_id, chunk, type='chunk')

FileInput dataclass

A file in a user message; url may be a data: URL.

media_type instance-attribute

url instance-attribute

filename = None class-attribute instance-attribute

__init__(*, media_type, url, filename=None)

MessageEvent dataclass

A message was saved to the transcript; it replaces any with its id.

message instance-attribute

type = 'message' class-attribute instance-attribute

__init__(*, message, type='message')

OperationEvent dataclass

An operation changed status.

operation_id instance-attribute

status instance-attribute

type = 'operation' class-attribute instance-attribute

__init__(*, operation_id, status, type='operation')

OperationResult dataclass

A settled operation.

session instance-attribute

operation_id instance-attribute

status instance-attribute

text = None class-attribute instance-attribute

requests = () class-attribute instance-attribute

reason = None class-attribute instance-attribute

__init__(*, session, operation_id, status, text=None, requests=(), reason=None)

PendingOperation dataclass

An open operation.

session instance-attribute

operation_id instance-attribute

status instance-attribute

__init__(*, session, operation_id, status)

Receipt dataclass

What submit returns once the operation is stored.

accepted is False when an operation with this id already existed.

session instance-attribute

operation_id instance-attribute

accepted instance-attribute

__init__(*, session, operation_id, accepted)

ResetEvent dataclass

The session was reset; messages that follow belong to the new context.

type = 'reset' class-attribute instance-attribute

__init__(*, type='reset')

RunEndEvent dataclass

The run for these operations ended; its reply has been saved.

operations instance-attribute

type = 'run-end' class-attribute instance-attribute

__init__(*, operations, type='run-end')

RunSnapshot dataclass

The run in progress when a watch started.

operations instance-attribute

partial = () class-attribute instance-attribute

The in-flight reply so far, as chunks; parts still streaming are left open, and the watch's ChunkEvents continue them.

__init__(*, operations, partial=())

RunStartEvent dataclass

A turn started running (again, after a crash) for these operations.

operations instance-attribute

type = 'run-start' class-attribute instance-attribute

__init__(*, operations, type='run-start')

SessionInfo dataclass

One session, as sessions.list() returns it.

id instance-attribute

parent = None class-attribute instance-attribute

The session this one was forked from.

busy = False class-attribute instance-attribute

Whether the session has an operation queued or running.

__init__(*, id, parent=None, busy=False)

SessionSnapshot dataclass

The first event watch yields: the session's state.

messages is the transcript since the newest reset, without what the run in progress has added: that is run.partial.

messages instance-attribute

pending instance-attribute

run = None class-attribute instance-attribute

type = 'snapshot' class-attribute instance-attribute

__init__(*, messages, pending, run=None, type='snapshot')

TextInput dataclass

Text in a user message.

text instance-attribute

__init__(*, text)

ToolOutput dataclass

The result of a tool call the client ran itself.

id instance-attribute

value instance-attribute

__init__(*, id, value)

ToolRequest dataclass

A tool call the turn stopped on: approve it, or run it and send the output.

id instance-attribute

name instance-attribute

args instance-attribute

kind instance-attribute

__init__(*, id, name, args, kind)

ToolSpec dataclass

A @tool method bound to its host, as a harness receives it.

fn instance-attribute

name instance-attribute

requires_approval = False class-attribute instance-attribute

replay = 'unsafe' class-attribute instance-attribute

__init__(*, fn, name, requires_approval=False, replay='unsafe')

Turn dataclass

One turn for Harness.run_turn to run.

Parameters:

Name Type Description Default
session str

The session id.

required
operation_id str

The operation this turn answers.

required
input HarnessInput

The operation's user message, or every answer to the requests the turn continues from.

required
history bytes | None

The session's history before this turn, as the subclass last returned it; None for a new session.

required
checkpoint bytes | None

The last saved bytes when resuming after a crash; None on a first run.

required
attempt int

0 on a first run, then how many times the turn was interrupted.

required
tools Sequence[ToolSpec]

The host's @tool methods, bound.

required
participant str | None

Who started the turn: the client tool calls it makes are theirs.

required
emit Callable[[ChunkEvent], None]

Streams a chunk of the reply to the session's watchers.

required
save SaveCheckpoint

Durably replaces the turn's checkpoint and, with reply, the assistant message's parts so far, in one transaction.

required

session instance-attribute

operation_id instance-attribute

input instance-attribute

history instance-attribute

checkpoint instance-attribute

attempt instance-attribute

tools instance-attribute

participant instance-attribute

emit instance-attribute

save instance-attribute

__init__(*, session, operation_id, input, history, checkpoint, attempt, tools, participant, emit, save)

TurnResult dataclass

What Harness.run_turn returns.

history replaces the session's, and reply (with metadata) replaces the turn's assistant message, in one transaction.

history instance-attribute

reply = () class-attribute instance-attribute

metadata = None class-attribute instance-attribute

status = 'done' class-attribute instance-attribute

text = None class-attribute instance-attribute

requests = () class-attribute instance-attribute

__init__(*, history, reply=(), metadata=None, status='done', text=None, requests=())

LifecycleCapability

A feature installed into a Durable Object's Lifecycle.

Subclasses pass a stable, unique id to __init__ and override the hooks they need; Lifecycle dispatches only to overridden hooks. Hooks run outside the host context: a capability calls user code through self.lifecycle.run_in_host_context.

Parameters:

Name Type Description Default
capability_id str

Identifies the capability: owns its jobs, receives routed messages, names its events. At most one capability per id in a Lifecycle.

required

Raises:

Type Description
ValueError

If capability_id is blank.

claims = 'selective' class-attribute

"catch-all" claims everything offered to the hooks it implements, so Lifecycle always dispatches to it last.

capability_id = capability_id instance-attribute

lifecycle property

The services Lifecycle grants this capability once installed.

Raises:

Type Description
RuntimeError

If the capability hasn't been installed with Lifecycle.use.

__init__(capability_id)

on_start() async

Initialize or recover state when the object wakes, before any work.

on_request(request) async

Return a response to claim an HTTP request, or None to pass it on.

on_websocket_upgrade(request) async

Return a response to claim a WebSocket upgrade and own its socket.

on_websocket_message(ws, message) async

Return True to consume a message on a socket this capability owns.

on_websocket_close(ws, code, reason, was_clean) async

Return True to consume a close on a socket this capability owns.

on_websocket_error(ws, error) async

Return True to consume an error on a socket this capability owns.

on_job(context) async

Run one due job this capability pushed.

Must be bounded: the alarm loop awaits each job in turn, so long work should be started detached, with durable evidence, and on_job should return.

on_job_error(context, error) async

Decide what happens to a job whose retries ran out (default: complete).

on_memory_limit(context) async

Apply this capability's policy after an alarm memory-limit strike.

on_route(context) async

Handle a message routed to this capability from another Lifecycle.

dispose() async

Release in-memory resources when the host is destroyed.

LifecycleJobs

One owner's view of the job queue; every change re-arms the alarm.

Parameters:

Name Type Description Default
queue JobQueue

The shared queue.

required
owner str

The capability id (or "host") every operation is scoped to.

required
rearm Callable[[], Awaitable[None]]

Recomputes the physical alarm from queue state.

required

__slots__ = ('_owner', '_queue', '_rearm') class-attribute instance-attribute

__init__(queue, owner, rearm)

push(*, fn, time, payload=None, id=None, retry=None, singleflight=False, hung_timeout=None, exclusive=False, recovery_loop=False) async

Push one job; a push with an existing id replaces that job.

Parameters:

Name Type Description Default
fn str

The name this owner's on_job dispatches on.

required
time datetime

When the job is due (timezone-aware).

required
payload JSONValue

JSON data passed back in the job.

None
id str | None

A stable id; generated when omitted.

None
retry RetryOptions | None

Dispatch retries (default: 3 attempts, 0.1 s base, 3 s max).

None
singleflight bool

Skip this job while a previous run of it is still in flight.

False
hung_timeout Duration | None

When an in-flight single-flight run counts as hung, and a dispatch as slow (default 30 s).

None
exclusive bool

Suppress ordinary alarm candidates while this job is pending.

False
recovery_loop bool

Put this job under the alarm memory-limit circuit breaker.

False

Returns:

Type Description
LifecycleJob

The stored job.

cancel(id) async

Cancel one job; return whether it existed.

reschedule(id, time) async

Move one job to time; return whether it existed.

get(id)

Return one job, or None.

list()

Return every job this owner holds, earliest first.

rearm() async

Recompute the physical alarm without changing the queue.

Changes re-arm automatically; this recovers a lost alarm for existing jobs (e.g. after an idempotent push that changed nothing).

Lifecycle

Coordinates one Durable Object's entry points, startup, jobs, and alarm.

Parameters:

Name Type Description Default
host Any

The Durable Object; Lifecycle reads host.ctx, and host hooks run in its host context.

required
hooks object | None

The object whose optional hooks Lifecycle calls: on_start, on_request, on_alarm, on_job, and _on_alarm_memory_limit (default: the host). Agent passes an object that applies its error handling around the user's hooks.

None
max_alarm_memory_limit_strikes int

Consecutive alarm memory-limit resets tolerated before the circuit breaker seals recovery work.

DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES
expose_error_details bool

Send an unhandled error's traceback to the client in the 500 response (or the upgrade's error frame). Off by default: tracebacks can reveal code, paths, and data. Meant for local development.

False

class_name = type(host).__name__ instance-attribute

The host class's name.

sql = Sql(self._ctx.storage) instance-attribute

Typed SQL over the host's database.

name property

The name the Durable Object was addressed by (ctx.id.name).

Raises:

Type Description
RuntimeError

If the object wasn't addressed by name (idFromName / getByName), so ctx.id.name is unset.

jobs property

The host's own view of the job queue; jobs go to host.on_job.

__init__(host, *, hooks=None, max_alarm_memory_limit_strikes=DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES, expose_error_details=False)

use(capability)

Install a capability before startup.

Capabilities dispatch in installation order, except that catch-alls always come last. At most one catch-all per hook.

Returns:

Type Description
Lifecycle

This Lifecycle, for chaining.

Raises:

Type Description
RuntimeError

If startup has begun, a capability with the same id is installed, or a second catch-all claims the same hook.

start() async

Start capabilities and the host, once per wake.

Entry points call this automatically; native RPC methods that need startup call it themselves (RPC bypasses fetch). Concurrent callers share one startup; a call from inside startup returns at once.

is_started()

Return whether startup has finished.

fetch(request) async

Handle an HTTP request or WebSocket upgrade for the object.

A plain request goes to the capabilities, then the host's on_request, then 404. An upgrade goes to the capabilities only.

websocket_message(ws, message) async

Dispatch a hibernated socket's message to the capability that owns it.

websocket_close(ws, code, reason, was_clean) async

Dispatch a hibernated socket's close to the capability that owns it.

websocket_error(ws, error) async

Dispatch a hibernated socket's error to the capability that owns it.

Transport teardown errors on a socket that is already closing are the connection going away, not application errors, and are dropped.

alarm() async

Run one alarm: due jobs, then the host's on_alarm, then re-arm.

rearm_alarm() async

Set the physical alarm from queue state (deferred while starting).

Serialized, so an earlier computation can't overwrite a later one.

track_alarm_work(work)

Keep work a job handed off inside the current alarm's breaker domain.

dispose() async

Dispose capabilities in reverse installation order.

disable_alarms() async

Permanently stop alarms and delete the physical alarm (host teardown).

route(envelope) async

Deliver a routed message to the addressed capability (internal).

LifecycleRoutes

Sending messages to capabilities in other Lifecycles (facets have no alarm).

Parameters:

Name Type Description Default
lifecycle Lifecycle

The owning Lifecycle.

required
capability_id str

Messages are addressed to the capability with this id on the target.

required

__slots__ = ('_capability_id', '_lifecycle') class-attribute instance-attribute

source property

Return this Lifecycle's address, or None at the route root.

__init__(lifecycle, capability_id)

to_root(payload) async

Send payload to this capability on the root Lifecycle.

to(target, payload) async

Send payload to this capability on the Lifecycle at target.

LifecycleServices

What a capability may use: identity, storage, sockets, jobs, events.

Parameters:

Name Type Description Default
lifecycle Lifecycle

The owning Lifecycle.

required
capability_id str

The capability these services are scoped to.

required

__slots__ = ('_capability_id', '_lifecycle', 'jobs', 'routes') class-attribute instance-attribute

jobs = lifecycle._jobs_for(capability_id) instance-attribute

This capability's view of the shared job queue.

routes = LifecycleRoutes(lifecycle, capability_id) instance-attribute

Messaging to the same capability in other Lifecycles.

name property

The host Durable Object's name.

class_name property

The host class's name.

storage property

The host's ctx.storage (the Workers SDK wrapper).

sql property

Typed SQL over the host's database; each capability owns its tables.

__init__(lifecycle, capability_id)

accept_websocket(ws, tags)

Accept ws into hibernation under tags.

websockets(tag=None)

Return every hibernated socket on the object, optionally by tag.

ready() async

Wait for startup, starting it if needed (returns at once inside it).

status()

Return the startup state.

track_alarm_work(work)

Keep work handed off by a job inside the alarm's memory-limit breaker.

Returns False (tracking nothing) outside an alarm invocation.

run_in_host_context(fn, *, connection=None, request=None) async

Run a user callback inside the host context.

The one way a capability calls user code, so get_current_agent() works there. Pass the connection or request it runs on behalf of.

emit(type, payload)

Publish a best-effort telemetry event under this capability's id.

JobContext dataclass

The due job being dispatched, and the attempt number within this alarm.

job instance-attribute

attempt instance-attribute

__init__(*, job, attempt)

LifecycleEvent dataclass

One best-effort telemetry event published through Lifecycle.

source instance-attribute

type instance-attribute

payload instance-attribute

__init__(*, source, type, payload)

LifecycleJob dataclass

One durable job in the Lifecycle queue.

Parameters:

Name Type Description Default
id str

Unique job id, stable across reschedules.

required
capability str

The owning capability's id, or "host".

required
fn str

The name the owner dispatches on (e.g. a callback name).

required
time datetime

When the job is due.

required
payload JSONValue

Owner-defined JSON payload.

None
retry RetryOptions | None

Dispatch retry policy, when the pusher gave one.

None
singleflight bool

Whether the job is skipped while a previous run is in flight.

False
exclusive bool

Whether the job suppresses ordinary alarm candidates while pending.

False
recovery_loop bool

Whether the alarm memory-limit circuit breaker governs this job.

False
created_at datetime

When the job was first pushed.

required

id instance-attribute

capability instance-attribute

fn instance-attribute

time instance-attribute

payload = None class-attribute instance-attribute

retry = None class-attribute instance-attribute

singleflight = False class-attribute instance-attribute

exclusive = False class-attribute instance-attribute

recovery_loop = False class-attribute instance-attribute

created_at instance-attribute

__init__(*, id, capability, fn, time, payload=None, retry=None, singleflight=False, exclusive=False, recovery_loop=False, created_at)

MemoryLimitContext dataclass

A recorded alarm memory-limit strike (upstream #1825).

Parameters:

Name Type Description Default
sealed bool

Whether the strike budget ran out and recovery-loop work was purged.

required
next_time datetime | None

The backoff wake armed for an unsealed strike.

None
executing LifecycleJob | None

The job that was running when the strike landed, if any.

None
purged_recovery_loop_jobs Sequence[LifecycleJob] | None

The recovery-loop jobs a sealing strike removed (snapshotted first).

None

sealed instance-attribute

next_time = None class-attribute instance-attribute

executing = None class-attribute instance-attribute

purged_recovery_loop_jobs = None class-attribute instance-attribute

__init__(*, sealed, next_time=None, executing=None, purged_recovery_loop_jobs=None)

Reschedule dataclass

A job outcome: run the job again at at.

at instance-attribute

__init__(*, at)

RouteAddress

Bases: NamedTuple

An opaque address a routing transport understands.

key instance-attribute

Stable equality and storage key.

data instance-attribute

The transport's serialized address.

RouteContext dataclass

A message routed to one capability from another Lifecycle.

source instance-attribute

payload instance-attribute

__init__(*, source, payload)

ChatMessage

Bases: TypedDict

One message of the conversation sent to the model.

content is a list only on a user message that holds an image.

role instance-attribute

content instance-attribute

name instance-attribute

tool_call_id instance-attribute

tool_calls instance-attribute

Completion dataclass

The model's answer: text, tool calls, or both, and any reasoning.

text instance-attribute

reasoning = '' class-attribute instance-attribute

tool_calls = () class-attribute instance-attribute

usage = Usage() class-attribute instance-attribute

from_output(data) classmethod

Parse either output shape a Workers AI chat model returns.

__init__(*, text, reasoning='', tool_calls=(), usage=Usage())

FunctionCall

Bases: TypedDict

The function half of an assistant message's tool call.

name instance-attribute

arguments instance-attribute

FunctionSchema

Bases: TypedDict

A tool's name, description, and JSON schema for its arguments.

name instance-attribute

description instance-attribute

parameters instance-attribute

ImageContentPart

Bases: TypedDict

An image inside a user message's content list.

type instance-attribute

image_url instance-attribute

ImageURL

Bases: TypedDict

An image as a data:image/...;base64, URL.

url instance-attribute

ReasoningDelta dataclass

The next piece of the model's reasoning.

text instance-attribute

__init__(*, text)

TextContentPart

Bases: TypedDict

Text inside a user message's content list.

type instance-attribute

text instance-attribute

TextDelta dataclass

The next piece of the answer's text.

text instance-attribute

__init__(*, text)

ToolCall dataclass

A tool call the model made; id is generated if the model sent none.

id instance-attribute

name instance-attribute

arguments instance-attribute

from_output(data) classmethod

Parse a flat {name, arguments} or nested {id, function} call.

__init__(*, id, name, arguments)

ToolCallDelta dataclass

The next piece of the tool call at index.

The first piece of a call carries its id and name; later pieces carry only more of the JSON arguments.

index instance-attribute

id = None class-attribute instance-attribute

name = None class-attribute instance-attribute

arguments = '' class-attribute instance-attribute

from_output(data) classmethod

Parse one entry of a chunk's delta.tool_calls.

__init__(*, index, id=None, name=None, arguments='')

ToolCallPayload

Bases: TypedDict

A tool call as an assistant message carries it back to the model.

id instance-attribute

type instance-attribute

function instance-attribute

ToolSchema

Bases: TypedDict

A tool the model may call.

type instance-attribute

function instance-attribute

Usage dataclass

Token counts for one request.

input_tokens = 0 class-attribute instance-attribute

output_tokens = 0 class-attribute instance-attribute

from_output(data) classmethod

Parse a usage object; None counts nothing.

__init__(*, input_tokens=0, output_tokens=0)

WorkersAIModel

A Workers AI chat model, called through the ai binding.

Parameters:

Name Type Description Default
name str

The model id, like "@cf/meta/llama-4-scout-17b-16e-instruct".

required
binding Any

The ai binding (env.AI).

required
clean_text Callable[[str], str] | None

Rewrites the text of each answer complete returns, like str.strip for a model that starts its answers with blank lines. None keeps the text as the model sent it. stream doesn't call it, since it needs the whole text.

None

Examples:

>>> model = WorkersAIModel("@cf/qwen/qwen3-30b-a3b-fp8", binding=env.AI)
>>> completion = await model.complete([{"role": "user", "content": "Hi"}])

name = name instance-attribute

The model id.

binding = binding instance-attribute

The ai binding.

clean_text = clean_text instance-attribute

Rewrites the text of each answer; None keeps it as sent.

__init__(name, *, binding, clean_text=None, **kwargs)

__repr__()

complete(messages, *, tools=(), options=None) async

Run the model on a conversation and return its answer.

Parameters:

Name Type Description Default
messages Sequence[ChatMessage]

The conversation, oldest first.

required
tools Sequence[ToolSchema]

The tools the model may call.

()
options Mapping[str, object] | None

Extra inputs such as max_tokens or temperature.

None

Raises:

Type Description
ValueError

If messages is empty.

stream(messages, *, tools=(), options=None) async

Run the model on a conversation and read its answer as it arrives.

Takes the same arguments as complete, and the block iterates over TextDelta, ReasoningDelta and ToolCallDelta pieces, then the request's Usage. Leaving the block before the answer ends cancels it.

Raises:

Type Description
ValueError

If messages is empty.

Examples:

>>> async with model.stream(messages) as events:
...     async for event in events:
...         if isinstance(event, TextDelta):
...             print(event.text, end="")

LoggingObservability

The default sink: JSON lines on agents.events (DEBUG).

Enable them with standard logging configuration, e.g. logging.getLogger("agents.events").setLevel(logging.DEBUG).

emit(event)

Log event and notify the subscribers of its channel.

Observability

Bases: Protocol

Where an agent's events go (Agent.observability).

emit(event)

Record one event. Shouldn't raise; failures are logged and dropped.

ObservabilityEvent dataclass

One structured event: what an agent did, with upstream's schema.

Parameters:

Name Type Description Default
type str

Upstream's event name, e.g. "rpc" or "queue:error".

required
agent str

The agent's class name.

required
name str

The agent's instance name.

required
payload dict[str, Any]

The event's data, with upstream's (camelCase) keys.

required
timestamp datetime

When the event happened (UTC); epoch milliseconds in JSON.

required

type instance-attribute

agent instance-attribute

name instance-attribute

payload instance-attribute

timestamp instance-attribute

__init__(*, type, agent, name, payload, timestamp)

Queue

Bases: LifecycleCapability

Durable background work for a Lifecycle object.

Each pushed item becomes a Lifecycle job due immediately. Items run one at a time in push order when the alarm fires; a raising callback is retried per its retry policy, then dropped after a queue:error event and the on_error hook. Items survive the object leaving memory, so callbacks should be idempotent.

Parameters:

Name Type Description Default
callbacks Mapping[str, QueueCallback] | None

Callbacks by name; looked up first.

None
target object | None

An object whose methods are callbacks too (e.g. the host itself); looked up after callbacks.

None
retry RetryOptions | None

The default retry policy (3 attempts, 0.1 s base, 3 s max).

None
on_error QueueErrorHandler | None

Observes an item's terminal failure. Runs as capability code, outside the host context.

None

Raises:

Type Description
(TypeError, ValueError)

If retry is invalid.

__init__(*, callbacks=None, target=None, retry=None, on_error=None)

push(callback, payload=None, *, id=None, retry=None) async

Push one item; it runs in push order once this call returns.

Parameters:

Name Type Description Default
callback str | Callable[..., Any]

A registered callback name, or a bound method of target. Called as callback(payload, item).

required
payload JSONValue

JSON data passed to the callback.

None
id str | None

A stable id. Pushing an existing id replaces that item in place (keeping its position) and supersedes a run of it still in flight. Generated when omitted.

None
retry RetryOptions | None

Overrides the Queue's default retry policy for this item.

None

Returns:

Type Description
QueueItem

The stored item.

Raises:

Type Description
ValueError

If the callback isn't registered, or id is blank.

TypeError

If callback is a callable and the Queue has no target.

get(id) async

Return one pending item, or None.

list(callback=None) async

Return pending items in push order, optionally for one callback.

cancel(id) async

Cancel one pending item; return whether it existed.

cancel_all(callback=None) async

Cancel every pending item, or every item for one callback.

Returns:

Type Description
int

How many items were cancelled.

on_start() async

Record the storage version once (.design/sql_schemas.md §4).

on_job(context) async

Run one due item handed over by the Lifecycle alarm loop.

on_job_error(context, error) async

Report an item's terminal failure; the item is dropped.

on_route(context) async

Handle a Queue operation routed from another Lifecycle.

QueueItem dataclass

One durable item waiting in a Queue.

Parameters:

Name Type Description Default
id str

The item's id.

required
callback str

The name of the callback the item runs.

required
payload JSONValue

The data passed to the callback.

required
created_at datetime

When the item was first pushed.

required
retry RetryOptions | None

The retry policy for the callback.

None

id instance-attribute

callback instance-attribute

payload instance-attribute

created_at instance-attribute

retry = None class-attribute instance-attribute

__init__(*, id, callback, payload, created_at, retry=None)

InvalidCronExpressionError

Bases: AgentsException, ValueError

A cron expression couldn't be parsed, or never matches.

Also a ValueError: usually a mistake in code, but catchable when the expression comes from user or model input.

Scheduler

Bases: LifecycleCapability

Persistent schedules for a Lifecycle object: one-shot, cron, and interval.

Each schedule is a Lifecycle job. When it comes due, its callback runs as callback(payload, schedule); a raising callback is retried per its retry policy, then reported (schedule:error and on_error). Recurring schedules then move to their next time; one-shots are deleted.

Parameters:

Name Type Description Default
callbacks Mapping[str, ScheduleCallback] | None

Callbacks by name; looked up first.

None
target object | None

An object whose methods are callbacks too (e.g. the host itself).

None
retry RetryOptions | None

The default retry policy (3 attempts, 0.1 s base, 3 s max).

None
hung_schedule_timeout Duration

When a still-running interval schedule counts as hung and may run again.

30
on_error ScheduleErrorHandler | None

Observes a schedule's terminal failure. Runs as capability code, outside the host context.

None

Raises:

Type Description
(TypeError, ValueError)

If retry is invalid.

__init__(*, callbacks=None, target=None, retry=None, hung_schedule_timeout=30, on_error=None)

set(when, callback, payload=None, *, retry=None, idempotent=None) async

Schedule callback(payload, schedule).

Parameters:

Name Type Description Default
when datetime | timedelta | float | str

A datetime runs it once then; a timedelta or number of seconds runs it once after that delay; a str runs it on that cron expression (UTC).

required
callback str | Callable[..., Any]

A registered callback name, or a bound method of target.

required
payload JSONValue

JSON data passed to the callback.

None
retry RetryOptions | None

Overrides the Scheduler's default retry policy.

None
idempotent bool | None

Reuse a matching existing schedule instead of adding another. None means yes for cron, no for one-shots.

None

Returns:

Type Description
Schedule

The new schedule, or the existing one it matched.

Raises:

Type Description
ValueError

If the callback isn't registered, or when is invalid.

TypeError

If when has the wrong type.

every(interval, callback, payload=None, *, retry=None, idempotent=None) async

Run callback(payload, schedule) every interval.

The first run is one interval from now. A run still in progress when the next is due is skipped, unless it has run longer than hung_schedule_timeout.

Parameters:

Name Type Description Default
interval Duration

The time between runs (at most 30 days).

required
callback str | Callable[..., Any]

A registered callback name, or a bound method of target.

required
payload JSONValue

JSON data passed to the callback.

None
retry RetryOptions | None

Overrides the Scheduler's default retry policy.

None
idempotent bool | None

Reuse a matching existing schedule (default: yes).

None

Raises:

Type Description
ValueError

If the callback isn't registered, or the interval is out of range.

get(id) async

Return one schedule, or None.

list(*, id=None, type=None, start=None, end=None) async

Return schedules, optionally filtered by id, type, or next run time.

cancel(id) async

Cancel one schedule; return whether it existed.

on_start() async

Forget startup warnings, and record the storage version once.

on_job(context) async

Run one due schedule handed over by the Lifecycle alarm loop.

on_job_error(context, error) async

Report a schedule's terminal failure; a recurring one moves on.

on_route(context) async

Handle a Scheduler operation routed from another Lifecycle.

Schedule dataclass

One persisted schedule.

Parameters:

Name Type Description Default
id str

The schedule's id.

required
callback str

The name of the callback it runs.

required
payload JSONValue

The data passed to the callback.

required
type ScheduleType

How it runs (ScheduleType).

required
time datetime

When it next runs.

required
retry RetryOptions | None

The retry policy given when it was created, if any.

None
delay timedelta | None

For "delayed": the delay it was created with.

None
cron str | None

For "cron": the cron expression.

None
interval timedelta | None

For "interval": the time between runs.

None

id instance-attribute

callback instance-attribute

payload instance-attribute

type instance-attribute

time instance-attribute

retry = None class-attribute instance-attribute

delay = None class-attribute instance-attribute

cron = None class-attribute instance-attribute

interval = None class-attribute instance-attribute

__init__(*, id, callback, payload, type, time, retry=None, delay=None, cron=None, interval=None)

Session

One conversation: its reads, writes, and change feed.

Get it from Sessions.session. Messages form a chain: each is appended after the newest, and reads return the chain oldest first.

__slots__ = ('_sessions', 'session_id') class-attribute instance-attribute

session_id = session_id instance-attribute

This session's id ("" for the default).

__init__(sessions, session_id)

append_message(message, *, source='server') async

Append message after the newest one.

An id already stored writes nothing and returns the stored message with inserted=False.

Raises:

Type Description
(TypeError, ValueError)

If message isn't JSON (e.g. holds NaN or an object).

update_message(message, *, source='server') async

Replace the stored message with message's id.

Returns the stored form, or None if the id isn't in the session. An identical message writes nothing and sends no change event.

upsert_message(message, *, source='server') async

Append message if its id is new, otherwise update it.

delete_messages(message_ids) async

Delete messages; the messages after them follow their parent.

clear_messages() async

Delete every message in the session.

history() async

Yield the conversation, oldest first, fetching content in windows.

history_batches(*, batch_size=50, max_batch_bytes=4 * 1024 * 1024) async

Yield history in batches of at most batch_size messages.

A batch also ends once its messages' JSON reaches max_batch_bytes (a single larger message is a batch of its own).

get_history() async

Return the whole conversation, oldest first.

get_recent_history(max_content_bytes) async

Return the newest messages whose stored size fits the budget.

Each message costs its full stored size; the newest is always included, however large.

get_history_row_stats() async

Return each stored message's size and token estimate, oldest first.

mirror(*, get, set, transform=None)

Keep a host's in-memory list in step with this session's writes.

Appends and updates edit the list get() returns in place; deletes and clears hand set a new list. transform turns stored messages into the list's type (whose items have an id, as an attribute or a key).

Sessions

Bases: LifecycleCapability

Durable conversation history for a Durable Object.

Install it with self.sessions = self.use(Sessions()); one conversation per object uses the default session.

Parameters:

Name Type Description Default
reserved_metadata_keys Sequence[str]

Metadata keys only the server may set: source="client" writes lose them.

()

__init__(*, reserved_metadata_keys=())

on_start() async

Create the tables once.

session(session_id='')

Return the (cached) handle for one session; "" is the default.

subscribe(listener)

Follow every committed write, in order, across all sessions.

A listener that raises is logged and reported as session:error; the write still succeeded, and the other listeners still run.

AppendEvent dataclass

A message was appended (inserted) or its id already existed.

type = 'append' class-attribute instance-attribute

session_id instance-attribute

message instance-attribute

inserted instance-attribute

__init__(*, type='append', session_id, message, inserted)

AppendResult dataclass

The result of an append or upsert.

inserted is False when the id already existed (nothing was written); message is the stored (sanitized) form.

inserted instance-attribute

message instance-attribute

__init__(*, inserted, message)

ClearEvent dataclass

Every message in the session was deleted.

type = 'clear' class-attribute instance-attribute

session_id instance-attribute

__init__(*, type='clear', session_id)

DeleteEvent dataclass

Messages were deleted (their children now follow their parent).

type = 'delete' class-attribute instance-attribute

session_id instance-attribute

message_ids instance-attribute

__init__(*, type='delete', session_id, message_ids)

RecentHistoryResult dataclass

The newest messages that fit a byte budget, oldest first.

messages always includes the leaf. truncated means older messages were left out; total_content_bytes is the stored size of the whole path.

messages instance-attribute

truncated instance-attribute

total_content_bytes instance-attribute

__init__(*, messages, truncated, total_content_bytes)

SessionMessage

Bases: TypedDict

A message in AI SDK UIMessage wire form (JSON values throughout).

Sessions reads parts only to sanitize them and estimate tokens, so part types it doesn't know are stored as they are.

id instance-attribute

role instance-attribute

parts instance-attribute

metadata instance-attribute

SessionRowStat dataclass

One stored message's size and token estimate, without its content.

id instance-attribute

role instance-attribute

bytes instance-attribute

The message row plus its continuation rows, in UTF-8 bytes.

token_estimate instance-attribute

Stamped when the message was written.

__init__(*, id, role, bytes, token_estimate)

UpdateEvent dataclass

A stored message changed.

type = 'update' class-attribute instance-attribute

session_id instance-attribute

message instance-attribute

__init__(*, type='update', session_id, message)

State

Bases: LifecycleCapability

One JSON value per object, saved in SQLite and cached in memory.

None means "no state": it's what get returns when nothing is stored, and a None state isn't pushed to connections.

Parameters:

Name Type Description Default
initial_state T | None

Saved (through set) on first access when nothing is stored.

None
validate_state_change StateValidator[T] | None

Called before a change is saved; raise to reject it.

None
on_changed StateChangeHandler[T] | None

Called after a change is saved (e.g. to broadcast it).

None

__init__(*, initial_state=None, validate_state_change=None, on_changed=None)

on_start() async

Create the state table on an object's first start.

get()

Return the current state, loading it on first access.

When nothing is stored, the initial state (if any) is saved through set and returned. A row that isn't valid JSON is replaced by the initial state, or deleted when there is none.

set(state, source='server')

Validate, save, and cache a new state, then call on_changed.

Saved first and cached second, so a value that fails to serialize or write is never served. The cache holds a fresh copy (parsed from the saved JSON), so the caller's object can't change it afterwards.

Raises:

Type Description
Exception

Whatever validate_state_change raises, rejecting the change.

(TypeError, ValueError)

If state isn't JSON-serializable.

StreamClosedError

Bases: AgentsException

The stream no longer accepts writes: it settled, or was deleted.

Raised by open() on a terminal stream and by an append that reaches a stream settled or deleted after its writer was created.

stream_id = stream_id instance-attribute

__init__(stream_id, detail)

StreamNotFoundError

Bases: AgentsException

read() targets a stream that was never opened (or was deleted).

status() returns None instead, for existence checks.

stream_id = stream_id instance-attribute

__init__(stream_id)

StreamSerializationError

Bases: AgentsException

A chunk or metadata value isn't JSON, or is over the size limit.

__init__(context, detail)

Streams

Bases: LifecycleCapability

Durable chunk logs with replay-then-tail reads.

Install it on an agent with self.streams = self.use(Streams()).

Parameters:

Name Type Description Default
max_chunk_bytes int

The limit on one serialized chunk (and on a stream's metadata).

DEFAULT_MAX_CHUNK_BYTES

__init__(*, max_chunk_bytes=DEFAULT_MAX_CHUNK_BYTES)

on_start() async

Create the tables once.

open(stream_id, *, tag=None, metadata=None) async

Open a stream for writing, or resume a live one.

Reopening a live stream returns a writer at its current cursor.

Parameters:

Name Type Description Default
stream_id str

1-256 characters.

required
tag str | None

A lookup key, fixed at creation and not unique: successive streams of one operation (a retried turn) share it, and list(tag=..., limit=1) finds the newest.

None
metadata dict[str, JSONValue] | None

JSON kept with the stream.

None

Raises:

Type Description
StreamClosedError

If the stream has already settled.

ValueError

If stream_id is empty or too long, or the live stream has a different tag.

StreamSerializationError

If metadata isn't JSON or is over the size limit.

read(stream_id, *, start=0) async

Replay chunks from start (inclusive), then follow live appends.

Ends once the stream has settled and every chunk has been yielded (an errored stream too: status tells the outcome) or it's deleted. Cancel the reading task to stop early.

Raises:

Type Description
StreamNotFoundError

If the stream doesn't exist.

read_batches(stream_id, *, start=0, batch_size=_DEFAULT_BATCH_SIZE, on_up_to_date=None) async

read, in batches: one per replay page, one per live wakeup.

A consumer paying per write (a socket send, an RPC hop) pays once per backlog rather than once per chunk.

Parameters:

Name Type Description Default
start int

The first seq to yield.

0
batch_size int

The most chunks in one replay batch.

_DEFAULT_BATCH_SIZE
on_up_to_date Callable[[], None] | None

Called once, synchronously, when the reader first catches up with everything stored so far (it may still be live).

None

Raises:

Type Description
StreamNotFoundError

If the stream doesn't exist.

status(stream_id) async

Return a stream's state and cursor, or None if it doesn't exist.

list(*, state=None, tag=None, limit=None) async

Return streams newest first (default at most 100).

delete(stream_id) async

Delete a settled stream and its chunks; False if there's none.

Raises:

Type Description
RuntimeError

If the stream is still live: settle it first.

StreamWriter

The producer's handle on one stream, from Streams.open.

Appends are synchronous durable writes; once the stream has settled (or been deleted), appends raise StreamClosedError.

__slots__ = ('_streams', 'stream_id') class-attribute instance-attribute

stream_id = stream_id instance-attribute

The stream this writer appends to.

cursor property

The next seq to be assigned (resume a producer from here).

__init__(streams, stream_id)

append(chunk)

Durably append chunk and wake live readers; return its seq.

Raises:

Type Description
StreamClosedError

If the stream settled or was deleted.

StreamSerializationError

If chunk isn't JSON or is over the size limit.

close(*, commit=None, discard=False)

Settle the stream as completed.

Does nothing if it's already settled or deleted (commit doesn't run then).

Parameters:

Name Type Description Default
commit Callable[[], None] | None

Synchronous writes (e.g. saving the finished message) committed in one transaction with the settle. If it raises, nothing is committed and the stream stays live.

None
discard bool

Delete the stream's rows in that same transaction (the chunks were handed off).

False

error(reason=None, *, commit=None, discard=False)

Settle the stream as errored, recording reason (see close).

StreamChunk dataclass

One durable chunk: seq is 0-based, assigned at append, and stable.

seq instance-attribute

chunk instance-attribute

__init__(*, seq, chunk)

StreamStatus dataclass

One stream's state and cursor.

Parameters:

Name Type Description Default
stream_id str

The stream's id.

required
state StreamState

Where it is in its life.

required
cursor int

The next seq to be assigned (the durable chunk count).

required
created_at datetime

When it was opened.

required
updated_at datetime

Its last write: an append or the settle. A streaming stream whose updated_at is old has a producer that stopped appending.

required
tag str | None

The lookup key it was opened with.

None
metadata dict[str, JSONValue] | None

The metadata it was opened with.

None
error str | None

The reason given to error().

None
closed_at datetime | None

When it settled.

None

stream_id instance-attribute

state instance-attribute

cursor instance-attribute

created_at instance-attribute

updated_at instance-attribute

tag = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

error = None class-attribute instance-attribute

closed_at = None class-attribute instance-attribute

__init__(*, stream_id, state, cursor, created_at, updated_at, tag=None, metadata=None, error=None, closed_at=None)

TaskHandle

Starts and inspects the runs of one definition (sees only its runs).

Parameters:

Name Type Description Default
tasks Tasks

The owning capability.

required
name str

The definition's name.

required

__slots__ = ('_tasks', 'name') class-attribute instance-attribute

name = name instance-attribute

__init__(tasks, name)

run(input, *, idempotency_key=None, run_id=None, metadata=None, retain=True) async

Durably accept a run and start it (see Tasks.run).

get(run_id) async

Return one run of this definition, or None.

get_by_idempotency_key(idempotency_key) async

Return this definition's run with idempotency_key, or None.

cancel(run_id, reason=None) async

Cancel a run of this definition; False for another definition's run.

task

Make an async method a task definition, named after the method.

self.<method> then gives a TaskHandle for starting and inspecting its runs. The handler is called as method(self, input, step) and replays from its first line on every attempt.

Raises:

Type Description
TypeError

If the function isn't async (checked when the class is defined).

Examples:

>>> class Reports(Agent):
...     @task
...     async def build(self, input: dict, step: TaskStep) -> str: ...
...
...     async def on_request(self, request):
...         receipt = await self.build.run({"id": 1})

__slots__ = ('fn', 'name') class-attribute instance-attribute

fn = fn instance-attribute

name = name instance-attribute

__init__(fn)

__get__(instance, owner=None)

__get__(instance: None, owner: type | None = None) -> Self
__get__(instance: object, owner: type | None = None) -> TaskHandle[In, Out]

Return the handle bound to instance (the descriptor, on the class).

Raises:

Type Description
RuntimeError

If no Tasks capability was created with target=instance.

DuplicateTaskStepError

Bases: AgentsException

A run used the same step name twice; step names are journal keys.

Parameters:

Name Type Description Default
step_name str

The repeated name.

required

step_name = step_name instance-attribute

__init__(step_name)

MissingTaskDefinitionError

Bases: AgentsException

A run's definition is no longer registered (removed or renamed).

The run fails; it's never deleted or run against a different handler.

Parameters:

Name Type Description Default
definition str

The definition name the run was started with.

required

definition = definition instance-attribute

__init__(definition)

NonRetryableError

Bases: AgentsException

Raise from a step function to fail the run now, skipping retries.

Errors of any class named NonRetryableError count too, as upstream.

StepTimeoutError

Bases: AgentsException, TimeoutError

A step attempt ran longer than its timeout (it's retried like any error).

Parameters:

Name Type Description Default
step_name str

The step.

required
attempt int

The attempt that timed out.

required
timeout_ms int

The timeout, in milliseconds.

required

step_name = step_name instance-attribute

__init__(step_name, attempt, timeout_ms)

TaskReplayDivergedError

Bases: AgentsException

A replay found a journal this handler can't have written.

Change an in-flight definition's steps by versioning its name instead.

Parameters:

Name Type Description Default
step_name str

Where the replay diverged.

required
detail str

What differed.

required

step_name = step_name instance-attribute

__init__(step_name, detail)

TaskSerializationError

Bases: AgentsException, TypeError

A task input, step result, metadata, or result isn't JSON, or is too big.

Parameters:

Name Type Description Default
context str

What was being serialized.

required
detail str

Why it failed.

required

__init__(context, detail)

Tasks

Bases: LifecycleCapability

Durable, replayable background work for a Lifecycle object.

Each run of a definition survives the object leaving memory: completed steps return their journaled results, sleeps keep their deadlines, and an interrupted attempt replays from the first unfinished step.

Parameters:

Name Type Description Default
definitions Mapping[str, TaskHandler] | None

Task definitions by name, each called as handler(input, step).

None
target object | None

An object whose @task methods are definitions too (named by the method); definitions wins on a clash.

None
step_retries StepRetries | None

Default step retries (5 attempts, 1 s, exponential).

None
step_timeout Duration | None

Default timeout of one step attempt (5 minutes).

None
on_error TaskErrorHandler | None

Observes a run's terminal failure, in the host context.

None

__init__(*, definitions=None, target=None, step_retries=None, step_timeout=None, on_error=None)

run(definition, input=None, *, idempotency_key=None, run_id=None, metadata=None, retain=True) async

Durably accept a run and start it; return without waiting for it.

The same idempotency_key (or run_id) joins the existing run (accepted=False) instead of starting another.

Parameters:

Name Type Description Default
definition str

The definition's name.

required
input JSONValue

JSON passed to the handler.

None
idempotency_key str | None

Deduplicates repeated starts onto one run.

None
run_id str | None

A run id to use (generated when omitted).

None
metadata dict[str, JSONValue] | None

JSON kept with the run.

None
retain bool

Keep the run's record after it settles (default True).

True

Raises:

Type Description
ValueError

If the definition isn't registered, or an id or key conflicts.

TaskSerializationError

If input or metadata isn't plain JSON, or is too big.

on_start() async

Create the tables once, then make every live run's wake sane.

on_job(context) async

Drive one due run handed over by the Lifecycle alarm loop.

On the root, a mirror of a facet's run is dispatched to that facet.

on_memory_limit(context) async

Contain a run whose wake hit the alarm memory-limit breaker.

Strips the claim and pushes the deadline to the backoff, so the run keeps its state (a replay still sees step.interrupted) and startup won't make it due again early. A sealed strike fails the run.

on_route(context) async

Handle a Tasks message routed between a facet and the root.

handle(definition)

Return a handle scoped to one definition's runs.

Raises:

Type Description
ValueError

If the definition isn't registered.

get(run_id) async

Return one run by id, or None.

get_by_idempotency_key(idempotency_key) async

Return the run started with idempotency_key, or None.

list(*, definition=None, status=None, limit=100) async

Return runs, newest first, optionally by definition and state.

cancel(run_id, reason=None) async

Cancel a run; return whether a live run accepted the request.

A parked run settles at once; a running attempt is cancelled and settles at its next step boundary.

delete(*, status=None, settled_before=None, limit=100) async

Delete settled runs and their journals, oldest first; return how many.

CancelledRun dataclass

A run that was cancelled.

state = 'cancelled' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

settled_at instance-attribute

reason = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, settled_at, reason=None, metadata=None)

CompletedRun dataclass

A run that finished with result.

state = 'completed' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

result instance-attribute

settled_at instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, result, settled_at, metadata=None)

FailedRun dataclass

A run that failed.

state = 'failed' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

error instance-attribute

settled_at instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, error, settled_at, metadata=None)

PendingRun dataclass

A run accepted but not started yet.

state = 'pending' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, metadata=None)

RunningRun dataclass

A run with an attempt executing.

state = 'running' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

attempt instance-attribute

started_at instance-attribute

status_message = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, attempt, started_at, status_message=None, metadata=None)

StepInterruption dataclass

The step an interrupted attempt (a dead isolate) left mid-execution.

name instance-attribute

attempt instance-attribute

__init__(*, name, attempt)

StepRetries dataclass

Retry policy for a step; unset fields use the Tasks defaults.

Parameters:

Name Type Description Default
limit int | None

Total attempts, including the first (default 5).

None
delay Duration | None

The delay before the first retry (default 1 s).

None
backoff Backoff | None

How the delay grows across retries (default exponential, capped at a day).

None

limit = None class-attribute instance-attribute

delay = None class-attribute instance-attribute

backoff = None class-attribute instance-attribute

__init__(*, limit=None, delay=None, backoff=None)

TaskError dataclass

What a failed run keeps of its error: the type name and message.

name instance-attribute

message instance-attribute

__init__(*, name, message)

TaskReceipt dataclass

The result of starting a run.

accepted is False when an existing run matched the run_id or idempotency_key (not an error).

run_id instance-attribute

definition instance-attribute

accepted instance-attribute

state instance-attribute

created_at instance-attribute

__init__(*, run_id, definition, accepted, state, created_at)

TaskStep

Bases: Protocol

The step API a task handler receives.

Named steps are the run's durable journal: do memoizes completed results, sleeps keep their first deadline, and both end the attempt instead of holding the invocation open. The handler replays from its first line on every attempt, so side effects belong inside do.

interrupted property

The step a dead isolate left running, or None on a clean attempt.

do(name, fn, *, retries=None, timeout=None) async

Run fn once as step name; replays return its journaled result.

sleep(name, duration) async

Sleep durably for duration; the first recorded deadline wins.

sleep_until(name, when) async

Sleep durably until when.

status(message) async

Record observable progress (replays stay silent over old ground).

idempotency_key(name)

Return the key do(name, ...) passes to its attempts.

TaskStepAttempt dataclass

What a step.do function receives on each attempt.

Parameters:

Name Type Description Default
attempt int

The 1-based attempt number for this step.

required
idempotency_key str

The same across every attempt and replay of this step: pass it to external services that deduplicate.

required

attempt instance-attribute

idempotency_key instance-attribute

__init__(*, attempt, idempotency_key)

WaitingRun dataclass

A run parked until a sleep or retry deadline.

state = 'waiting' class-attribute

run_id instance-attribute

definition instance-attribute

created_at instance-attribute

reason instance-attribute

wake_at instance-attribute

status_message = None class-attribute instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, run_id, definition, created_at, reason, wake_at, status_message=None, metadata=None)

Connection

Bases: Generic[ConnState]

One client connection.

id, uri, and tags are fixed when the connection is accepted; state and the flags are read from the socket's attachment each time. Equal connections wrap the same socket (ids are client-chosen, so two sockets can share one).

__slots__ = ('_id', '_tags', '_uri', '_ws') class-attribute instance-attribute

id property

The connection id (the client's _pk, or generated).

uri property

The URL the connection was opened with.

tags property

The tags the connection was accepted under; the id comes first.

state property

The connection's own state; replace it with set_state.

readonly property writable

Whether the client is refused when it changes the host's state.

protocol_enabled property

Whether protocol frames (identity, state) are sent to this client.

Decided when the connection opens.

__init__(ws, meta)

set_state(state)

Replace this connection's state (JSON, kept across hibernation).

Raises:

Type Description
ConnectionStateTooLargeError

If the state doesn't fit in the socket's 16 KiB attachment.

send(message)

Send a text or binary frame.

Raises:

Type Description
JsException

If the socket has closed.

close(code=None, reason=None)

Close the connection.

1008 and 4000-4999 tell the client not to reconnect.

__eq__(other)

Return whether other wraps the same socket.

__hash__()

Hash the id (equal connections share one; JS sockets are unhashable).

__repr__()

Show the id and tags.

ConnectionStateTooLargeError

Bases: AgentsException

A connection's state doesn't fit in its socket attachment (16 KiB).

The limit is shared with the SDK's own connection metadata.

DuplicateConnectionIdError

Bases: AgentsException

More than one live connection has the id get_connection was asked for.

Connection ids come from the client (_pk), so two sockets can share one; use get_connections(tag=id) to reach all of them.

Parameters:

Name Type Description Default
id str

The shared connection id.

required

id = id instance-attribute

__init__(id)

StreamingResponse

Sends one streaming call's results: chunks, then an end or an error.

Passed as the first argument to @callable(streaming=True) methods. Every method is a no-op returning False once the stream is closed.

__slots__ = ('_closed', '_connection', '_id') class-attribute instance-attribute

is_closed property

Whether end or error has been called.

__init__(connection, id)

send(chunk)

Send one chunk; return False if closed or the client has gone.

Raises:

Type Description
(TypeError, ValueError)

If chunk isn't JSON-serializable (ValueError for NaN).

end(final=None)

Close the stream, with an optional final result.

None means "no result": the client's call resolves with undefined (.design/agent_api.md §1.8).

error(message)

Close the stream with an error; the client's call rejects.

CallableMetadata dataclass

What @callable records about a method.

Parameters:

Name Type Description Default
description str | None

What the method does.

None
streaming bool

Whether the method streams its result (a StreamingResponse first argument, or an async generator).

False

description = None class-attribute instance-attribute

streaming = False class-attribute instance-attribute

__init__(*, description=None, streaming=False)

ConnectionContext dataclass

What a connection was opened with.

request instance-attribute

The WebSocket upgrade request.

__init__(*, request)

WebSocketHandlers dataclass

Connection hooks; each runs in the host context with the connection.

Parameters:

Name Type Description Default
on_connect Callable[[Connection, ConnectionContext], Awaitable[None]] | None

A connection was accepted (after the protocol frames, if any).

None
on_message Callable[[Connection, str | bytes], Awaitable[bool | None]] | None

A frame the SDK didn't consume arrived. For handlers added with WebSockets.use, returning True claims it, so later handlers don't see it.

None
on_close Callable[[Connection, int, str, bool], Awaitable[None]] | None

The client closed the connection.

None
on_error Callable[[Connection, BaseException], Awaitable[None]] | None

The connection failed.

None

on_connect = None class-attribute instance-attribute

on_message = None class-attribute instance-attribute

on_close = None class-attribute instance-attribute

on_error = None class-attribute instance-attribute

__init__(*, on_connect=None, on_message=None, on_close=None, on_error=None)

WebSockets

Bases: LifecycleCapability

Hibernatable WebSocket connections, with the Agents connect protocol.

Accepts every upgrade (it's the catch-all), whether or not handlers are given. With state, it pushes the current state after the identity frame on connect and applies the cf_agent_state frames clients send; broadcasting a change is the state owner's call (wire the State's on_changed to broadcast_state).

Parameters:

Name Type Description Default
handlers WebSocketHandlers | None

Connection hooks, run in the host context.

None
protocol bool | ConnectionDecision

Whether new connections get the protocol frames (identity, then state): True for all, a decision per connection (False marks it no-protocol: it never gets protocol frames, but works otherwise), or False for none, when the host sends them itself with send_connect_frames and applies state frames with apply_state_frame (Agent does this).

True
readonly ConnectionDecision | None

Decides whether a new connection is readonly (its state changes are refused).

None
state SyncedState | None

The state to sync to clients, normally the host's State capability.

None
callables object | None

An object whose @callable methods clients may call with rpc frames (Agent passes itself).

None
connection_tags ConnectionTagger | None

Returns the tags to accept a new connection under (at most 9, plus the id, which is always the first tag).

None

claims = 'catch-all' class-attribute instance-attribute

__init__(*, handlers=None, protocol=True, readonly=None, state=None, connection_tags=None, callables=None)

use(handlers)

Add handlers for another component sharing these connections.

They run before the configured handlers, and their on_message can claim a message by returning True.

get_connections(tag=None)

Yield the open connections, optionally only those with tag.

get_connection(id)

Return the open connection with id, or None.

Raises:

Type Description
DuplicateConnectionIdError

If more than one open connection has that id.

broadcast(message, *, exclude=())

Send message to every open connection, except exclude.

An id excludes every connection with that id; a Connection excludes exactly that one.

on_websocket_upgrade(request) async

Accept an upgrade as a hibernatable connection.

on_websocket_message(ws, message) async

Handle a message on a connection this capability accepted.

on_websocket_close(ws, code, reason, was_clean) async

Run the close handlers, then complete the close handshake.

on_websocket_error(ws, error) async

Run the error handlers.

dispose() async

Close every connection when the host is destroyed.

send_connect_frames(connection, *, name=None, agent=None)

Send the connect sequence: the identity frame, then the state.

The identity carries stateFollows when state follows, so clients resolve ready only once it has arrived. Sends nothing to a no-protocol connection. name and agent default as for send_identity.

send_identity(connection, *, name=None, agent=None)

Send the identity frame alone, unless the connection is no-protocol.

Clients resolve ready on it, so a host that also pushes state on connect should use send_connect_frames. name defaults to the object's name and agent to the host class in kebab case; a host whose public identity differs (a facet) passes its own.

send_state(connection)

Send the current state, unless there is none or it's no-protocol.

apply_state_frame(connection, frame)

Apply a parsed cf_agent_state frame from a client.

Refuses a readonly connection with cf_agent_state_error. Logs a change the validator rejects in full and answers it with a generic cf_agent_state_error. Hosts that drive the protocol themselves call this inside the host context.

Returns:

Type Description
bool

Whether the frame was a state frame (handled either way).

broadcast_state(exclude=None)

Push the current state to every protocol-enabled connection.

exclude is the connection a change came from, which already has the value it sent. Wire a State's on_changed to this.

get_current_agent()

Return the agent the running code belongs to, or None outside one.

Set around every hook, @callable method, queued callback, and public agent method (including ones reached through native RPC), and inherited by tasks they start. Lost in callbacks the JS runtime calls directly (setTimeout, event listeners): call an agent method from there.

get_agent_by_name(namespace, name, *, jurisdiction=None, location_hint=None, routing_retry=None) async

Return a started agent's stub, for native RPC.

Native RPC bypasses fetch, where startup normally happens, so the agent's startup is run first.

Parameters:

Name Type Description Default
namespace Any

The agent's Durable Object binding (self.env.MyAgent).

required
name str

The instance name.

required
jurisdiction str | None

Restrict the agent to a jurisdiction.

None
location_hint str | None

Where to create the agent if it doesn't exist yet.

None
routing_retry RoutingRetry

Retries on errors the platform marks transient.

None

Returns:

Type Description
Any

The Durable Object stub; await stub.method(...) calls the agent.

get_sub_agent_by_name(parent, cls, name) async

Return a stub for a sub-agent, called through its parent.

Each call is one extra hop through the parent, and the parent's on_before_sub_agent gate doesn't run (as get_agent_by_name doesn't run on_before_connect). Method calls only; no fetch.

Raises:

Type Description
ValueError

If name contains NUL.

route_agent_request(request, env, *, prefix='agents', cors=False, jurisdiction=None, location_hint=None, routing_retry=None, on_before_connect=None, on_before_request=None) async

Forward a request for /{prefix}/{agent}/{name}/... to that agent.

{agent} is a Durable Object binding's name in kebab case (ChatRoom → chat-room); the agent is idFromName(name). The request is forwarded unchanged, URL included.

Parameters:

Name Type Description Default
request Request

The incoming request.

required
env Any

The Worker's env, scanned for Durable Object bindings.

required
prefix str

The path prefix (may contain /).

'agents'
cors bool | Mapping[str, str]

True for permissive CORS headers, or the headers to use; answers OPTIONS preflights and adds them to non-WebSocket responses.

False
jurisdiction str | None

Restrict the agent to a jurisdiction (e.g. "eu").

None
location_hint str | None

Where to create the agent if it doesn't exist yet.

None
routing_retry RoutingRetry

Retries on errors the platform marks transient (None for the defaults, False to disable).

None
on_before_connect BeforeHook | None

Runs before a WebSocket upgrade is forwarded (e.g. authorization).

None
on_before_request BeforeHook | None

Runs before any other request is forwarded.

None

Returns:

Type Description
Response | None

The agent's response; None if the path isn't an agent route; a 400 if it names no binding.

route_sub_agent_request(request, parent, *, from_path=None) async

Forward a request for a sub-agent through its parent (custom routing).

For URLs route_agent_request doesn't route: the parent's on_before_sub_agent gate runs, then the sub-agent gets the request.

Parameters:

Name Type Description Default
request Request

The incoming request.

required
parent Any

The parent agent's stub (e.g. from get_agent_by_name).

required
from_path str | None

The /sub/{class}/{name}/... path to route on, when it isn't the request's own path.

None

Returns:

Type Description
Response

The sub-agent's response; 400 if there's no /sub/ path.

build_agent_path(path, *, prefix='agents', leaf_path=None, root_binding=None)

Return the routable path of an agent (/agents/root/name/sub/...).

Parameters:

Name Type Description Default
path Sequence[AgentPathStep]

The agent's path, root first (e.g. an agent's self_path).

required
prefix str

The routing prefix (route_agent_request's prefix).

'agents'
leaf_path str | None

A path to append after the agent (e.g. /history).

None
root_binding str | None

The root's env binding name, when it differs from its class name.

None

Raises:

Type Description
ValueError

If a part isn't routable (an empty path, a class named Sub, a name that's ., .., or contains NUL, a prefix or leaf path that isn't a plain pathname).

build_agent_url(origin, path, *, prefix='agents', leaf_path=None, root_binding=None)

Return an agent's URL on origin (https://, wss://, ...).

Raises:

Type Description
ValueError

If origin isn't a bare HTTP(S)/WS(S) origin, or the path isn't routable (see build_agent_path).

tool(fn=None, /, *, requires_approval=False, replay='unsafe')

tool(fn: F) -> F
tool(*, requires_approval: bool = False, replay: Replay = 'unsafe') -> Callable[[F], F]

Make an async method a tool the harness gives the model.

The method's name, signature, and docstring describe the tool.

Parameters:

Name Type Description Default
requires_approval bool

Stop the turn with a needs_input result before each call, until the client sends an Approval.

False
replay Replay

"safe" lets a crash-interrupted call run again on resume; "unsafe" (the default) reports it to the model as not run.

'unsafe'

Raises:

Type Description
TypeError

If the function isn't async.

ValueError

If replay isn't "safe" or "unsafe".

Examples:

>>> class Notes(Agent):
...     @tool(replay="safe")
...     async def search(self, query: str) -> list[str]:
...         '''Search the notes.'''

subscribe(channel, listener)

Call listener with every event the default sink sees on channel.

In-process only, for tests and local debugging. Dispose the result to unsubscribe.

callable(fn=None, /, *, description=None, streaming=False)

callable(fn: F) -> F
callable(*, description: str | None = None, streaming: bool = False) -> Callable[[F], F]

Make an async method callable by clients over rpc frames.

Works bare (@callable) or with options (@callable(streaming=True)). A streaming=True method gets a StreamingResponse before the client's arguments; an async generator streams one chunk per yield. A subclass override must be decorated again to stay callable.

Parameters:

Name Type Description Default
fn Callable[..., Any] | None

The method, when used bare.

None
description str | None

What the method does (reported by get_callable_methods).

None
streaming bool

Pass a StreamingResponse as the first argument.

False

Raises:

Type Description
TypeError

If the method isn't async, or is an async generator declared streaming=True.

agents.harness.transcript

Transcript records: the messages a harness keeps and the chunks it streams.

A port of upstream's experimental/channels/protocol.ts transcript and response types, and of apply-chunks.ts and the chunk grammar in response.ts (cloudflare/agents 455b47e). They live here rather than in Channels because the harness owns the transcript and must not depend on Channels.

The records are not agents.chat's UIMessage classes: a tool part is one type: "tool" class with a state and an owner, and a response has no start or finish chunk. Import this module by its path (from agents.harness.transcript import TranscriptMessage); its names would collide with chat's in the root agents namespace.

__all__ = ('Data', 'DataPart', 'FilePart', 'JSONObject', 'MessagePart', 'Metadata', 'ReasoningDelta', 'ReasoningEnd', 'ReasoningPart', 'ReasoningStart', 'ResponseChunk', 'ResponseGrammar', 'ResponseGrammarError', 'SourceDocumentPart', 'SourceUrlPart', 'TextDelta', 'TextEnd', 'TextPart', 'TextStart', 'ToolApproval', 'ToolApprovalRequest', 'ToolInputAvailable', 'ToolInputDelta', 'ToolInputError', 'ToolInputStart', 'ToolOutputAvailable', 'ToolOutputDenied', 'ToolOutputError', 'ToolPart', 'ToolState', 'TranscriptMessage', 'apply_chunks', 'chunk_from_wire', 'message_from_wire', 'part_from_wire', 'to_wire') module-attribute

JSONObject = dict[str, JSONValue]

A JSON object (upstream's JsonObject).

ToolState = Literal['input-streaming', 'input-available', 'approval-requested', 'approval-responded', 'output-available', 'output-error', 'output-denied']

Where a tool call is: its input streaming in, waiting, or finished.

MessagePart = TextPart | ReasoningPart | FilePart | SourceUrlPart | SourceDocumentPart | DataPart | ToolPart

One part of a TranscriptMessage.

ResponseChunk = TextStart | TextDelta | TextEnd | ReasoningStart | ReasoningDelta | ReasoningEnd | ToolInputStart | ToolInputDelta | ToolInputAvailable | ToolInputError | ToolApprovalRequest | ToolOutputAvailable | ToolOutputError | ToolOutputDenied | FilePart | SourceUrlPart | SourceDocumentPart | Data | Metadata

One streamed piece of a response. A response has no start or finish chunk: it begins when it is opened and ends when it is closed.

ResponseGrammarError

Bases: AgentsException

A response chunk breaks the chunk grammar (upstream response.ts).

TextPart dataclass

Text in a message.

type = 'text' class-attribute

text instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, text, provider_metadata=wire('providerMetadata', None))

ReasoningPart dataclass

The model's reasoning.

type = 'reasoning' class-attribute

text instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, text, provider_metadata=wire('providerMetadata', None))

FilePart dataclass

A file, in a message or as a chunk; url may be a data: URL.

type = 'file' class-attribute

media_type = wire('mediaType') class-attribute instance-attribute

url instance-attribute

filename = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, media_type=wire('mediaType'), url, filename=None, provider_metadata=wire('providerMetadata', None))

SourceUrlPart dataclass

A cited web page, in a message or as a chunk.

type = 'source-url' class-attribute

source_id = wire('sourceId') class-attribute instance-attribute

url instance-attribute

title = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, source_id=wire('sourceId'), url, title=None, provider_metadata=wire('providerMetadata', None))

SourceDocumentPart dataclass

A cited document, in a message or as a chunk.

type = 'source-document' class-attribute

source_id = wire('sourceId') class-attribute instance-attribute

media_type = wire('mediaType') class-attribute instance-attribute

title instance-attribute

filename = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, source_id=wire('sourceId'), media_type=wire('mediaType'), title, filename=None, provider_metadata=wire('providerMetadata', None))

DataPart dataclass

Application data in a message.

A later part with the same name and a set id replaces it.

type = 'data' class-attribute

name instance-attribute

id = None class-attribute instance-attribute

data instance-attribute

__init__(*, name, id=None, data)

ToolApproval dataclass

A tool call's approval request, and the decision once there is one.

id instance-attribute

approved = None class-attribute instance-attribute

reason = None class-attribute instance-attribute

__init__(*, id, approved=None, reason=None)

ToolPart dataclass

One tool call and, once it has finished, its result.

owner is the participant whose client may run a client tool call; it is None for tools the agent runs.

type = 'tool' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

tool_name = wire('toolName') class-attribute instance-attribute

state instance-attribute

input = None class-attribute instance-attribute

output = None class-attribute instance-attribute

error_text = wire('errorText', None) class-attribute instance-attribute

preliminary = None class-attribute instance-attribute

approval = None class-attribute instance-attribute

owner = None class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

dynamic = None class-attribute instance-attribute

title = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), tool_name=wire('toolName'), state, input=None, output=None, error_text=wire('errorText', None), preliminary=None, approval=None, owner=None, provider_executed=wire('providerExecuted', None), dynamic=None, title=None, provider_metadata=wire('providerMetadata', None))

TranscriptMessage dataclass

One message in a session's transcript.

id instance-attribute

role instance-attribute

parts instance-attribute

metadata = None class-attribute instance-attribute

__init__(*, id, role, parts, metadata=None)

TextStart dataclass

Opens a text part.

type = 'text-start' class-attribute

id instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, id, provider_metadata=wire('providerMetadata', None))

TextDelta dataclass

Appends to an open text part.

type = 'text-delta' class-attribute

id instance-attribute

delta instance-attribute

__init__(*, id, delta)

TextEnd dataclass

Closes a text part.

type = 'text-end' class-attribute

id instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, id, provider_metadata=wire('providerMetadata', None))

ReasoningStart dataclass

Opens a reasoning part.

type = 'reasoning-start' class-attribute

id instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, id, provider_metadata=wire('providerMetadata', None))

ReasoningDelta dataclass

Appends to an open reasoning part.

type = 'reasoning-delta' class-attribute

id instance-attribute

delta instance-attribute

__init__(*, id, delta)

ReasoningEnd dataclass

Closes a reasoning part.

type = 'reasoning-end' class-attribute

id instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, id, provider_metadata=wire('providerMetadata', None))

ToolInputStart dataclass

Opens a tool call whose input streams in.

type = 'tool-input-start' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

tool_name = wire('toolName') class-attribute instance-attribute

owner = None class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

dynamic = None class-attribute instance-attribute

title = None class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), tool_name=wire('toolName'), owner=None, provider_executed=wire('providerExecuted', None), dynamic=None, title=None)

ToolInputDelta dataclass

More of an open tool call's input, as JSON text.

type = 'tool-input-delta' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

delta instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), delta)

ToolInputAvailable dataclass

A tool call's whole input; closes its tool input, open or not.

type = 'tool-input-available' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

tool_name = wire('toolName') class-attribute instance-attribute

input instance-attribute

owner = None class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

dynamic = None class-attribute instance-attribute

title = None class-attribute instance-attribute

provider_metadata = wire('providerMetadata', None) class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), tool_name=wire('toolName'), input, owner=None, provider_executed=wire('providerExecuted', None), dynamic=None, title=None, provider_metadata=wire('providerMetadata', None))

ToolInputError dataclass

A tool call whose input isn't valid; closes its tool input, open or not.

type = 'tool-input-error' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

tool_name = wire('toolName') class-attribute instance-attribute

input instance-attribute

error_text = wire('errorText') class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

dynamic = None class-attribute instance-attribute

title = None class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), tool_name=wire('toolName'), input, error_text=wire('errorText'), provider_executed=wire('providerExecuted', None), dynamic=None, title=None)

ToolApprovalRequest dataclass

A tool call waits for approval.

type = 'tool-approval-request' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

approval_id = wire('approvalId') class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), approval_id=wire('approvalId'))

ToolOutputAvailable dataclass

A tool call's output; a preliminary one is replaced by the next.

type = 'tool-output-available' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

output instance-attribute

preliminary = None class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), output, preliminary=None, provider_executed=wire('providerExecuted', None))

ToolOutputError dataclass

A tool call failed.

type = 'tool-output-error' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

error_text = wire('errorText') class-attribute instance-attribute

provider_executed = wire('providerExecuted', None) class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'), error_text=wire('errorText'), provider_executed=wire('providerExecuted', None))

ToolOutputDenied dataclass

A tool call was denied approval.

type = 'tool-output-denied' class-attribute

tool_call_id = wire('toolCallId') class-attribute instance-attribute

__init__(*, tool_call_id=wire('toolCallId'))

Data dataclass

Application data; a transient chunk is shown live and not kept.

type = 'data' class-attribute

name instance-attribute

id = None class-attribute instance-attribute

data instance-attribute

transient = None class-attribute instance-attribute

__init__(*, name, id=None, data, transient=None)

Metadata dataclass

Merged into the metadata of the message the response builds.

type = 'metadata' class-attribute

metadata instance-attribute

__init__(*, metadata)

ResponseGrammar

Checks a response's chunks, in order, against upstream's grammar.

Port of the check in upstream response.ts: a delta or end needs its part open, a start needs its id free within its kind (text and reasoning ids are separate), and tool-input-available / -error close a tool input that may never have opened.

__slots__ = ('_open',) class-attribute instance-attribute

__init__()

check(chunk)

Raise if chunk can't come next; records nothing.

Raises:

Type Description
ResponseGrammarError

If the chunk breaks the grammar.

append(chunk)

Check chunk, then record the part it opens or closes.

Raises:

Type Description
ResponseGrammarError

If the chunk breaks the grammar; nothing is recorded.

to_wire(record)

Return a record's JSON form: camelCase keys, None optionals left out.

A tool part in state output-available always carries output, since null is a legitimate tool result.

message_from_wire(data)

Parse a TranscriptMessage from its JSON form.

Raises:

Type Description
ValueError

If a required field is missing, or the role or a part type is unknown.

part_from_wire(data)

Parse a MessagePart from its JSON form.

Raises:

Type Description
ValueError

If the type is unknown or a required field is missing.

chunk_from_wire(data)

Parse a ResponseChunk from its JSON form.

Raises:

Type Description
ValueError

If the type is unknown or a required field is missing.

apply_chunks(message, chunks)

Return message with a response's chunks applied; message is kept.

Port of upstream apply-chunks.ts applyChunks. Parts still open at the end keep what they have. Deltas for parts that aren't open, and results for unknown tool calls, are dropped.

agents.harness.pydantic_ai

A harness that runs a Pydantic AI agent.

Needs Pydantic AI 2.64 or later: cf-agents[pydantic-ai]. It runs on Python 3.13 and 3.14 Workers. On Python 3.13 Workers, pywrangler's default package index stops at pydantic 2.10, so add a newer index with the same ABI to the Worker's pyproject.toml::

[tool.uv.pip]
extra-index-url = ["https://index.pyodide.org/0.29.3"]

agents.harness never imports this package.

__all__ = ('PydanticAIHarness', 'WorkersAIModel') module-attribute

PydanticAIHarness

Bases: Harness

Runs a Pydantic AI agent, one turn per operation.

The agent keeps its model, instructions, and own tools. Each turn adds the target's @tool methods, passes the target as deps, and asks for text. A turn that stops on tool calls needing approval or the client settles needs_input. The turn streams ChunkEvents and saves the assistant message's parts after every step.

Parameters:

Name Type Description Default
id str

The capability id.

required
agent Agent[Any, Any]

The Pydantic AI agent to run.

required
target object | None

The object whose @tool methods are the tools, and the run's deps.

None
max_restarts int

How many times a crash-interrupted turn is resumed.

5
heartbeat Duration

How often a session with open work is checked.

30

Examples:

>>> class Notes(DurableObject):
...     def __init__(self, ctx, env):
...         super().__init__(ctx, env)
...         agent = pydantic_ai.Agent("openai:gpt-5", instructions="Keep notes.")
...         self.harness = PydanticAIHarness("notes", agent, target=self)
...         Lifecycle(self).use(self.harness)

agent = agent instance-attribute

The Pydantic AI agent each turn runs.

__init__(id, agent, *, target=None, max_restarts=5, heartbeat=30)

run_turn(turn) async

Run the agent from the turn's checkpoint, or its history and input.

reset_history(handoff)

Start the new history with the handoff note as a system prompt.

Pydantic AI adds an agent's system_prompt only to an empty history, so after a reset with a handoff only its instructions (which apply to every request) still reach the model.

WorkersAIModel

Bases: WorkersAIModel, Model

A Workers AI chat model that a Pydantic AI agent can run.

Prompts may hold images: BinaryImage or image BinaryContent, and ImageUrl, which is downloaded because Workers AI takes only data: URLs. Other files in a prompt raise TypeError. A tool's images reach the model in a user message after the tool results, and its other files as a note naming them. Streamed requests stream text, reasoning and tool calls token by token, and skip whitespace-only text ahead of the answer.

Building one turns off Pydantic AI's price lookup for the isolate, so usage.cost stays None: the price table doesn't fit in a Durable Object's memory. Call genai_prices.data_snapshot.set_custom_snapshot first to keep your own prices.

Parameters:

Name Type Description Default
name str

The model id, like "@cf/qwen/qwen3-30b-a3b-fp8".

required
binding Any

The ai binding (env.AI).

required
settings ModelSettings | None

Default settings; max_tokens, temperature, top_p, top_k, seed, presence_penalty and frequency_penalty reach the model.

None
profile ModelProfileSpec | None

The Pydantic AI model profile.

None
clean_text Callable[[str], str] | None

Rewrites the text of each answer before Pydantic AI sees it. None keeps the text as the model sent it. Streamed requests don't call it, since it needs the whole text.

None

Examples:

>>> model = WorkersAIModel(
...     "@cf/qwen/qwen3-30b-a3b-fp8", binding=env.AI, clean_text=str.strip
... )
>>> agent = pydantic_ai.Agent(model, instructions="Be brief.")

model_name property

The model id.

system property

The provider, for telemetry.

__init__(name, *, binding, settings=None, profile=None, clean_text=None)

request(messages, model_settings, model_request_parameters) async

Send the conversation to Workers AI and return its answer.

request_stream(messages, model_settings, model_request_parameters, run_context=None) async

Send the conversation to Workers AI and stream its answer.

agents.models

Model clients that harnesses adapt to their agent frameworks.

__all__ = ('ChatMessage', 'Completion', 'CompletionEvent', 'ContentPart', 'FunctionCall', 'FunctionSchema', 'ImageContentPart', 'ImageURL', 'ReasoningDelta', 'TextContentPart', 'TextDelta', 'ToolCall', 'ToolCallDelta', 'ToolCallPayload', 'ToolSchema', 'Usage', 'WorkersAIModel') module-attribute

CompletionEvent = TextDelta | ReasoningDelta | ToolCallDelta | Usage

What WorkersAIModel.stream yields; Usage counts the whole request.

ContentPart = TextContentPart | ImageContentPart

One part of a user message's content list.

ChatMessage

Bases: TypedDict

One message of the conversation sent to the model.

content is a list only on a user message that holds an image.

role instance-attribute

content instance-attribute

name instance-attribute

tool_call_id instance-attribute

tool_calls instance-attribute

Completion dataclass

The model's answer: text, tool calls, or both, and any reasoning.

text instance-attribute

reasoning = '' class-attribute instance-attribute

tool_calls = () class-attribute instance-attribute

usage = Usage() class-attribute instance-attribute

from_output(data) classmethod

Parse either output shape a Workers AI chat model returns.

__init__(*, text, reasoning='', tool_calls=(), usage=Usage())

FunctionCall

Bases: TypedDict

The function half of an assistant message's tool call.

name instance-attribute

arguments instance-attribute

FunctionSchema

Bases: TypedDict

A tool's name, description, and JSON schema for its arguments.

name instance-attribute

description instance-attribute

parameters instance-attribute

ImageContentPart

Bases: TypedDict

An image inside a user message's content list.

type instance-attribute

image_url instance-attribute

ImageURL

Bases: TypedDict

An image as a data:image/...;base64, URL.

url instance-attribute

ReasoningDelta dataclass

The next piece of the model's reasoning.

text instance-attribute

__init__(*, text)

TextContentPart

Bases: TypedDict

Text inside a user message's content list.

type instance-attribute

text instance-attribute

TextDelta dataclass

The next piece of the answer's text.

text instance-attribute

__init__(*, text)

ToolCall dataclass

A tool call the model made; id is generated if the model sent none.

id instance-attribute

name instance-attribute

arguments instance-attribute

from_output(data) classmethod

Parse a flat {name, arguments} or nested {id, function} call.

__init__(*, id, name, arguments)

ToolCallDelta dataclass

The next piece of the tool call at index.

The first piece of a call carries its id and name; later pieces carry only more of the JSON arguments.

index instance-attribute

id = None class-attribute instance-attribute

name = None class-attribute instance-attribute

arguments = '' class-attribute instance-attribute

from_output(data) classmethod

Parse one entry of a chunk's delta.tool_calls.

__init__(*, index, id=None, name=None, arguments='')

ToolCallPayload

Bases: TypedDict

A tool call as an assistant message carries it back to the model.

id instance-attribute

type instance-attribute

function instance-attribute

ToolSchema

Bases: TypedDict

A tool the model may call.

type instance-attribute

function instance-attribute

Usage dataclass

Token counts for one request.

input_tokens = 0 class-attribute instance-attribute

output_tokens = 0 class-attribute instance-attribute

from_output(data) classmethod

Parse a usage object; None counts nothing.

__init__(*, input_tokens=0, output_tokens=0)

WorkersAIModel

A Workers AI chat model, called through the ai binding.

Parameters:

Name Type Description Default
name str

The model id, like "@cf/meta/llama-4-scout-17b-16e-instruct".

required
binding Any

The ai binding (env.AI).

required
clean_text Callable[[str], str] | None

Rewrites the text of each answer complete returns, like str.strip for a model that starts its answers with blank lines. None keeps the text as the model sent it. stream doesn't call it, since it needs the whole text.

None

Examples:

>>> model = WorkersAIModel("@cf/qwen/qwen3-30b-a3b-fp8", binding=env.AI)
>>> completion = await model.complete([{"role": "user", "content": "Hi"}])

name = name instance-attribute

The model id.

binding = binding instance-attribute

The ai binding.

clean_text = clean_text instance-attribute

Rewrites the text of each answer; None keeps it as sent.

__init__(name, *, binding, clean_text=None, **kwargs)

__repr__()

complete(messages, *, tools=(), options=None) async

Run the model on a conversation and return its answer.

Parameters:

Name Type Description Default
messages Sequence[ChatMessage]

The conversation, oldest first.

required
tools Sequence[ToolSchema]

The tools the model may call.

()
options Mapping[str, object] | None

Extra inputs such as max_tokens or temperature.

None

Raises:

Type Description
ValueError

If messages is empty.

stream(messages, *, tools=(), options=None) async

Run the model on a conversation and read its answer as it arrives.

Takes the same arguments as complete, and the block iterates over TextDelta, ReasoningDelta and ToolCallDelta pieces, then the request's Usage. Leaving the block before the answer ends cancels it.

Raises:

Type Description
ValueError

If messages is empty.

Examples:

>>> async with model.stream(messages) as events:
...     async for event in events:
...         if isinstance(event, TextDelta):
...             print(event.text, end="")

agents.mcp

The MCP client (upstream mcp/client), with no dependency on the MCP SDK.

Hosting MCP servers is in agents.mcp.server, which needs cf-agents[mcp-server]. This package never imports it.

__all__ = ('AddMcpServerResult', 'AudioContent', 'BlobResourceContents', 'CallToolResult', 'ContentBlock', 'DurableObjectOAuthProvider', 'EmbeddedResource', 'FetchTransport', 'GetPromptResult', 'HttpRequest', 'HttpResponse', 'HttpTransport', 'ImageContent', 'MCPAuthorizationRequiredError', 'MCPBlockedUrlError', 'MCPClientConnection', 'MCPClientManager', 'MCPConnectionError', 'MCPConnectionState', 'MCPError', 'MCPOAuthError', 'MCPOAuthProvider', 'MCPOAuthResult', 'MCPProtocolError', 'MCPRpcError', 'MCPServerIdConflictError', 'MCPServerInfo', 'MCPServerNotFoundError', 'MCPServerNotReadyError', 'MCPServerRecord', 'MCPServersState', 'MCPTransportError', 'OAuthClientInformation', 'OAuthClientMetadata', 'OAuthTokens', 'Prompt', 'PromptArgument', 'PromptMessage', 'ReadResourceResult', 'Resource', 'ResourceContents', 'ResourceLink', 'ResourceTemplate', 'ServerPrompt', 'ServerResource', 'ServerResourceTemplate', 'ServerTool', 'StateCheck', 'TextContent', 'TextResourceContents', 'Tool', 'TransportType', 'UnknownContent', 'normalize_server_id') module-attribute

ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource | UnknownContent

ResourceContents = TextResourceContents | BlobResourceContents

TransportType = Literal['auto', 'streamable-http']

auto is Streamable HTTP; the legacy SSE transport isn't supported yet.

MCPClientConnection

A connection to one MCP server.

init() connects (or reaches AUTHENTICATING), discover() loads the catalog, and the call methods use it once it's READY.

Parameters:

Name Type Description Default
server_id str

The server's id.

required
url str

The server's endpoint.

required
http HttpTransport

The transport every request goes through.

required
client_info Mapping[str, str]

This client's name and version.

required
headers Mapping[str, str]

Extra headers sent on every request.

required
transport_type str

The stored transport type; only Streamable HTTP is supported.

'auto'
auth SessionAuth | None

OAuth, when the server has a callback URL.

None
prior SessionSnapshot | None

A stored session to restore without a new handshake.

None
emit Callable[[str, dict[str, Any]], None]

Publishes an observability event (type, payload).

required
on_change Callable[[], None]

Called after every state or catalog change.

required
on_authorize Callable[[MCPClientConnection], None]

Called when the connection needs the user to authorize.

required

server_id = server_id instance-attribute

url = url instance-attribute

state = MCPConnectionState.CONNECTING instance-attribute

error = None instance-attribute

Why the connection failed or discovery didn't finish.

auth_url = None instance-attribute

Where the user must authorize, while AUTHENTICATING.

capabilities property

dict | None: the server's capabilities, once connected.

instructions property

str | None: the server's instructions for the model.

snapshot property

SessionSnapshot | None: what restoring this connection needs.

tools property

Sequence[dict]: the server's tools, as it sent them.

prompts property

Sequence[dict]: the server's prompts, as it sent them.

resources property

Sequence[dict]: the server's resources, as it sent them.

resource_templates property

Sequence[dict]: the server's resource templates, as it sent them.

__init__(server_id, url, *, http, client_info, headers, transport_type='auto', auth=None, prior=None, emit, on_change, on_authorize)

__repr__()

Return <MCPClientConnection id='x' state=ready>.

is_auth_accepted()

Return whether the connection is past authorization (index.ts:818).

init() async

Connect: negotiate the protocol, or restore the stored session.

Never raises: failures become the FAILED state, and a server that needs OAuth leaves the connection AUTHENTICATING.

discover(*, timeout) async

Load the catalog the server advertises, then become READY.

Never raises: on an error or timeout the connection goes back to CONNECTED with the error kept, so it can be retried (upstream connection.ts:527).

call_tool(name, arguments=None, *, timeout=60) async

Call a tool. A tool error is is_error=True, not an exception.

Raises:

Type Description
MCPServerNotReadyError

If the connection isn't READY.

MCPRpcError

If the server rejects the call or it times out.

MCPTransportError

If the server can't be reached.

MCPAuthorizationRequiredError

If the server now needs OAuth (the connection is AUTHENTICATING afterwards).

get_prompt(name, arguments=None) async

Render a prompt (raises as call_tool).

read_resource(uri) async

Read a resource (raises as call_tool).

close() async

Stop the listener and end the session; never raises.

MCPAuthorizationRequiredError

Bases: MCPError

The server needs OAuth; the user must visit auth_url first.

Parameters:

Name Type Description Default
auth_url str

The authorization URL to send the user to.

required

auth_url = auth_url instance-attribute

__init__(auth_url)

MCPBlockedUrlError

Bases: MCPError

A server URL points at a private or metadata address.

url = url instance-attribute

__init__(url)

MCPConnectionError

Bases: MCPError

A server couldn't be connected; it stays stored and can be retried.

Parameters:

Name Type Description Default
server_id str

The server's id.

required
message str

Why the connection failed.

required

server_id = server_id instance-attribute

__init__(server_id, message)

MCPError

Bases: AgentsException

Base class for every MCP exception.

MCPOAuthError

Bases: MCPError

An OAuth step failed: discovery, registration, the code exchange or a refresh.

MCPProtocolError

Bases: MCPError

A server broke the protocol, or needs a feature the client lacks.

MCPRpcError

Bases: MCPError

A server answered a request with a JSON-RPC error.

Parameters:

Name Type Description Default
code int

The JSON-RPC error code (-32601 is "method not found").

required
message str

The server's message.

required
data Any

The error's data member, if any.

None

code = code instance-attribute

message = message instance-attribute

data = data instance-attribute

__init__(code, message, data=None)

MCPServerIdConflictError

Bases: MCPError

add_server was given an id that belongs to a different name or URL.

server_id = server_id instance-attribute

__init__(server_id)

MCPServerNotFoundError

Bases: MCPError

No server with this id is registered.

server_id = server_id instance-attribute

__init__(server_id)

MCPServerNotReadyError

Bases: MCPError

A call needs a server that isn't ready yet.

server_id = server_id instance-attribute

state = state instance-attribute

__init__(server_id, state)

MCPTransportError

Bases: MCPError

The HTTP request to a server failed: network, DNS, TLS, or a dropped body.

FetchTransport

The default transport: the Workers fetch.

__slots__ = () class-attribute instance-attribute

request(request) async

Send request with fetch and enter its response.

Raises:

Type Description
MCPTransportError

If the request or the body read fails.

HttpRequest dataclass

One outbound request.

Parameters:

Name Type Description Default
method str

The HTTP method.

required
url str

The absolute URL.

required
headers Mapping[str, str]

The request headers.

dict()
body str | None

The body, if any.

None

method instance-attribute

url instance-attribute

headers = field(default_factory=dict) class-attribute instance-attribute

body = None class-attribute instance-attribute

__init__(*, method, url, headers=dict(), body=None)

HttpResponse

Bases: Protocol

A response whose body is read as it arrives.

status property

int: the HTTP status.

headers property

Mapping[str, str]: the headers, with lower-case names.

chunks()

Yield the body's chunks (read once).

HttpTransport

Bases: Protocol

Sends requests. Leaving the context ends the request, read or not.

request(request)

Send request and enter its response.

Raises:

Type Description
MCPTransportError

If the request fails before a response arrives, or the body read does.

MCPClientManager

Bases: LifecycleCapability

Connects a Durable Object to MCP servers and keeps them across wakes.

Installed by Agent when AgentOptions(mcp=...) is set; works on any Lifecycle (lifecycle.use(MCPClientManager(...))).

Parameters:

Name Type Description Default
client_name str

Sent to servers as this client's identity.

required
client_version str

Sent to servers as this client's identity.

required
create_oauth_provider Callable[[str], MCPOAuthProvider] | None

Builds the OAuth provider for a server's callback URL. The default stores everything in Durable Object storage.

None
on_oauth_callback Callable[[MCPOAuthResult, Request], Awaitable[Response | None]] | None

Runs after every OAuth callback; a returned Response replaces the default redirect.

None
oauth_success_redirect str | None

Where the callback redirects, resolved against the request's origin; the error redirect gets ?error=<message>.

None
oauth_error_redirect str | None

Where the callback redirects, resolved against the request's origin; the error redirect gets ?error=<message>.

None
discovery_timeout Duration

How long loading a server's catalog may take.

15
keep_alive Callable[[], Awaitable[Disposable]] | None

Takes a keep-alive lease, held while a background connect runs.

None
http HttpTransport | None

The transport for every request (tests pass their own).

None

http = http or FetchTransport() instance-attribute

The transport every request goes through.

on_server_state_changed = self._changed.subscribe instance-attribute

Subscribe to every server state or catalog change.

connections property

Mapping[str, MCPClientConnection]: live connections by server id.

__init__(*, client_name, client_version, create_oauth_provider=None, on_oauth_callback=None, oauth_success_redirect=None, oauth_error_redirect=None, discovery_timeout=15, keep_alive=None, http=None)

on_start() async

Create the table, then restore every stored server in the background.

on_request(request) async

Claim an OAuth callback for one of this object's servers.

dispose() async

Close every connection.

add_server(name, url, *, id=None, callback_url=None, headers=None, transport='auto', retry=None) async

Register a server, connect to it and load its catalog.

Adding the same name and URL again returns the existing server.

Parameters:

Name Type Description Default
name str

A display name.

required
url str

The server's Streamable HTTP endpoint.

required
id str | None

A stable id (normalized); by default a random one.

None
callback_url str | None

The OAuth callback URL; without one, OAuth servers fail.

None
headers Mapping[str, str] | None

Sent on every request, and stored with the server.

None
transport TransportType

auto or streamable-http (the same thing for now).

'auto'
retry RetryOptions | None

Connection retries when the server is restored.

None

Returns:

Type Description
AddMcpServerResult

ready, or authenticating with the URL the user must visit.

Raises:

Type Description
MCPServerIdConflictError

If id belongs to a different name or URL.

MCPBlockedUrlError

If url points at a private address.

MCPConnectionError

If connecting or discovery fails (the server stays stored).

connect_server(id) async

Connect a stored server again (after a failure), and load its catalog.

Raises:

Type Description
MCPServerNotFoundError

If no server has this id.

MCPConnectionError

If connecting or discovery fails.

remove_server(id) async

Close the server's connection and delete it and its OAuth state.

This doesn't revoke tokens at the OAuth provider.

close_connection(id) async

Close the server's connection, keeping it stored.

Raises:

Type Description
MCPServerNotFoundError

If there's no connection with this id.

discover(id, *, timeout=None) async

Reload a connected server's catalog.

Raises:

Type Description
MCPServerNotFoundError

If there's no connection with this id.

wait_for_connections(*, timeout=None) async

Wait until every background connect and discovery has settled.

Never raises. timeout bounds the wait; 0 returns at once.

list_servers()

Return every stored server.

servers_state()

Return what the cf_agent_mcp_servers frame carries.

list_tools(*, server_id=None, server_name=None, state=None)

Return the tools of the servers matching every given filter.

list_prompts(*, server_id=None, server_name=None, state=None)

Return the prompts of the servers matching every given filter.

list_resources(*, server_id=None, server_name=None, state=None)

Return the resources of the servers matching every given filter.

list_resource_templates(*, server_id=None, server_name=None, state=None)

Return the resource templates of the servers matching every given filter.

call_tool(server_id, name, arguments=None, *, timeout=None) async

Call a tool. A tool error is is_error=True, not an exception.

Raises:

Type Description
MCPServerNotFoundError

If there's no connection with this id.

MCPServerNotReadyError

If the server isn't ready.

(MCPRpcError, MCPTransportError, MCPAuthorizationRequiredError)

If the call fails.

read_resource(server_id, uri) async

Read a resource (raises as call_tool).

get_prompt(server_id, name, arguments=None) async

Render a prompt (raises as call_tool).

AudioContent dataclass

Bases: _Record

Base64-encoded audio.

data instance-attribute

mime_type = wire('mimeType') class-attribute instance-attribute

annotations = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

type = 'audio' class-attribute

__init__(*, data, mime_type=wire('mimeType'), annotations=None, meta=wire('_meta', None))

BlobResourceContents dataclass

Bases: _Record

A binary resource's contents, base64-encoded.

uri instance-attribute

blob instance-attribute

mime_type = wire('mimeType', None) class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

__init__(*, uri, blob, mime_type=wire('mimeType', None), meta=wire('_meta', None))

CallToolResult dataclass

Bases: _Record

What a tool call returned. is_error is a tool error, not an exception.

content = dataclasses.field(default_factory=list) class-attribute instance-attribute

structured_content = wire('structuredContent', None) class-attribute instance-attribute

is_error = wire('isError', False) class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

from_wire(payload) classmethod

Return the result for a JSON object.

__init__(*, content=list(), structured_content=wire('structuredContent', None), is_error=wire('isError', False), meta=wire('_meta', None))

EmbeddedResource dataclass

Bases: _Record

A resource's contents embedded in a result.

resource instance-attribute

annotations = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

type = 'resource' class-attribute

from_wire(payload) classmethod

Return the embedded resource for a JSON object.

Raises:

Type Description
KeyError

If a required field is missing.

__init__(*, resource, annotations=None, meta=wire('_meta', None))

GetPromptResult dataclass

Bases: _Record

A rendered prompt.

messages instance-attribute

description = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

from_wire(payload) classmethod

Return the result for a JSON object.

Raises:

Type Description
KeyError

If a required field is missing.

__init__(*, messages, description=None, meta=wire('_meta', None))

ImageContent dataclass

Bases: _Record

A base64-encoded image.

data instance-attribute

mime_type = wire('mimeType') class-attribute instance-attribute

annotations = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

type = 'image' class-attribute

__init__(*, data, mime_type=wire('mimeType'), annotations=None, meta=wire('_meta', None))

Prompt dataclass

Bases: _Record

A prompt template a server offers.

name instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

arguments = None class-attribute instance-attribute

icons = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

from_wire(payload) classmethod

Return the prompt for a JSON object.

Raises:

Type Description
KeyError

If a required field is missing.

__init__(*, name, title=None, description=None, arguments=None, icons=None, meta=wire('_meta', None))

PromptArgument dataclass

Bases: _Record

One argument a prompt takes.

name instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

required = None class-attribute instance-attribute

__init__(*, name, title=None, description=None, required=None)

PromptMessage dataclass

One message of a rendered prompt.

role instance-attribute

content instance-attribute

__init__(*, role, content)

ReadResourceResult dataclass

Bases: _Record

A resource's contents.

contents instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

from_wire(payload) classmethod

Return the result for a JSON object.

Raises:

Type Description
KeyError

If a required field is missing.

__init__(*, contents, meta=wire('_meta', None))

Resource dataclass

Bases: _Record

A resource a server offers.

uri instance-attribute

name instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

mime_type = wire('mimeType', None) class-attribute instance-attribute

size = None class-attribute instance-attribute

annotations = None class-attribute instance-attribute

icons = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

__init__(*, uri, name, title=None, description=None, mime_type=wire('mimeType', None), size=None, annotations=None, icons=None, meta=wire('_meta', None))

Bases: _Record

A link to a resource (not necessarily one resources/list returns).

uri instance-attribute

name instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

mime_type = wire('mimeType', None) class-attribute instance-attribute

size = None class-attribute instance-attribute

annotations = None class-attribute instance-attribute

icons = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

type = 'resource_link' class-attribute

__init__(*, uri, name, title=None, description=None, mime_type=wire('mimeType', None), size=None, annotations=None, icons=None, meta=wire('_meta', None))

ResourceTemplate dataclass

Bases: _Record

A parameterized resource (an RFC 6570 URI template).

uri_template = wire('uriTemplate') class-attribute instance-attribute

name instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

mime_type = wire('mimeType', None) class-attribute instance-attribute

annotations = None class-attribute instance-attribute

icons = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

__init__(*, uri_template=wire('uriTemplate'), name, title=None, description=None, mime_type=wire('mimeType', None), annotations=None, icons=None, meta=wire('_meta', None))

ServerPrompt dataclass

A prompt and the server it belongs to.

server_id instance-attribute

prompt instance-attribute

__init__(*, server_id, prompt)

ServerResource dataclass

A resource and the server it belongs to.

server_id instance-attribute

resource instance-attribute

__init__(*, server_id, resource)

ServerResourceTemplate dataclass

A resource template and the server it belongs to.

server_id instance-attribute

resource_template instance-attribute

__init__(*, server_id, resource_template)

ServerTool dataclass

A tool and the server it belongs to.

server_id instance-attribute

tool instance-attribute

__init__(*, server_id, tool)

TextContent dataclass

Bases: _Record

Text in a tool result or prompt message.

text instance-attribute

annotations = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

type = 'text' class-attribute

__init__(*, text, annotations=None, meta=wire('_meta', None))

TextResourceContents dataclass

Bases: _Record

A text resource's contents.

uri instance-attribute

text instance-attribute

mime_type = wire('mimeType', None) class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

__init__(*, uri, text, mime_type=wire('mimeType', None), meta=wire('_meta', None))

Tool dataclass

Bases: _Record

A tool a server offers. input_schema is plain JSON Schema.

name instance-attribute

input_schema = wire('inputSchema') class-attribute instance-attribute

title = None class-attribute instance-attribute

description = None class-attribute instance-attribute

output_schema = wire('outputSchema', None) class-attribute instance-attribute

annotations = None class-attribute instance-attribute

execution = None class-attribute instance-attribute

icons = None class-attribute instance-attribute

meta = wire('_meta', None) class-attribute instance-attribute

__init__(*, name, input_schema=wire('inputSchema'), title=None, description=None, output_schema=wire('outputSchema', None), annotations=None, execution=None, icons=None, meta=wire('_meta', None))

UnknownContent dataclass

A content block of a type this client doesn't know, kept as sent.

fields instance-attribute

type property

str | None: the block's type.

__init__(*, fields)

DurableObjectOAuthProvider

Bases: MCPOAuthProvider

Keeps OAuth state in Durable Object storage, with dynamic registration.

Keys are upstream's: /{client_name}/{server_id}/{client_id}/token and so on.

Parameters:

Name Type Description Default
storage Any

The Durable Object's ctx.storage.

required
client_name str

Prefixes every key, and names the client when it registers.

required
redirect_url str

The OAuth callback URL.

required

client_name = client_name instance-attribute

client_metadata property

OAuthClientMetadata: a public client (no secret), as upstream.

__init__(storage, client_name, redirect_url)

tokens() async

Return the stored tokens.

save_tokens(tokens) async

Store new tokens; the discovery state is no longer needed.

clear_tokens() async

Forget the tokens.

client_information() async

Return the registered client's credentials.

save_client_information(info) async

Store a registration; sets client_id.

clear_client_information() async

Forget the registration and its tokens.

discovery_state() async

Return what discovery found for the pending authorization.

save_discovery_state(state) async

Store what discovery found.

create_state() async

Return a new state parameter, stored for 10 minutes.

check_state(state) async

Return whether state was issued here and is unexpired.

consume_state(state) async

Use state up.

save_code_verifier(state, verifier) async

Store the PKCE verifier for state.

code_verifier(state) async

Return the PKCE verifier for state (or upstream's legacy one).

delete_code_verifier(state) async

Forget the PKCE verifier for state.

clear() async

Delete every key stored for this server, 128 at a time.

MCPOAuthProvider

Bases: ABC

Stores one server's OAuth state; override it for another client setup.

The client sets server_id and client_id before use.

Parameters:

Name Type Description Default
redirect_url str

The OAuth callback URL.

required

redirect_url = redirect_url instance-attribute

server_id = '' instance-attribute

The server this provider stores state for.

client_id = None instance-attribute

The registered OAuth client id, once there is one.

client_metadata abstractmethod property

OAuthClientMetadata: the dynamic registration request.

__init__(redirect_url)

tokens() abstractmethod async

Return the stored tokens.

save_tokens(tokens) abstractmethod async

Store new tokens.

clear_tokens() abstractmethod async

Forget the tokens (a refresh failed).

client_information() abstractmethod async

Return the registered client's credentials.

save_client_information(info) abstractmethod async

Store a registration; sets client_id.

clear_client_information() abstractmethod async

Forget the registration and its tokens.

discovery_state() abstractmethod async

Return what discovery found for the pending authorization.

save_discovery_state(state) abstractmethod async

Store what discovery found.

create_state() abstractmethod async

Return a new state parameter (<nonce>.<server_id>), stored.

check_state(state) abstractmethod async

Return whether state was issued here and is unexpired.

Checking doesn't use it up; consume_state does, once the callback succeeds.

consume_state(state) abstractmethod async

Use state up.

save_code_verifier(state, verifier) abstractmethod async

Store the PKCE verifier for the authorization state started.

code_verifier(state) abstractmethod async

Return the PKCE verifier for state.

delete_code_verifier(state) abstractmethod async

Forget the PKCE verifier for state.

clear() abstractmethod async

Forget everything stored for this server.

AddMcpServerResult dataclass

What add_server / add_mcp_server returns.

Parameters:

Name Type Description Default
id str

The server's id.

required
state Literal['ready', 'authenticating']

ready, or authenticating when the user must visit auth_url first.

required
auth_url str | None

The authorization URL, while authenticating.

None

id instance-attribute

state instance-attribute

auth_url = None class-attribute instance-attribute

__init__(*, id, state, auth_url=None)

MCPConnectionState

Bases: StrEnum

Where a server connection is (upstream MCPConnectionState).

AUTHENTICATING = 'authenticating' class-attribute instance-attribute

Waiting for the user to finish OAuth.

CONNECTING = 'connecting' class-attribute instance-attribute

CONNECTED = 'connected' class-attribute instance-attribute

Connected; the catalog isn't loaded (yet, or discovery failed).

DISCOVERING = 'discovering' class-attribute instance-attribute

READY = 'ready' class-attribute instance-attribute

FAILED = 'failed' class-attribute instance-attribute

MCPOAuthResult dataclass

The outcome of an OAuth callback, passed to on_mcp_oauth_callback.

error may contain untrusted text from the OAuth provider.

server_id instance-attribute

success instance-attribute

error = None class-attribute instance-attribute

__init__(*, server_id, success, error=None)

MCPServerInfo dataclass

One server in the cf_agent_mcp_servers frame.

state is not-connected for a stored server with no live connection. error may contain untrusted text from an OAuth provider: escape it before showing it.

name instance-attribute

server_url instance-attribute

auth_url instance-attribute

state instance-attribute

error instance-attribute

instructions instance-attribute

capabilities instance-attribute

__init__(*, name, server_url, auth_url, state, error, instructions, capabilities)

MCPServerRecord dataclass

One stored server (a cf_agents_mcp_servers row).

Parameters:

Name Type Description Default
id str

The server's identity.

required
name str

The server's identity.

required
server_url str

The server's identity.

required
callback_url str

The OAuth callback URL ("" for none, as upstream stores it).

''
client_id str | None

The OAuth client id, once registered.

None
auth_url str | None

The pending authorization URL, while authenticating.

None
options dict[str, Any]

The decoded server_options JSON (upstream's camelCase shape), including keys this client doesn't read.

dict()

id instance-attribute

name instance-attribute

server_url instance-attribute

callback_url = '' class-attribute instance-attribute

client_id = None class-attribute instance-attribute

auth_url = None class-attribute instance-attribute

options = field(default_factory=dict) class-attribute instance-attribute

transport_type property

str: the stored transport type (auto when unset).

headers property

dict[str, str]: headers sent on every request.

retry property

RetryOptions | None: the stored connection retries.

snapshot property

SessionSnapshot | None: the stored session, if any.

__init__(*, id, name, server_url, callback_url='', client_id=None, auth_url=None, options=dict())

MCPServersState dataclass

What the cf_agent_mcp_servers frame carries.

tools, prompts and resources are the servers' own JSON objects with a serverId added, as upstream sends them.

servers = field(default_factory=dict) class-attribute instance-attribute

tools = field(default_factory=list) class-attribute instance-attribute

prompts = field(default_factory=list) class-attribute instance-attribute

resources = field(default_factory=list) class-attribute instance-attribute

__init__(*, servers=dict(), tools=list(), prompts=list(), resources=list())

OAuthClientInformation

Bases: TypedDict

An RFC 7591 registration response: the client's credentials.

issuer is added by the client, to drop credentials registered with a different authorization server.

client_id instance-attribute

client_secret instance-attribute

client_id_issued_at instance-attribute

client_secret_expires_at instance-attribute

token_endpoint_auth_method instance-attribute

redirect_uris instance-attribute

issuer instance-attribute

OAuthClientMetadata

Bases: TypedDict

An RFC 7591 client registration request.

redirect_uris instance-attribute

client_name instance-attribute

client_uri instance-attribute

grant_types instance-attribute

response_types instance-attribute

token_endpoint_auth_method instance-attribute

scope instance-attribute

OAuthTokens

Bases: TypedDict

An RFC 6749 token response.

access_token instance-attribute

token_type instance-attribute

expires_in instance-attribute

scope instance-attribute

refresh_token instance-attribute

StateCheck dataclass

Whether an OAuth state parameter is one this provider issued.

valid instance-attribute

error = None class-attribute instance-attribute

__init__(*, valid, error=None)

normalize_server_id(value)

Return value as a storage- and tool-name-safe server id.

Lowercase, runs of characters outside [a-z0-9_-] become one -, leading and trailing - / _ are trimmed, ids that don't start with a letter get an id- prefix, and the result is cut to 64 characters.

Examples:

>>> normalize_server_id("GitHub MCP!")
'github-mcp'
>>> normalize_server_id("42-things")
'id-42-things'