McpAgent backed by a Durable Object. State persists across requests - the built-in UI lets you call tools and read resources to see it in action.
What it demonstrates
McpAgent- the Agents SDK class for building MCP servers with persistent state- Tools - registering an
addtool that modifies the counter - Resources - exposing the counter value as an MCP resource
- State management -
setStateandonStateChangedfor durable state - Streamable HTTP transport - the default transport for
McpAgent
Server Implementation
src/server.ts
How It Works
1
Extend McpAgent
McpAgent extends the base Agent class with MCP protocol support. Each instance is backed by a Durable Object.2
Define state
The
initialState property sets the default state. This state persists across hibernation and restarts.3
Register tools and resources
In the
init() method, register MCP tools and resources. Tools can read and modify state via this.state and this.setState().4
Serve the MCP
MyMCP.serve() creates a Worker handler that routes requests to the MCP agent.Testing with the Built-in UI
Run the example locally:- Call the
addtool with different numbers - Read the
counterresource to see the current value - Watch state persist across requests
Testing with MCP Inspector
You can also connect with the MCP Inspector:- Install the inspector:
npm install -g @modelcontextprotocol/inspector - Run your MCP server:
npm run dev - Open the inspector
- Set transport to Streamable HTTP
- Set URL to
http://localhost:5173/mcp
Key Features
Persistent State
State is stored in Durable Objects and survives:- Worker restarts
- Hibernation (when idle)
- Redeployments
Tools
MCP tools are functions that can be called by MCP clients:Resources
MCP resources are read-only data exposed to clients:Prompts
MCP prompts are reusable message templates:Advanced: Using SQLite
Deployment
Deploy to Cloudflare Workers:Related Examples
MCP Client
Connect to MCP servers as a client
MCP Worker
Simplest stateless MCP server
MCP Authenticated
Adding OAuth to an MCP server
MCP Guide
In-depth guide to Model Context Protocol