Skip to content

Commit a241181

Browse files
docs: Improve MCP connection state documentation with enum usage
Enhanced documentation to properly reference MCPConnectionState enum: - Import and use MCPConnectionState enum in all examples - Update return type signatures to use typeof MCPConnectionState - Add comprehensive state transition documentation - Include breaking change callouts with migration guidance - Document all connection states with detailed descriptions This provides clearer guidance for developers using the updated API from PR #672.
1 parent 0aab361 commit a241181

File tree

1 file changed

+75
-44
lines changed

1 file changed

+75
-44
lines changed

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

Lines changed: 75 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,35 @@ 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+
## Connection States
15+
16+
MCP connections progress through several states, represented by the `MCPConnectionState` enum:
17+
18+
```ts
19+
import { MCPConnectionState } from "agents";
20+
21+
// Available states:
22+
MCPConnectionState.AUTHENTICATING // Waiting for OAuth authorization
23+
MCPConnectionState.CONNECTING // Establishing transport connection
24+
MCPConnectionState.CONNECTED // Transport connected, capabilities not yet discovered
25+
MCPConnectionState.DISCOVERING // Discovering server capabilities
26+
MCPConnectionState.READY // Fully connected and ready to use
27+
MCPConnectionState.FAILED // Connection failed
28+
```
29+
30+
**State transitions:**
31+
- **Non-OAuth servers**: CONNECTING → CONNECTED → DISCOVERING → READY
32+
- **OAuth servers**: AUTHENTICATING → (callback) → CONNECTING → CONNECTED → DISCOVERING → READY
33+
- Any state can transition to FAILED on error
34+
35+
## Example Usage
1336

1437
<TypeScriptExample>
1538

1639
```ts title="src/index.ts"
17-
import { Agent, type AgentNamespace } from "agents";
40+
import { Agent, type AgentNamespace, MCPConnectionState } from "agents";
1841

1942
type Env = {
2043
MyAgent: AgentNamespace<MyAgent>;
@@ -31,15 +54,17 @@ export class MyAgent extends Agent<Env, never> {
3154
"https://weather-mcp.example.com/mcp",
3255
);
3356

34-
if (result.state === "authenticating") {
57+
if (result.state === MCPConnectionState.AUTHENTICATING) {
3558
return new Response(JSON.stringify({ authUrl: result.authUrl }), {
3659
headers: { "Content-Type": "application/json" },
3760
});
3861
}
3962

4063
return new Response(`Connected: ${result.id}`, { status: 200 });
4164
} catch (error) {
42-
return new Response(`Connection failed: ${error}`, { status: 500 });
65+
return new Response(`Connection failed: ${error.message}`, {
66+
status: 500,
67+
});
4368
}
4469
}
4570
}
@@ -50,27 +75,6 @@ export class MyAgent extends Agent<Env, never> {
5075

5176
Connections persist in the Agent's [SQL storage](/agents/api-reference/store-and-sync-state), and when an Agent connects to an MCP server, all tools from that server become available automatically.
5277

53-
## Connection States
54-
55-
When connecting to an MCP server, the connection progresses through different states represented by the `MCPConnectionState` enum:
56-
57-
- **`authenticating`** — Server requires OAuth; waiting for user authentication
58-
- **`connecting`** — Establishing connection to the server
59-
- **`connected`** — Transport connection established, awaiting initialization
60-
- **`discovering`** — Retrieving available tools, prompts, and resources
61-
- **`ready`** — Fully connected and all capabilities available
62-
- **`failed`** — Connection or discovery failed
63-
64-
### Typical Connection Flow
65-
66-
**For servers without OAuth:**
67-
`connecting``connected``discovering``ready`
68-
69-
**For servers with OAuth:**
70-
`authenticating` → (user completes OAuth) → `connecting``connected``discovering``ready`
71-
72-
If any step fails, the state transitions to `failed` and an error is thrown.
73-
7478
## Agent MCP Client Methods
7579

7680
### `addMcpServer()`
@@ -91,8 +95,8 @@ async addMcpServer(
9195
};
9296
}
9397
): Promise<
94-
| { id: string; state: "authenticating"; authUrl: string }
95-
| { id: string; state: "ready"; authUrl?: undefined }
98+
| { id: string; state: typeof MCPConnectionState.AUTHENTICATING; authUrl: string }
99+
| { id: string; state: typeof MCPConnectionState.READY; authUrl?: undefined }
96100
>
97101
```
98102

