agents-sdk
Build stateful AI agents using the Cloudflare Agents SDK. Load when creating agents with persistent state, scheduling, RPC, MCP servers, email handling, or streaming chat. Covers Agent class, AIChatAgent, state management, and Code Mode for reduced token usage.
What this skill does
# Cloudflare Agents SDK
Build persistent, stateful AI agents on Cloudflare Workers using the `agents` npm package.
## FIRST: Verify Installation
```bash
npm install agents
```
Agents require a binding in `wrangler.jsonc`:
```jsonc
{
"durable_objects": {
// "class_name" must match your Agent class name exactly
"bindings": [{ "name": "Counter", "class_name": "Counter" }]
},
"migrations": [
// Required: list all Agent classes for SQLite storage
{ "tag": "v1", "new_sqlite_classes": ["Counter"] }
]
}
```
## Choosing an Agent Type
| Use Case | Base Class | Package |
|----------|------------|---------|
| Custom state + RPC, no chat | `Agent` | `agents` |
| Chat with message persistence | `AIChatAgent` | `@cloudflare/ai-chat` |
| Building an MCP server | `McpAgent` | `agents/mcp` |
## Key Concepts
- **Agent** base class provides state, scheduling, RPC, MCP, and email capabilities
- **AIChatAgent** adds streaming chat with automatic message persistence and resumable streams
- **Code Mode** generates executable code instead of tool calls—reduces token usage significantly
- **this.state / this.setState()** - automatic persistence to SQLite, broadcasts to clients
- **this.schedule()** - schedule tasks at Date, delay (seconds), or cron expression
- **@callable** decorator - expose methods to clients via WebSocket RPC
## Quick Reference
| Task | API |
|------|-----|
| Persist state | `this.setState({ count: 1 })` |
| Read state | `this.state.count` |
| Schedule task | `this.schedule(60, "taskMethod", payload)` |
| Schedule cron | `this.schedule("0 * * * *", "hourlyTask")` |
| Cancel schedule | `this.cancelSchedule(id)` |
| Queue task | `this.queue("processItem", payload)` |
| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |
| RPC method | `@callable() async myMethod() { ... }` |
| Streaming RPC | `@callable({ streaming: true }) async stream(res) { ... }` |
## Minimal Agent
```typescript
import { Agent, routeAgentRequest, callable } from "agents";
type State = { count: number };
export class Counter extends Agent<Env, State> {
initialState = { count: 0 };
@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 })
};
```
## Streaming Chat Agent
Use `AIChatAgent` for chat with automatic message persistence and resumable streaming.
**Install additional dependencies first:**
```bash
npm install @cloudflare/ai-chat ai @ai-sdk/openai
```
**Add wrangler.jsonc config** (same pattern as base Agent):
```jsonc
{
"durable_objects": {
"bindings": [{ "name": "Chat", "class_name": "Chat" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Chat"] }]
}
```
```typescript
import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { streamText, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";
export class Chat extends AIChatAgent<Env> {
async onChatMessage(onFinish) {
const result = streamText({
model: openai("gpt-4o"),
messages: await convertToModelMessages(this.messages),
onFinish
});
return result.toUIMessageStreamResponse();
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};
```
**Client** (React):
```tsx
import { useAgent } from "agents/react";
import { useAgentChat } from "@cloudflare/ai-chat/react";
const agent = useAgent({ agent: "Chat", name: "my-chat" });
const { messages, input, handleSubmit } = useAgentChat({ agent });
```
## Detailed References
- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling, queues
- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams, UI patterns
- **[references/codemode.md](references/codemode.md)** - Generate code instead of tool calls (token savings)
- **[references/mcp.md](references/mcp.md)** - MCP server integration
- **[references/email.md](references/email.md)** - Email routing and handling
## When to Use Code Mode
Code Mode generates executable JavaScript instead of making individual tool calls. Use it when:
- Chaining multiple tool calls in sequence
- Complex conditional logic across tools
- MCP server orchestration (multiple servers)
- Token budget is constrained
See [references/codemode.md](references/codemode.md) for setup and examples.
## Best Practices
1. **Prefer streaming**: Use `streamText` and `toUIMessageStreamResponse()` for chat
2. **Use AIChatAgent for chat**: Handles message persistence and resumable streams automatically
3. **Type your state**: `Agent<Env, State>` ensures type safety for `this.state`
4. **Use @callable for RPC**: Cleaner than manual WebSocket message handling
5. **Code Mode for complex workflows**: Reduces round-trips and token usage
6. **Schedule vs Queue**: Use `schedule()` for time-based, `queue()` for sequential processing
Related 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.