You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
docs: MCP connection state improvements and discovery lifecycle
Updates documentation for PR cloudflare/agents#672
## Changes
- Updated addMcpServer() return type to discriminated union
- Added MCPConnectionState enum documentation
- Documented new "connected" state in connection lifecycle
- Added connection state transition diagrams
- Documented new discovery behavior with timeout and cancellation
- Created comprehensive changelog with migration guide
## Breaking Changes
- MCPClientConnection.init() no longer auto-discovers capabilities
- addMcpServer() return type changed to discriminated union
- New "connected" state added to connection lifecycle
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
title: MCP connection state improvements and standardized tool discovery
3
+
description: The Agents SDK now includes a formalized MCPConnectionState enum, improved discovery lifecycle with timeouts and cancellation, and better error handling for MCP server connections.
4
+
products:
5
+
- agents
6
+
- workers
7
+
date: 2025-11-26
8
+
---
9
+
10
+
We have improved the MCP (Model Context Protocol) client connection lifecycle in the [Agents SDK](https://github.com/cloudflare/agents) with better state management, explicit discovery control, and enhanced reliability.
11
+
12
+
## New Features
13
+
14
+
### MCPConnectionState Enum
15
+
16
+
A new `MCPConnectionState` enum formalizes the connection lifecycle with six distinct states:
17
+
18
+
-`AUTHENTICATING` — Waiting for OAuth authorization
19
+
-`CONNECTING` — Establishing transport connection
20
+
-`CONNECTED` — Transport connected, ready for discovery
21
+
-`DISCOVERING` — Fetching server capabilities
22
+
-`READY` — Fully connected with all tools available
23
+
-`FAILED` — Connection or discovery error
24
+
25
+
```ts
26
+
import { MCPConnectionState } from"agents";
27
+
28
+
if (result.state===MCPConnectionState.READY) {
29
+
// Server is connected and tools are available
30
+
}
31
+
```
32
+
33
+
### Enhanced Discovery Control
34
+
35
+
Discovery is now a separate, explicit phase with full lifecycle management:
-**Cancellation support** — New discoveries automatically cancel previous in-flight requests
39
+
-**Better error handling** — Discovery failures throw errors immediately instead of continuing with empty tool arrays
40
+
-**New `discover()` method** — On `MCPClientConnection` for manual discovery control
41
+
-**New `discoverIfConnected()` method** — On `MCPClientManager` for simpler per-server discovery
42
+
43
+
### Improved `addMcpServer()` Return Type
44
+
45
+
The return type is now a discriminated union that makes OAuth vs. ready states explicit:
46
+
47
+
```ts
48
+
const result =awaitthis.addMcpServer("Weather", "https://weather.example.com/mcp");
49
+
50
+
if (result.state==="authenticating") {
51
+
// Redirect user to result.authUrl
52
+
} else {
53
+
// result.state === "ready", tools are available
54
+
}
55
+
```
56
+
57
+
### Better `createConnection()` Return Value
58
+
59
+
The `createConnection()` method now returns the connection object for immediate use, eliminating the need for separate lookup calls.
60
+
61
+
## Bug Fixes
62
+
63
+
-**Fixed discovery hanging on repeated requests** — New discoveries now cancel previous in-flight ones via AbortController
64
+
-**Fixed Durable Object crash-looping** — `restoreConnectionsFromStorage()` now starts connections in background to avoid blocking initialization and causing timeouts
65
+
-**Fixed OAuth callback race condition** — When `auth_url` exists in storage during restoration, state is set to `AUTHENTICATING` directly instead of calling `connectToServer()` which was overwriting the state
66
+
67
+
## Migration Guide
68
+
69
+
### Breaking Change: `MCPClientConnection.init()` No Longer Auto-Discovers
70
+
71
+
Previously, `init()` would automatically trigger discovery. Now connection and discovery are separate phases.
72
+
73
+
**For most use cases, no changes are needed** — `addMcpServer()` handles both connection and discovery automatically.
74
+
75
+
If you are using lower-level APIs like `MCPClientConnection` directly, you must now call `discover()` explicitly after connection:
A new `connected` state represents a connected transport with no tools loaded yet. This state occurs between `CONNECTING` and `DISCOVERING`, allowing you to distinguish between:
123
+
124
+
-**`connected`** — Transport is connected, but capabilities are not yet discovered
125
+
-**`ready`** — Transport is connected and all capabilities have been discovered
126
+
127
+
Update any code that checks connection states to account for this new intermediate state.
128
+
129
+
## Learn More
130
+
131
+
-[MCP Client API reference](/agents/model-context-protocol/mcp-client-api/)
132
+
-[Connect to MCP servers guide](/agents/guides/connect-mcp-client/)
133
+
-[OAuth handling for MCP clients](/agents/guides/oauth-mcp-client/)
@@ -50,7 +50,7 @@ Connections persist in the Agent's [SQL storage](/agents/api-reference/store-and
50
50
51
51
### `addMcpServer()`
52
52
53
-
Add a connection to an MCP server and make its tools available to your Agent.
53
+
Add a connection to an MCP server and make its tools available to your Agent. This method establishes the connection and automatically discovers server capabilities (tools, resources, prompts).
returnnewResponse(`Failed to connect: ${error.message}`, { status: 500 });
138
+
}
110
139
}
111
140
}
112
141
```
113
142
114
143
</TypeScriptExample>
115
144
116
-
If the MCP server requires OAuth authentication, `authUrl` will be returned for user authentication. Connections persist across requests and the Agent will automatically reconnect if the connection is lost.
145
+
If the MCP server requires OAuth authentication, the result will include `state: "authenticating"` with an `authUrl` for user authentication. Otherwise, the server transitions to `"ready"` state with all tools discovered and available. Connections persist across requests and the Agent will automatically reconnect if the connection is lost.
117
146
118
147
:::note[Default JSON Schema Validation]
119
148
@@ -193,8 +222,9 @@ An `MCPServersState` object containing:
The `state` field can be: `authenticating`, `connecting`, `ready`, `discovering`, or `failed`. Use this method to monitor connection status, list available tools, or build UI for connected servers.
261
+
The `state` field represents the connection lifecycle:
262
+
263
+
-**`authenticating`** — Waiting for OAuth authorization
264
+
-**`connecting`** — Establishing transport connection
265
+
-**`connected`** — Transport connected, but capabilities not yet discovered
266
+
-**`discovering`** — Discovering server capabilities (tools, resources, prompts)
267
+
-**`ready`** — Fully connected with all capabilities discovered
268
+
-**`failed`** — Connection or discovery failed
269
+
270
+
Use this method to monitor connection status, list available tools, or build UI for connected servers.
You can also provide a `customHandler` function for full control over the callback response. Refer to the [OAuth handling guide](/agents/guides/oauth-mcp-client) for details.
253
292
293
+
## Connection State Lifecycle
294
+
295
+
The Agents SDK exports an `MCPConnectionState` enum that defines the connection lifecycle states:
Any state can transition to `FAILED` if an error occurs.
328
+
329
+
### Key Changes in Connection Behavior
330
+
331
+
Previously, `init()` would automatically trigger discovery. Now:
332
+
333
+
1.**Connection and discovery are separate phases** — After a successful connection (state `CONNECTED`), you must explicitly call discovery
334
+
2.**`addMcpServer()` handles both automatically** — For most use cases, use `addMcpServer()` which connects and discovers in one call
335
+
3.**Discovery has a 15-second timeout** — If a server does not respond within 15 seconds, discovery fails and the connection returns to `CONNECTED` state
336
+
4.**Discovery can be cancelled** — Repeated discovery requests automatically cancel previous in-flight discoveries
337
+
254
338
## Error Handling
255
339
256
340
Use error detection utilities to handle connection errors:
0 commit comments