Skip to content

Commit 7f9565b

Browse files
docs: Add MCPConnectionState enum and update MCP documentation
This documentation sync corresponds to PR #672 in cloudflare/agents: cloudflare/agents#672 Changes: - Document new MCPConnectionState enum for type-safe connection states - Update all code examples to use enum constants instead of string literals - Add migration guide for transitioning from string literals - Document improved error handling with fail-fast behavior - Create changelog entry for the release - Update OAuth flow documentation with enum usage The MCPConnectionState enum provides better type safety when working with MCP server connection states (AUTHENTICATING, CONNECTING, DISCOVERING, READY, FAILED). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
1 parent 6cff60b commit 7f9565b

File tree

3 files changed

+156
-17
lines changed

3 files changed

+156
-17
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
---
2+
title: MCPConnectionState enum for improved type safety
3+
description: MCP connection states are now defined using an enum for better type safety and reliability, with improved error handling and fail-fast behavior
4+
products:
5+
- agents
6+
- workers
7+
date: 2025-11-21
8+
---
9+
10+
The Agents SDK now exports an `MCPConnectionState` enum that provides better type safety and consistency when working with MCP server connection states.
11+
12+
### MCPConnectionState enum
13+
14+
Connection states are now available as enum constants instead of string literals:
15+
16+
```ts
17+
import { MCPConnectionState } from "agents";
18+
19+
// Check connection states using enum constants
20+
if (server.state === MCPConnectionState.READY) {
21+
console.log("Server is ready to use");
22+
}
23+
```
24+
25+
Available states:
26+
27+
- `MCPConnectionState.AUTHENTICATING` - Waiting for OAuth authorization to complete
28+
- `MCPConnectionState.CONNECTING` - Establishing transport connection to MCP server
29+
- `MCPConnectionState.DISCOVERING` - Discovering server capabilities (tools, resources, prompts)
30+
- `MCPConnectionState.READY` - Fully connected and ready to use
31+
- `MCPConnectionState.FAILED` - Connection failed at some point
32+
33+
### Migration from string literals
34+
35+
If you were using string literals to check connection states, update your code:
36+
37+
```ts title="Before"
38+
if (server.state === "ready") {
39+
// Do something
40+
}
41+
```
42+
43+
```ts title="After"
44+
import { MCPConnectionState } from "agents";
45+
46+
if (server.state === MCPConnectionState.READY) {
47+
// Do something
48+
}
49+
```
50+
51+
### Improved error handling
52+
53+
MCP client connections now use fail-fast behavior with `Promise.all` instead of `Promise.allSettled`, providing quicker feedback when server capability discovery fails. The SDK also now only attempts to register capabilities that the server advertises, improving reliability and reducing unnecessary errors.
54+
55+
### Updated connection flow
56+
57+
The connection state machine has been refined:
58+
59+
- **Non-OAuth servers**: `CONNECTING``DISCOVERING``READY`
60+
- **OAuth servers**: `AUTHENTICATING` → (callback) → `CONNECTING``DISCOVERING``READY`
61+
- **Errors**: Any state can transition to `FAILED` on error
62+
63+
### Additional improvements
64+
65+
- MCP server state broadcasts now occur before and after OAuth connection establishment, providing better real-time updates to connected clients
66+
- Connection state is set to `FAILED` before throwing errors during capability discovery, ensuring proper state management
67+
68+
For more information, refer to the [McpClient API reference](/agents/model-context-protocol/mcp-client-api/).

src/content/docs/agents/guides/oauth-mcp-client.mdx

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ Use the `useAgent` hook for automatic state updates:
140140

