agents-sdk

द्वारा Cloudflare

Cloudflare Workers पर Agents SDK का उपयोग करके AI एजेंट बनाएं। स्टेटफुल एजेंट, ड्यूरेबल वर्कफ़्लो, रीयल-टाइम WebSocket ऐप, शेड्यूल किए गए कार्य, MCP सर्वर या चैट एप्लिकेशन बनाते समय लोड करें। इसमें Agent क्लास, स्टेट प्रबंधन, कॉल करने योग्य RPC, Workflows एकीकरण और React हुक शामिल हैं।

npx skills add https://github.com/cloudflare/skills --skill agents-sdk

Cloudflare Agents SDK

Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.

Retrieval Sources

Cloudflare docs: https://developers.cloudflare.com/agents/

TopicDocs URLUse for
Getting startedQuick startFirst agent, project setup
Adding to existing projectAdd to existing projectInstall into existing Workers app
ConfigurationConfigurationwrangler.jsonc, bindings, assets, deployment
Agent classAgents APIAgent lifecycle, patterns, pitfalls
StateStore and sync statesetState, validateStateChange, persistence
RoutingRoutingURL patterns, routeAgentRequest
Callable methodsCallable methods@callable, RPC, streaming, timeouts
SchedulingSchedule tasksschedule(), scheduleEvery(), cron
WorkflowsRun workflowsAgentWorkflow, durable multi-step tasks
HTTP/WebSocketsWebSocketsLifecycle hooks, hibernation
Chat agentsChat agentsAIChatAgent, streaming, tools, persistence
Client SDKClient SDKuseAgent, AgentClient, state, RPC, HTTP
Client toolsClient toolsClient-side tools, autoContinueAfterToolResult
Server-driven messagesAutonomous responsessaveMessages, waitUntilStable, server-initiated turns
Resumable streamingChat agentsStream recovery on disconnect
EmailEmailEmail routing, secure reply resolver
MCP clientMCP clientConnecting to MCP servers
MCP serverMCP serverBuilding MCP servers with createMcpHandler
MCP transportsMCP transportsStreamable HTTP, SSE, RPC transport options
Securing MCP serversSecuring MCPOAuth, proxy MCP, hardening
Human-in-the-loopHuman-in-the-loopWorkflow approvals, elicitation, timeout handling
Durable executionDurable executionrunFiber(), stash(), surviving DO eviction
QueueQueueBuilt-in FIFO queue, queue()
RetriesRetriesthis.retry(), backoff/jitter
ObservabilityObservabilityDiagnostics-channel events
Push notificationsPush notificationsWeb Push + VAPID from agents
WebhooksWebhooksReceiving external webhooks
Cross-domain authCross-domain authWebSocket auth, tokens, CORS
Readonly connectionsReadonlyshouldConnectionBeReadonly
VoiceVoiceExperimental STT/TTS, withVoice
Browse the webBrowser toolsExperimental CDP browser automation
ThinkThinkExperimental higher-level chat agent class
MigrationsAI SDK v5, AI SDK v6Upgrading @cloudflare/ai-chat

Capabilities

The Agents SDK provides:

  • Persistent state — SQLite-backed, auto-synced to clients via setState
  • Callable RPC@callable() methods invoked over WebSocket
  • Scheduling — One-time, recurring (scheduleEvery), and cron tasks
  • Workflows — Durable multi-step background processing via AgentWorkflow
  • Durable executionrunFiber() / stash() for work that survives DO eviction
  • Queue — Built-in FIFO queue with retries via queue()
  • Retriesthis.retry() with exponential backoff and jitter
  • MCP integration — Connect to MCP servers or build your own with createMcpHandler
  • Email handling — Receive and reply to emails with secure routing
  • Streaming chatAIChatAgent with resumable streams, message persistence, tools
  • Server-driven messagessaveMessages, waitUntilStable for proactive agent turns
  • React hooksuseAgent, useAgentChat for client apps
  • Observabilitydiagnostics_channel events for state, RPC, schedule, lifecycle
  • Push notifications — Web Push + VAPID delivery from agents
  • Webhooks — Receive and verify external webhooks
  • Voice (experimental) — STT/TTS via @cloudflare/voice
  • Browser tools (experimental) — CDP-powered browsing via agents/browser
  • Think (experimental) — Higher-level chat agent via @cloudflare/think

