Skip to main content
A stateful MCP server using 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 add tool that modifies the counter
  • Resources - exposing the counter value as an MCP resource
  • State management - setState and onStateChanged for 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:
Open http://localhost:5173 to see the built-in tool tester. You can:
  • Call the add tool with different numbers
  • Read the counter resource to see the current value
  • Watch state persist across requests

Testing with MCP Inspector

You can also connect with the MCP Inspector:
  1. Install the inspector: npm install -g @modelcontextprotocol/inspector
  2. Run your MCP server: npm run dev
  3. Open the inspector
  4. Set transport to Streamable HTTP
  5. 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:
Resources can dynamically read from agent state, SQLite, KV, or any other source.

Prompts

MCP prompts are reusable message templates:

Advanced: Using SQLite

Deployment

Deploy to Cloudflare Workers:
Your MCP server will be available at:
Clients can connect using the Streamable HTTP transport.

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

Further Reading