Cloudflare Agents SDK

SkillCloud & infra

Build AI agents with Cloudflare Agents SDK on Workers + Durable Objects. Provides WebSockets, state persistence, scheduling, and multi-agent coordination. Prevents 23 documented errors.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the Cloudflare Agents SDK skill

What this skill tells your AI

The instructions your AI receives, as published by dennislee928/ethic-latex in .claude/skills/cloudflare-agents/SKILL.md and read by ahel’s review.

Status: Production Ready ✅ Last Updated: 2026-01-09 Dependencies: cloudflare-worker-base (recommended) Latest Versions: agents@0.3.3, @modelcontextprotocol/sdk@latest Production Tested: Cloudflare's own MCP servers (https://github.com/cloudflare/mcp-server-cloudflare)

Recent Updates (2025-2026):

  • Jan 2026: Agents SDK v0.3.6 with callable methods fix, protocol version support updates
  • Nov 2025: Agents SDK v0.2.24+ with resumable streaming (streams persist across disconnects, page refreshes, and sync across tabs/devices), MCP client improvements, schedule fixes
  • Sept 2025: AI SDK v5 compatibility, automatic message migration
  • Aug 2025: MCP Elicitation support, http-streamable transport, task queues, email integration
  • April 2025: MCP support (MCPAgent class), import { context } from agents
  • March 2025: Package rename (agents-sdk → agents)

Resumable Streaming (agents@0.2.24+)

AIChatAgent now supports resumable streaming, enabling clients to reconnect and continue receiving streamed responses without data loss. This solves critical real-world scenarios:

  • Long-running AI responses that exceed connection timeout
  • Users on unreliable networks (mobile, airplane WiFi)
  • Users switching between devices mid-conversation
  • Background tasks where users navigate away and return
  • Real-time collaboration where multiple clients need to stay in sync

Key capability: Streams persist across page refreshes, broken connections, and sync across open tabs and devices.

Implementation (automatic in AIChatAgent):

export class ChatAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    return streamText({
      model: openai('gpt-4o-mini'),
      messages: this.messages,
      onFinish
    }).toTextStreamResponse();

    // ✅ Stream automatically resumable
    // - Client disconnects? Stream preserved
    // - Page refresh? Stream continues
    // - Multiple tabs? All stay in sync
  }
}

No code changes needed - just use AIChatAgent with agents@0.2.24 or later.

Source: Agents SDK v0.2.24 Changelog


What is Cloudflare Agents?

The Cloudflare Agents SDK enables building AI-powered autonomous agents that run on Cloudflare Workers + Durable Objects. Agents can:

  • Communicate in real-time via WebSockets and Server-Sent Events
  • Persist state with built-in SQLite database (up to 1GB per agent)
  • Schedule tasks using delays, specific dates, or cron expressions
  • Run workflows by triggering asynchronous Cloudflare Workflows
  • Browse the web using Browser Rendering API + Puppeteer
  • Implement RAG with Vectorize vector database + Workers AI embeddings
  • Build MCP servers implementing the Model Context Protocol
  • Support human-in-the-loop patterns for review and approval
  • Scale to millions of independent agent instances globally

Each agent instance is a globally unique, stateful micro-server that can run for seconds, minutes, or hours.


Do You Need Agents SDK?

STOP: Before using Agents SDK, ask yourself if you actually need it.

Use JUST Vercel AI SDK (Simpler) When:

  • ✅ Building a basic chat interface
  • ✅ Server-Sent Events (SSE) streaming is sufficient (one-way: server → client)
  • ✅ No persistent agent state needed (or you manage it separately with D1/KV)
  • ✅ Single-user, single-conversation scenarios
  • ✅ Just need AI responses, no complex workflows or scheduling

This covers 80% of chat applications. For these cases, use Vercel AI SDK directly on Workers - it's simpler, requires less infrastructure, and handles streaming automatically.

Example (no Agents SDK needed):

// worker.ts - Simple chat with AI SDK only
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

export default {
  async fetch(request: Request, env: Env) {
    const { messages } = await request.json();

    const result = streamText({
      model: openai('gpt-4o-mini'),
      messages
    });

    return result.toTextStreamResponse(); // Automatic SSE streaming
  }
}

// client.tsx - React with built-in hooks
import { useChat } from 'ai/react';

function ChatPage() {
  const { messages, input, handleSubmit } = useChat({ api: '/api/chat' });
  // Done. No Agents SDK needed.
}

Result: 100 lines of code instead of 500. No Durable Objects setup, no WebSocket complexity, no migrations.


