Agent MCP Client: Connection, Discovery, OAuth and Transport
How the Cloudflare Agents SDK registers MCP servers, discovers tools, handles OAuth and transports, and exposes tools to chat agents.
This page summarises Cloudflare Agents SDK documentation on the MCP client: connecting Workers-based agents to remote Model Context Protocol servers, restoring sessions after Durable Object hibernation, and feeding tool catalogs into chat and Think harnesses. If you are wiring external APIs into an agent or debugging missing tools after wake, start here.
MCP client in Agents: what it does
Section titled “MCP client in Agents: what it does”The MCP client manager lets an Agent persist server configuration, authenticate when required, negotiate protocol capabilities, discover tools, prompts, and resources, and invoke callTool, getPrompt, or readResource. Registrations survive restarts: the SDK stores configuration in SQLite, stores OAuth tokens securely, and restores connections when the Agent wakes.
MCP server registrations persist across Agent restarts. The SDK stores server configuration in SQLite, stores OAuth tokens securely, and restores connections when the Agent wakes.
— Cloudflare, MCP Client
Discovery is the step that tells the agent what it can call:
MCP discovery fetches the available tools, prompts, and resources from an MCP server so your agent knows what capabilities are available.
— Cloudflare, Agents SDK v0.2.24 with resumable streaming, MCP improvements, and schedule fixes
addMcpServer and registerServer: how to attach an MCP server
Section titled “addMcpServer and registerServer: how to attach an MCP server”For many agents, a single addMcpServer call is enough. Since optional OAuth support landed, servers without authentication need no callbackHost:
await this.addMcpServer("my-server", "https://mcp.example.com");addMcpServer() no longer eagerly creates an OAuth provider for every connection. For servers that do not require authentication, a simple call is all you need:
— Cloudflare, Agents SDK v0.6.0: RPC transport for MCP, optional OAuth, hardened schema conversion, and @cloudflare/ai-chat fixes
If the server returns 401, the SDK reports that OAuth is required and you must pass callbackHost in addMcpServer options.
For clearer lifecycle control, the MCPClientManager API separates registration from connection:
const { id } = await this.mcp.registerServer({ name: "my-server", url: "https://my-mcp-server.example.com",});
await this.mcp.connectToServer(id);await this.mcp.discoverIfConnected(id);HTTP registrations deduplicate on name and URL (URLs are normalised). The same name with a different URL creates a new connection. Optional id on addMcpServer yields readable tool keys (for example tool_github_create_pull_request) instead of opaque connection IDs.
MCPConnectionState: connection progress you can observe
Section titled “MCPConnectionState: connection progress you can observe”The SDK exposes a formal MCPConnectionState enum: idle, connecting, authenticating, connected, discovering, and ready. Subscribe to this.mcp.onServerStateChanged to react when state changes (for example to broadcast the server list to clients). MCP server list broadcasts are filtered to exclude connections where shouldSendProtocolMessages returned false.
Diagnostic channels mirror key moments for operations:
| Type | When |
|---|---|
mcp:client:preconnect |
Before connecting |
mcp:client:connect |
Connect attempt completes or fails |
mcp:client:authorize |
OAuth flow begins |
mcp:client:discover |
Capability discovery succeeds or fails |
See Diagnostics channels — MCP events.
MCP discovery: timeouts, errors, and cancellation
Section titled “MCP discovery: timeouts, errors, and cancellation”The dedicated discover() method on MCPClientConnection supports AbortController, a configurable timeout (default 15s), and fails fast: discovery failures throw instead of silently continuing. That behaviour matters when a chat turn runs before the catalog is complete—without discovery, getAITools() returns an incomplete set.
waitForMcpConnections: chat agents and missing tools after hibernation
Section titled “waitForMcpConnections: chat agents and missing tools after hibernation”AIChatAgent can wait for MCP connections to settle before onChatMessage, so this.mcp.getAITools() includes the full catalog—especially after Durable Object hibernation when connections restore in the background.
| Value | Behavior |
|---|---|
{ timeout: 10_000 } |
Wait up to 10 seconds (default) |
{ timeout: N } |
Wait up to N milliseconds |
true |
Wait until all connections are ready |
false |
Do not wait (pre-0.2.0 behaviour) |
AIChatAgent now waits for MCP server connections to settle before calling onChatMessage. This ensures this.mcp.getAITools() returns the full set of tools, especially after Durable Object hibernation when connections are being restored in the background.
— Cloudflare, Chat agents — waitForMcpConnections
For manual control, call this.mcp.waitForConnections() inside onChatMessage (MCP Client — waitForConnections()). @cloudflare/think supports the same waitForMcpConnections property (MCP tools in Think).
Transport selection, resumable SSE, and protocol negotiation
Section titled “Transport selection, resumable SSE, and protocol negotiation”The client picks a transport and improves reliability on long-lived streams:
Auto transport selection: Automatically determines the best transport method, falling back from streamable-http to SSE as needed
— Cloudflare, Agents SDK adds MCP Elicitation support, http-streamable support, task queues, email integration and more
In-flight tool calls over SSE can survive a dropped connection: clients reconnect with Last-Event-ID and replay missed events. Overlapping JSON-RPC requests are correlated correctly across HTTP and RPC transports.
On protocol version, the client manager uses @modelcontextprotocol/client and probes MCP 2026-07-28 with server/discover; legacy servers continue with the initialize handshake on the same connection—existing addMcpServer calls need no separate protocol-version flag (Agents SDK adds MCP Specification 2026-07-28 support, Migrate to MCP SDK v2). Stateless elicitation uses input_required through multi-round-trip requests (MRTR); OAuth callbacks validate issuer metadata through the v2 SDK, with discovery state and credentials persisting across redirects and hibernation.
OAuth, callback URLs, and confused-deputy protections
Section titled “OAuth, callback URLs, and confused-deputy protections”When OAuth is required, configure callbackHost in addMcpServer. Workers OAuth Provider helpers include consent and upstream sign-in flows for MCP confused-deputy protections, sliding refresh expiry via refreshTokenIdleTTL, and related utilities (Workers OAuth Provider changelog).
If you hide identity on connect (sendIdentityOnConnect is false), you must set callbackPath on addMcpServer. The default callback URL can leak the Durable Object instance name. Callback detection matches via the OAuth state parameter rather than a loose /callback substring, which enables custom callback paths (Agents SDK v0.4.0).
Think harness: includeMcpTools and schema reuse
Section titled “Think harness: includeMcpTools and schema reuse”By default, Think merges MCP tools into every model turn via getAITools(). The SDK now reuses converted input and output schemas while a connection keeps the same tool catalog, avoiding repeated JSON Schema→Zod conversion each turn (MCP and Code Mode updates).
Set includeMcpTools = false when tools are exposed through Code Mode or another path outside Think’s automatic set:
export class MyAgent extends Think { includeMcpTools = false; waitForMcpConnections = true;}This setting skips Think’s automatic getAITools() call. MCP registration, restoration, discovery, raw catalog access, direct calls, and Code Mode connectors continue to work.
— Cloudflare, Agents SDK reduces MCP schema conversion, adds exposure controls for MCP in Think and Code Mode SDK adds direct host APIs
Use listTools() when you only need the raw MCP catalog. Code Mode integration may require the MCP SDK and Zod peers (@cloudflare/codemode/mcp). activeTools in beforeTurn cannot skip schema conversion—use includeMcpTools instead (MCP tools — Think).
Security and server-side MCP SDK constraints
Section titled “Security and server-side MCP SDK constraints”Before connect, the client validates server URLs to reduce SSRF risk: private ranges, loopback, link-local, and cloud metadata endpoints are blocked (Agents SDK v0.7.0).
If you host MCP servers with MCP SDK 1.26.0+, stateless servers should use a new McpServer instance per request rather than a shared global instance; the SDK guards against connecting an instance already bound to a transport (Agents SDK v0.4.0 — MCP SDK upgrade).
Hosting MCP: publishing catalog changes
Section titled “Hosting MCP: publishing catalog changes”When your Worker acts as an MCP server, notify.toolsChanged(), notify.promptsChanged(), notify.resourcesChanged(), and notify.resourceUpdated(uri) publish the matching MCP list-change notifications to open subscriptions; calling a notifier with no subscriber is a no-op (MCP Server handler API).
Apps such as the ChatGPT App demo extend capability by exposing more MCP tools and resources.
Common mistakes
Section titled “Common mistakes”- Calling the model before discovery finishes without
waitForMcpConnectionsorwaitForConnections(). - Requiring
callbackHostfor public MCP endpoints that never return401(unnecessary OAuth provider setup in older patterns). - Using default OAuth callback paths when
sendIdentityOnConnectisfalse(instance name leakage). - Pointing agents at blocked URLs (internal/metadata hosts) and assuming the SDK will still connect.
- Sharing one global
McpServeracross stateless HTTP requests on the server side after MCP SDK 1.26.0. - Using
activeToolsto hide MCP tools in Think instead ofincludeMcpTools = false.
How to check this on your site
Section titled “How to check this on your site”-
Confirm your agent class sets
waitForMcpConnections(or you awaitthis.mcp.waitForConnections()) per Chat agents and MCP Client. -
Register a test server with
addMcpServerorregisterServer/connectToServer, then rundiscoverIfConnectedand verify tools appear before the first chat message (resumable streaming changelog). -
Watch
mcp:client:connectandmcp:client:discoveron Diagnostics channels during connect and discovery. -
For OAuth servers, exercise the flow with an explicit
callbackPathwhensendIdentityOnConnectis false (Agents SDK v0.4.0). -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match your SDK version or behaviour, email yimasynthetic@gmail.com with the page URL and the exact sentence you believe is wrong, and we will clarify or correct it.