Building AI Agents with Cloudflare Workers: A Developer's Guide



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:

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:

  1. Entry point: A Worker receives the user request — HTTP, WebSocket, or a phone-call webhook (Twilio, Vonage, Telnyx).
  2. Agent state: The Worker forwards to a Durable Object representing the agent's session — conversation history, active tool calls, session config.
  3. Model invocation: The DO calls Workers AI (edge models) or an external provider (OpenAI, Anthropic, Google — fetched directly from the edge).
  4. Tool execution: Tool calls run inline in the DO, as subrequests to other Workers, or via MCP to external tool servers.
  5. 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:

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:

It's the wrong default for:

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:

  1. Install Wrangler and create a Worker project: npm create cloudflare@latest my-agent
  2. Add the Agents SDK: npm install agents
  3. Copy the scaffold above and add your tools and system prompt
  4. wrangler deploy
  5. (Optional) Wire up MCP servers for external integrations
  6. (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.

Ship your first AI agent today

Free plan includes 100 ARC credits. No credit card required. Be live in minutes.

Get Started Free →