Use Agents SDK When You Need:

  • WebSocket connections (true bidirectional real-time communication)
  • Durable Objects (globally unique, stateful agent instances)
  • Built-in state persistence (SQLite storage up to 1GB per agent)
  • Multi-agent coordination (agents calling and communicating with each other)
  • Scheduled tasks (delays, cron expressions, recurring jobs)
  • Human-in-the-loop workflows (approval gates, review processes)
  • Long-running agents (background processing, autonomous workflows)
  • MCP servers with stateful tool execution

This is ~20% of applications - when you need the infrastructure that Agents SDK provides.


Key Understanding: What Agents SDK IS vs IS NOT

Agents SDK IS:

  • 🏗️ Infrastructure layer for WebSocket connections, Durable Objects, and state management
  • 🔧 Framework for building stateful, autonomous agents
  • 📦 Wrapper around Durable Objects with lifecycle methods

Agents SDK IS NOT:

  • AI inference provider (you bring your own: AI SDK, Workers AI, OpenAI, etc.)
  • Streaming response handler (use AI SDK for automatic parsing)
  • LLM integration (that's a separate concern)

Think of it this way:

  • Agents SDK = The building (WebSockets, state, rooms)
  • AI SDK / Workers AI = The AI brain (inference, reasoning, responses)

You can use them together (recommended for most cases), or use Workers AI directly (if you're willing to handle manual SSE parsing).


Decision Flowchart

Building an AI application?
│
├─ Need WebSocket bidirectional communication? ───────┐
│  (Client sends while server streams, agent-initiated messages)
│
├─ Need Durable Objects stateful instances? ──────────┤
│  (Globally unique agents with persistent memory)
│
├─ Need multi-agent coordination? ────────────────────┤
│  (Agents calling/messaging other agents)
│
├─ Need scheduled tasks or cron jobs? ────────────────┤
│  (Delayed execution, recurring tasks)
│
├─ Need human-in-the-loop workflows? ─────────────────┤
│  (Approval gates, review processes)
│
└─ If ALL above are NO ─────────────────────────────→ Use AI SDK directly
                                                       (Much simpler approach)

   If ANY above are YES ────────────────────────────→ Use Agents SDK + AI SDK
                                                       (More infrastructure, more power)

Architecture Comparison

FeatureAI SDK OnlyAgents SDK + AI SDK
Setup Complexity🟢 Low (npm install, done)🔴 Higher (Durable Objects, migrations, bindings)
Code Volume🟢 ~100 lines🟡 ~500+ lines
Streaming✅ Automatic (SSE)✅ Automatic (AI SDK) or manual (Workers AI)
State Management⚠️ Manual (D1/KV)✅ Built-in (SQLite)
WebSockets❌ Manual setup✅ Built-in
React Hooks✅ useChat, useCompletion⚠️ Custom hooks needed
Multi-agent❌ Not supported✅ Built-in (routeAgentRequest)
Scheduling❌ External (Queue/Workflow)✅ Built-in (this.schedule)
Use CaseSimple chat, completionsComplex stateful workflows

Still Not Sure?

Start with AI SDK. You can always migrate to Agents SDK later if you discover you need WebSockets or Durable Objects. It's easier to add infrastructure later than to remove it.

For most developers: If you're building a chat interface and don't have specific requirements for WebSockets, multi-agent coordination, or scheduled tasks, use AI SDK directly. You'll ship faster and with less complexity.

Proceed with Agents SDK only if you've identified a specific need for its infrastructure capabilities.


Quick Start (10 Minutes)

1. Scaffold Project with Template

npm create cloudflare@latest my-agent -- \
  --template=cloudflare/agents-starter \
  --ts \
  --git \
  --deploy false

What this creates:

  • Complete Agent project structure
  • TypeScript configuration
  • wrangler.jsonc with Durable Objects bindings
  • Example chat agent implementation
  • React client with useAgent hook

2. Or Add to Existing Worker

cd my-existing-worker
npm install agents

Then create an Agent class:

// src/index.ts
import { Agent, AgentNamespace } from "agents";

export class MyAgent extends Agent {
  async onRequest(request: Request): Promise<Response> {
    return new Response("Hello from Agent!");
  }
}

export default MyAgent;

3. Configure Durable Objects Binding

Create or update wrangler.jsonc:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-agent",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-21",
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": {
    "bindings": [
      {
        "name": "MyAgent",        // MUST match class name
        "class_name": "MyAgent"   // MUST match exported class
      }
    ]
  },
  "migrations": [
    {
      "tag": "v1",
      "new_sqlite_classes": ["MyAgent"]  // CRITICAL: Enables SQLite storage
    }
  ]
}

