Skip to main content

Overview

The Agent class is the core building block for creating stateful agents on Cloudflare Workers. It extends PartyServer to provide WebSocket connections, state management, RPC methods, SQL storage, scheduling, email routing, MCP client support, and workflow integration.

Type Parameters

Cloudflare.Env
default:"Cloudflare.Env"
Environment type containing bindings (KV, D1, R2, etc.)
unknown
default:"unknown"
State type to store within the Agent
Record<string, unknown>
default:"Record<string, unknown>"
Props type passed to the Agent on creation

Properties

state

State
required
Current state of the Agent. Read-only. Use setState() to update.

initialState

State
Initial state for the Agent. Override to provide default state values.

name

string
required
The unique name/ID of this Agent instance (inherited from PartyServer).

env

Env
required
The environment bindings for this Agent (KV, D1, R2, etc.).

ctx

AgentContext
required
The Durable Object context (storage, waitUntil, etc.).

mcp

MCPClientManager
required
MCP client manager for connecting to external MCP servers.

observability

Observability
Observability implementation for emitting events. Defaults to genericObservability.

Static Options

options

AgentStaticOptions
Static configuration options for the Agent class. Override in subclasses.

Methods

setState()

State
required
New state to set
Update the Agent’s state. Persists to storage and broadcasts to all connected clients.
Throws an error if called from a readonly connection context.

sql()

TemplateStringsArray
required
SQL query template strings
(string | number | boolean | null)[]
Values to be inserted into the query
Execute SQL queries against the Agent’s database.
Returns: T[] - Array of query results Throws: SqlError - If the query fails

schedule()

Schedule a callback to run at a future time or on a recurring interval.
keyof this
required
Name of the method to call
ScheduleOptions
required
Scheduling options
Returns: Promise<string> - Schedule ID

queue()

Queue a callback for asynchronous execution.
keyof this
required
Name of the method to call
T
Data to pass to the callback
RetryOptions
Retry options for this specific queue item
Returns: Promise<void>

retry()

Retry an async operation with exponential backoff and jitter.
(attempt: number) => Promise<T>
required
The async function to retry. Receives the current attempt number (1-indexed).
RetryOptions
Retry configuration (falls back to static options)
(err: unknown, nextAttempt: number) => boolean
Predicate to determine if an error should be retried. Return false to stop immediately.
Returns: Promise<T> - The result of fn on success Throws: The last error if all attempts fail or shouldRetry returns false

replyToEmail()

Reply to an email received via routeAgentEmail().
AgentEmail
required
The email to reply to
ReplyOptions
required
string
required
Sender name
string
Email subject (defaults to “Re: original subject”)
string
required
Email body
string
default:"text/plain"
MIME content type
Record<string, string>
Additional headers
string | null
Secret for signing agent headers (enables secure reply routing). Required if the email was routed via createSecureReplyEmailResolver.

runWorkflow()

Run a Workflow and track its execution.
string
required
Name of the Workflow binding in env
Params
required
Parameters to pass to the workflow
RunWorkflowOptions
string
Unique workflow instance ID (auto-generated if not provided)
Record<string, unknown>
Custom metadata to store with the workflow
Returns: Promise<string> - Workflow instance ID

getWorkflows()

Query tracked workflows.
WorkflowQueryCriteria
string
Filter by workflow binding name
WorkflowStatus
Filter by status (“queued”, “running”, “complete”, “errored”, etc.)
number
default:"100"
Maximum number of results
number
default:"0"
Number of results to skip
Returns: Promise<WorkflowPage>

approveWorkflow()

Approve a workflow waiting for approval.
string
required
Workflow instance ID
T
Metadata to pass to the workflow

rejectWorkflow()

Reject a workflow waiting for approval.
string
required
Workflow instance ID
string
Reason for rejection

Lifecycle Hooks

onConnect()

Connection
required
The new WebSocket connection
ConnectionContext
required
Connection context (includes the upgrade request)
Called when a new WebSocket connection is established.

onMessage()

Connection
required
The connection that sent the message
string | ArrayBuffer
required
The message data
Called when a WebSocket message is received.

onClose()

Connection
required
The connection that closed
number
required
WebSocket close code
string
required
Close reason
boolean
required
Whether the close was clean
Called when a WebSocket connection closes.

onRequest()

Request
required
The HTTP request
Called when an HTTP request is received.
Returns: Response | Promise<Response>

onStart()

Props
Props passed to the Agent on creation
Called when the Agent is created or wakes from hibernation.

onEmail()

AgentEmail
required
The incoming email message
Called when an email is routed to this Agent via routeAgentEmail().

onStateChanged()

State | undefined
required
The new state
Connection | 'server'
required
Source of the state update
Called after state has been persisted and broadcast. This is a notification hook—errors are routed to onError and do not affect persistence.

validateStateChange()

State
required
The proposed new state
Connection | 'server'
required
Source of the state update
Called before state is persisted. Throw an error to reject the update. Must be synchronous.

onWorkflowProgress()

WorkflowProgressCallback
required
Progress event from the workflow
Called when a tracked workflow reports progress.

onWorkflowComplete()

WorkflowCompleteCallback
required
Completion event from the workflow
Called when a tracked workflow completes.

onWorkflowError()

WorkflowErrorCallback
required
Error event from the workflow
Called when a tracked workflow errors.

onError()

Called when an error occurs. Override to customize error handling.

Connection Management

getConnections()

Get all active WebSocket connections.
Returns: Iterable<Connection>

broadcast()

string | ArrayBuffer
required
Message to broadcast
string[]
Connection IDs to exclude
Broadcast a message to all connected clients (optionally excluding some).

setConnectionReadonly()

Connection
required
The connection to mark
boolean
default:"true"
Whether the connection should be readonly
Mark a connection as readonly (cannot call setState).

isConnectionReadonly()

Connection
required
The connection to check
Check if a connection is marked as readonly.
Returns: boolean

shouldConnectionBeReadonly()

Connection
required
The connection being established
ConnectionContext
required
Connection context
Override to determine if a connection should be readonly on connect.
Returns: boolean