cloudflare-agents
Comprehensive guide for the Cloudflare Agents SDK - build AI-powered autonomous agents on Workers + Durable Objects. Use when: building AI agents, creating stateful agents with WebSockets, implementing chat agents with streaming, scheduling tasks with cron/delays, running asynchronous workflows, building RAG (Retrieval Augmented Generation) systems with Vectorize, creating MCP (Model Context Protocol) servers, implementing human-in-the-loop workflows, browsing the web with Browser Rendering, managing agent state with SQL, syncing state between agents and clients, calling agents from Workers, building multi-agent systems, or encountering Agent configuration errors. Prevents 15+ documented issues: migrations not atomic, missing new_sqlite_classes, Agent class not exported, binding name mismatch, global uniqueness gotchas, WebSocket state handling, scheduled task callback errors, state size limits, workflow binding missing, browser binding required, vectorize index not found, MCP transport confusion, authentication bypassed, instance naming errors, and state sync failures. Keywords: Cloudflare Agents, agents sdk, cloudflare agents sdk, Agent class, Durable Objects agents, stateful agents, WebSocket agents, this.setState, this.sql, this.schedule, schedule tasks, cron agents, run workflows, agent workflows, browse web, puppeteer agents, browser rendering, rag agents, vectorize agents, embeddings, mcp server, McpAgent, mcp tools, model context protocol, routeAgentRequest, getAgentByName, useAgent hook, AgentClient, agentFetch, useAgentChat, AIChatAgent, chat agents, streaming chat, human in the loop, hitl agents, multi-agent, agent orchestration, autonomous agents, long-running agents, AI SDK, Workers AI, "Agent class must extend", "new_sqlite_classes", "migrations required", "binding not found", "agent not exported", "callback does not exist", "state limit exceeded"
What this skill does
# Cloudflare Agents SDK
**Status**: Production Ready ✅
**Last Updated**: 2025-10-21
**Dependencies**: cloudflare-worker-base (recommended)
**Latest Versions**: agents@latest, @modelcontextprotocol/sdk@latest
**Production Tested**: Cloudflare's own MCP servers (https://github.com/cloudflare/mcp-server-cloudflare)
---
## 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.
---
## 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"] // 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
```bash
npx wrangler@latest deploy
```
Your agent is now running at: `https://my-agent.<subdomain>.workers.dev`
---
## Configuration Deep Dive
### Complete wrangler.jsonc Example
```jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-agent",
"main": "src/index.ts",
"account_id": "YOUR_ACCOUNT_ID",
"compatibility_date": "2025-10-21",
"compatibility_flags": ["nodejs_compat"],
// Durable Objects configuration (REQUIRED)
"durable_objects": {
"bindings": [
{
"name": "MyAgent",
"class_name": "MyAgent"
}
]
},
// Migrations (REQUIRED)
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["MyAgent"] // Enables state persistence
}
],
// Optional: Workers AI binding (for AI model calls)
"ai": {
"binding": "AI"
},
// Optional: Vectorize binding (for RAG)
"vectorize": {
"bindings": [
{
"binding": "VECTORIZE",
"index_name": "my-agent-vectors"
}
]
},
// Optional: Browser Rendering binding (for web browsing)
"browser": {
"binding": "BROWSER"
},
// Optional: Workflows binding (for async workflows)
"workflows": [
{
"name": "MY_WORKFLOW",
"class_name": "MyWorkflow",
"script_name": "my-workflow-script" // If in different project
}
],
// Optional: D1 binding (for additional persistent data)
"d1_databases": [
{
"binding": "DB",
"database_name": "my-agent-db",
"database_id": "your-database-id"
}
],
// Optional: R2 binding (for file storage)
"r2_buckets": [
{
"binding": "BUCKET",
"bucket_name": "my-agent-files"
}
],
// Optional: Environment variables
"vars": {
"ENVIRONMENT": "production"
},
// Optional: Secrets (set with: wrangler secret put KEY)
// OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.
// Observability
"observability": {
"enabled": true
}
}
```
### Migrations Best Practices
**Atomic Deployments**: Migrations are **atomic operations** - they cannot be gradually deployed.
```jsonc
{
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["MyAgent"] // Initial: enable SQLite
},
{
"tag": "v2",
"renamed_classes": [
{"from": "MyAgent", "to": "MyRenamedAgent"}
]
},
{
"tag": "v3",
"deleted_classes": ["OldAgent"]
},
{
"tag": "v4",
"transferred_classes": [
{
"from": "AgentInOldScript",
"from_script": "old-worker",
"to": "AgentInNewScript"
}
]
}
]
}
```
**Migration Rules:**
- ✅ Each migration needs a unique `tag`
- ✅ Cannot enable SQLite on existing deployed class (must be in first migration)
- ✅ Migrations apply in order during deployment
- ✅ Cannot edit or remove previous migration tags
- ❌ Never deploy new migrations gradually (atomic only)
### Environment-Specific Migrations
```jsonc
{
"migrations": [{"tag": "v1", "new_sqlite_classes": ["MyAgent"]}],
"env": {
"staging": {
"migrations": [
{"tag": "v1", "new_sqlite_classes": ["MyAgent"]},
{"tag": "v2-staging", "renamed_classes": [{"from": "MyAgent", "to": "StagingAgent"}]}
]
}
}
}
```
---
## Agent Class API
The `Agent` class is the foundation of the Agents SDK. Extend it to create your agent.
### Basic Agent Structure
```typescript
import { Agent } from "agents";
interface Env {
// Environment variables and bindings
OPENAI_API_KEY: string;
AI: Ai;
VECTORIZE: Vectorize;
DB: D1Database;
}
interface State {
// Your agent's persistent state
counter: number;
messages: string[];
lastUpdated: Date | null;
}
export class MyAgent extends Agent<Env, State> {
// Optional: Set initial state (first time agent is created)
initialState: State = {
counter: 0,
messages: [],
lastUpdated: null
};
// Optional: Called when agent instance starts or wakes from hibernation
async onStart() {
console.log('Agent started:', this.name, 'State:', this.state);
}
// Handle HTTP requests
async onRequest(request: Request): Promise<Response> {
return Response.json({ message: "Hello from Agent", state: this.state });
}
// Handle WebSocket connections (optional)
async onConnect(connection: Connection, ctx: ConnectionContext) {
console.log('Client connected:', connection.id);
// Connections are automatically accepted
}
// Handle WebSocket messages (optional)
async onMessage(connection: Connection, message: WSMessage) {
if (typeof message === 'string') {
connection.send(`Echo: ${message}`);
}
}
// Handle WebSocket errors (optional)
async onError(connection: Connection, error: unknown): Promise<void> {
console.error('Connection error:', error);
}
// Handle WebSocket close (optional)
async onClose(connection: Connection, code: number, reason: string, wasClean: boolean): Promise<void> {
console.log('Connection closed:', code, reason);
}
// Called when state is updated from any source (optional)
onStateUpdaRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.