Skip to content
Cloudflare Docs

Agents API

This page provides an overview of the Agents SDK. For detailed documentation on each feature, refer to the linked reference pages.

Overview

The Agents SDK provides two main APIs:

APIDescription
Server-side Agent classEncapsulates agent logic: connections, state, methods, AI models, error handling
Client-side SDKAgentClient, useAgent, and useAgentChat for connecting from browsers

Agent class

An Agent is a class that extends the base Agent class:

TypeScript
import { Agent } from "agents";
class MyAgent extends Agent<Env, State> {
// Your agent logic
}
export default MyAgent;

Each Agent can have millions of instances. Each instance is a separate micro-server that runs independently, allowing horizontal scaling. Instances are addressed by a unique identifier (user ID, email, ticket number, etc.).

Lifecycle

flowchart TD
    A["onStart<br/>(instance wakes up)"] --> B["onRequest<br/>(HTTP)"]
    A --> C["onConnect<br/>(WebSocket)"]
    A --> D["onEmail"]
    C --> E["onMessage ↔ send()<br/>onError (on failure)"]
    E --> F["onClose"]
MethodWhen it runs
onStart(props?)When the instance starts, or wakes from hibernation. Receives optional initialization props passed via getAgentByName or routeAgentRequest.
onRequest(request)For each HTTP request to the instance
onConnect(connection, ctx)When a WebSocket connection is established
onMessage(connection, message)For each WebSocket message received
onError(connection, error)When a WebSocket error occurs
onClose(connection, code, reason, wasClean)When a WebSocket connection closes
onEmail(email)When an email is routed to the instance
onStateUpdate(state, source)When state changes (from server or client)

Core properties

PropertyTypeDescription
this.envEnvEnvironment variables and bindings
this.ctxExecutionContextExecution context for the request
this.stateStateCurrent persisted state
this.sqlFunctionExecute SQL queries on embedded SQLite

Server-side API reference

FeatureMethodsDocumentation
StatesetState(), onStateUpdate(), initialStateStore and sync state
Callable methods@callable() decoratorCallable methods
Schedulingschedule(), scheduleEvery(), getSchedules(), cancelSchedule()Schedule tasks
Queuequeue(), dequeue(), dequeueAll(), getQueue()Queue tasks
WebSocketsonConnect(), onMessage(), onClose(), broadcast()WebSockets
HTTP/SSEonRequest()HTTP and SSE
EmailonEmail(), replyToEmail()Email routing
WorkflowsrunWorkflow(), waitForApproval()Run Workflows
MCP ClientaddMcpServer(), removeMcpServer(), getMcpServers()MCP Client API
AI ModelsWorkers AI, OpenAI, Anthropic bindingsUsing AI models
ContextgetCurrentAgent()getCurrentAgent()
Observabilityobservability.emit()Observability

SQL API

Each Agent instance has an embedded SQLite database accessed via this.sql:

TypeScript
// Create tables
this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT)`;
// Insert data
this.sql`INSERT INTO users (id, name) VALUES (${id}, ${name})`;
// Query data
const users = this.sql<User>`SELECT * FROM users WHERE id = ${id}`;

For state that needs to sync with clients, use the State API instead.

Client-side API reference

FeatureMethodsDocumentation
WebSocket clientAgentClientClient SDK
HTTP clientagentFetch()Client SDK
React hookuseAgent()Client SDK
Chat hookuseAgentChat()Client SDK

Quick example

TypeScript
import { useAgent } from "agents/react";
import type { MyAgent } from "./server";
function App() {
const agent = useAgent<MyAgent, State>({
agent: "my-agent",
name: "user-123",
});
// Call methods on the agent
agent.stub.someMethod();
// Update state (syncs to server and all clients)
agent.setState({ count: 1 });
}

Chat agents

For AI chat applications, extend AIChatAgent instead of Agent:

TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
class ChatAgent extends AIChatAgent<Env> {
async onChatMessage(onFinish) {
// this.messages contains the conversation history
// Return a streaming response
}
}

Features include:

  • Built-in message persistence
  • Automatic resumable streaming (reconnect mid-stream)
  • Works with useAgentChat React hook

Refer to Build a chat agent for a complete tutorial.

Routing

Agents are accessed via URL patterns:

https://your-worker.workers.dev/agents/:agent-name/:instance-name

Use routeAgentRequest() in your Worker to route requests:

TypeScript
import { routeAgentRequest } from "agents";
export default {
async fetch(request: Request, env: Env) {
return (
routeAgentRequest(request, env) ||
new Response("Not found", { status: 404 })
);
},
};

Refer to Routing for custom paths, CORS, and instance naming patterns.

Next steps