title: "Building AI Agents with Cloudflare Workers: A Developer's Guide"
slug: building-ai-agents-cloudflare-workers
meta_description: "A practical developer guide to deploying AI agents on Cloudflare Workers and Durable Objects, with MCP hosting, edge inference, and a working agent scaffold."
date: 2026-06-21
author: CloudClaw Team
category: Developers
tags: ["cloudflare-workers", "ai-agents", "mcp", "edge-compute", "developer-guide", "serverless"]
target_keyword: "deploy AI agents on Cloudflare"
secondary_keywords: ["Cloudflare Workers AI", "Durable Objects agent", "MCP server hosting", "edge AI agents", "agents SDK"]
schema_type: "Article"
schema_fields: ["headline", "author", "datePublished", "image", "publisher", "mainEntityOfPage"]
internal_links:
- "/for-developers"
- "/blog/mcp-server-hosting-guide"
- "/pricing"
cta: "CloudClaw MCP hosting + developer platform"
Building AI Agents with Cloudflare Workers: A Developer's Guide
If you're building AI agents in 2026, you're probably tired of the same loop: prototype the agent locally, hit a wall on deployment, wrestle with a container orchestrator, and end up with a single-region deployment that adds 200ms of latency to every model call. Cloudflare Workers — and specifically the Workers AI + Durable Objects + Agents stack — has quietly become one of the best platforms to deploy AI agents on Cloudflare's edge without any of that pain.
This is a practical, opinionated guide for developers. We'll cover the architecture, when to reach for Workers vs. alternatives, a working agent scaffold you can copy, and how CloudClaw's platform layers on top if you'd rather not run your own inference routing, tool execution, and MCP hosting. If you want the deeper MCP-specific material first, read our MCP server hosting guide.
Why Cloudflare Workers for AI agents
The standard objections to serverless for AI workloads (cold starts, timeout limits, no state) have largely been addressed by the Workers platform over the last two cycles. Here's what's actually good about it for agents specifically:
- Global edge by default. Your agent runs in the datacenter closest to the user (330+ cities). For latency-sensitive agent loops — tool calls, streaming responses, voice — this matters more than people expect.
- Workers AI. Cloudflare runs a growing catalog of open models (Llama, Mistral, Qwen, Gemma, embedding models, whisper-class STT, image models) directly on their GPUs at the edge. You're not paying egress to a third-party model API for the common cases.
- Durable Objects. Single-stateful objects with strong consistency — perfect for an agent's conversational state, tool call history, and session memory. This is the piece that makes stateful agents actually work on serverless.
- Agents SDK. Cloudflare's first-party
agentspackage wraps Durable Objects + Workers AI + tool calling into a clean Agent base class with built-in state, scheduling, and streaming. - MCP client and server support. Workers can act as MCP servers and as MCP clients, which means your agent can expose tools to (and consume tools from) any MCP-compatible system. More on this below.
- No cold-start tax worth talking about. Worker cold starts are in the single-digit milliseconds. Durable Object startup is fast enough for interactive agent loops.
The trade-off to know about: if your agent needs to run a 10-minute batch inference job, Workers' CPU and wall-clock limits will bite you. Workers are optimized for the request/response + streaming + WebSocket loop that most interactive agents actually are, not for long-running batch work. Use the right tool.
The architecture in one diagram (in words)
A production agent on Workers typically looks like this:
- Entry point: A Worker receives the user request — HTTP, WebSocket, or a phone-call webhook (Twilio, Vonage, Telnyx).
- Agent state: The Worker forwards to a Durable Object representing the agent's session — conversation history, active tool calls, session config.
- Model invocation: The DO calls Workers AI (edge models) or an external provider (OpenAI, Anthropic, Google — fetched directly from the edge).
- Tool execution: Tool calls run inline in the DO, as subrequests to other Workers, or via MCP to external tool servers.
- Response: The agent streams the response back over the original transport.
State lives in the Durable Object. Compute lives at the edge. Tools live anywhere MCP can reach. That's the whole model.
A working agent scaffold
Here's a minimal but real agent using the Cloudflare Agents SDK. This is a starting point, not a toy — extend it with your own tools and prompts.
typescript
// agent.ts
import { Agent, AgentNamespace } from "agents";
import { tool } from "@ai-sdk/v4";
import { z } from "zod";
import { streamText } from "ai";
// Define a tool inline
const lookupOrder = tool({
description: "Look up an order by ID",
parameters: z.object({
orderId: z.string(),
}),
execute: async ({ orderId }, { env }) => {
const row = await env.DB.prepare(
"SELECT * FROM orders WHERE id = ?"
).bind(orderId).first();
return row ?? { error: "not found" };
},
});
export class SupportAgent extends Agent {
// Called on every user message
async onMessage(message: string) {
const result = streamText({
model: "claude-3-5-sonnet", // or an env.LLM binding to Workers AI
system: "You are a helpful support agent. Use tools to look up data.",
messages: this.history, // persisted automatically by the Agent base class
tools: { lookupOrder },
onFinish: async (result) => {
// persist the assistant turn
await this.appendResponse(result);
},
});
return result.toDataStreamResponse();
}
// Optional: scheduled wakeups for proactive agents
async onAlarm() {
// e.g., follow up with a user, run a batch step, etc.
}
}
// Worker entry point
export default {
async fetch(req, env) {
const url = new URL(req.url);
// Route to the agent DO by session id
const sessionId = url.searchParams.get("session") ?? "default";
const stub = env.SupportAgent.get(
env.SupportAgent.idFromName(sessionId)
);
return stub.fetch(req);
},
} satisfies ExportedHandler<Env>;
interface Env {
SupportAgent: AgentNamespace<SupportAgent>;
DB: D1Database;
LLM: Ai; // Workers AI binding
}
Deploy with wrangler deploy. The agent is now live at the edge, with stateful sessions and tool calling. Add MCP servers, vector search (via Vectorize), R2 for file storage, and Queues for async work as you need them.
MCP: the missing piece for production agents
Most real agents aren't just LLMs with inline tools — they consume tools from external systems (CRMs, databases, internal APIs, third-party SaaS). The Model Context Protocol is the standard for this, and Workers are an excellent host for MCP servers.
You can run an MCP server directly on a Worker (the @modelcontextprotocol/sdk works server-side on Workers with minor adaptations), and you can have your agent DO act as an MCP client to compose tools from multiple MCP servers. We cover the full MCP hosting model in the MCP server hosting guide — read that if you're going production with MCP.
The short version: don't bake tool definitions into your agent code if you can avoid it. Expose them as MCP servers, point your agent at them, and you get swappable tools, third-party integrations, and a clean separation between agent logic and the systems it talks to.
What CloudClaw adds
You can run all of the above yourself on Cloudflare — it's a great stack. What CloudClaw provides is the layer most teams don't want to build and maintain:
- Managed MCP server hosting on Cloudflare's edge. Bring your MCP server (or use one of 200+ templates) and we handle deployment, scaling, secrets, and observability. See CloudClaw for developers.
- 200+ pre-built agent templates for lead capture, appointment booking, intake, and support — so you're not reinventing prompt-and-tool scaffolding per project.
- A model-routing layer to swap providers (Workers AI, OpenAI, Anthropic, Google, open models) without rewriting agent code.
- Telephony, SMS, and chat transport bindings so your agent can answer a phone, send an SMS, or live in a website widget without integration glue.
- Usage-based pricing on ARC credits. Pay for what your agents actually do. Model your workload on the pricing page.
For agencies building agent products for clients, the CloudClaw for agencies program adds white-label deployments, multi-tenant management, and revenue sharing.
When to use Workers vs. something else
Workers + Durable Objects is the right default for:
- Interactive, request/response or streaming agents (chat, voice, support)
- Multi-region latency-sensitive workloads
- Agents that compose many MCP tools
- Teams that want zero infrastructure to operate
It's the wrong default for:
- Long-running batch inference (use Modal, Replicate, or a dedicated GPU host)
- Agents that need to hold a single multi-GB model in memory across calls (use a dedicated inference server)
- Heavily regulated workloads where you need explicit single-region data residency that Workers' routing can't guarantee
For everything in the first bucket, Workers is now hard to beat on developer experience and operational cost.
Ship an agent this week
The fastest path from zero to a deployed agent:
- Install Wrangler and create a Worker project:
npm create cloudflare@latest my-agent - Add the Agents SDK:
npm install agents - Copy the scaffold above and add your tools and system prompt
wrangler deploy- (Optional) Wire up MCP servers for external integrations
- (Optional) Move the whole thing onto CloudClaw for managed MCP hosting, model routing, and transport bindings
Most developers can go from clone to deployed agent in an afternoon. Going to production with monitoring, multi-region failover, and a real tool ecosystem is where CloudClaw earns its keep — but the DIY path is genuinely good now, and we'd rather you ship on Workers than on a worse stack.
Explore CloudClaw's developer platform and MCP hosting →
Building something specific? Join the developer Discord or book a technical call with our team — we're happy to talk architecture.