Claude
Skills
Sign in
Back

cloudflare-agents

Included with Lifetime
$97 forever

Build AI agents with Cloudflare Agents SDK on Workers + Durable Objects. Includes critical guidance on choosing between Agents SDK (infrastructure/state) vs AI SDK (simpler flows). Use when: deciding SDK choice, building WebSocket agents with state, RAG with Vectorize, MCP servers, multi-agent orchestration, or troubleshooting "Agent class must extend", "new_sqlite_classes", binding errors.

Backend & APIs

What this skill does


# Cloudflare Agents SDK

**Status**: Production Ready ✅
**Last Updated**: 2025-11-23
**Dependencies**: cloudflare-worker-base (recommended)
**Latest Versions**: [email protected] (Nov 13, 2025), @modelcontextprotocol/sdk@latest
**Production Tested**: Cloudflare's own MCP servers (https://github.com/cloudflare/mcp-server-cloudflare)

**Recent Updates (2025)**:
- **Sept 2025**: AI SDK v5 compatibility, automatic message migration
- **April 2025**: MCP support (MCPAgent class), `import { context }` from agents
- **March 2025**: Package rename (agents-sdk → agents)

---

## 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](https://sdk.vercel.ai/) directly on Workers - it's simpler, requires less infrastructure, and handles streaming automatically.

**Example** (no Agents SDK needed):
```typescript
// 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

| Feature | AI SDK Only | Agents 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 Case** | Simple chat, completions | Complex 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

```bash
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

```bash
cd my-existing-worker
npm install agents
```

**Then create an Agent class:**

```typescript
// 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`:

```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"]  // C

Related in Backend & APIs