FIRST: Verify Installation

npm ls agents  # Should show agents package

If not installed:

npm install agents

For chat agents:

npm install agents @cloudflare/ai-chat ai @ai-sdk/react

Wrangler Configuration

{
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": {
    "bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}

Gotchas:

  • Do NOT enable experimentalDecorators in tsconfig (breaks @callable)
  • Never edit old migrations — always add new tags
  • Each agent class needs its own DO binding + migration entry
  • Add "ai": { "binding": "AI" } for Workers AI

Agent Class

import { Agent, routeAgentRequest, callable } from "agents";

type State = { count: number };

export class Counter extends Agent<Env, State> {
  initialState = { count: 0 };

  validateStateChange(nextState: State, source: Connection | "server") {
    if (nextState.count < 0) throw new Error("Count cannot be negative");
  }

  onStateUpdate(state: State, source: Connection | "server") {
    console.log("State updated:", state);
  }

  @callable()
  increment() {
    this.setState({ count: this.state.count + 1 });
    return this.state.count;
  }
}

export default {
  fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};

Routing

Requests route to /agents/{agent-name}/{instance-name}:

ClassURL
Counter/agents/counter/user-123
ChatRoom/agents/chat-room/lobby

Client: useAgent({ agent: "Counter", name: "user-123" })

Custom routing: use getAgentByName(env.MyAgent, "instance-id") then agent.fetch(request).

Core APIs

TaskAPI
Read statethis.state.count
Write statethis.setState({ count: 1 })
SQL querythis.sql`SELECT * FROM users WHERE id = ${id}`
Schedule (delay)await this.schedule(60, "task", payload)
Schedule (cron)await this.schedule("0 * * * *", "task", payload)
Schedule (interval)await this.scheduleEvery(30, "poll")
RPC method@callable() myMethod() { ... }
Streaming RPC@callable({ streaming: true }) stream(res) { ... }
Start workflowawait this.runWorkflow("ProcessingWorkflow", params)
Durable fiberawait this.runFiber("name", async (ctx) => { ... })
Enqueue workthis.queue("handler", payload)
Retry with backoffawait this.retry(fn, { maxAttempts: 5 })
Broadcast to clientsthis.broadcast(message)
Get connectionsthis.getConnections(tag?)

React Client

Read client-sdk.md for client selection and current connection examples. For chat UI and tools, also read streaming-chat.md.

References

Core

Chat & Streaming

Background Processing

Integrations

Experimental

Cloudflare की और Skills

building-ai-agent-on-cloudflare
Cloudflare
Cloudflare पर Agents SDK का उपयोग करके AI एजेंट बनाता है, जिसमें स्थिति प्रबंधन, रीयल-टाइम WebSockets, निर्धारित कार्य, उपकरण एकीकरण और चैट क्षमताएं शामिल हैं। Workers पर तैनात करने के लिए उत्पादन-तैयार एजेंट कोड उत्पन्न करता है। उपयोग करें जब: उपयोगकर्ता "एजेंट बनाएं", "AI एजेंट", "चैट एजेंट", "स्थिति-युक्त एजेंट" चाहता है, "Agents SDK" का उल्लेख करता है, "रीयल-टाइम AI", "WebSocket AI" की आवश्यकता है,
development
building-mcp-server-on-cloudflare
Cloudflare
Cloudflare Workers पर रिमोट MCP (मॉडल कॉन्टेक्स्ट प्रोटोकॉल) सर्वर बनाता है, जिसमें टूल्स, OAuth प्रमाणीकरण और प्रोडक्शन डिप्लॉयमेंट शामिल हैं। सर्वर कोड जनरेट करता है, प्रमाणीकरण प्रदाताओं को कॉन्फ़िगर करता है और Workers पर डिप्लॉय करता है। उपयोग तब करें जब: उपयोगकर्ता "MCP सर्वर बनाएं", "MCP टूल्स बनाएं", "रिमोट MCP", "MCP डिप्लॉय करें", "MCP में OAuth जोड़ें" या Cloudflare पर मॉडल कॉन्टेक्स्ट प्रोटो
development
cloudflare
Cloudflare
Cloudflare प्लेटफ़ॉर्म का व्यापक कौशल, जिसमें Workers, Pages, स्टोरेज (KV, D1, R2), AI (Workers AI, Vectorize, Agents SDK), नेटवर्किंग (Tunnel, Spectrum), सुरक्षा (WAF, DDoS), और इंफ्रास्ट्रक्चर-एज़-कोड (Terraform, Pulumi) शामिल हैं। किसी भी Cloudflare विकास कार्य के लिए उपयोग करें।
durable-objects
Cloudflare
Cloudflare Durable Objects बनाएँ और समीक्षा करें। स्टेटफुल कोऑर्डिनेशन (चैट रूम, मल्टीप्लेयर गेम, बुकिंग सिस्टम) बनाते समय, RPC विधियाँ, SQLite स्टोरेज, अलार्म, WebSockets लागू करते समय, या DO कोड की सर्वोत्तम प्रथाओं के लिए समीक्षा करते समय उपयोग करें। Workers एकीकरण, wrangler कॉन्फ़िगरेशन और Vitest के साथ परीक्षण शामिल है।
sandbox-sdk
Cloudflare
सैंडबॉक्स्ड एप्लिकेशन बनाएं सुरक्षित कोड निष्पादन के लिए। AI कोड निष्पादन, कोड इंटरप्रेटर, CI/CD सिस्टम, इंटरैक्टिव डेव एनवायरनमेंट या अविश्वसनीय कोड निष्पादित करते समय लोड करें। इसमें सैंडबॉक्स SDK जीवनचक्र, कमांड, फाइलें, कोड इंटरप्रेटर और पूर्वावलोकन URL शामिल हैं।
web-perf
Cloudflare
क्रोम DevTools MCP का उपयोग करके वेब प्रदर्शन का विश्लेषण करता है। कोर वेब वाइटल्स (FCP, LCP, TBT, CLS, स्पीड इंडेक्स) को मापता है, रेंडर-ब्लॉकिंग संसाधनों, नेटवर्क निर्भरता श्रृंखलाओं, लेआउट शिफ्ट्स, कैशिंग समस्याओं और पहुंच संबंधी अंतरालों की पहचान करता है। जब पेज लोड प्रदर्शन, Lighthouse स्कोर या साइट स्पीड का ऑडिट, प्रोफाइल, डीबग या ऑप्टिमाइज़ करने के लिए क
workers-best-practices
Cloudflare
Cloudflare Workers कोड की समीक्षा करता है और उसे उत्पादन सर्वोत्तम प्रथाओं के अनुसार लिखता है। नए Workers लिखते समय, Worker कोड की समीक्षा करते समय, wrangler.jsonc कॉन्फ़िगर करते समय, या सामान्य Workers एंटी-पैटर्न (स्ट्रीमिंग, फ्लोटिंग प्रॉमिसेस, ग्लोबल स्टेट, सीक्रेट्स, बाइंडिंग्स, ऑब्जर्वेबिलिटी) की जाँच करते समय लोड करें। पूर्व-प्रशिक्षित ज्ञान की तुलना में Cloudflare दस्तावेज़ों से पुनर्प्राप्ति को प्राथमिकता देता है।
wrangler
Cloudflare
Cloudflare Workers CLI जो Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines और Secrets Store को डिप्लॉय, डेवलप और प्रबंधित करने के लिए है। wrangler कमांड चलाने से पहले लोड करें ताकि सही सिंटैक्स और सर्वोत्तम प्रथाओं को सुनिश्चित किया जा सके।