Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Agents SDK: Agent Class, Durable State, RPC, MCP, and Client

How the Cloudflare Agents SDK maps agents to Durable Objects, exposes RPC and WebSockets, connects browsers, calls LLMs, and hosts MCP servers.

This page summarizes Cloudflare’s documentation on building agents with the Agents SDK (agents npm package): a stateful agent runtime on Workers, the server-side Agent class, browser client APIs, Workers AI and other model providers, and optional Model Context Protocol (MCP) servers. If you are new, start from the Agents quick start; if you already have a Worker, use Add to existing project.

Agents on Workers: what the Agents SDK is for

Section titled “Agents on Workers: what the Agents SDK is for”

Hosted agents are meant to persist, think, and act on Cloudflare’s network: each session keeps state across requests and can talk to clients in real time over WebSockets.

Build AI agents that persist, think, and act. Agents run on Cloudflare’s global network, maintain state across requests, and connect to clients in real-time via WebSockets.

— Cloudflare, Quick start

At product level, Cloudflare describes agents as four cooperating parts—channels (chat, email, voice, Slack, webhooks), an agent harness (model/tool loop), the Agents SDK runtime (Agent class, state, routing, scheduling), and tools (MCP, browser, sandbox, AI Search, payments, Code Mode). See Build Agents on Cloudflare for that overview. Workers AI also positions agents as assistants built with Workers AI plus the SDK (Workers AI — Agents).

Agent class: Durable Objects, state, and built-in capabilities

Section titled “Agent class: Durable Objects, state, and built-in capabilities”

The server-side Agent class is the main API: it wraps connections, state, methods, models, and error handling.

The Agents SDK provides two main APIs:

API — Server-side Agent class — Encapsulates agent logic: connections, state, methods, AI models, error handling
Client-side SDK — AgentClient, useAgent, and useAgentChat for connecting from browsers

Agents require Cloudflare Durable Objects. Refer to Configuration to learn how to add the required bindings.

— Cloudflare, Agent class

Under the hood, Agent instances are Durable Objects—globally addressable, single-threaded, with durable key-value and SQLite storage—extended through an extra layer:

The Agent class is an extension of DurableObject — agents are Durable Objects. … Agent does not extend DurableObject directly. It extends Server from the partyserver package, which extends DurableObject. Think of it as layers: DurableObject > Server > Agent.

— Cloudflare, Agent class internals

You subclass Agent, override a few methods, and get state management, WebSockets, scheduling, RPC, and related behavior without rebuilding that stack (Agent class internals). In code you typically use this.state, SQL via this.sql, WebSocket hooks such as onConnect / onMessage, this.schedule, and model calls inside methods (Introducing the Agents SDK).

If deployment fails or agents never instantiate, the usual gap is missing Durable Object configuration. The Agent class page points to Configuration for required bindings. On deploy, Cloudflare creates a Worker, one Durable Object namespace per agent class, and SQLite storage per namespace:

When you deploy, Cloudflare automatically creates:

Worker - Your deployed code
Durable Object namespaces - One per agent class
SQLite storage - Attached to each namespace

— Cloudflare, Configuration — Automatic resources

Client SDK: browsers, RPC, and typed AgentClient

Section titled “Client SDK: browsers, RPC, and typed AgentClient”

Browsers connect through AgentClient, useAgent, and useAgentChat (Agent class). Recent SDK releases add typed RPC: pass your agent type so call, stub, and onStateUpdate infer methods, arguments, return types, and state (Agents SDK v0.8.0 changelog).

AgentClient now accepts an optional agent type parameter for full type inference on RPC calls, matching the typed experience already available with useAgent.

— Cloudflare, Agents SDK v0.8.0: readable state, idempotent schedules, typed AgentClient, and Zod 4

Routing conventions matter: useAgent and useAgentChat convert the agent name to kebab-case so it matches what routeAgentRequest expects (MCP servers Agents SDK updates). If the client connects but RPC or query params fail, compare the name you pass in React with the route configuration in the Worker.

Project setup: new agent app vs existing Worker

Section titled “Project setup: new agent app vs existing Worker”

For a first project, Cloudflare recommends the cloudflare/agents-starter template (Quick start):

npm create cloudflare@latest -- --template cloudflare/agents-starter
cd agents-starter
npm install
npm run dev

That layout includes src/server.ts (agent), src/client.tsx (React UI), wrangler.jsonc, tsconfig.json extending agents/tsconfig, and vite.config.ts with the agents/vite plugin (Quick start). Open http://localhost:5173 after npm run dev to confirm state sync with the sample counter.

Add Agents SDK to an existing Workers project

Section titled “Add Agents SDK to an existing Workers project”

This guide shows how to add agents to an existing Cloudflare Workers project. If you are starting fresh, refer to Building a chat agent instead.

— Cloudflare, Add to existing project

