Agent class API reference for Python
Use this reference to choose the attributes, hooks and methods for an
agents.Agent subclass. Agent is a
Durable Object.
Override the hooks you need and decorate client methods with @callable.
self.ctx and self.env work as on any Durable Object. Leave fetch,
alarm and the webSocket* handlers to the SDK.
Durations are a timedelta or a number of seconds everywhere in the SDK, so
a default of 30 means 30 seconds. Every public name below imports from
agents.
Class attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
initial_state |
S \| None |
None |
State a new agent starts with. Each agent gets its own copy. |
options |
AgentOptions |
AgentOptions() |
Settings for every instance of the class. |
observability |
Observability \| None |
LoggingObservability() |
Where structured events go. None turns them off. |
Agent is generic over its state type: class Counter(Agent[CounterState]).
S defaults to dict[str, Any].
AgentOptions
A frozen dataclass with keyword-only fields. A subclass's options replaces
its parent's. To extend them, use
dataclasses.replace(Parent.options, ...).
| Field | Type | Default | Description |
|---|---|---|---|
send_identity_on_connect |
bool |
True |
Send the cf_agent_identity frame when a client connects. |
hung_schedule_timeout |
Duration |
30 |
When a running interval schedule counts as hung and runs again. |
keep_alive_interval |
Duration |
30 |
Alarm interval while keep_alive() is held. |
retry |
RetryOptions |
RetryOptions() |
Default retries for scheduled and queued callbacks. |
fiber_recovery_hook_timeout |
Duration |
10 |
Timeout for the SDK's own fiber-recovery hooks. |
fiber_recovery_scan_deadline |
Duration |
10 |
Soft deadline for one fiber-recovery scan. |
fiber_recovery_max_age |
Duration \| None |
24 hours | When to stop retrying a failed recovery. None retries forever. |
max_alarm_memory_limit_strikes |
int |
3 |
Alarm memory-limit resets tolerated before recovery work stops. |
mcp |
MCPOptions \| None |
None |
Turns on the MCP client. |
expose_error_details |
bool |
False |
Put an unhandled error's traceback in the 500 body. Local development only. |
RetryOptions
| Field | Type | Default | Description |
|---|---|---|---|
max_attempts |
int |
3 |
Total attempts, including the first. |
base_delay |
Duration |
0.1 |
Base delay for the backoff. |
max_delay |
Duration |
3.0 |
The longest wait between attempts. |
The wait before each retry is random, up to
min(2 ** attempt * base_delay, max_delay).
Hooks
Override these on your subclass. All are async def except
validate_state_change.
| Hook | Called | Default |
|---|---|---|
on_start() |
Once per wake, before any request, message or alarm. | Does nothing. |
on_request(request) -> Response |
For an HTTP request the SDK doesn't handle itself. | 404. |
on_connect(connection, ctx) |
After a client connects and receives its protocol frames. | Does nothing. |
on_message(connection, message) |
For a frame that isn't a state update or an RPC call. message is str or bytes. |
Does nothing. |
on_close(connection, code, reason, was_clean) |
When a client disconnects. | Does nothing. |
on_error(connection, error) |
When a hook, callback or socket fails. connection is set only for a socket's own error. |
Re-raises. |
on_state_changed(state, source) |
After a state change is saved and sent to clients. | Does nothing. |
validate_state_change(next_state, source) |
Before a state change is saved. Raise to reject it. Synchronous. | Accepts. |
get_connection_tags(connection, ctx) -> list[str] |
Once per new connection. At most 9 tags of up to 256 characters, or ValueError. |
[]. |
should_connection_be_readonly(connection, ctx) -> bool |
Once per new connection. | False. |
should_send_protocol_messages(connection, ctx) -> bool |
Once per new connection. | True. |
on_alarm() |
On every alarm, after due schedules and queue items. | Does nothing. |
on_fiber_recovered(ctx) -> FiberRecoveryResult \| None |
On wake, for a fiber whose isolate stopped. Runs before on_start. |
Logs a warning. |
on_before_sub_agent(request, child) |
Before a request is forwarded to a sub-agent. | Forwards it. |
source is "server" or the Connection a client's change came from. ctx
is a ConnectionContext, whose request is the WebSocket upgrade request.
When on_error returns normally, the error counts as handled. A failed
request gets a 500, and a failed connect or message leaves the connection
open.
Errors from on_start, on_state_changed, and scheduled, queued or task
callbacks that ran out of retries reach on_error only as a report.
Returning normally doesn't recover them. on_start still fails, and
so does the request, message or alarm that woke the agent.
Identity
| Member | Type | Description |
|---|---|---|
name |
str |
The instance name. |
sql |
Sql |
The agent's SQLite database. See SQL. |
tasks |
Tasks |
Durable task runs. See Run durable tasks. |
dynamic_agents |
DynamicAgents |
This agent's sub-agents. |
parent_path, self_path |
Sequence[AgentPathStep] |
Agents from the root down. Empty on a root. |
lifecycle |
Lifecycle |
What the capabilities are installed on. See Lifecycle and capabilities. |
websockets |
WebSockets |
The installed WebSockets capability. Add handlers that share the agent's connections with websockets.use(...); they run before on_message. |
mcp |
MCPClientManager |
The MCP client. Raises MCPNotEnabledError unless options.mcp is set. |
session_affinity |
str |
The Durable Object id as a string. Stable per instance. |
State
state
@property
def state(self) -> S | None
The current state. Treat it as read-only.
set_state
def set_state(self, state: S) -> None
Validates, saves and broadcasts state, then runs on_state_changed in the
background. Raises ReadonlyConnectionError when called while serving a
readonly connection, or whatever validate_state_change raises.
SQL
def sql(self, query: LiteralString, *params: SqlValue, row: type[R] | None = None) -> Sequence[dict[str, Any]]
self.sql is an Sql object. Calling it runs one statement and returns its
rows as dicts. It is synchronous.
paramsfill the?placeholders.SqlValueisint | float | str | bytes | None.rowannotates the rows' type for a type checker. The SDK doesn't validate the rows.- Raises
SqlErrorwhen SQLite rejects the statement,TypeErrorfor an unsupported parameter type, andValueErrorfor an integer outside ±253.
Connections
| Method | Returns | Description |
|---|---|---|
get_connections(tag=None) |
Iterator[Connection] |
Open connections, optionally only those with tag. |
get_connection(id) |
Connection \| None |
One connection. Raises DuplicateConnectionIdError if two share the id. |
broadcast(message, *, exclude=()) |
None |
Sends to every open connection except exclude (connections or ids). |
get_callable_methods() |
dict[str, CallableMetadata] |
The @callable methods, by name. |
Connection
| Member | Type | Description |
|---|---|---|
id |
str |
The client's connection id, or a generated one. |
uri |
str \| None |
The URL the client connected with. |
tags |
Sequence[str] |
The connection's tags, with its id first. |
state |
ConnState \| None |
Per-connection JSON state. |
set_state(state) |
None |
Replaces the state. Raises ConnectionStateTooLargeError past 16 KiB. |
readonly |
bool |
Whether the client may change the agent's state. Settable. |
protocol_enabled |
bool |
Whether the client gets protocol frames. |
send(message) |
None |
Sends a str or bytes frame. |
close(code=None, reason=None) |
None |
Closes the connection. |
@callable
@callable
@callable(description: str | None = None, streaming: bool = False)
Lets clients call an async method over their WebSocket. With
streaming=True, the method receives a StreamingResponse before the
client's arguments. An async generator streams one chunk per yield without
streaming=True. Raises TypeError for a non-async method, or an async
generator with streaming=True.
StreamingResponse
| Member | Description |
|---|---|
send(chunk) |
Sends one chunk. Returns False once closed or after the client leaves. Raises TypeError for a chunk JSON can't encode. |
end(final=None) |
Closes the stream. The client's call resolves with final. |
error(message) |
Closes the stream and rejects the client's call with message. |
is_closed |
Whether end or error has been called. |
Schedules
| Method | Returns |
|---|---|
schedule(when, callback, payload=None, *, retry=None, idempotent=None) |
Schedule |
schedule_every(interval, callback, payload=None, *, retry=None, idempotent=None) |
Schedule |
get_schedule_by_id(id) |
Schedule \| None |
list_schedules(*, id=None, type=None, start=None, end=None) |
Sequence[Schedule] |
cancel_schedule(id) |
bool |
whenis adatetimeto run once at that time, atimedeltaor number of seconds to run once after that delay, or a cronstrevaluated in UTC.intervalis at most 30 days. A longer one raisesValueError.callbackis a method of the agent or its name. It's called ascallback(payload, schedule). A name the agent doesn't have raisesValueError.idempotentdefaults toTruefor cron and interval schedules andFalsefor one-off schedules.
Schedule is a dataclass with id, callback, payload, type
("scheduled", "delayed", "cron" or "interval"), time (next run, UTC
datetime), retry, and delay, cron or interval for its type.
Queue
| Method | Returns |
|---|---|
queue(callback, payload=None, *, retry=None, id=None) |
str, the item id |
dequeue(id) |
bool |
dequeue_all() |
int |
dequeue_all_by_callback(callback) |
int |
get_queue(id) |
QueueItem \| None |
queue_items(callback=None) |
Sequence[QueueItem] |
The callback is called as callback(payload, item). Queuing an existing id
replaces that pending item. A blank id or an unknown callback raises
ValueError. QueueItem has id, callback, payload, created_at and
retry.
Capabilities
use
def use[C: LifecycleCapability](self, capability: C) -> C
Installs a capability and returns it. Call it in __init__. After startup it raises RuntimeError, as it does for an id that's already installed.
MCP
| Method | Description |
|---|---|
async add_mcp_server(name, url, *, id=None, headers=None, transport="auto", callback_host=None, callback_path=None, agents_prefix="agents", retry=None) |
Stores a server, connects and loads its catalog. See Connect to MCP servers. |
async remove_mcp_server(id) |
Closes a server's connection and deletes it and its OAuth state. |
get_mcp_servers() |
What the cf_agent_mcp_servers frame carries. |
async on_mcp_oauth_callback(result, request) |
A hook. Return a Response to replace the redirect after OAuth. |
create_mcp_oauth_provider(callback_url) |
A hook. Return your own MCPOAuthProvider. |
Without options.mcp, add_mcp_server, remove_mcp_server and get_mcp_servers raise MCPNotEnabledError.
Fibers and keep-alive
| Method | Returns |
|---|---|
run_fiber(name, fn) |
What fn returns |
stash(data) |
None |
start_fiber(name, fn, *, fiber_id=None, idempotency_key=None, metadata=None, wait_for_completion=False) |
StartFiberResult |
inspect_fiber(fiber_id), inspect_fiber_by_key(key) |
FiberInspection \| None |
list_fibers(*, status=None, name=None, limit=None) |
Sequence[FiberInspection] |
cancel_fiber(fiber_id, reason=None), cancel_fiber_by_key(key, reason=None) |
bool |
resolve_fiber(fiber_id, result) |
bool |
delete_fibers(*, status=None, settled_before=None, limit=None) |
int |
keep_alive() |
Disposable |
keep_alive_while(fn) |
What fn returns |
fn receives a FiberContext with id and stash(data). stash outside a
fiber raises RuntimeError.
start_fiberrunsfnin the background and discards its return value. A blankfiber_idoridempotency_keyraisesValueError.list_fibersreturns 50 records by default and at most 100.delete_fibersdeletescompleted,errorandabortedrecords by default, 100 at a time by default and at most 500. It deletesinterruptedrecords only whenstatusnames them.cancel_fiberandresolve_fiberreturnFalsefor an unknown or finished fiber.
See Long-running work.
Teardown
async def destroy(self) -> None
Deletes the agent's storage, alarm and connections. The object resets right after this returns, so don't use it again. The next request for the same name creates a fresh agent.
Module functions
route_agent_request
async def route_agent_request(
request: Request,
env: Any,
*,
prefix: str = "agents",
cors: bool | Mapping[str, str] = False,
jurisdiction: str | None = None,
location_hint: str | None = None,
routing_retry: RoutingRetryOptions | Literal[False] | None = None,
on_before_connect: BeforeHook | None = None,
on_before_request: BeforeHook | None = None,
) -> Response | None
Forwards /{prefix}/{agent}/{name}/... to that agent. Returns None for any
other path, and a 400 when {agent} matches no binding. See
Route requests.
get_agent_by_name
async def get_agent_by_name(
namespace: Any,
name: str,
*,
jurisdiction: str | None = None,
location_hint: str | None = None,
routing_retry: RoutingRetryOptions | Literal[False] | None = None,
) -> Any
Starts the agent and returns its Durable Object stub for RPC calls.
get_sub_agent_by_name and route_sub_agent_request
async def get_sub_agent_by_name(parent: Any, cls: type, name: str) -> SubAgentStub
async def route_sub_agent_request(request: Request, parent: Any, *, from_path: str | None = None) -> Response
See Use sub-agents.
retry
async def retry(
fn: Callable[[int], Awaitable[T]],
*,
max_attempts: int = 3,
base_delay: Duration = 0.1,
max_delay: Duration = 3.0,
should_retry: Callable[[Exception, int], bool] | None = None,
) -> T
Calls fn(attempt) until it returns, with the same random backoff as
RetryOptions. attempt starts at 1. should_retry gets
the error and the next attempt number, and returning False re-raises the
error at once. After the last attempt, the last error propagates. Retries
live in memory only, so a restart loses them. For retries that survive a
restart, use a task step.
get_current_agent
def get_current_agent() -> CurrentAgent | None
Returns the agent the running code belongs to, with the connection and
request being served, or None outside an agent. It works in hooks,
@callable methods, callbacks and RPC methods, and in asyncio tasks they
start.
Exceptions
Every exception the SDK raises on purpose subclasses AgentsException.
| Exception | Raised when |
|---|---|
SqlError |
SQLite rejects a statement. error.query holds it. |
ReadonlyConnectionError |
set_state runs while serving a readonly connection. |
ConnectionStateTooLargeError |
Connection.set_state exceeds 16 KiB. |
DuplicateConnectionIdError |
get_connection finds two connections with one id. |
InvalidCronExpressionError |
schedule gets an invalid cron string. Also a ValueError. |
NonRetryableError |
You raise it in a task step to fail the run without retries. |
StepTimeoutError |
A task step attempt runs past its timeout. Also a TimeoutError. |
DuplicateTaskStepError |
A task run reuses a step name. |
TaskReplayDivergedError |
A task's steps changed while a run was in progress. |
MissingTaskDefinitionError |
A run's @task method was removed or renamed. The run fails. |
TaskSerializationError |
A task input, step result or result isn't JSON, or is over 1 MiB. Also a TypeError. |
FiberConflictError |
fiber_id and idempotency_key name different existing fibers. |
FiberNotFoundError |
A fiber is deleted while start_fiber(..., wait_for_completion=True) waits. |
SubAgentAbortedError |
A call to a sub-agent was cut off by dynamic_agents.abort. |
ChatStreamError |
A chat turn yielded an Error chunk. on_error receives it. |
StreamClosedError, StreamNotFoundError, StreamSerializationError |
A write to a settled stream, a read of a missing one, or a chunk that isn't JSON. Raised by AIChatAgent.streams. |
Logging and events
The SDK logs to loggers under agents, such as agents.agent and
agents.routing, with the standard
logging module.
It also emits structured events, such as rpc, state:update and
queue:error. The default LoggingObservability writes each event as one
JSON line to the agents.events logger at DEBUG. To see them:
import logging
logging.getLogger("agents.events").setLevel(logging.DEBUG)
On Workers, the SDK sends its logs to the JavaScript console for you. Don't add
logging.basicConfig() as well, or each line appears twice.
To send events elsewhere, set observability to an object with an
emit(event: ObservabilityEvent) method. See
Observe an agent, which also lists every event.