CRITICAL Configuration Rules:

  • name and class_name MUST be identical
  • new_sqlite_classes MUST be in first migration (cannot add later)
  • ✅ Agent class MUST be exported (or binding will fail)
  • ✅ Migration tags CANNOT be reused (each migration needs unique tag)

4. Deploy

npx wrangler@latest deploy

Your agent is now running at: https://my-agent.<subdomain>.workers.dev


Architecture Overview: How the Pieces Fit Together

Understanding what each tool does prevents confusion and helps you choose the right combination.

The Stack

┌─────────────────────────────────────────────────────────┐
│                    Your Application                      │
│                                                          │
│  ┌────────────────┐         ┌──────────────────────┐   │
│  │  Agents SDK    │         │   AI Inference       │   │
│  │  (Infra Layer) │   +     │   (Brain Layer)      │   │
│  │                │         │                      │   │
│  │ • WebSockets   │         │  Choose ONE:         │   │
│  │ • Durable Objs │         │  • Vercel AI SDK ✅   │   │
│  │ • State (SQL)  │         │  • Workers AI ⚠️      │   │
│  │ • Scheduling   │         │  • OpenAI Direct     │   │
│  │ • Multi-agent  │         │  • Anthropic Direct  │   │
│  └────────────────┘         └──────────────────────┘   │
│         ↓                             ↓                │
│  Manages connections          Generates responses      │
│  and state                    and handles streaming    │
└─────────────────────────────────────────────────────────┘
                          ↓
              Cloudflare Workers + Durable Objects

What Each Tool Provides

1. Agents SDK (This Skill)

Purpose: Infrastructure for stateful, real-time agents

Provides:

  • ✅ WebSocket connection management (bidirectional real-time)
  • ✅ Durable Objects wrapper (globally unique agent instances)
  • ✅ Built-in state persistence (SQLite up to 1GB)
  • ✅ Lifecycle methods (onStart, onConnect, onMessage, onClose)
  • ✅ Task scheduling (this.schedule() with cron/delays)
  • ✅ Multi-agent coordination (routeAgentRequest())
  • ✅ Client libraries (useAgent, AgentClient, agentFetch)

Does NOT Provide:

  • ❌ AI inference (no LLM calls)
  • ❌ Streaming response parsing (bring your own)
  • ❌ Provider integrations (OpenAI, Anthropic, etc.)

Think of it as: The building and infrastructure (rooms, doors, plumbing) but NOT the residents (AI).


2. Vercel AI SDK (Recommended for AI)

Purpose: AI inference with automatic streaming

Provides:

  • ✅ Automatic streaming response handling (SSE parsing done for you)
  • ✅ Multi-provider support (OpenAI, Anthropic, Google, etc.)
  • ✅ React hooks (useChat, useCompletion, useAssistant)
  • ✅ Unified API across providers
  • ✅ Tool calling / function calling
  • ✅ Works on Cloudflare Workers ✅

Example:

import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = streamText({
  model: openai('gpt-4o-mini'),
  messages: [...]
});

// Returns SSE stream - no manual parsing needed
return result.toTextStreamResponse();

When to use with Agents SDK:

  • ✅ Most chat applications
  • ✅ When you want React hooks
  • ✅ When you use multiple AI providers
  • ✅ When you want clean, abstracted AI calls

Combine with Agents SDK:

import { AIChatAgent } from "agents/ai-chat-agent";
import { streamText } from "ai";

export class MyAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    // Agents SDK provides: WebSocket, state, this.messages
    // AI SDK provides: Automatic streaming, provider abstraction

    return streamText({
      model: openai('gpt-4o-mini'),
      messages: this.messages  // Managed by Agents SDK
    }).toTextStreamResponse();
  }
}

3. Workers AI (Alternative for AI)

Purpose: Cloudflare's on-platform AI inference

Provides:

  • ✅ Cost-effective inference (included in Workers subscription)
  • ✅ No external API keys needed
  • ✅ Models: LLaMA 3, Qwen, Mistral, embeddings, etc.
  • ✅ Runs on Cloudflare's network (low latency)

Does NOT Provide:

  • ❌ Automatic streaming parsing (returns raw SSE format)
  • ❌ React hooks
  • ❌ Multi-provider abstraction

Manual parsing required:

const response = await env.AI.run('@cf/meta/llama-3-8b-instruct', {
  messages: [...],
  stream: true
});

// Returns raw SSE format - YOU must parse
for await (const chunk of response) {
  const text = new TextDecoder().decode(chunk);  // Uint8Array → string
  if (text.startsWith('data: ')) {              // Check SSE format
    const data = JSON.parse(text.slice(6));     // Parse JSON
    if (data.response) {                        // Extract .response field
      fullResponse += data.response;
    }
  }
}