141141
```tsx title="src/App.tsx"
142142
import { useAgent } from "agents/react";
143-
import type { MCPServersState } from "agents";
143+
import { MCPConnectionState, type MCPServersState } from "agents";
144144

145145
function App() {
146146
const [mcpState, setMcpState] = useState<MCPServersState>({
@@ -164,7 +164,7 @@ function App() {
164164
{Object.entries(mcpState.servers).map(([id, server]) => (
165165
<div key={id}>
166166
<strong>{server.name}</strong>: {server.state}
167-
{server.state === "authenticating" && server.auth_url && (
167+
{server.state === MCPConnectionState.AUTHENTICATING && server.auth_url && (
168168
<button onClick={() => window.open(server.auth_url, "_blank")}>
169169
Authorize
170170
</button>
@@ -187,6 +187,8 @@ If you're not using React, poll the connection status:
187187
<TypeScriptExample>
188188

189189
```ts title="src/index.ts"
190+
import { MCPConnectionState } from "agents";
191+
190192
export class MyAgent extends Agent<Env, never> {
191193
async onRequest(request: Request): Promise<Response> {
192194
const url = new URL(request.url);
@@ -201,9 +203,9 @@ export class MyAgent extends Agent<Env, never> {
201203
([id, server]) => ({
202204
serverId: id,
203205
name: server.name,
204-
state: server.state, // "authenticating" | "connecting" | "ready" | "failed"
205-
isReady: server.state === "ready",
206-
needsAuth: server.state === "authenticating",
206+
state: server.state,
207+
isReady: server.state === MCPConnectionState.READY,
208+
needsAuth: server.state === MCPConnectionState.AUTHENTICATING,
207209
authUrl: server.auth_url,
208210
}),
209211
);
@@ -220,17 +222,17 @@ export class MyAgent extends Agent<Env, never> {
220222

221223
</TypeScriptExample>
222224

223-
Connection states: `authenticating` (needs OAuth) > `connecting` (completing setup) > `ready` (available for use)
225+
Connection states follow this progression: `AUTHENTICATING` (needs OAuth) `CONNECTING` (completing setup) `DISCOVERING` (fetching capabilities) → `READY` (available for use)
224226

225227
## Handle authentication failures
226228

227-
When OAuth fails, the connection `state` becomes `"failed"`. Detect this in your UI and allow users to retry or clean up:
229+
When OAuth fails, the connection `state` becomes `MCPConnectionState.FAILED`. Detect this in your UI and allow users to retry or clean up:
228230

229231
<TypeScriptExample>
230232

231233
```tsx title="src/App.tsx"
232234
import { useAgent } from "agents/react";
233-
import type { MCPServersState } from "agents";
235+
import { MCPConnectionState, type MCPServersState } from "agents";
234236

235237
function App() {
236238
const [mcpState, setMcpState] = useState<MCPServersState>({
@@ -270,7 +272,7 @@ function App() {
270272
<div key={id}>
271273
<strong>{server.name}</strong>: {server.state}
272274

273-
{server.state === "failed" && (
275+
{server.state === MCPConnectionState.FAILED && (
274276
<div>
275277
<p>Connection failed. Please try again.</p>
276278
<button onClick={() => handleRetry(id, server.server_url, server.name)}>

src/content/docs/agents/model-context-protocol/mcp-client-api.mdx

Lines changed: 77 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,55 @@ sidebar:
99

1010
import { Render, TypeScriptExample } from "~/components";
1111

12-
Your Agent can connect to external [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers to access tools, resources, and prompts. The `Agent` class provides three methods to manage MCP connections:
12+
Your Agent can connect to external [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers to access tools, resources, and prompts. The `Agent` class provides three methods to manage MCP connections.
13+
14+
## MCPConnectionState Enum
15+
16+
The `MCPConnectionState` enum defines the possible states of an MCP server connection:
17+
18+
```ts
19+
import { MCPConnectionState } from "agents";
20+
21+
MCPConnectionState.AUTHENTICATING // "authenticating" - Waiting for OAuth authorization
22+
MCPConnectionState.CONNECTING // "connecting" - Establishing transport connection
23+
MCPConnectionState.DISCOVERING // "discovering" - Discovering server capabilities
24+
MCPConnectionState.READY // "ready" - Fully connected and ready to use
25+
MCPConnectionState.FAILED // "failed" - Connection failed
26+
```
27+
28+
The connection state machine follows these transitions:
29+
30+
- **Non-OAuth flow**: `CONNECTING``DISCOVERING``READY`
31+
- **OAuth flow**: `AUTHENTICATING` → (callback) → `CONNECTING``DISCOVERING``READY`
32+
- **Error**: Any state can transition to `FAILED` on error
33+
34+
Use these constants instead of string literals when checking connection states.
35+
36+
### Migration from String Literals
37+
38+
If you were previously using string literals to check connection states, update your code to use the enum:
39+
40+
<TypeScriptExample>
41+
42+
```ts title="Before"
43+
// Old approach with string literals
44+
if (server.state === "ready") {
45+
console.log("Server is ready");
46+
}
47+
```
48+
49+
```ts title="After"
50+
// New approach with MCPConnectionState enum
51+
import { MCPConnectionState } from "agents";
52+
53+
if (server.state === MCPConnectionState.READY) {
54+
console.log("Server is ready");
55+
}
56+
```
57+
58+
</TypeScriptExample>
59+
60+
## Agent MCP Client Methods Example
1361

1462
<TypeScriptExample>
1563

@@ -183,19 +231,16 @@ None.
183231
An `MCPServersState` object containing:
184232

185233
```ts
234+
import { MCPConnectionState } from "agents";
235+
186236
{
187237
servers: Record<
188238
string,
189239
{
190240
name: string;
191241
server_url: string;
192242
auth_url: string | null;
193-
state:
194-
| "authenticating"
195-
| "connecting"
196-
| "ready"
197-
| "discovering"
198-
| "failed";
243+
state: MCPConnectionState;
199244
capabilities: ServerCapabilities | null;
200245
instructions: string | null;
201246
}
@@ -228,7 +273,31 @@ export class MyAgent extends Agent<Env, never> {
228273

229274
</TypeScriptExample>
230275

231-
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.
276+
Use this method to monitor connection status, list available tools, or build UI for connected servers. Check the connection state using the `MCPConnectionState` enum:
277+
278+
<TypeScriptExample>
279+
280+
```ts title="src/index.ts"
281+
import { MCPConnectionState } from "agents";
282+
283+
export class MyAgent extends Agent<Env, never> {
284+
async onRequest(request: Request): Promise<Response> {
285+
const mcpState = this.getMcpServers();
286+
287+
for (const [id, server] of Object.entries(mcpState.servers)) {
288+
if (server.state === MCPConnectionState.READY) {
289+
console.log(`Server ${id} is ready`);
290+
} else if (server.state === MCPConnectionState.AUTHENTICATING) {
291+
console.log(`Server ${id} needs authentication`);
292+
}
293+
}
294+
295+
return new Response("OK");
296+
}
297+
}
298+
```
299+
300+
</TypeScriptExample>
232301

233302
## OAuth Configuration
234303

0 commit comments

Comments
 (0)