agents 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
  8. package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
  9. package/dist/browser/ai.js +1 -1
  10. package/dist/browser/index.d.ts +7 -3
  11. package/dist/browser/index.js +2 -2
  12. package/dist/browser/tools/ai-sdk.d.ts +68 -3
  13. package/dist/browser/tools/pi.d.ts +2 -2
  14. package/dist/browser/tools/tanstack-ai.d.ts +2 -2
  15. package/dist/{browser-CI97khiJ.d.ts → browser-C9T74n4c.d.ts} +84 -5
  16. package/dist/{browser-tool-Cxtiwfua.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  17. package/dist/capability-DBAKc6UZ.js.map +1 -1
  18. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  19. package/dist/chat/index.d.ts +37 -6
  20. package/dist/chat/index.js +39 -3
  21. package/dist/chat/index.js.map +1 -1
  22. package/dist/chat-sdk/index.d.ts +3 -3
  23. package/dist/chat-sdk/index.js +1 -1
  24. package/dist/cli.js +64 -63
  25. package/dist/client-CkT8voRY.js +3740 -0
  26. package/dist/client-CkT8voRY.js.map +1 -0
  27. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  28. package/dist/client.d.ts +1 -1
  29. package/dist/{connector-Dl098To-.js → connector-Bphz6wIw.js} +16 -4
  30. package/dist/connector-Bphz6wIw.js.map +1 -0
  31. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  32. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  33. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  34. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  35. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  36. package/dist/experimental/channels/index.d.ts +2 -2
  37. package/dist/experimental/channels/web/index.d.ts +2 -2
  38. package/dist/experimental/channels/web/index.js +1 -1
  39. package/dist/experimental/webmcp.js +1 -1
  40. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  41. package/dist/harness/ai-sdk/index.d.ts +2 -2
  42. package/dist/harness/container/index.d.ts +2 -2
  43. package/dist/harness/container/index.js +1 -1
  44. package/dist/harness/container/index.js.map +1 -1
  45. package/dist/harness/opencode/index.d.ts +1 -1
  46. package/dist/harness/pi/index.d.ts +128 -12
  47. package/dist/harness/pi/index.js +128 -20
  48. package/dist/harness/pi/index.js.map +1 -1
  49. package/dist/harness/think/index.d.ts +2 -2
  50. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  51. package/dist/images-D4gtE06D.js.map +1 -0
  52. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  53. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  54. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  55. package/dist/index.d.ts +21 -21
  56. package/dist/index.js +2 -2
  57. package/dist/{input-schema-0uUu392-.js → input-schema-D6GilRXI.js} +2 -2
  58. package/dist/{input-schema-0uUu392-.js.map → input-schema-D6GilRXI.js.map} +1 -1
  59. package/dist/{input-schema-waggtYrH.js → input-schema-y8W5bOdM.js} +2 -2
  60. package/dist/{input-schema-waggtYrH.js.map → input-schema-y8W5bOdM.js.map} +1 -1
  61. package/dist/internal_context.d.ts +1 -1
  62. package/dist/lifecycle/index.d.ts +3 -3
  63. package/dist/lifecycle/index.js +1 -1
  64. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  65. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  66. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  67. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  68. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  69. package/dist/mcp/client/index.d.ts +42 -36
  70. package/dist/mcp/client/index.js +2 -2
  71. package/dist/mcp/client/x402.d.ts +8 -8
  72. package/dist/mcp/index.d.ts +17 -17
  73. package/dist/mcp/index.js +5 -5
  74. package/dist/mcp/index.js.map +1 -1
  75. package/dist/models/ai-sdk/index.d.ts +9 -5
  76. package/dist/models/ai-sdk/index.js +1 -1
  77. package/dist/models/opencode/index.d.ts +3 -3
  78. package/dist/models/opencode/index.js +2 -2
  79. package/dist/models/opencode/index.js.map +1 -1
  80. package/dist/models/pi-ai/index.d.ts +4 -4
  81. package/dist/models/pi-ai/index.js +53 -29
  82. package/dist/models/pi-ai/index.js.map +1 -1
  83. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  84. package/dist/queue/index.d.ts +1 -1
  85. package/dist/queue/index.js +1 -1
  86. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  87. package/dist/queue-B_wl6K0Z.js.map +1 -0
  88. package/dist/react.d.ts +2 -2
  89. package/dist/routing/index.d.ts +2 -2
  90. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  91. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  92. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  93. package/dist/schedules/index.d.ts +1 -1
  94. package/dist/schedules/index.js +1 -1
  95. package/dist/serializable.d.ts +1 -1
  96. package/dist/session-CRY0bGiI.js.map +1 -1
  97. package/dist/sessions/index.d.ts +1 -1
  98. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  99. package/dist/settings-D2F_qONv.js.map +1 -0
  100. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  101. package/dist/src-BO1FdLK1.js.map +1 -0
  102. package/dist/state/index.d.ts +1 -1
  103. package/dist/streams/index.d.ts +1 -1
  104. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  105. package/dist/sub-routing.d.ts +12 -12
  106. package/dist/tasks/index.d.ts +1 -1
  107. package/dist/tasks/index.js +1 -1
  108. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  109. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  110. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  111. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  112. package/dist/tool-CmAGY6Fo.js.map +1 -0
  113. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  114. package/dist/tool-Kxcj8_22.js.map +1 -0
  115. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  116. package/dist/voice/index.d.ts +2 -2
  117. package/dist/web/fetch/index.js +1 -1
  118. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  119. package/dist/web/fetch/tools/pi.d.ts +5 -0
  120. package/dist/web/fetch/tools/pi.js +25 -2
  121. package/dist/web/fetch/tools/pi.js.map +1 -1
  122. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  123. package/dist/web/search/index.js +1 -1
  124. package/dist/web/search/tools/ai-sdk.js +2 -2
  125. package/dist/web/search/tools/pi.d.ts +4 -0
  126. package/dist/web/search/tools/pi.js +23 -2
  127. package/dist/web/search/tools/pi.js.map +1 -1
  128. package/dist/web/search/tools/tanstack-ai.js +2 -2
  129. package/dist/websockets/index.d.ts +2 -2
  130. package/dist/websockets/index.js +1 -1
  131. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  132. package/dist/websockets-W4uhRg4-.js.map +1 -0
  133. package/dist/workflow-types.d.ts +1 -1
  134. package/dist/workflows.d.ts +1 -1
  135. package/docs/agent-class.md +30 -4
  136. package/docs/browse-the-web.md +14 -0
  137. package/docs/chat-agents.md +13 -10
  138. package/docs/client-tools-continuation.md +1 -1
  139. package/docs/codemode.md +1 -1
  140. package/docs/configuration.md +6 -3
  141. package/docs/cross-domain-authentication.md +1 -1
  142. package/docs/fetch-the-web.md +20 -0
  143. package/docs/harnesses/pi.md +211 -22
  144. package/docs/harnesses/think.md +1 -1
  145. package/docs/http-websockets.md +40 -32
  146. package/docs/human-in-the-loop.md +2 -2
  147. package/docs/lifecycle.md +56 -0
  148. package/docs/mcp-client.md +104 -7
  149. package/docs/models-pi-ai.md +24 -10
  150. package/docs/models.md +42 -17
  151. package/docs/resumable-streaming.md +1 -1
  152. package/docs/retries.md +3 -6
  153. package/docs/search-the-web.md +10 -0
  154. package/docs/voice.md +1 -1
  155. package/package.json +13 -12
  156. package/dist/ai-sdk-CpuRsjP5.d.ts +0 -72
  157. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  158. package/dist/client-DMWujQJ1.js +0 -2325
  159. package/dist/client-DMWujQJ1.js.map +0 -1
  160. package/dist/connector-Dl098To-.js.map +0 -1
  161. package/dist/images-CfuRCjwq.js.map +0 -1
  162. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  163. package/dist/queue-CcIjVYTE.js.map +0 -1
  164. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  165. package/dist/settings-Dk2il2Hf.js.map +0 -1
  166. package/dist/src-DoGNJ4Ud.js.map +0 -1
  167. package/dist/tool-CxKsvxjm.js.map +0 -1
  168. package/dist/tool-DkT_DJBm.js.map +0 -1
  169. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -43,6 +43,7 @@ Agents have several lifecycle hooks that are called at different points:
43
43
  | `onClose(connection, code, reason, wasClean)` | When a WebSocket connection closes |
44
44
  | `onError(connection, error)` | When a WebSocket error occurs |
45
45
  | `onError(error)` | When a server error occurs (overloaded) |
46
+ | `onFetchError(request, error)` | When an HTTP request or WebSocket upgrade fails |
46
47
 
47
48
  ### Lifecycle Flow
48
49
 
@@ -406,6 +407,8 @@ export class MyAgent extends Agent {
406
407
  }
407
408
  ```
408
409
 
410
+ `onError` observes errors. To choose what the client receives when a request or upgrade fails, override `onFetchError`. By default the client gets `500 Internal Server Error`, or for an upgrade a socket that closes with code `1011`, without the error's details. See [`this.onFetchError`](./agent-class.md#thisonfetcherror).
411
+
409
412
  ## Hibernation
410
413
 
411
414
  Agent WebSockets always use Cloudflare's Hibernation API. An idle Agent can leave memory while its WebSocket clients remain connected; there is no non-hibernating mode.
@@ -448,34 +451,38 @@ export class MyAgent extends Agent<Env, { counter: number }> {
448
451
 
449
452
  ## Common Patterns
450
453
 
451
- ### Authentication on Connect
454
+ ### Authentication
452
455
 
453
- Validate users when they connect:
456
+ Check the caller in your Worker, before `routeAgentRequest()` forwards the upgrade. A client you reject there never reaches the agent, and the agent does not wake up for it.
454
457
 
455
458
  ```typescript
456
- export class SecureAgent extends Agent {
457
- async onConnect(connection: Connection, ctx: ConnectionContext) {
458
- const url = new URL(ctx.request.url);
459
- const token = url.searchParams.get("token");
460
-
461
- if (!token || !(await this.validateToken(token))) {
462
- connection.close(4001, "Unauthorized");
463
- return;
464
- }
465
-
466
- const user = await this.getUserFromToken(token);
467
- connection.setState({ userId: user.id, role: user.role });
468
-
469
- connection.send(JSON.stringify({ type: "authenticated", user }));
470
- }
471
-
472
- private async validateToken(token: string): Promise<boolean> {
473
- // Validate JWT, check database, etc.
474
- return true;
459
+ import { routeAgentRequest } from "agents";
460
+
461
+ export default {
462
+ async fetch(request: Request, env: Env) {
463
+ return (
464
+ (await routeAgentRequest(request, env, {
465
+ onBeforeConnect: async (req) => {
466
+ const token = new URL(req.url).searchParams.get("token");
467
+ const user = token ? await verifyToken(token, env) : null;
468
+ if (!user) {
469
+ return new Response("Unauthorized", { status: 401 });
470
+ }
471
+ // `set` replaces any value the client sent.
472
+ const forwarded = new Request(req);
473
+ forwarded.headers.set("x-user-id", user.id);
474
+ return forwarded;
475
+ }
476
+ })) ?? new Response("Not found", { status: 404 })
477
+ );
475
478
  }
476
- }
479
+ };
477
480
  ```
478
481
 
482
+ In `onConnect`, read the checked identity from `ctx.request.headers.get("x-user-id")` and keep it with `connection.setState()`.
483
+
484
+ You can also reject a connection from `onConnect` by calling `connection.close()`. The agent runs no message, callable, or state update the client sends after that close. That includes frames the client sends as soon as it connects, before it has received the Close frame. Prefer the Worker check anyway: `onConnect` runs inside the agent, so every rejected client still wakes it.
485
+
479
486
  ### Chat Room with Broadcast
480
487
 
481
488
  ```typescript
@@ -616,16 +623,17 @@ export class PresenceAgent extends Agent {
616
623
 
617
624
  ### Agent Lifecycle Methods
618
625
 
619
- | Method | Signature | Description |
620
- | ---------------------------- | --------------------------------------------------------------- | ------------------------------------------------------ |
621
- | `onStart` | `(props?) => void \| Promise<void>` | Called once when agent starts |
622
- | `onRequest` | `(request: Request) => Response \| Promise<Response>` | Handle HTTP requests |
623
- | `onConnect` | `(connection, ctx) => void \| Promise<void>` | WebSocket connected |
624
- | `onMessage` | `(connection, message) => void \| Promise<void>` | Message received |
625
- | `onClose` | `(connection, code, reason, wasClean) => void \| Promise<void>` | Connection closed |
626
- | `onError` | `(connection, error) => void \| Promise<void>` | WebSocket error |
627
- | `onError` | `(error) => void \| Promise<void>` | Server error (overload) |
628
- | `shouldSendProtocolMessages` | `(connection, ctx) => boolean` | Control per-connection protocol frames (default: true) |
626
+ | Method | Signature | Description |
627
+ | ---------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------ |
628
+ | `onStart` | `(props?) => void \| Promise<void>` | Called once when agent starts |
629
+ | `onRequest` | `(request: Request) => Response \| Promise<Response>` | Handle HTTP requests |
630
+ | `onConnect` | `(connection, ctx) => void \| Promise<void>` | WebSocket connected |
631
+ | `onMessage` | `(connection, message) => void \| Promise<void>` | Message received |
632
+ | `onClose` | `(connection, code, reason, wasClean) => void \| Promise<void>` | Connection closed |
633
+ | `onError` | `(connection, error) => void \| Promise<void>` | WebSocket error |
634
+ | `onError` | `(error) => void \| Promise<void>` | Server error (overload) |
635
+ | `onFetchError` | `(request, error) => Response \| void \| Promise<Response \| void>` | Choose the response for a failed request or upgrade |
636
+ | `shouldSendProtocolMessages` | `(connection, ctx) => boolean` | Control per-connection protocol frames (default: true) |
629
637
 
630
638
  ### Connection Management Methods
631
639
 
@@ -203,7 +203,7 @@ export class MyAgent extends AIChatAgent {
203
203
  const workersai = createWorkersAI({ binding: this.env.AI });
204
204
 
205
205
  const result = streamText({
206
- model: workersai("@cf/moonshotai/kimi-k2.7-code"),
206
+ model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
207
207
  messages: await convertToModelMessages(this.messages),
208
208
  tools: {
209
209
  // Tool with conditional approval
@@ -376,7 +376,7 @@ export class MyAgent extends AIChatAgent {
376
376
  const workersai = createWorkersAI({ binding: this.env.AI });
377
377
 
378
378
  const result = streamText({
379
- model: workersai("@cf/moonshotai/kimi-k2.7-code"),
379
+ model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
380
380
  messages: await convertToModelMessages(this.messages),
381
381
  tools: {
382
382
  // No execute function - client handles via onToolCall
package/docs/lifecycle.md CHANGED
@@ -93,6 +93,57 @@ A warm object skips startup but still offers every request to its middleware.
93
93
  There is no `next()` today: a capability either handles a request or declines
94
94
  it, and cannot wrap or observe a downstream response.
95
95
 
96
+ ## Failed requests
97
+
98
+ When startup, a capability's request or upgrade hook, or `onRequest` throws,
99
+ the lifecycle logs the error with `console.error` and sends a response that
100
+ does not include it:
101
+
102
+ - an HTTP request gets `500 Internal Server Error`;
103
+ - a WebSocket upgrade gets a socket that closes at once with code `1011`.
104
+
105
+ An error's message and stack can reveal internals, such as secret names or
106
+ file paths, to callers who are not authenticated. To send something else,
107
+ implement `onFetchError`. It runs after the error is logged, with the request
108
+ and the thrown value:
109
+
110
+ ```ts
111
+ export class MyObject extends DurableObject<Env> {
112
+ readonly lifecycle = Lifecycle.install(this);
113
+
114
+ onFetchError(request: Request, error: unknown): Response | undefined {
115
+ // Show details only in local development.
116
+ if (this.env.ENVIRONMENT !== "development") return;
117
+ const detail = error instanceof Error ? error.stack : String(error);
118
+ return new Response(detail, { status: 500 });
119
+ }
120
+ }
121
+ ```
122
+
123
+ Return nothing to send the default response. If `onFetchError` throws, the
124
+ lifecycle logs that error and also sends the default. In both cases, if the
125
+ original thrown value is not an `Error`, the lifecycle rethrows it to the
126
+ runtime instead. `error` is whatever was thrown, so narrow it before you read
127
+ it. `request` may already have had its body read.
128
+
129
+ For a WebSocket upgrade, return either an HTTP error response or a `101`
130
+ response with your own socket:
131
+
132
+ ```ts
133
+ onFetchError(request: Request, error: unknown): Response | undefined {
134
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return;
135
+ const pair = new WebSocketPair();
136
+ pair[1].accept();
137
+ pair[1].send(JSON.stringify({ error: "unavailable" }));
138
+ pair[1].close(1011, "Startup failed");
139
+ return new Response(null, { status: 101, webSocket: pair[0] });
140
+ }
141
+ ```
142
+
143
+ `onFetchError` runs in the object's context, so `getCurrentAgent()` returns
144
+ the object and the request. After a failed startup, `onStart` has not
145
+ finished, so do not rely on state it sets up.
146
+
96
147
  ## Reusable capabilities
97
148
 
98
149
  A capability implements only the phases it needs:
@@ -466,6 +517,11 @@ Handlers are wire-agnostic. Both kinds of connection dispatch the same
466
517
  `onConnect`/`onMessage`/`onClose`/`onError`, appear in `getConnections()`,
467
518
  and honour `connection.close(code, reason)`.
468
519
 
520
+ Once the host closes a connection, neither wire runs another message or
521
+ callable from it. This holds for frames the client sent before it received
522
+ the Close frame, so a client that `onConnect` rejects cannot run anything.
523
+ Messages the client sent before closing the connection itself still run.
524
+
469
525
  ## Native RPC
470
526
 
471
527
  Native Durable Object RPC does not pass through `fetch`. An RPC method that
@@ -36,8 +36,9 @@ export class MyObject extends DurableObject<Env> {
36
36
 
37
37
  The lifecycle calls the manager automatically:
38
38
 
39
- - `onStart()` initializes its schema and restores persisted connections before
40
- the host handles work.
39
+ - `onStart()` initializes its schema and starts restoring persisted HTTP and
40
+ RPC connections in the background, so startup never waits on an MCP server.
41
+ Use `waitForConnections()` when you need restored tools.
41
42
  - `onRequest()` intercepts registered OAuth callback URLs before the host's
42
43
  request handler.
43
44
 
@@ -145,6 +146,8 @@ await this.addMcpServer("internal", "https://internal-mcp.example.com/mcp", {
145
146
  });
146
147
  ```
147
148
 
149
+ The headers are sent with every request, including the SSE stream, and are stored with the server so a restored connection sends them too. They are stored as plain text in the Durable Object's SQLite storage. `registerServer()` on a standalone `MCPClientManager` takes the same `transport.headers`.
150
+
148
151
  ### Legacy OAuth metadata compatibility
149
152
 
150
153
  SDK v2 validates authorization-server metadata issuers by default. A trusted Legacy server with known mismatched RFC 8414 metadata can opt out explicitly:
@@ -161,7 +164,7 @@ This weakens OAuth mix-up protection. Do not enable it for unknown servers or as
161
164
 
162
165
  ### Retry Options
163
166
 
164
- Configure retry behavior for connection and reconnection attempts:
167
+ Configure how many quick attempts a connection makes before it counts as failed:
165
168
 
166
169
  ```typescript
167
170
  await this.addMcpServer("github", "https://mcp.github.com/mcp", {
@@ -173,7 +176,44 @@ await this.addMcpServer("github", "https://mcp.github.com/mcp", {
173
176
  });
174
177
  ```
175
178
 
176
- These options are persisted and used when reconnecting after hibernation or after OAuth completion. Default: 3 attempts, 500ms base delay, 5s max delay. See [Retries](./retries.md) for more details.
179
+ These options are persisted and used for every connection attempt: when the server is added, when it is restored after hibernation, after OAuth completes, and on `reconnectMcpServer()`. Default: 3 attempts, 500ms base delay, 5s max delay. See [Retries](./retries.md) for more details.
180
+
181
+ ### Failures and reconnecting
182
+
183
+ Each connection makes a few quick attempts with the [retry options](#retry-options). If they all fail (the server is down, times out, or returns an error), the server is `failed` with the error, and the failure is recorded with the server. Nothing retries it on a timer, and later wakes show the same `failed` state without contacting the server. The server stays failed until something asks to connect it again.
184
+
185
+ When a wake finds a server that was not failed, the agent connects it again in the background with the same quick attempts. If the server is unreachable at that moment, it is `failed` from then on.
186
+
187
+ Retrying cannot help when authorization was refused, so these failures skip the quick attempts too:
188
+
189
+ - The server answered `401` and the agent cannot ask the user, for example a revoked static token passed in `transport.headers`, or no OAuth callback configured. When it can ask, the server moves to `authenticating` with a new link instead.
190
+ - The server answered `403`. A `403` with `error="insufficient_scope"` still starts a [step-up](#re-authorization-during-a-session) first; it only counts as refused when no step-up is possible.
191
+ - The authorization server refused with an OAuth error such as `invalid_target`, `invalid_scope` or `access_denied`. An expired or revoked refresh token (`invalid_grant`) starts a new authorization instead. `server_error` and `temporarily_unavailable` count as an outage.
192
+ - The authorization server rejected dynamic client registration with a `4xx` other than `429`.
193
+ - The server still answers `401` right after the user completed an authorization, for example because it rejects tokens from its own authorization server. The link that was just used is never shown again.
194
+
195
+ The server is marked `failed` with `Authorization was refused: …`. A callback where the user denied access, or whose code could not be exchanged, is recorded the same way, so a later wake does not start another flow the user just turned down.
196
+
197
+ #### Reconnecting on request
198
+
199
+ To try a failed server again, for example from a "Reconnect" button, call `reconnectMcpServer(id)`. It forgets why the server failed and its pending link, then connects now. It returns the same result as `addMcpServer()`, including a fresh `authUrl` when the user needs to authorize again.
200
+
201
+ ```typescript
202
+ import { Agent, callable } from "agents";
203
+
204
+ class MyAgent extends Agent<Env> {
205
+ @callable()
206
+ async reconnectServer(id: string) {
207
+ return this.reconnectMcpServer(id);
208
+ }
209
+ }
210
+ ```
211
+
212
+ Calling `addMcpServer()` for a server that is already registered does not retry a failure:
213
+
214
+ - `ready`: returned as is.
215
+ - `authenticating`: returns the link the server is waiting on.
216
+ - `failed`: throws the recorded error, which names `reconnectMcpServer()`.
177
217
 
178
218
  ### Protocol negotiation and elicitation
179
219
 
@@ -243,7 +283,17 @@ type AddMcpServerResult =
243
283
  ```
244
284
 
245
285
  - **`ready`** - Server connected and tools discovered
246
- - **`authenticating`** - Server requires OAuth; redirect user to `authUrl`
286
+ - **`authenticating`** - Server requires OAuth; redirect user to `authUrl`. This includes servers that accept the MCP handshake without a token but require one to list tools, prompts or resources.
287
+
288
+ Calling `addMcpServer()` again for a server that is already registered returns its current state, replaces a link that expired, and throws for a failed server (see [Reconnecting on request](#reconnecting-on-request)). If the server is still connecting (for example while it is restored after the agent wakes), the call waits for that attempt and returns its result. Pass a stable `id` so the server keeps the same id everywhere.
289
+
290
+ ### Best practices
291
+
292
+ - Add servers with a stable `id`, from a callable the user triggers or from `onStart`.
293
+ - Render each server from `getMcpServers()` (`onMcpUpdate` in `useAgent`): send the user to `auth_url` while it is `authenticating`, and show `error` with a **Reconnect** button that calls `reconnectMcpServer(id)` while it is `failed`.
294
+ - Catch [`MCPAuthorizationRequiredError`](#re-authorization-during-a-session) from `callTool()`, `readResource()` and `getPrompt()`, and give the user `error.authUrl`.
295
+ - Call [`waitForConnections()`](#waiting-for-connections) before relying on restored tools. `AIChatAgent` waits up to 10 seconds by default; in Think, set `waitForMcpConnections`.
296
+ - Close the OAuth popup with [`configureOAuthCallback()`](#oauth-authentication).
247
297
 
248
298
  ## OAuth Authentication
249
299
 
@@ -300,6 +350,35 @@ For example: `https://my-worker.workers.dev/agents/my-agent/default/callback`
300
350
 
301
351
  OAuth tokens are securely stored in SQLite and persist across agent restarts.
302
352
 
353
+ A server waiting for authorization keeps its link, across wakes too, until the user completes it or you call `reconnectMcpServer(id)`. Whether an old link still works is up to the authorization server and the OAuth provider (the default provider accepts a callback for 10 minutes). If the user completes a link that no longer works, the callback reports the error and the server keeps waiting; call `reconnectMcpServer(id)` to get a fresh link. If a callback already redeemed the link and the agent restarted before it finished, the agent reconnects with the saved tokens instead.
354
+
355
+ ### Re-authorization during a session
356
+
357
+ A request can need authorization again after the server is `ready`: a tool call that needs a scope the grant lacks (`403 insufficient_scope`), or a `401` whose token refresh fails. `callTool()`, `readResource()` and `getPrompt()` then throw `MCPAuthorizationRequiredError`. The server moves to `authenticating` and its `auth_url` is saved, so clients see the new link through `getMcpServers()` like at connect time. Send the user to `error.authUrl`; the normal OAuth callback completes the flow and reconnects. Retry the request when the server is `ready` again. Tools from `getAITools()` call `callTool()`, so their `execute` throws the same error. If no usable link was produced (for example, a custom OAuth provider that does not put a fresh `state` in each authorization URL, or a callback for this server is already being processed), the call throws the SDK's plain `UnauthorizedError` as before. `MCPAuthorizationRequiredError` extends `UnauthorizedError`, so existing `instanceof UnauthorizedError` checks keep matching.
358
+
359
+ During a scope step-up the session keeps its current grant, so requests it already covers keep working while the user decides. If the user declines, the server goes back to `ready` on that grant, and the next request that needs the scope asks again.
360
+
361
+ When the token refresh was refused, no grant is left to keep working on. The server then waits for the sign-in as it does at connect time: every request throws `MCPAuthorizationRequiredError` with the same link, and if the user declines, the server is marked `failed`.
362
+
363
+ A request to a server that is waiting for its first authorization throws `MCPAuthorizationRequiredError` with the link it is waiting on.
364
+
365
+ Calls for a `serverId` with no connection (never registered, removed, or still being restored) throw `MCPConnectionNotFoundError`.
366
+
367
+ Re-authorization is limited, as the MCP authorization spec asks. If the user completes three authorizations for the same scopes within an hour and the server still asks for them (for example because the authorization server never grants a scope), the next challenge does not produce a link. The server moves to `failed` with an error naming the scopes, the request throws the SDK's `UnauthorizedError`, and the server stays failed until you call `reconnectMcpServer(id)`.
368
+
369
+ ```typescript
370
+ import { MCPAuthorizationRequiredError } from "agents/mcp/client";
371
+
372
+ try {
373
+ return await this.mcp.callTool({ serverId, name: "deploy", arguments: {} });
374
+ } catch (error) {
375
+ if (error instanceof MCPAuthorizationRequiredError) {
376
+ return { needsAuthorization: true, authUrl: error.authUrl };
377
+ }
378
+ throw error;
379
+ }
380
+ ```
381
+
303
382
  ### Custom Callback Handling
304
383
 
305
384
  For custom OAuth completion behavior:
@@ -501,6 +580,7 @@ function Dashboard() {
501
580
  const [tools, setTools] = useState([]);
502
581
  const [servers, setServers] = useState({});
503
582
 
583
+ // reconnectServer is a @callable() that calls this.reconnectMcpServer(id)
504
584
  const agent = useAgent({
505
585
  agent: "MyAgent",
506
586
  onMcpUpdate: (mcpState) => {
@@ -514,7 +594,20 @@ function Dashboard() {
514
594
  <h2>Connected Servers</h2>
515
595
  {Object.entries(servers).map(([id, server]) => (
516
596
  <div key={id}>
517
- {server.name}: {server.connectionState}
597
+ {server.name}: {server.state}
598
+ {server.state === "authenticating" && server.auth_url && (
599
+ <a href={server.auth_url} target="_blank">
600
+ Authorize
601
+ </a>
602
+ )}
603
+ {server.state === "failed" && (
604
+ <>
605
+ {server.error}
606
+ <button onClick={() => agent.call("reconnectServer", [id])}>
607
+ Reconnect
608
+ </button>
609
+ </>
610
+ )}
518
611
  </div>
519
612
  ))}
520
613
 
@@ -566,6 +659,8 @@ if (connectResult.state === "connected") {
566
659
  }
567
660
  ```
568
661
 
662
+ Connection work for one server runs one operation at a time: `connectToServer()`, `discoverIfConnected()`, `establishConnection()`, OAuth callback handling and restore for the same server wait for each other instead of interleaving. Work for different servers runs in parallel.
663
+
569
664
  ### Event Subscription
570
665
 
571
666
  ```typescript
@@ -581,7 +676,7 @@ const disposable = this.mcp.onServerStateChanged(() => {
581
676
 
582
677
  ### Waiting for Connections
583
678
 
584
- After hibernation or when connections are being restored in the background, MCP tools may not be immediately available. Use `waitForConnections()` to wait until all in-flight connection and discovery operations have settled:
679
+ After hibernation or when connections are being restored in the background, MCP tools may not be immediately available. This applies to HTTP and RPC servers alike. Use `waitForConnections()` to wait until all in-flight connection and discovery operations have settled:
585
680
 
586
681
  ```typescript
587
682
  // Wait indefinitely for all connections to be ready
@@ -597,6 +692,8 @@ This is useful when you need to call `this.mcp.getAITools()` immediately after t
597
692
 
598
693
  ### Error Recovery
599
694
 
695
+ On an `Agent`, retry a failed server with [`reconnectMcpServer(id)`](#reconnecting-on-request). On a standalone manager, `connectToServer()` is the explicit retry: it clears a recorded failure and the step-up budget before connecting.
696
+
600
697
  ```typescript
601
698
  async retryConnection(serverId: string) {
602
699
  const result = await this.mcp.connectToServer(serverId);
@@ -21,7 +21,7 @@ import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
21
21
 
22
22
  const ai = createAI({ binding: env.AI, id: "prod", cacheTtl: 60 });
23
23
 
24
- ai("@cf/zai-org/glm-5.3-flash"); // Workers AI: our catalog, our compat layer
24
+ ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"); // Workers AI: our catalog, our compat layer
25
25
  ai(getBuiltinModel("anthropic", "claude-opus-4-8")); // their model, our transport
26
26
  ```
27
27
 
@@ -65,9 +65,12 @@ import { createAI } from "agents/models/pi-ai";
65
65
  export default {
66
66
  async fetch(_request: Request, env: { AI: Ai }) {
67
67
  const ai = createAI({ binding: env.AI });
68
- const reply = await ai.complete(ai("@cf/zai-org/glm-5.3-flash"), {
69
- messages: [{ role: "user", content: "Hello", timestamp: Date.now() }]
70
- });
68
+ const reply = await ai.complete(
69
+ ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
70
+ {
71
+ messages: [{ role: "user", content: "Hello", timestamp: Date.now() }]
72
+ }
73
+ );
71
74
  // `content` is an array of parts — text, thinking, tool calls.
72
75
  const text = reply.content
73
76
  .filter((part) => part.type === "text")
@@ -102,7 +105,7 @@ Workers AI and catalog models go to AI Gateway's
102
105
 
103
106
  ```ts
104
107
  // 1. Workers AI — ours.
105
- ai("@cf/zai-org/glm-5.3-flash");
108
+ ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017");
106
109
 
107
110
  // 2. pi-ai's Cloudflare AI Gateway catalog — a string, resolved by pi, not us.
108
111
  ai("anthropic/claude-opus-4.8");
@@ -180,7 +183,7 @@ import { createModels } from "@earendil-works/pi-ai/models";
180
183
  const models = createModels();
181
184
  models.setProvider(ai.provider); // provider id: "cloudflare"
182
185
  models.getModel("cloudflare", "anthropic/claude-opus-4.8");
183
- models.streamSimple(ai("@cf/zai-org/glm-5.3-flash"), context);
186
+ models.streamSimple(ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"), context);
184
187
  ```
185
188
 
186
189
  The provider's static list is every Workers AI id pi-ai knows plus every `<provider>/<id>` in
@@ -205,7 +208,7 @@ ai("anthropic/claude-opus-4.8", {
205
208
  requestTimeoutMs: 30_000,
206
209
  retries: { maxAttempts: 3, backoff: "exponential", retryDelayMs: 500 },
207
210
  byokAlias: "team-a", // which stored BYOK key, by alias
208
- fallback: ["@cf/zai-org/glm-5.3-flash"], // ids or models, in any mix
211
+ fallback: ["@cf/deepseek-ai/deepseek-v4.1-flash-1017"], // ids or models, in any mix
209
212
  headers: { "x-request-source": "docs" },
210
213
  sessionAffinity: "chat-42", // Workers AI prefix-cache routing
211
214
  reasoningEffort: "low", // "low" | "medium" | "high" | null
@@ -234,6 +237,12 @@ thinking level) is remapped through the model's own `thinkingLevelMap` — as fa
234
237
  can carry it; see [thinking shapes](#thinking-shapes) for the one limit. Precedence is call,
235
238
  then model, then `createAI` settings.
236
239
 
240
+ With a `sessionId`, an Anthropic model whose `baseUrl` is `api.anthropic.com` uses pi-ai's message
241
+ threads, and AI Gateway forwards the `thread` field, so later requests send only the new messages.
242
+ A thread expires after a few minutes idle; when Anthropic can no longer continue one, pi-ai sends
243
+ the whole conversation again as a new thread. To send the whole conversation every time, set `disableContinuation: true` on the call or
244
+ `compat.supportsMessageThreads: false` on the model.
245
+
237
246
  ## How a request travels
238
247
 
239
248
  | Model | `api` | Through the binding | With an account id and token |
@@ -335,7 +344,7 @@ and are not resumed. The run id is on the `cloudflare` diagnostic as `runId`.
335
344
  ## Fallback
336
345
 
337
346
  ```ts
338
- ai(claude, { fallback: ["@cf/zai-org/glm-5.3-flash"] });
347
+ ai(claude, { fallback: ["@cf/deepseek-ai/deepseek-v4.1-flash-1017"] });
339
348
  ```
340
349
 
341
350
  Legs may be Workers AI ids or models, in any mix. They are tried in order: a leg is abandoned
@@ -365,11 +374,16 @@ Image generation is Workers AI only. The knobs a model takes are the model's:
365
374
  `flux-1-schnell` takes a prompt and `steps` and nothing else, so `width`,
366
375
  `height`, `seed`, `guidance` and `negativePrompt` are dropped for it and listed
367
376
  in a `cloudflare-compat` diagnostic on the result rather than sent and ignored.
368
- Every other model in the catalog takes the full set.
377
+ The FLUX.2 models (`@cf/black-forest-labs/flux-2-klein-9b`, `flux-2-klein-4b`
378
+ and `flux-2-dev`) take `width`, `height`, `seed` and `guidance`, `steps` on
379
+ `flux-2-dev` only, and up to four image input parts as reference images. They
380
+ take multipart form data, which goes straight to Workers AI, so the gateway
381
+ options do not apply to them. Every other model in the catalog takes the full
382
+ set.
369
383
 
370
384
  ## Requirements
371
385
 
372
- This subpath needs `@earendil-works/pi-ai@~1.5.0`, an optional peer of `agents`. `agents`
386
+ This subpath needs `@earendil-works/pi-ai@~1.6.0`, an optional peer of `agents`. `agents`
373
387
  takes no vendor package as a dependency, optional or otherwise. An unlisted `@cf/` id resolves with default metadata (a
374
388
  128k context window, 8192 output tokens, zero cost); pass overrides when you know better.
375
389
 
package/docs/models.md CHANGED
@@ -6,7 +6,7 @@ forms, through the `AI` binding or
6
6
 
7
7
  ```ts
8
8
  // A string runs on env.AI.run.
9
- ai("@cf/zai-org/glm-4.7-flash"); // Workers AI
9
+ ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"); // Workers AI
10
10
  ai("anthropic/claude-opus-4.8"); // the AI Gateway catalog
11
11
  ai("dynamic/support"); // a dynamic route on your gateway
12
12
 
@@ -59,7 +59,7 @@ export default {
59
59
  const ai = createAI({ binding: env.AI, id: "default", cacheTtl: 60 });
60
60
 
61
61
  const workersAI = await generateText({
62
- model: ai("@cf/zai-org/glm-4.7-flash"),
62
+ model: ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
63
63
  prompt: "Say hello in three words"
64
64
  });
65
65
 
@@ -144,7 +144,10 @@ await generateText({
144
144
 
145
145
  // Or install it globally: bare strings then resolve through this provider.
146
146
  globalThis.AI_SDK_DEFAULT_PROVIDER = createAI({ binding: env.AI });
147
- await generateText({ model: "@cf/zai-org/glm-4.7-flash", prompt: "Hi" });
147
+ await generateText({
148
+ model: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
149
+ prompt: "Hi"
150
+ });
148
151
  ```
149
152
 
150
153
  Every modality is on the registry too (`registry.imageModel`,
@@ -266,7 +269,9 @@ fallbacks), and the call goes through `env.AI.run` like a Workers AI model:
266
269
  const ai = createAI({ binding: env.AI, id: "prod" });
267
270
 
268
271
  await generateText({ model: ai("dynamic/support"), prompt: "Hi" });
269
- ai("@cf/zai-org/glm-4.7-flash", { fallback: ["dynamic/support"] });
272
+ ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017", {
273
+ fallback: ["dynamic/support"]
274
+ });
270
275
  ```
271
276
 
272
277
  The route belongs to a gateway, so set the gateway `id` it was created on. It
@@ -308,30 +313,47 @@ const { rerankedDocuments } = await rerank({
308
313
  ```
309
314
 
310
315
  Bytes stay bytes and base64 stays base64: some models answer with a raw body
311
- (`image/png`, `audio/mpeg`, `audio/wav`) and some with JSON (`{ image }`,
312
- `{ audio }`), the content type decides, and nothing is converted on the way
313
- through. The media type comes off the bytes rather than the model name —
314
- `flux-1-schnell` answers with JPEG and MeloTTS with WAV.
316
+ (`image/png`, `audio/mpeg`) and some with JSON (`{ image }`, `{ audio }`), the
317
+ content type decides, and nothing is converted on the way through. The media
318
+ type comes off the bytes rather than the model name — the flux models answer
319
+ with JPEG where the others answer with PNG.
315
320
 
316
321
  Per-call knobs go under `providerOptions.cloudflare`, next to the gateway
317
322
  options:
318
323
 
319
- | Modality | Call options used | `providerOptions.cloudflare` |
320
- | ------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
321
- | Image | `prompt`, `n`, `size`, `seed`, `files`, `mask` | `steps`, `guidance`, `negativePrompt`, `strength` |
322
- | Speech | `text`, `voice` → `speaker`, `outputFormat` → `encoding`, `language` → `lang` (MeloTTS) | — |
323
- | Transcription | `audio`, `mediaType` | `language`, `task`, `initialPrompt`, `prefix`, `vadFilter` |
324
- | Reranking | `query`, `documents`, `topN` → `top_k` | — |
324
+ | Modality | Call options used | `providerOptions.cloudflare` |
325
+ | ------------- | -------------------------------------------------------- | ---------------------------------------------------------- |
326
+ | Image | `prompt`, `n`, `size`, `seed`, `files`, `mask` | `steps`, `guidance`, `negativePrompt`, `strength` |
327
+ | Speech | `text`, `voice` → `speaker`, `outputFormat` → `encoding` | — |
328
+ | Transcription | `audio`, `mediaType` | `language`, `task`, `initialPrompt`, `prefix`, `vadFilter` |
329
+ | Reranking | `query`, `documents`, `topN` → `top_k` | — |
325
330
 
326
331
  Anything a model cannot take comes back in `warnings` rather than being sent:
327
332
  `aspectRatio` everywhere, `size`/`seed`/`guidance` on `flux-1-schnell` (which
328
333
  takes only a prompt and steps), `speed` and `instructions` on every speech
329
- model, `voice` on MeloTTS. Object documents are stringified for reranking, with
334
+ model, and `language` on Aura, which takes its language from the model id
335
+ (`@cf/deepgram/aura-2-es`). Object documents are stringified for reranking, with
330
336
  a `compatibility` warning.
331
337
 
332
338
  The run path generates one image per call, so `maxImagesPerCall` is 1 and
333
339
  `generateImage` fans a larger `n` out into parallel calls.
334
340
 
341
+ The FLUX.2 models (`@cf/black-forest-labs/flux-2-klein-9b`, `flux-2-klein-4b`
342
+ and `flux-2-dev`) take multipart form data rather than JSON, and the provider
343
+ sends it as that, straight to Workers AI, so the gateway options do not apply
344
+ and a `warnings` entry says so when any are set. They take `size`, `seed` and
345
+ `guidance`, `steps` on `flux-2-dev` only (the klein models always run four),
346
+ and up to four reference images from the prompt's `images`, which the prompt
347
+ can refer to as image 0 to image 3:
348
+
349
+ ```ts
350
+ const { image } = await generateImage({
351
+ model: ai.image("@cf/black-forest-labs/flux-2-klein-9b"),
352
+ prompt: { text: "Put the lizard from image 0 in the snow", images: [lizard] },
353
+ size: "1024x768"
354
+ });
355
+ ```
356
+
335
357
  `@cf/deepgram/nova-3` takes its audio as a raw body (`audio: { body,
336
358
  contentType }`), and the provider sends it as one. Of the transcription options
337
359
  it takes `language`; the whisper-only ones come back in `warnings`.
@@ -422,7 +444,7 @@ of it. A leg is any model id, or any AI SDK language model:
422
444
 
423
445
  ```ts
424
446
  const model = ai(anthropic("claude-opus-4-8"), {
425
- fallback: ["openai/gpt-5.5", "@cf/zai-org/glm-4.7-flash"]
447
+ fallback: ["openai/gpt-5.5", "@cf/deepseek-ai/deepseek-v4.1-flash-1017"]
426
448
  });
427
449
  ```
428
450
 
@@ -539,7 +561,10 @@ so `ai`'s built-in retry loop honours `isRetryable` without extra wiring.
539
561
  import { CloudflareAIError } from "agents/models/ai-sdk";
540
562
 
541
563
  try {
542
- await generateText({ model: ai("@cf/zai-org/glm-4.7-flash"), prompt: "hi" });
564
+ await generateText({
565
+ model: ai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
566
+ prompt: "hi"
567
+ });
543
568
  } catch (error) {
544
569
  if (error instanceof CloudflareAIError) {
545
570
  error.status; // 402
@@ -28,7 +28,7 @@ export class ChatAgent extends AIChatAgent {
28
28
  const workersai = createWorkersAI({ binding: this.env.AI });
29
29
 
30
30
  const result = streamText({
31
- model: workersai("@cf/moonshotai/kimi-k2.7-code"),
31
+ model: workersai("@cf/deepseek-ai/deepseek-v4.1-flash-1017"),
32
32
  messages: await convertToModelMessages(this.messages)
33
33
  });
34
34
 
package/docs/retries.md CHANGED
@@ -325,7 +325,7 @@ With `maxAttempts: 5` and `baseDelayMs: 500`:
325
325
 
326
326
  ### MCP Server Retries
327
327
 
328
- When adding an MCP server, you can configure retry options for connection and reconnection attempts:
328
+ When adding an MCP server, you can configure how many quick attempts each connection makes:
329
329
 
330
330
  ```typescript
331
331
  await this.addMcpServer("github", "https://mcp.github.com", {
@@ -333,12 +333,9 @@ await this.addMcpServer("github", "https://mcp.github.com", {
333
333
  });
334
334
  ```
335
335
 
336
- These options are persisted and used when:
336
+ These options are persisted and used for every connection attempt: adding the server, restoring it after hibernation, establishing it after OAuth completes, and `reconnectMcpServer()`.
337
337
 
338
- - Restoring server connections after hibernation
339
- - Establishing connections after OAuth completion
340
-
341
- Default: 3 attempts, 500ms base delay, 5s max delay.
338
+ Default: 3 attempts, 500ms base delay, 5s max delay. If those attempts fail, the server is `failed` until you call `reconnectMcpServer()`; see [Failures and reconnecting](./mcp-client.md#failures-and-reconnecting).
342
339
 
343
340
  ### Internal Retries
344
341