Agent skill

Building AI Agent On Cloudflare

by CommandCodeAI in CommandCodeAI/agent-skills

Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities.

MITAuto-check passedBackend & APIs

Install Building AI Agent On Cloudflare

skills CLI
$ npx skills add CommandCodeAI/agent-skills --skill building-ai-agent-on-cloudflare -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install CommandCodeAI/agent-skills building-ai-agent-on-cloudflare --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/CommandCodeAI/agent-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/building-ai-agent-on-cloudflare .claude/skills/building-ai-agent-on-cloudflare && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
building-ai-agent-on-cloudflare
GitHub stars
132
Token cost
~2.3k tokens
SKILL.md length
232 words
Files
5 (incl. references)
Skills in repo
5
Repo updated
First seen
Licence
MIT

At a glance

Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities.

  • : user wants to build an agent
  • SKILL.md covers When to Use, Prerequisites, Quick Start and Core Concepts, plus 11 more sections
  • Calls npm, npx and wrangler
  • Mentions Agents SDK

What it does

Building AI Agent On Cloudflare is an agent skill from CommandCodeAI/agent-skills. Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities. Generates production-ready agent code deployed to Workers. Use when: user wants to "build an agent", "AI agent", "chat agent", "stateful agent", mentions "Agents SDK", needs "real-time AI", "WebSocket AI", or asks about agent "state management", "scheduled tasks", or "tool calling".

Its SKILL.md is about 2.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 5 other files, including reference files (for example `references/agent-patterns.md`, `references/examples.md` and `references/state-patterns.md`).

It sits in Backend & APIs, covering Realtime and WebSockets, Building AI agents and Scheduled and recurring tasks. It works with Cloudflare and Cloudflare Workers. The repository describes itself as: A curated list of awesome Skills, resources, and tools for customizing coding agent workflows. The licence is MIT.

When your agent uses it

  • : user wants to build an agent
  • Mentions Agents SDK
  • Needs real-time AI
  • Asks about agent state management

Example prompts

  • “build an agent”
  • “AI agent”
  • “chat agent”
  • “/building-ai-agent-on-cloudflare”

Requirements

  • Node.js

What it can do on your machine

Read from SKILL.md and the folder at commit f490dd9. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npm
    • npx
    • wrangler
    • curl

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use npm, npx, wrangler and curl, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Building AI Agent On Cloudflare loads about 2.3k tokens when it runs, and up to ~11k if it reads all its reference files. Until then it costs about 118 tokens; SKILL.md has 232 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~118
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~11k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from CommandCodeAI/agent-skills at commit f490dd9, republished under its MIT licence (© CommandCodeAI). 232 words, ~2,322 tokens.

Download SKILL.mdSave it as .claude/skills/building-ai-agent-on-cloudflare/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
building-ai-agent-on-cloudflare
description
Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities. Generates production-ready agent code deployed to Workers. Use when: user wants to "build an agent", "AI agent", "chat agent", "stateful agent", mentions "Agents SDK", needs "real-time AI", "WebSocket AI", or asks about agent "state management", "scheduled tasks", or "tool calling".

Building Cloudflare Agents

Creates AI-powered agents using Cloudflare's Agents SDK with persistent state, real-time communication, and tool integration.

When to Use

  • User wants to build an AI agent or chatbot
  • User needs stateful, real-time AI interactions
  • User asks about the Cloudflare Agents SDK
  • User wants scheduled tasks or background AI work
  • User needs WebSocket-based AI communication

Prerequisites

  • Cloudflare account with Workers enabled
  • Node.js 18+ and npm/pnpm/yarn
  • Wrangler CLI (npm install -g wrangler)

Quick Start

bash
npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter
cd my-agent
npm start

Agent runs at http://localhost:8787

Core Concepts

What is an Agent?

An Agent is a stateful, persistent AI service that:

  • Maintains state across requests and reconnections
  • Communicates via WebSockets or HTTP
  • Runs on Cloudflare's edge via Durable Objects
  • Can schedule tasks and call tools
  • Scales horizontally (each user/session gets own instance)
Agent Lifecycle
Client connects → Agent.onConnect() → Agent processes messages
                                    → Agent.onMessage()
                                    → Agent.setState() (persists + syncs)
Client disconnects → State persists → Client reconnects → State restored

Basic Agent Structure

typescript
import { Agent, Connection } from "agents";