@@ -112,25 +116,30 @@ async addMcpServer(
112116

113117
A Promise that resolves to a discriminated union based on the connection state:
114118

115-
**When authentication is required:**
119+
**When OAuth authentication is required:**
116120
- **`id`** (string) — Unique identifier for this server connection
117-
- **`state`** (`"authenticating"`) — Indicates OAuth authentication is needed
118-
- **`authUrl`** (string) — OAuth authorization URL for user authentication
121+
- **`state`** `MCPConnectionState.AUTHENTICATING`
122+
- **`authUrl`** (string) — OAuth authorization URL where the user must authenticate
119123

120-
**When connection is ready:**
124+
**When connection is successful:**
121125
- **`id`** (string) — Unique identifier for this server connection
122-
- **`state`** (`"ready"`) — Indicates the server is fully connected and ready
123-
- **`authUrl`** (undefined) — No authentication URL when ready
126+
- **`state`** `MCPConnectionState.READY`
127+
- **`authUrl`** `undefined`
124128

125129
#### Throws
126130

127-
Throws an error if the connection or discovery process fails. Always wrap `addMcpServer()` calls in try-catch blocks to handle connection failures gracefully.
131+
- Throws an error if connection fails
132+
- Throws an error if capability discovery fails
133+
134+
The server stays in storage after errors, allowing retry via `connectToServer(id)`
128135

129136
#### Example
130137

131138
<TypeScriptExample>
132139

133140
```ts title="src/index.ts"
141+
import { MCPConnectionState } from "agents";
142+
134143
export class MyAgent extends Agent<Env, never> {
135144
async onRequest(request: Request): Promise<Response> {
136145
try {
@@ -139,28 +148,42 @@ export class MyAgent extends Agent<Env, never> {
139148
"https://weather-mcp.example.com/mcp",
140149
);
141150

142-
if (result.state === "authenticating") {
151+
if (result.state === MCPConnectionState.AUTHENTICATING) {
143152
// User needs to complete OAuth flow
144-
return new Response(JSON.stringify({ serverId: result.id, authUrl: result.authUrl }), {
145-
headers: { "Content-Type": "application/json" },
146-
});
153+
return new Response(
154+
JSON.stringify({ serverId: result.id, authUrl: result.authUrl }),
155+
{
156+
headers: { "Content-Type": "application/json" },
157+
},
158+
);
147159
}
148160

149-
return new Response(`Connected: ${result.id}`, { status: 200 });
161+
return new Response("Connected and ready", { status: 200 });
150162
} catch (error) {
151-
return new Response(`Connection failed: ${error}`, { status: 500 });
163+
return new Response(`Failed to connect: ${error.message}`, {
164+
status: 500,
165+
});
152166
}
153167
}
154168
}
155169
```
156170

157171
</TypeScriptExample>
158172

159-
If the MCP server requires OAuth authentication, the response will have `state: "authenticating"` with an `authUrl` for user authentication. Connections persist across requests and the Agent will automatically reconnect if the connection is lost.
173+
If the MCP server requires OAuth authentication, the result will include `authUrl` for user authentication. When connection and discovery succeed, the server is immediately in the `READY` state with all capabilities loaded.
160174

161-
:::note[Breaking Change: Error Handling Required]
175+
:::caution[Breaking Change]
162176

163-
As of the latest version, `addMcpServer()` now throws errors on connection or discovery failures instead of returning a failed state. Always wrap calls in try-catch blocks to handle errors gracefully. The return type is now a discriminated union based on the connection state.
177+
As of this version, `addMcpServer()` now throws errors on connection or discovery failures instead of silently continuing. The method also returns a discriminated union with a `state` field instead of a simple object with `authUrl`. Wrap calls in try-catch blocks to handle errors:
178+
179+
```ts
180+
try {
181+
const result = await this.addMcpServer(name, url);
182+
// Check result.state instead of result.authUrl
183+
} catch (error) {
184+
// Handle connection/discovery failures
185+
}
186+
```
164187

165188
:::
166189

@@ -278,7 +301,15 @@ export class MyAgent extends Agent<Env, never> {
278301

279302
</TypeScriptExample>
280303

281-
The `state` field can be: `authenticating`, `connecting`, `connected`, `ready`, `discovering`, or `failed`. Use this method to monitor connection status, list available tools, or build UI for connected servers.
304+
The `state` field follows the `MCPConnectionState` enum values:
305+
- `authenticating` — Waiting for OAuth authorization
306+
- `connecting` — Establishing transport connection
307+
- `connected` — Transport connected, capabilities not yet discovered
308+
- `discovering` — Discovering server capabilities (tools, resources, prompts)
309+
- `ready` — Fully connected with all capabilities loaded
310+
- `failed` — Connection failed
311+
312+
Use this method to monitor connection status, list available tools, or build UI for connected servers.
282313

283314
## OAuth Configuration
284315

0 commit comments

Comments
 (0)