When to use:

  • ✅ Cost is critical (embeddings, high-volume)
  • ✅ Need Cloudflare-specific models
  • ✅ Willing to handle manual SSE parsing
  • ✅ No external dependencies allowed

Trade-off: Save money, spend time on manual parsing.


Recommended Combinations

Option A: Agents SDK + Vercel AI SDK (Recommended ⭐)

Use when: You need WebSockets/state AND want clean AI integration

import { AIChatAgent } from "agents/ai-chat-agent";
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

export class ChatAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    return streamText({
      model: openai('gpt-4o-mini'),
      messages: this.messages,  // Agents SDK manages history
      onFinish
    }).toTextStreamResponse();
  }
}

Pros:

  • ✅ Best developer experience
  • ✅ Automatic streaming
  • ✅ WebSockets + state from Agents SDK
  • ✅ Clean, maintainable code

Cons:

  • ⚠️ Requires external API keys
  • ⚠️ Additional cost for AI provider

Option B: Agents SDK + Workers AI

Use when: You need WebSockets/state AND cost is critical

import { Agent } from "agents";

export class BudgetAgent extends Agent<Env> {
  async onMessage(connection, message) {
    const response = await this.env.AI.run('@cf/meta/llama-3-8b-instruct', {
      messages: [...],
      stream: true
    });

    // Manual SSE parsing required (see Workers AI section above)
    for await (const chunk of response) {
      // ... manual parsing ...
    }
  }
}

Pros:

  • ✅ Cost-effective
  • ✅ No external dependencies
  • ✅ WebSockets + state from Agents SDK

Cons:

  • ❌ Manual SSE parsing complexity
  • ❌ Limited model selection
  • ❌ More code to maintain

Option C: Just Vercel AI SDK (No Agents)

Use when: You DON'T need WebSockets or Durable Objects

// worker.ts - Simple Workers route
export default {
  async fetch(request: Request, env: Env) {
    const { messages } = await request.json();

    const result = streamText({
      model: openai('gpt-4o-mini'),
      messages
    });

    return result.toTextStreamResponse();
  }
}

// client.tsx - Built-in React hooks
import { useChat } from 'ai/react';

function Chat() {
  const { messages, input, handleSubmit } = useChat({ api: '/api/chat' });
  return <form onSubmit={handleSubmit}>...</form>;
}

Pros:

  • ✅ Simplest approach
  • ✅ Least code
  • ✅ Fast to implement
  • ✅ Built-in React hooks

Cons:

  • ❌ No WebSockets (only SSE)
  • ❌ No Durable Objects state
  • ❌ No multi-agent coordination

Best for: 80% of chat applications


Decision Matrix

Your NeedsRecommended StackComplexityCost
Simple chat, no stateAI SDK only🟢 Low$$ (AI provider)
Chat + WebSockets + stateAgents SDK + AI SDK🟡 Medium$$$ (infra + AI)
Chat + WebSockets + budgetAgents SDK + Workers AI🔴 High$ (infra only)
Multi-agent workflowsAgents SDK + AI SDK🔴 High$$$ (infra + AI)
MCP server with toolsAgents SDK (McpAgent)🟡 Medium$ (infra only)

Key Takeaway