interface Env {
  AI: Ai;  // Workers AI binding
}

interface State {
  messages: Array<{ role: string; content: string }>;
  preferences: Record<string, string>;
}

export class MyAgent extends Agent<Env, State> {
  // Initial state for new instances
  initialState: State = {
    messages: [],
    preferences: {},
  };

  // Called when agent starts or resumes
  async onStart() {
    console.log("Agent started with state:", this.state);
  }

  // Handle WebSocket connections
  async onConnect(connection: Connection) {
    connection.send(JSON.stringify({
      type: "welcome",
      history: this.state.messages,
    }));
  }

  // Handle incoming messages
  async onMessage(connection: Connection, message: string) {
    const data = JSON.parse(message);

    if (data.type === "chat") {
      await this.handleChat(connection, data.content);
    }
  }

  // Handle disconnections
  async onClose(connection: Connection) {
    console.log("Client disconnected");
  }

  // React to state changes
  onStateUpdate(state: State, source: string) {
    console.log("State updated by:", source);
  }

  private async handleChat(connection: Connection, userMessage: string) {
    // Add user message to history
    const messages = [
      ...this.state.messages,
      { role: "user", content: userMessage },
    ];

    // Call AI
    const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
      messages,
    });

    // Update state (persists and syncs to all clients)
    this.setState({
      ...this.state,
      messages: [
        ...messages,
        { role: "assistant", content: response.response },
      ],
    });

    // Send response
    connection.send(JSON.stringify({
      type: "response",
      content: response.response,
    }));
  }
}

Entry Point Configuration

typescript
// src/index.ts
import { routeAgentRequest } from "agents";
import { MyAgent } from "./agent";

export default {
  async fetch(request: Request, env: Env) {
    // routeAgentRequest handles routing to /agents/:class/:name
    return (
      (await routeAgentRequest(request, env)) ||
      new Response("Not found", { status: 404 })
    );
  },
};

export { MyAgent };

Clients connect via: wss://my-agent.workers.dev/agents/MyAgent/session-id

Wrangler Configuration

toml
name = "my-agent"
main = "src/index.ts"
compatibility_date = "2024-12-01"

[ai]
binding = "AI"

[durable_objects]
bindings = [{ name = "AGENT", class_name = "MyAgent" }]

[[migrations]]
tag = "v1"
new_classes = ["MyAgent"]

State Management

Reading State
typescript
// Current state is always available
const currentMessages = this.state.messages;
const userPrefs = this.state.preferences;
Updating State
typescript
// setState persists AND syncs to all connected clients
this.setState({
  ...this.state,
  messages: [...this.state.messages, newMessage],
});

// Partial updates work too
this.setState({
  preferences: { ...this.state.preferences, theme: "dark" },
});
SQL Storage

For complex queries, use the embedded SQLite database:

typescript
// Create tables
await this.sql`
  CREATE TABLE IF NOT EXISTS documents (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    content TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`;

// Insert
await this.sql`
  INSERT INTO documents (title, content)
  VALUES (${title}, ${content})
`;

// Query
const docs = await this.sql`
  SELECT * FROM documents WHERE title LIKE ${`%${search}%`}
`;

Scheduled Tasks

Agents can schedule future work:

typescript
async onMessage(connection: Connection, message: string) {
  const data = JSON.parse(message);

  if (data.type === "schedule_reminder") {
    // Schedule task for 1 hour from now
    const { id } = await this.schedule(3600, "sendReminder", {
      message: data.reminderText,
      userId: data.userId,
    });

    connection.send(JSON.stringify({ type: "scheduled", taskId: id }));
  }
}

// Called when scheduled task fires
async sendReminder(data: { message: string; userId: string }) {
  // Send notification, email, etc.
  console.log(`Reminder for ${data.userId}: ${data.message}`);

  // Can also update state
  this.setState({
    ...this.state,
    lastReminder: new Date().toISOString(),
  });
}
Schedule Options
typescript
// Delay in seconds
await this.schedule(60, "taskMethod", { data });

// Specific date
await this.schedule(new Date("2025-01-01T00:00:00Z"), "taskMethod", { data });

// Cron expression (recurring)
await this.schedule("0 9 * * *", "dailyTask", {});  // 9 AM daily
await this.schedule("*/5 * * * *", "everyFiveMinutes", {});  // Every 5 min