Install agents, define an Agent subclass, add Durable Object bindings in Wrangler, and wire request routing to the agent (Getting started — Add Agents to an existing project). You can also install with npm i agents and extend Agent<Env> as in the Introducing the Agents SDK announcement.

Wrangler configuration: nodejs_compat and project layout

Section titled “Wrangler configuration: nodejs_compat and project layout”

Agents depend on Node.js compatibility for crypto, streams, and related APIs:

The nodejs_compat flag is required for agents:

— Cloudflare, Configuration — compatibility flags

Set compatibility_flags to include nodejs_compat in wrangler.jsonc (or TOML equivalent) as shown on Configuration. A typical starter-shaped tree lists src/index.ts, public/index.html, tests, and wrangler.jsonc on the same page.

Callable methods and @callable(): Vite and TypeScript pitfalls

Section titled “Callable methods and @callable(): Vite and TypeScript pitfalls”

Exposing RPC with @callable() requires the Vite plugin and the shared TypeScript config—not legacy TypeScript decorators:

If your dev server fails with SyntaxError: Invalid or unexpected token when using @callable(), you need two things:

  1. Add the agents/vite plugin …
  2. Extend agents/tsconfig …

Do not set “experimentalDecorators”: true in your tsconfig.json. The Agents SDK uses TC39 standard decorators, not TypeScript legacy decorators. Enabling experimentalDecorators applies an incompatible transform that silently breaks @callable() at runtime.

— Cloudflare, Callable methods

Minimal pattern from Quick start and Callable methods:

// vite.config.ts — plugins: [agents(), react(), cloudflare()]
// tsconfig.json — { "extends": "agents/tsconfig" }

Calling LLMs from an Agent: multi-model pipelines and streaming

Section titled “Calling LLMs from an Agent: multi-model pipelines and streaming”

Because an Agent holds state for the whole request, you can chain models—fast classifier, reasoning planner, embedding model—in one method without losing intermediate context (Calling LLMs — Multi-model pipelines). The triage example on that page uses createAI with a Workers AI binding, generateText, embed, vector search, and this.sql to persist results.

Agents can also call any OpenAI-compatible HTTP API (including non-OpenAI base URLs) and stream via SSE in onRequest or over WebSockets (Using AI Models — OpenAI-compatible endpoints). For edge-hosted models, Workers AI is the natural binding; Cloudflare’s agent stack overview lists Workers AI as the model provider alongside the SDK (Build agents on Cloudflare — Bionic + Cloudflare).

Toolkit context inside an agent method can use import { context } from "agents" to read the current agent, request, and WebSocket connection without heavy dependency injection (MCP servers Agents SDK updates).

MCP on Agents SDK: MCPAgent and remote servers

Section titled “MCP on Agents SDK: MCPAgent and remote servers”

Cloudflare supports building and deploying MCP servers on Workers (Model Context Protocol (MCP)). The SDK adds MCPAgent for MCP server authors (MCP servers Agents SDK updates).

One-click deployment from the dashboard creates a live server on your workers.dev host, a Git repo with CI deploys, and immediate testing with MCP clients:

Once deployed, this server will be live at your workers.dev subdomain … You can connect to it immediately using the AI Playground (a remote MCP client), MCP inspector or other MCP clients.

— Cloudflare, Build a Remote MCP server

For OAuth and permission-scoped tools, see the WorkOS / AuthKit pattern where the MCP server exposes tools based on the signed-in user’s role (Authorization — WorkOS). Hardening guidance lives under Securing MCP servers.

Cloudflare also positions the platform as more than a deploy target: Agents SDK, remote MCP on Workers, Workers AI, and Worker Loader (sandbox behind Code Mode) form a full build stack (Build agents on Cloudflare — Bionic + Cloudflare).

Mistake Symptom Fix
Missing nodejs_compat Runtime errors around Node APIs Add flag per Configuration
No Durable Object binding Agent class never runs / deploy errors Follow Configuration
experimentalDecorators: true @callable() breaks silently at runtime Use TC39 decorators + agents/tsconfig (Callable methods)
Skipping agents/vite on Vite 8 SyntaxError on @callable() Add agents() plugin (Callable methods)
Wrong agent name in client RPC or query params not routed Use kebab-case naming; SDK auto-converts in hooks (MCP servers Agents SDK updates)
Zod v3 with latest agents Dependency conflicts SDK packages require Zod ^4.0.0 (Agents SDK v0.8.0)
  1. Scaffold or open an Agents project using the quick start or add-to-existing guide; confirm nodejs_compat and Durable Object bindings in Configuration.

  2. Run npm run dev and load the local UI (for example http://localhost:5173 per Quick start); verify state updates over the client connection (useAgent / AgentClient).

  3. If you use @callable(), confirm vite.config.ts includes agents() and tsconfig.json extends agents/tsconfig (Callable methods); trigger an RPC from the browser and watch Worker logs.

  4. For MCP, deploy via Build a Remote MCP server and connect with an MCP client or inspector as described on that page.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will fix or clarify it.