Agents SDK is infrastructure, not AI. You combine it with AI inference tools:

  • For best DX: Agents SDK + Vercel AI SDK ⭐
  • For cost savings: Agents SDK + Workers AI (accept manual parsing)
  • For simplicity: Just AI SDK (if you don't need WebSockets/state)

The rest of this skill focuses on Agents SDK (the infrastructure layer). For AI inference patterns, see the ai-sdk-core or cloudflare-workers-ai skills.


Configuration (wrangler.jsonc)

Critical Required Configuration:

{
  "durable_objects": {
    "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
  },
  "migrations": [
    { "tag": "v1", "new_sqlite_classes": ["MyAgent"] }  // MUST be in first migration
  ]
}

Common Optional Bindings: ai, vectorize, browser, workflows, d1_databases, r2_buckets

CRITICAL Migration Rules:

  • new_sqlite_classes MUST be in tag "v1" (cannot add SQLite to existing deployed class)
  • name and class_name MUST match exactly
  • ✅ Migrations are atomic (all instances updated simultaneously)
  • ✅ Each tag must be unique, cannot edit/remove previous tags

See: https://developers.cloudflare.com/agents/api-reference/configuration/


Core Agent Patterns

Agent Class Basics - Extend Agent<Env, State> with lifecycle methods:

  • onStart() - Agent initialization
  • onRequest() - Handle HTTP requests
  • onConnect/onMessage/onClose() - WebSocket handling
  • onStateUpdate() - React to state changes

Key Properties:

  • this.env - Environment bindings (AI, DB, etc.)
  • this.state - Current agent state (read-only)
  • this.setState() - Update persisted state
  • this.sql - Built-in SQLite database
  • this.name - Agent instance identifier
  • this.schedule() - Schedule future tasks

See: Official Agent API docs at https://developers.cloudflare.com/agents/api-reference/agents-api/


WebSockets & Real-Time Communication

Agents support WebSockets for bidirectional real-time communication. Use when you need:

  • Client can send messages while server streams
  • Agent-initiated messages (notifications, updates)
  • Long-lived connections with state

Basic Pattern:

export class ChatAgent extends Agent<Env, State> {
  async onConnect(connection: Connection, ctx: ConnectionContext) {
    // Auth check, add to participants, send welcome
  }

  async onMessage(connection: Connection, message: WSMessage) {
    // Process message, update state, broadcast response
  }
}

SSE Alternative: For one-way server → client streaming (simpler, HTTP-based), use Server-Sent Events instead of WebSockets.

See: https://developers.cloudflare.com/agents/api-reference/websockets/


State Management

Two State Mechanisms:

  1. this.setState(newState) - JSON-serializable state (up to 1GB)

    • Automatically persisted, syncs to WebSocket clients
    • Use for: User preferences, session data, small datasets
  2. this.sql - Built-in SQLite database (up to 1GB)

    • Tagged template literals prevent SQL injection
    • Use for: Relational data, large datasets, complex queries

State Rules:

  • ✅ JSON-serializable only (objects, arrays, primitives, null)
  • ✅ Persists across restarts, immediately consistent
  • ❌ No functions or circular references
  • ❌ 1GB total limit (state + SQL combined)

SQL Pattern:

await this.sql`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)`
await this.sql`INSERT INTO users (email) VALUES (${userEmail})`  // ← Prepared statement
const users = await this.sql`SELECT * FROM users WHERE email = ${email}`  // ← Returns array

State Type Safety Gotcha

CRITICAL: Providing a type parameter to state methods does NOT validate that the result matches your type definition. In TypeScript, properties (fields) that do not exist or conform to the type you provided will be dropped silently.

interface MyState {
  count: number;
  name: string;
}

export class MyAgent extends Agent<Env, MyState> {
  initialState = { count: 0, name: "default" };

  async increment() {
    // TypeScript allows this, but runtime may differ
    const currentState = this.state; // Type is MyState

    // If state was corrupted/modified externally:
    // { count: "invalid", otherField: 123 }
    // TypeScript still shows it as MyState
    // count field doesn't match (string vs number)
    // otherField is dropped silently
  }
}

Prevention: Add runtime validation for critical state operations:

// Validate state shape at runtime
function validateState(state: unknown): state is MyState {
  return (
    typeof state === 'object' &&
    state !== null &&
    'count' in state &&
    typeof (state as MyState).count === 'number' &&
    'name' in state &&
    typeof (state as MyState).name === 'string'
  );
}

async increment() {
  if (!validateState(this.state)) {
    console.error('State validation failed', this.state);
    // Reset to valid state
    await this.setState(this.initialState);
    return;
  }

  // Safe to use
  const newCount = this.state.count + 1;
  await this.setState({ ...this.state, count: newCount });
}

See: https://developers.cloudflare.com/agents/api-reference/store-and-sync-state/


Schedule Tasks

Agents can schedule tasks to run in the future using this.schedule().

Delay (Seconds)

export class MyAgent extends Agent {
  async onRequest(request: Request): Promise<Response> {
    // Schedule task to run in 60 seconds
    const { id } = await this.schedule(60, "checkStatus", { requestId: "123" });

    return Response.json({ scheduledTaskId: id });
  }

  // This method will be called in 60 seconds
  async checkStatus(data: { requestId: string }) {
    console.log('Checking status for request:', data.requestId);
    // Perform check, update state, send notification, etc.
  }
}

Specific Date

export class MyAgent extends Agent {
  async scheduleReminder(reminderDate: string) {
    const date = new Date(reminderDate);

    const { id } = await this.schedule(date, "sendReminder", {
      message: "Time for your appointment!"
    });

    return id;
  }

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
53
Last commit
Sep 2026

ahel review

  • S4info
    community integration — published by dennislee928, not cloudflare

Automated review, not a security audit. Ruleset v1.

Advanced
Catalog kind
skill
Gateway key
cloudflare-agents
Source
github.com/dennislee928/ethic-latex