// Manage schedules
const schedules = await this.getSchedules();
await this.cancelSchedule(taskId);

Chat Agent (AI-Powered)

For chat-focused agents, extend AIChatAgent:

typescript
import { AIChatAgent } from "agents/ai-chat-agent";

export class ChatBot extends AIChatAgent<Env> {
  // Called for each user message
  async onChatMessage(message: string) {
    const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        ...this.messages,  // Automatic history management
        { role: "user", content: message },
      ],
      stream: true,
    });

    // Stream response back to client
    return response;
  }
}

Features included:

  • Automatic message history
  • Resumable streaming (survives disconnects)
  • Built-in saveMessages() for persistence

Client Integration

React Hook
tsx
import { useAgent } from "agents/react";

function Chat() {
  const { state, send, connected } = useAgent({
    agent: "my-agent",
    name: userId,  // Agent instance ID
  });

  const sendMessage = (text: string) => {
    send(JSON.stringify({ type: "chat", content: text }));
  };

  return (
    <div>
      {state.messages.map((msg, i) => (
        <div key={i}>{msg.role}: {msg.content}</div>
      ))}
      <input onKeyDown={(e) => e.key === "Enter" && sendMessage(e.target.value)} />
    </div>
  );
}
Vanilla JavaScript
javascript
const ws = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/user123");

ws.onopen = () => {
  console.log("Connected to agent");
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received:", data);
};

ws.send(JSON.stringify({ type: "chat", content: "Hello!" }));

Common Patterns

See references/agent-patterns.md for:

  • Tool calling and function execution
  • Multi-agent orchestration
  • RAG (Retrieval Augmented Generation)
  • Human-in-the-loop workflows

Deployment

bash
# Deploy
npx wrangler deploy

# View logs
wrangler tail

# Test endpoint
curl https://my-agent.workers.dev/agents/MyAgent/test-user

Troubleshooting

See references/troubleshooting.md for common issues.

References

© CommandCodeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (references) in skills/building-ai-agent-on-cloudflare of CommandCodeAI/agent-skills.

  • SKILL.md
  • references/agent-patterns.md
  • references/examples.md
  • references/state-patterns.md
  • references/troubleshooting.md

Open the folder on GitHubat commit f490dd9

Compare with similar skills

Building AI Agent On Cloudflare next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Building AI Agent On Cloudflare compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Building AI Agent On Cloudflare this skillCommandCodeAI/agent-skills132—~2.3kAutomated safety check: PassMIT
Agents SDKhodgef/apiker1273 repos~3kAutomated safety check: PassMIT
Cloudflare Browser Renderingcloudflare/moltworker10k—~742Automated safety check: PassApache-2.0
Durable Objectshodgef/apiker1274 repos~1.5kAutomated safety check: PassMIT
Cloudflare WorkersEpicenterHQ/epicenter4.8k—~576Automated safety check: PassCustom licence
HonoEpicenterHQ/epicenter4.8k—~513Automated safety check: PassCustom licence

Similar skills

  • Agents SDK

    hodgef/apiker

    Build AI agents on Cloudflare Workers using the Agents SDK. An agent skill from hodgef/apiker.

    127 GitHub starsUsed in 3 repos~3k tokens
    Backend & APIsAuto-check passed
  • Cloudflare Browser Rendering

    cloudflare/moltworker

    Official

    Drives headless Chrome through Cloudflare Browser Rendering over a CDP WebSocket to take screenshots, navigate and scrape pages, and record multi-page videos.

    10k GitHub stars~742 tokensUpdated 5 mo ago
    Productivity & AutomationAuto-check passed
  • Durable Objects

    hodgef/apiker

    Create and review Cloudflare Durable Objects. An agent skill from hodgef/apiker.

    127 GitHub starsUsed in 4 repos~1.5k tokens
    Backend & APIsAuto-check passed
  • Cloudflare Workers

    EpicenterHQ/epicenter

    Cloudflare Workers patterns for Worker runtime APIs, Durable Objects, KV, R2, D1, Queues, WebSockets, streaming responses, bindings, wrangler configuration, and deployment limits.

    4.8k GitHub stars~576 tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Hono

    EpicenterHQ/epicenter

    Hono patterns for TypeScript API routes, middleware, request and response typing, streaming, WebSockets, and Cloudflare Workers deployment.

    4.8k GitHub stars~513 tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Sentry Instrument

    getsentry/sentry-for-ai

    Official

    Instrument an application with Sentry — detect the platform, install and initialize the SDK if needed, and wire up any signal — error monitoring, tracing/performance, logging, metrics, profiling…

    268 GitHub stars~3.2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed

