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
1
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.2
Mark Methods as Callable
The
@callable() decorator exposes methods as RPC endpoints. Clients can call them like local functions via agent.stub.methodName().3
Update State
this.setState() updates the agent’s state and automatically broadcasts the change to all connected WebSocket clients.4
Connect from React
The
useAgent hook establishes a WebSocket connection, receives state updates via onStateUpdate, and provides a type-safe stub for calling methods.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