A counter agent with persistent state, callable methods, and real-time sync to a React frontend. This is the simplest example showing the core patterns of Cloudflare Agents.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/cloudflare/agents/llms.txt
Use this file to discover all available pages before exploring further.
What it demonstrates
- Persistent State - Counter value survives restarts and hibernation
- Callable Methods - Type-safe RPC via the
@callable()decorator - Real-time Sync - State changes automatically sync to all connected clients
- React Integration -
useAgenthook for frontend integration
Server Implementation
server.ts
React Client
client.tsx
How it works
Define Agent State
The
CounterState type defines the shape of the agent’s persistent state. This state is stored in Durable Objects and syncs to all connected clients.Mark Methods as Callable
The
@callable() decorator exposes methods as RPC endpoints. Clients can call them like local functions via agent.stub.methodName().Update State
this.setState() updates the agent’s state and automatically broadcasts the change to all connected WebSocket clients.Key Concepts
State Persistence
Agent state is stored in Durable Objects and survives:- Worker restarts
- Hibernation (when no clients are connected)
- Redeployments
Real-time Broadcasting
WhensetState() is called:
- State is persisted to Durable Objects storage
- Update is broadcast to all connected WebSocket clients
- Each client’s
onStateUpdatecallback fires with the new state
Type Safety
TheuseAgent hook is fully typed:
Running the Example
Next Steps
AI Chat Example
Add AI chat with streaming and tool execution
Workflows Example
Build multi-step workflows with human approval
MCP Server
Expose your agent as an MCP server
API Reference
Full Agent class documentation