More from CommandCodeAI/agent-skills

  • Youtube Transcript

    CommandCodeAI/agent-skills

    Download YouTube video transcripts when user provides a YouTube URL or asks to download/get/fetch a transcript from YouTube.

    132 GitHub starsUsed in 1 repo~3.4k tokens
    Auto-check: notes
  • Building MCP Server On Cloudflare

    CommandCodeAI/agent-skills

    Builds remote MCP (Model Context Protocol) servers on Cloudflare Workers with tools, OAuth authentication, and production deployment.

    132 GitHub stars~1.5k tokensUpdated 7 mo ago
    Auto-check passed
  • AWS Agentic AI

    CommandCodeAI/agent-skills

    AWS Bedrock AgentCore comprehensive expert for deploying and managing all AgentCore services.

    132 GitHub stars~1.5k tokensUpdated 7 mo ago
    Auto-check passed
  • Welcome Me

    CommandCodeAI/agent-skills

    Greet user with a specific message when they say they're new or ask for a welcome message.

    132 GitHub stars~182 tokensUpdated 7 mo ago
    Auto-check passed

Questions about Building AI Agent On Cloudflare

What does Building AI Agent On Cloudflare do?

Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities. Building AI Agent On Cloudflare is an agent skill from CommandCodeAI/agent-skills. Builds AI agents on Cloudflare using the Agents SDK with state management, real-time WebSockets, scheduled tasks, tool integration, and chat capabilities.

When should I use Building AI Agent On Cloudflare?

Building AI Agent On Cloudflare fits situations like: : user wants to build an agent; mentions Agents SDK; needs real-time AI; asks about agent state management.

How do I install Building AI Agent On Cloudflare in Claude Code?

Run `npx skills add CommandCodeAI/agent-skills --skill building-ai-agent-on-cloudflare -a claude-code`. Or copy the skill folder (skills/building-ai-agent-on-cloudflare in CommandCodeAI/agent-skills) into .claude/skills/building-ai-agent-on-cloudflare in your project. Claude Code loads it when a task matches its description.

How do I install Building AI Agent On Cloudflare in Codex?

Run `npx skills add CommandCodeAI/agent-skills --skill building-ai-agent-on-cloudflare -a codex`. Or copy the skill folder (skills/building-ai-agent-on-cloudflare in CommandCodeAI/agent-skills) into .agents/skills/building-ai-agent-on-cloudflare in your project. Codex loads it when a task matches its description.

Can I use Building AI Agent On Cloudflare in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add CommandCodeAI/agent-skills --skill building-ai-agent-on-cloudflare -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/building-ai-agent-on-cloudflare, .gemini/skills/building-ai-agent-on-cloudflare, .github/skills/building-ai-agent-on-cloudflare and .opencode/skills/building-ai-agent-on-cloudflare in your project.

What does Building AI Agent On Cloudflare need to run?

Going by SKILL.md and its folder, Building AI Agent On Cloudflare needs the command-line tools its instructions call (npm, npx, wrangler and curl). Our summary lists: Node.js.

Does Building AI Agent On Cloudflare access the network?

SKILL.md contains no URLs. Its commands use npm, npx and curl, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Building AI Agent On Cloudflare safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Building AI Agent On Cloudflare use?

Building AI Agent On Cloudflare is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Building AI Agent On Cloudflare use?

About 2.3k tokens (SKILL.md is roughly 9.3k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 8.2k tokens, read only when the agent opens those files.

What are the alternatives to Building AI Agent On Cloudflare?

Skills that share tags, products or a category with Building AI Agent On Cloudflare: Agents SDK (hodgef/apiker, 127 stars), Cloudflare Browser Rendering (cloudflare/moltworker, 10k stars), Durable Objects (hodgef/apiker, 127 stars) and Cloudflare Workers (EpicenterHQ/epicenter, 4.8k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Building AI Agent On Cloudflare?

CommandCodeAI (a GitHub organization) maintains it in CommandCodeAI/agent-skills, which has 132 GitHub stars. The repository holds 5 skills in this directory. The repository was last updated on March 10, 2026.

Source: CommandCodeAI/agent-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.