Agents SDK: Durable State, Recovery, Chat, and MCP
How the Cloudflare Agents SDK runs stateful AI agents on Workers with persistence, reconnect recovery, chat, scheduling, and MCP tool access.
This page summarizes Cloudflare’s documentation on the Agents SDK (agents / @cloudflare/agents): building production AI agents on Workers backed by Durable Objects, with SQLite state, WebSocket clients, long-running recovery, and integrations such as MCP, Workflows, and chat messengers. Changelog posts in the cluster repeat one theme: agents should keep working through deploys, evictions, stalled model streams, and client reconnects—not only on a happy path.
What the Agents SDK is for
Section titled “What the Agents SDK is for”The Agents SDK is the infrastructure layer for agents that need memory, real-time clients, and edge deployment. Cloudflare describes it this way:
The Cloudflare Agents SDK provides the infrastructure for building production agents:
Persistent state — Each agent instance has its own SQLite database for storing context and memory Real-time sync — State changes automatically broadcast to all connected clients via WebSockets Hibernation — Agents sleep when idle and wake on demand, so you only pay for what you use Global edge deployment — Agents run close to your users on Cloudflare’s network Built-in capabilities — Scheduling, task queues, workflows, email handling, and more
— Cloudflare, What are agents?
You typically extend the Agent class, route HTTP/WebSocket traffic (for example with routeAgentRequest), and connect browsers or servers through the Client SDK, which supports WebSockets or HTTP, state sync, RPC, and streaming.
For implementation shapes (routing, tools, delegation), see Agentic patterns, which lists common agent patterns and notes that samples use the AI SDK in Durable Objects.
Durable state: one agent instance, one database
Section titled “Durable state: one agent instance, one database”Each named agent instance owns durable SQLite storage inside its Durable Object. That is where conversation context, schedules, chat protocol state, and related metadata live across restarts.
Recent releases expose state more directly to application code—for example a readable state property and synchronous state management (Agents SDK v0.8.0). The Chat SDK StateAdapter stores Chat SDK shards (subscriptions, locks, queues, transcripts, thread history) in that SQLite layer via ChatSdkStateAgent sub-agents under your ingress agent.
Hibernation matters for cost and correctness: when work is waiting (for example model retry backoff), the object can sleep instead of staying in memory. Agents SDK v0.30.0 with Pi 1.4 documents onWake so PiHarness can hibernate until a sleeping Pi task is due.
Recovery: deploys, evictions, reconnects, and routing
Section titled “Recovery: deploys, evictions, reconnects, and routing”Most cluster material is about recovery—finishing or resuming work after production interruptions.
Chat turns and WebSocket state
Section titled “Chat turns and WebSocket state”Chat-focused releases (v0.12.4, v0.14.0) hardened durable chat recovery so turns survive deploys, evictions, and stalled model streams. Concrete fixes in v0.12.4 include:
agents@0.12.4 prevents duplicate initial state frames during WebSocket connection setup. This avoids stale initial state messages overwriting state updates already sent by the client.
— Cloudflare, Agents SDK v0.12.4
Tool calls that span a Durable Object restart defer user finish hooks until after startup, and hook failures are isolated so one bad hook does not block other recoveries—same changelog entry.
Earlier, v0.2.24 added resumable streaming plus MCP and schedule lifecycle fixes. v0.5.0 rewrote @cloudflare/ai-chat with data parts and tool approval persistence while claiming zero breaking changes for consumers.
Transient routing to an agent
Section titled “Transient routing to an agent”When resolving an agent by name, transient Durable Object routing failures can be retried:
import { getAgentByName } from "agents";
const agent = await getAgentByName(env.AssistantAgent, "user-123", { routingRetry: { maxAttempts: 3, },});— pattern from Agents SDK v0.12.4.
Long work without losing the object
Section titled “Long work without losing the object”For runs that exceed idle eviction windows, v0.7.0 adds keepAlive() to reduce eviction during long tasks. Use it when documentation or your own measurements show eviction mid-work; it is not a substitute for durable checkpoints where the SDK already persists turns.
PiHarness and storage errors
Section titled “PiHarness and storage errors”On the Pi execution path, v0.30.0 / Pi 1.4 adds:
- Parked tasks when repeated crashes would otherwise restart forever (
pending()shows parked;session.retry()reruns). - Recovery from storage errors by reopening Pi instead of failing every call until a full object restart.
- Retried model streams when
agents/models/pi-aitreats cut-off or idle streams as transient.
runTurn, Think, and background sub-agents
Section titled “runTurn, Think, and background sub-agents”Newer releases converge chat and reasoning on fewer entry points. v0.17.0 adds:
This release adds first-class detached (background) sub-agent runs with live progress and durable milestones, a single runTurn turn-admission entry point, and a large round of recovery and reliability fixes that continue converging @cloudflare/think and @cloudflare/ai-chat onto one model.
— Cloudflare, Agents SDK adds background sub-agents and a unified turn entry point
Practical meaning: route user-visible turns through one admission API (runTurn), run heavy or delegated work as detached sub-agents with durable progress, and rely on the same recovery stack for chat. v0.14.0 also adds durable Think submissions, Agent Skills, declarative scheduled tasks, Workflows reasoning steps, and messengers (Telegram first).
v0.16.1 extends agents that touch real systems: Browser Run, Code Mode, client-provided tools when delegating to Think sub-agents, plus stronger recovery from connection churn.
MCP, tools, and observability
Section titled “MCP, tools, and observability”| Capability | What it solves | Documented in |
|---|---|---|
waitForMcpConnections |
MCP tools ready before onChatMessage runs |
v0.7.0 |
RPC between Agent and McpAgent in one Worker |
No HTTP hop for in-Worker MCP | v0.6.0 |
| Optional OAuth on MCP | Simpler connections when OAuth is not required | v0.6.0 |
diagnostics_channel observability rewrite |
Production debugging of agent lifecycle | v0.7.0 |
| Built-in retry utilities | Transient failures around protocol/tools | v0.5.0 |
v0.6.0 states you can define an Agent and McpAgent in the same Worker and connect them over RPC with no network overhead.
At the workspace level, Enterprise AI agent workspace shows governed model access (AI Gateway) and enterprise tools via MCP portals—useful when your agent is one part of a larger authenticated workspace, not only a single Worker.
Scheduling and Workflows
Section titled “Scheduling and Workflows”Workflows integration (v0.3.7) adds first-class Cloudflare Workflows, synchronous state, and scheduleEvery().
The recurring foot-gun is calling schedule() on every Durable Object restart (for example inside onStart()):
schedule() now supports an idempotent option that deduplicates by (type, callback, payload), preventing duplicate rows from accumulating when called in places that run on every Durable Object restart such as onStart().
— Cloudflare, Agents SDK v0.8.0
Cron schedules are idempotent by default; delayed and date schedules need { idempotent: true } when registered from restart-prone hooks. The SDK warns if onStart() schedules without idempotency, and if an alarm cycle processes many stale one-shot rows for the same callback (schedule:duplicate_warning on diagnostics_channel).
Sandboxed code and human approval
Section titled “Sandboxed code and human approval”@cloudflare/computer gives agents a workspace to run code; from v0.7.0 that execution can resume after deploy or crash and pause for external approval (for example tool approval):
@cloudflare/computer ↗︎ gives your agent a workspace to run code in. From v0.7.0, that code can resume after a deploy or crash, and pause on an external action, for example to approve a tool call.
— Cloudflare, Cloudflare Computer now helps agents recover from interruptions and wait for approval
That pairs with @cloudflare/ai-chat tool approval persistence (v0.5.0) for human-in-the-loop flows.
Communication channels beyond browser chat
Section titled “Communication channels beyond browser chat”- Chat — autonomous responses and client SDK entry points.
- Webhooks — isolated stateful agent instances per external entity; fits event-driven triggers without an open browser session (aligned with the workspace diagram’s webhooks/schedules).
- Cross-origin browser clients —
routeAgentRequestaccepts{ cors: true }for default permissive CORS on agent responses (Agents SDK updates).
Common mistakes
Section titled “Common mistakes”- Duplicate schedules after every restart — Use
{ idempotent: true }for delayed/date schedules inonStart(); rely on default idempotency for cron (v0.8.0). - Stale WebSocket state on reconnect — Ensure clients tolerate server-driven state sync; server-side duplicate initial state frames were a known bug fixed in v0.12.4.
- MCP tools missing on first message — Await MCP readiness (
waitForMcpConnections) before handling chat (v0.7.0). - Long jobs without keep-alive or checkpoints — Combine
keepAlive()where appropriate with SDK durable turn/stream features. - Rolling back after Pi 1.4 — Treat Pi session schema migration as irreversible for that object’s stored sessions.
How to check this on your site
Section titled “How to check this on your site”-
Confirm your Worker uses the Agents SDK patterns from What are agents? and that clients connect via the Client SDK (WebSocket or HTTP as documented).
-
Deploy a build that includes recent recovery fixes you depend on (for example resumable streaming or chat recovery), then trigger a deploy or Durable Object eviction during an active turn and verify the conversation resumes without duplicate or overwritten state.
-
If you use
schedule()inonStart(), inspect Worker logs for idempotency warnings andschedule:duplicate_warningevents after restarts (v0.8.0). -
For MCP-backed chat, verify tools are available on the first
onChatMessageafter cold start (v0.7.0). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact passage you are asking about.