agents 0.32.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 (187) 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 +2 -3
  10. package/dist/browser/ai.js.map +1 -1
  11. package/dist/browser/index.d.ts +33 -21
  12. package/dist/browser/index.js +937 -4
  13. package/dist/browser/index.js.map +1 -0
  14. package/dist/browser/tools/ai-sdk.d.ts +4 -4
  15. package/dist/browser/tools/ai-sdk.js +9 -3
  16. package/dist/browser/tools/ai-sdk.js.map +1 -1
  17. package/dist/browser/tools/pi.d.ts +11 -8
  18. package/dist/browser/tools/pi.js +58 -11
  19. package/dist/browser/tools/pi.js.map +1 -1
  20. package/dist/browser/tools/tanstack-ai.d.ts +4 -4
  21. package/dist/browser/tools/tanstack-ai.js +3 -3
  22. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  23. package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
  24. package/dist/browser-tool-DOqT1oSD.js +360 -0
  25. package/dist/browser-tool-DOqT1oSD.js.map +1 -0
  26. package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  27. package/dist/capability-DBAKc6UZ.js.map +1 -1
  28. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  29. package/dist/chat/index.d.ts +37 -6
  30. package/dist/chat/index.js +39 -3
  31. package/dist/chat/index.js.map +1 -1
  32. package/dist/chat/react.js +1 -0
  33. package/dist/chat/react.js.map +1 -1
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/cli.js +62 -60
  37. package/dist/client-CkT8voRY.js +3740 -0
  38. package/dist/client-CkT8voRY.js.map +1 -0
  39. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
  42. package/dist/connector-Bphz6wIw.js.map +1 -0
  43. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  44. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  45. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  46. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  47. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  48. package/dist/experimental/channels/index.d.ts +2 -2
  49. package/dist/experimental/channels/web/index.d.ts +2 -2
  50. package/dist/experimental/channels/web/index.js +1 -1
  51. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  52. package/dist/harness/ai-sdk/index.d.ts +2 -2
  53. package/dist/harness/container/index.d.ts +2 -2
  54. package/dist/harness/container/index.js +1 -1
  55. package/dist/harness/container/index.js.map +1 -1
  56. package/dist/harness/opencode/index.d.ts +1 -1
  57. package/dist/harness/pi/index.d.ts +200 -37
  58. package/dist/harness/pi/index.js +202 -100
  59. package/dist/harness/pi/index.js.map +1 -1
  60. package/dist/harness/think/index.d.ts +2 -2
  61. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  62. package/dist/images-D4gtE06D.js.map +1 -0
  63. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  64. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  65. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  66. package/dist/index.d.ts +21 -21
  67. package/dist/index.js +2 -2
  68. package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
  69. package/dist/input-schema-D6GilRXI.js.map +1 -0
  70. package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
  71. package/dist/input-schema-y8W5bOdM.js.map +1 -0
  72. package/dist/internal_context.d.ts +1 -1
  73. package/dist/lifecycle/index.d.ts +3 -3
  74. package/dist/lifecycle/index.js +1 -1
  75. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  76. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  77. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  78. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  79. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  80. package/dist/mcp/client/index.d.ts +42 -36
  81. package/dist/mcp/client/index.js +2 -2
  82. package/dist/mcp/index.d.ts +16 -16
  83. package/dist/mcp/index.js +2 -2
  84. package/dist/models/ai-sdk/index.d.ts +9 -5
  85. package/dist/models/ai-sdk/index.js +1 -1
  86. package/dist/models/opencode/index.d.ts +3 -3
  87. package/dist/models/opencode/index.js +2 -2
  88. package/dist/models/opencode/index.js.map +1 -1
  89. package/dist/models/pi-ai/index.d.ts +4 -4
  90. package/dist/models/pi-ai/index.js +64 -170
  91. package/dist/models/pi-ai/index.js.map +1 -1
  92. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  93. package/dist/queue/index.d.ts +1 -1
  94. package/dist/queue/index.js +1 -1
  95. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  96. package/dist/queue-B_wl6K0Z.js.map +1 -0
  97. package/dist/react.d.ts +2 -2
  98. package/dist/routing/index.d.ts +2 -2
  99. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  100. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  101. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  102. package/dist/schedules/index.d.ts +1 -1
  103. package/dist/schedules/index.js +1 -1
  104. package/dist/serializable.d.ts +1 -1
  105. package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
  106. package/dist/session-CRY0bGiI.js.map +1 -0
  107. package/dist/sessions/index.d.ts +1 -1
  108. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  109. package/dist/settings-D2F_qONv.js.map +1 -0
  110. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  111. package/dist/src-BO1FdLK1.js.map +1 -0
  112. package/dist/state/index.d.ts +1 -1
  113. package/dist/streams/index.d.ts +1 -1
  114. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  115. package/dist/sub-routing.d.ts +12 -12
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +1 -1
  118. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  119. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  120. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  121. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  122. package/dist/tool-CmAGY6Fo.js.map +1 -0
  123. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  124. package/dist/tool-Kxcj8_22.js.map +1 -0
  125. package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
  126. package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
  127. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  128. package/dist/voice/index.d.ts +2 -2
  129. package/dist/web/fetch/index.js +1 -1
  130. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  131. package/dist/web/fetch/tools/pi.d.ts +9 -7
  132. package/dist/web/fetch/tools/pi.js +31 -7
  133. package/dist/web/fetch/tools/pi.js.map +1 -1
  134. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  135. package/dist/web/search/index.js +1 -1
  136. package/dist/web/search/tools/ai-sdk.js +2 -2
  137. package/dist/web/search/tools/pi.d.ts +9 -4
  138. package/dist/web/search/tools/pi.js +27 -11
  139. package/dist/web/search/tools/pi.js.map +1 -1
  140. package/dist/web/search/tools/tanstack-ai.js +2 -2
  141. package/dist/websockets/index.d.ts +2 -2
  142. package/dist/websockets/index.js +1 -1
  143. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  144. package/dist/websockets-W4uhRg4-.js.map +1 -0
  145. package/dist/workflow-types.d.ts +1 -1
  146. package/dist/workflows.d.ts +1 -1
  147. package/docs/agent-class.md +30 -4
  148. package/docs/browse-the-web.md +50 -3
  149. package/docs/chat-agents.md +13 -10
  150. package/docs/client-tools-continuation.md +1 -1
  151. package/docs/codemode.md +1 -1
  152. package/docs/configuration.md +6 -3
  153. package/docs/cross-domain-authentication.md +1 -1
  154. package/docs/fetch-the-web.md +20 -0
  155. package/docs/harnesses/pi.md +242 -33
  156. package/docs/harnesses/think.md +1 -1
  157. package/docs/http-websockets.md +40 -32
  158. package/docs/human-in-the-loop.md +2 -2
  159. package/docs/lifecycle.md +56 -0
  160. package/docs/mcp-client.md +104 -7
  161. package/docs/models-pi-ai.md +24 -10
  162. package/docs/models.md +42 -17
  163. package/docs/resumable-streaming.md +1 -1
  164. package/docs/retries.md +3 -6
  165. package/docs/search-the-web.md +10 -0
  166. package/docs/voice.md +1 -1
  167. package/package.json +16 -9
  168. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  169. package/dist/browser-1eUbPvC2.js +0 -931
  170. package/dist/browser-1eUbPvC2.js.map +0 -1
  171. package/dist/browser-tool-DRan7Lk6.js +0 -497
  172. package/dist/browser-tool-DRan7Lk6.js.map +0 -1
  173. package/dist/client-DMWujQJ1.js +0 -2325
  174. package/dist/client-DMWujQJ1.js.map +0 -1
  175. package/dist/connector-CM-uuxKM.js.map +0 -1
  176. package/dist/images-CfuRCjwq.js.map +0 -1
  177. package/dist/input-schema-B0Etuo-o.js.map +0 -1
  178. package/dist/input-schema-BQykTEp_.js.map +0 -1
  179. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  180. package/dist/queue-CcIjVYTE.js.map +0 -1
  181. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  182. package/dist/session-7CDgVE0z.js.map +0 -1
  183. package/dist/settings-Dk2il2Hf.js.map +0 -1
  184. package/dist/src-DoGNJ4Ud.js.map +0 -1
  185. package/dist/tool-CxKsvxjm.js.map +0 -1
  186. package/dist/tool-DkT_DJBm.js.map +0 -1
  187. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -1,2325 +0,0 @@
1
- import { getAgentByName } from "./agent-routing.js";
2
- import { t as LifecycleCapability } from "./capability-DBAKc6UZ.js";
3
- import { tryN } from "./retries.js";
4
- import { t as callV2Tool } from "./invoker-BC1SZ3q1.js";
5
- import { DurableObjectOAuthClientProvider } from "./mcp/client/do-oauth-client-provider.js";
6
- import { nanoid } from "nanoid";
7
- import { z } from "zod";
8
- import { Client, SSEClientTransport, SdkHttpError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
9
- import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/client/validators/cf-worker";
10
- //#region src/mcp/abort.ts
11
- function abortError(signal) {
12
- return signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason ?? "Aborted"));
13
- }
14
- /**
15
- * Stop awaiting an operation when its owner aborts. The underlying operation
16
- * remains responsible for observing the same signal and cancelling its work.
17
- */
18
- async function raceWithSignal(promise, signal) {
19
- if (!signal) return promise;
20
- if (signal.aborted) throw abortError(signal);
21
- return new Promise((resolve, reject) => {
22
- const onAbort = () => reject(abortError(signal));
23
- signal.addEventListener("abort", onAbort, { once: true });
24
- promise.then(resolve, reject).finally(() => {
25
- signal.removeEventListener("abort", onAbort);
26
- });
27
- });
28
- }
29
- //#endregion
30
- //#region src/mcp/rpc.ts
31
- const RPC_DO_PREFIX = "rpc:";
32
- /** Narrow an unknown runtime binding to an MCP Durable Object namespace. */
33
- function isDurableObjectNamespace(namespace) {
34
- return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
35
- }
36
- var RPCClientTransport = class {
37
- constructor(options) {
38
- this._started = false;
39
- this._namespace = options.namespace;
40
- this._name = options.name;
41
- this._props = options.props;
42
- }
43
- setProtocolVersion(version) {
44
- this._protocolVersion = version;
45
- }
46
- getProtocolVersion() {
47
- return this._protocolVersion;
48
- }
49
- async start() {
50
- if (this._started) throw new Error("Transport already started");
51
- const doName = `${RPC_DO_PREFIX}${this._name}`;
52
- this._stub = await getAgentByName(this._namespace, doName, { props: this._props });
53
- this._started = true;
54
- }
55
- async close() {
56
- this._started = false;
57
- this._stub = void 0;
58
- this.onclose?.();
59
- }
60
- async send(message, options) {
61
- if (!this._started || !this._stub) throw new Error("Transport not started");
62
- try {
63
- const result = await raceWithSignal(this._stub.handleMcpMessage(message), options?.requestSignal);
64
- if (!result || options?.requestSignal?.aborted) return;
65
- const extra = void 0;
66
- const messages = Array.isArray(result) ? result : [result];
67
- for (const msg of messages) this.onmessage?.(msg, extra);
68
- } catch (error) {
69
- this.onerror?.(error);
70
- throw error;
71
- }
72
- }
73
- };
74
- //#endregion
75
- //#region src/core/events.ts
76
- function toDisposable(fn) {
77
- return { dispose: fn };
78
- }
79
- var DisposableStore = class {
80
- constructor() {
81
- this._items = [];
82
- }
83
- add(d) {
84
- this._items.push(d);
85
- return d;
86
- }
87
- dispose() {
88
- while (this._items.length) try {
89
- this._items.pop().dispose();
90
- } catch {}
91
- }
92
- };
93
- var Emitter = class {
94
- constructor() {
95
- this._listeners = /* @__PURE__ */ new Set();
96
- this.event = (listener) => {
97
- this._listeners.add(listener);
98
- return toDisposable(() => this._listeners.delete(listener));
99
- };
100
- }
101
- fire(data) {
102
- for (const listener of [...this._listeners]) try {
103
- listener(data);
104
- } catch (err) {
105
- console.error("Emitter listener error:", err);
106
- }
107
- }
108
- dispose() {
109
- this._listeners.clear();
110
- }
111
- };
112
- //#endregion
113
- //#region src/mcp/client/catalog.ts
114
- async function fetchMcpTools(client, options) {
115
- let aggregate = [];
116
- let page = { tools: [] };
117
- do {
118
- const params = { cursor: page.nextCursor };
119
- page = await (options.probing ? client.request({
120
- method: "tools/list",
121
- params
122
- }) : client.listTools(params)).catch(options.onCapabilityError({ tools: [] }, "tools/list"));
123
- aggregate = aggregate.concat(page.tools);
124
- } while (page.nextCursor);
125
- return aggregate;
126
- }
127
- async function fetchMcpResources(client, options) {
128
- let aggregate = [];
129
- let page = { resources: [] };
130
- do {
131
- const params = { cursor: page.nextCursor };
132
- page = await (options.probing ? client.request({
133
- method: "resources/list",
134
- params
135
- }) : client.listResources(params)).catch(options.onCapabilityError({ resources: [] }, "resources/list"));
136
- aggregate = aggregate.concat(page.resources);
137
- } while (page.nextCursor);
138
- return aggregate;
139
- }
140
- async function fetchMcpPrompts(client, options) {
141
- let aggregate = [];
142
- let page = { prompts: [] };
143
- do {
144
- const params = { cursor: page.nextCursor };
145
- page = await (options.probing ? client.request({
146
- method: "prompts/list",
147
- params
148
- }) : client.listPrompts(params)).catch(options.onCapabilityError({ prompts: [] }, "prompts/list"));
149
- aggregate = aggregate.concat(page.prompts);
150
- } while (page.nextCursor);
151
- return aggregate;
152
- }
153
- async function fetchMcpResourceTemplates(client, options) {
154
- let aggregate = [];
155
- let page = { resourceTemplates: [] };
156
- do {
157
- const params = { cursor: page.nextCursor };
158
- page = await (options.probing ? client.request({
159
- method: "resources/templates/list",
160
- params
161
- }) : client.listResourceTemplates(params)).catch(options.onCapabilityError({ resourceTemplates: [] }, "resources/templates/list"));
162
- aggregate = aggregate.concat(page.resourceTemplates);
163
- } while (page.nextCursor);
164
- return aggregate;
165
- }
166
- //#endregion
167
- //#region src/mcp/client/runtime.ts
168
- var CompatibleWorkerJsonSchemaValidator = class extends CfWorkerJsonSchemaValidator {
169
- constructor(..._args) {
170
- super(..._args);
171
- this.legacy = new CfWorkerJsonSchemaValidator({ draft: "7" });
172
- }
173
- getValidator(schema) {
174
- const dialect = schema.$schema;
175
- return typeof dialect === "string" && /draft-0?7/i.test(dialect) ? this.legacy.getValidator(schema) : super.getValidator(schema);
176
- }
177
- };
178
- const DEFAULT_CLIENT_OPTIONS = {
179
- jsonSchemaValidator: new CompatibleWorkerJsonSchemaValidator(),
180
- versionNegotiation: { mode: "auto" },
181
- inputRequired: { autoFulfill: true }
182
- };
183
- function normalizeMcpClientOptions(options) {
184
- return {
185
- ...DEFAULT_CLIENT_OPTIONS,
186
- ...options,
187
- versionNegotiation: {
188
- ...DEFAULT_CLIENT_OPTIONS.versionNegotiation,
189
- ...options?.versionNegotiation
190
- },
191
- inputRequired: {
192
- ...DEFAULT_CLIENT_OPTIONS.inputRequired,
193
- ...options?.inputRequired
194
- }
195
- };
196
- }
197
- function elicitationCapabilitiesFromHandlers(handlers) {
198
- if (!handlers) return void 0;
199
- const elicitation = {};
200
- if (handlers.form) elicitation.form = {};
201
- if (handlers.url) elicitation.url = {};
202
- return elicitation.form || elicitation.url ? elicitation : void 0;
203
- }
204
- function listChangedHandlers(configured, callbacks) {
205
- return {
206
- tools: {
207
- ...configured?.tools,
208
- onChanged: (error, tools) => {
209
- callbacks.tools(error, tools);
210
- configured?.tools?.onChanged(error, tools);
211
- }
212
- },
213
- prompts: {
214
- ...configured?.prompts,
215
- onChanged: (error, prompts) => {
216
- callbacks.prompts(error, prompts);
217
- configured?.prompts?.onChanged(error, prompts);
218
- }
219
- },
220
- resources: {
221
- ...configured?.resources,
222
- onChanged: (error, resources) => {
223
- callbacks.resources(error, resources);
224
- configured?.resources?.onChanged(error, resources);
225
- }
226
- }
227
- };
228
- }
229
- function createMcpSdkClient(info, options, capabilitySeed, handlerModes, callbacks) {
230
- const elicitation = options.capabilities?.elicitation ?? elicitationCapabilitiesFromHandlers(handlerModes) ?? capabilitySeed?.elicitation;
231
- return {
232
- client: new Client(info, {
233
- ...options,
234
- capabilities: {
235
- ...capabilitySeed,
236
- ...options.capabilities,
237
- ...elicitation ? { elicitation } : {}
238
- },
239
- listChanged: listChangedHandlers(options.listChanged, callbacks)
240
- }),
241
- elicitationEnabled: elicitation !== void 0
242
- };
243
- }
244
- //#endregion
245
- //#region src/mcp/client/errors.ts
246
- function toErrorMessage(error) {
247
- return error instanceof Error ? error.message : String(error);
248
- }
249
- function getErrorStatus(error) {
250
- if (!error || typeof error !== "object") return void 0;
251
- const record = error;
252
- if (typeof record.code === "number") return record.code;
253
- if (typeof record.status === "number") return record.status;
254
- if (typeof record.data?.status === "number") return record.data.status;
255
- }
256
- function getErrorCause(error) {
257
- if (!error || typeof error !== "object") return void 0;
258
- return error.cause ?? error.data?.cause;
259
- }
260
- function isUnauthorized(error) {
261
- if (getErrorStatus(error) === 401) return true;
262
- const cause = getErrorCause(error);
263
- if (cause && cause !== error && isUnauthorized(cause)) return true;
264
- const msg = toErrorMessage(error);
265
- return msg.includes("Unauthorized") || msg.includes("401");
266
- }
267
- function isTransportNotImplemented(error) {
268
- const status = getErrorStatus(error);
269
- if (status === 404 || status === 405) return true;
270
- const cause = getErrorCause(error);
271
- if (cause && cause !== error && isTransportNotImplemented(cause)) return true;
272
- const msg = toErrorMessage(error);
273
- return msg.includes("404") || msg.includes("405") || msg.includes("Error POSTing to endpoint: Not Found") || msg.includes("Not Implemented") || msg.includes("not implemented");
274
- }
275
- //#endregion
276
- //#region src/mcp/client/connection.ts
277
- /**
278
- * Connection state machine for MCP client connections.
279
- *
280
- * State transitions:
281
- * - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
282
- * - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
283
- * - Any state can transition to FAILED on error
284
- */
285
- const MCPConnectionState = {
286
- /** Waiting for OAuth authorization to complete */
287
- AUTHENTICATING: "authenticating",
288
- /** Establishing transport connection to MCP server */
289
- CONNECTING: "connecting",
290
- /** Transport connection established */
291
- CONNECTED: "connected",
292
- /** Discovering server capabilities (tools, resources, prompts) */
293
- DISCOVERING: "discovering",
294
- /** Fully connected and ready to use */
295
- READY: "ready",
296
- /** Connection failed at some point */
297
- FAILED: "failed"
298
- };
299
- var MCPClientConnection = class {
300
- constructor(url, _info, options = {
301
- client: {},
302
- transport: {}
303
- }) {
304
- this.url = url;
305
- this._info = _info;
306
- this.options = options;
307
- this.connectionState = MCPConnectionState.CONNECTING;
308
- this.connectionError = null;
309
- this.tools = [];
310
- this.prompts = [];
311
- this.resources = [];
312
- this.resourceTemplates = [];
313
- this._probingCapabilities = false;
314
- this._onObservabilityEvent = new Emitter();
315
- this.onObservabilityEvent = this._onObservabilityEvent.event;
316
- this._onListChanged = new Emitter();
317
- this.onListChanged = this._onListChanged.event;
318
- this._elicitationEnabled = false;
319
- this.options = {
320
- ...options,
321
- client: normalizeMcpClientOptions(options.client)
322
- };
323
- this.client = this.createClient();
324
- }
325
- createClient() {
326
- const created = createMcpSdkClient(this._info, this.options.client, this.options.capabilitySeed, this.options.elicitationHandlers, {
327
- tools: (error, tools) => {
328
- if (!error && tools) this.tools = tools;
329
- this._onListChanged.fire();
330
- },
331
- prompts: (error, prompts) => {
332
- if (!error && prompts) this.prompts = prompts;
333
- this._onListChanged.fire();
334
- },
335
- resources: (error, resources) => {
336
- if (!error && resources) this.resources = resources;
337
- this._onListChanged.fire();
338
- }
339
- });
340
- this._elicitationEnabled = created.elicitationEnabled;
341
- return created.client;
342
- }
343
- /**
344
- * Configure the handler used for server-initiated elicitation requests.
345
- *
346
- * If the connection has not been initialized yet, rebuild the SDK client so
347
- * handler-driven elicitation capabilities are reflected in the initial
348
- * handshake. A rebuild (rather than `Client.registerCapabilities`) is
349
- * required because SDK capability registration is merge-only — it cannot
350
- * un-advertise a mode when handlers are cleared before connecting. Active
351
- * connections keep their negotiated capabilities until they reconnect.
352
- */
353
- configureElicitationHandlers(handlers) {
354
- this.options.elicitationHandlers = handlers;
355
- this.options.capabilitySeed = void 0;
356
- if (!this._transport) this.client = this.createClient();
357
- }
358
- /**
359
- * Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
360
- * Sets connection state based on the result and emits observability events
361
- *
362
- * @returns Error message if connection failed, undefined otherwise
363
- */
364
- async init() {
365
- const transportType = this.options.transport.type;
366
- if (!transportType) throw new Error("Transport type must be specified");
367
- if (this._transport) {
368
- this._transport = void 0;
369
- try {
370
- await this.client.close();
371
- } catch {}
372
- this.client = this.createClient();
373
- }
374
- const res = await this.tryConnect(transportType);
375
- this.connectionState = res.state;
376
- if (res.state === MCPConnectionState.CONNECTED && res.transport) {
377
- if (this._elicitationEnabled) this.client.setRequestHandler("elicitation/create", async (request, context) => await this.handleElicitationRequest(request, context.mcpReq.signal));
378
- this.lastConnectedTransport = res.transport;
379
- this._onObservabilityEvent.fire({
380
- type: "mcp:client:connect",
381
- payload: {
382
- url: this.url.toString(),
383
- transport: res.transport,
384
- state: this.connectionState
385
- },
386
- timestamp: Date.now()
387
- });
388
- return;
389
- } else if (res.state === MCPConnectionState.FAILED && res.error) {
390
- const errorMessage = toErrorMessage(res.error);
391
- this._onObservabilityEvent.fire({
392
- type: "mcp:client:connect",
393
- payload: {
394
- url: this.url.toString(),
395
- transport: transportType,
396
- state: this.connectionState,
397
- error: errorMessage
398
- },
399
- timestamp: Date.now()
400
- });
401
- return errorMessage;
402
- }
403
- }
404
- /**
405
- * Finish OAuth by probing transports based on configured type.
406
- * - Explicit: finish on that transport
407
- * - Auto: try streamable-http, then sse on 404/405/Not Implemented
408
- */
409
- async finishAuthProbe(callbackParams) {
410
- if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
411
- const configuredType = this.options.transport.type;
412
- if (!configuredType) throw new Error("Transport type must be specified");
413
- const finishAuth = async (base) => {
414
- const transport = this.getTransport(base);
415
- let completed = false;
416
- try {
417
- if ("finishAuth" in transport && typeof transport.finishAuth === "function") {
418
- await transport.finishAuth(callbackParams);
419
- completed = true;
420
- }
421
- } finally {
422
- if (typeof transport.close === "function") await transport.close().catch(() => {});
423
- }
424
- if (completed) this.client = this.createClient();
425
- };
426
- if (configuredType === "rpc") throw new Error("RPC transport does not support authentication");
427
- const authTransport = this._pendingAuthTransport ?? this._transport;
428
- this._pendingAuthTransport = void 0;
429
- if (authTransport && "finishAuth" in authTransport && typeof authTransport.finishAuth === "function") {
430
- let completed = false;
431
- try {
432
- await authTransport.finishAuth(callbackParams);
433
- completed = true;
434
- } finally {
435
- if (typeof authTransport.close === "function") await authTransport.close().catch(() => {});
436
- if (this._transport === authTransport) this._transport = void 0;
437
- }
438
- if (completed) this.client = this.createClient();
439
- return;
440
- }
441
- if (configuredType === "sse" || configuredType === "streamable-http") {
442
- await finishAuth(configuredType);
443
- return;
444
- }
445
- try {
446
- await finishAuth("streamable-http");
447
- } catch (e) {
448
- if (isTransportNotImplemented(e)) {
449
- await finishAuth("sse");
450
- return;
451
- }
452
- throw e;
453
- }
454
- }
455
- /**
456
- * Complete OAuth authorization
457
- */
458
- async completeAuthorization(callback, options = {}) {
459
- const expectedState = options.alreadyAccepted ? MCPConnectionState.CONNECTING : MCPConnectionState.AUTHENTICATING;
460
- if (this.connectionState !== expectedState) throw new Error(`Connection must be in ${expectedState} state to complete authorization`);
461
- if (!options.alreadyAccepted) this.connectionState = MCPConnectionState.CONNECTING;
462
- try {
463
- const callbackParams = typeof callback === "string" ? new URLSearchParams({ code: callback }) : callback;
464
- await this.finishAuthProbe(callbackParams);
465
- } catch (error) {
466
- this.connectionState = MCPConnectionState.FAILED;
467
- throw error;
468
- }
469
- }
470
- /**
471
- * Discover server capabilities and register tools, resources, prompts, and templates.
472
- * This method does the work but does not manage connection state - that's handled by discover().
473
- */
474
- async discoverAndRegister() {
475
- const discoveredCapabilities = this.client.getServerCapabilities();
476
- const shouldProbeCapabilities = !discoveredCapabilities && this.isResumedStreamableHttpSession();
477
- this.serverCapabilities = discoveredCapabilities;
478
- this._probingCapabilities = shouldProbeCapabilities;
479
- if (!discoveredCapabilities && !shouldProbeCapabilities) throw new Error("The MCP Server failed to return server capabilities");
480
- const operations = [];
481
- const operationNames = [];
482
- operations.push(Promise.resolve(this.client.getInstructions()));
483
- operationNames.push("instructions");
484
- if (discoveredCapabilities?.tools || shouldProbeCapabilities) {
485
- operations.push(this.registerTools());
486
- operationNames.push("tools");
487
- }
488
- if (discoveredCapabilities?.resources || shouldProbeCapabilities) {
489
- operations.push(this.registerResources());
490
- operationNames.push("resources");
491
- }
492
- if (discoveredCapabilities?.prompts || shouldProbeCapabilities) {
493
- operations.push(this.registerPrompts());
494
- operationNames.push("prompts");
495
- }
496
- if (discoveredCapabilities?.resources || shouldProbeCapabilities) {
497
- operations.push(this.registerResourceTemplates());
498
- operationNames.push("resource templates");
499
- }
500
- try {
501
- const results = await Promise.all(operations);
502
- for (let i = 0; i < results.length; i++) {
503
- const result = results[i];
504
- switch (operationNames[i]) {
505
- case "instructions":
506
- this.instructions = result;
507
- break;
508
- case "tools":
509
- this.tools = result;
510
- break;
511
- case "resources":
512
- this.resources = result;
513
- break;
514
- case "prompts":
515
- this.prompts = result;
516
- break;
517
- case "resource templates":
518
- this.resourceTemplates = result;
519
- break;
520
- }
521
- }
522
- } catch (error) {
523
- this._onObservabilityEvent.fire({
524
- type: "mcp:client:discover",
525
- payload: {
526
- url: this.url.toString(),
527
- error: toErrorMessage(error)
528
- },
529
- timestamp: Date.now()
530
- });
531
- throw error;
532
- }
533
- }
534
- /**
535
- * Discover server capabilities with timeout and cancellation support.
536
- * If called while a previous discovery is in-flight, the previous discovery will be aborted.
537
- *
538
- * @param options Optional configuration
539
- * @param options.timeoutMs Timeout in milliseconds (default: 15000)
540
- * @returns Result indicating success/failure with optional error message
541
- */
542
- async discover(options = {}) {
543
- const { timeoutMs = 15e3 } = options;
544
- if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
545
- this._onObservabilityEvent.fire({
546
- type: "mcp:client:discover",
547
- payload: {
548
- url: this.url.toString(),
549
- state: this.connectionState
550
- },
551
- timestamp: Date.now()
552
- });
553
- return {
554
- success: false,
555
- reason: "error",
556
- error: `Discovery skipped - connection in ${this.connectionState} state`
557
- };
558
- }
559
- if (this._discoveryAbortController) {
560
- this._discoveryAbortController.abort();
561
- this._discoveryAbortController = void 0;
562
- }
563
- const abortController = new AbortController();
564
- this._discoveryAbortController = abortController;
565
- this.connectionState = MCPConnectionState.DISCOVERING;
566
- let timeoutId;
567
- try {
568
- const timeoutPromise = new Promise((_, reject) => {
569
- timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
570
- });
571
- if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
572
- const abortPromise = new Promise((_, reject) => {
573
- abortController.signal.addEventListener("abort", () => {
574
- reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
575
- });
576
- });
577
- await Promise.race([
578
- this.discoverAndRegister(),
579
- timeoutPromise,
580
- abortPromise
581
- ]);
582
- if (timeoutId !== void 0) clearTimeout(timeoutId);
583
- this.connectionState = MCPConnectionState.READY;
584
- this._onObservabilityEvent.fire({
585
- type: "mcp:client:discover",
586
- payload: { url: this.url.toString() },
587
- timestamp: Date.now()
588
- });
589
- return { success: true };
590
- } catch (e) {
591
- if (timeoutId !== void 0) clearTimeout(timeoutId);
592
- this.connectionState = isUnauthorized(e) ? MCPConnectionState.AUTHENTICATING : MCPConnectionState.CONNECTED;
593
- const error = e instanceof Error ? e.message : String(e);
594
- return {
595
- success: false,
596
- reason: this._probingCapabilities && e instanceof SdkHttpError && e.status === 404 ? "stale-session" : "error",
597
- error
598
- };
599
- } finally {
600
- this._discoveryAbortController = void 0;
601
- }
602
- }
603
- /**
604
- * Cancel any in-flight discovery operation.
605
- * Called when closing the connection.
606
- */
607
- cancelDiscovery() {
608
- if (this._discoveryAbortController) {
609
- this._discoveryAbortController.abort();
610
- this._discoveryAbortController = void 0;
611
- }
612
- }
613
- /**
614
- * Notification handler registration for tools
615
- * Should only be called if serverCapabilities.tools exists
616
- */
617
- async registerTools() {
618
- if (this._probingCapabilities) this.client.setNotificationHandler("notifications/tools/list_changed", async () => {
619
- this.tools = await this.fetchTools();
620
- this._onListChanged.fire();
621
- });
622
- return this.fetchTools();
623
- }
624
- /**
625
- * Notification handler registration for resources
626
- * Should only be called if serverCapabilities.resources exists
627
- */
628
- async registerResources() {
629
- if (this._probingCapabilities) this.client.setNotificationHandler("notifications/resources/list_changed", async () => {
630
- this.resources = await this.fetchResources();
631
- this._onListChanged.fire();
632
- });
633
- return this.fetchResources();
634
- }
635
- /**
636
- * Notification handler registration for prompts
637
- * Should only be called if serverCapabilities.prompts exists
638
- */
639
- async registerPrompts() {
640
- if (this._probingCapabilities) this.client.setNotificationHandler("notifications/prompts/list_changed", async () => {
641
- this.prompts = await this.fetchPrompts();
642
- this._onListChanged.fire();
643
- });
644
- return this.fetchPrompts();
645
- }
646
- async registerResourceTemplates() {
647
- return this.fetchResourceTemplates();
648
- }
649
- catalogFetchOptions() {
650
- return {
651
- probing: this._probingCapabilities,
652
- onCapabilityError: this._capabilityErrorHandler.bind(this)
653
- };
654
- }
655
- async fetchTools() {
656
- return fetchMcpTools(this.client, this.catalogFetchOptions());
657
- }
658
- async fetchResources() {
659
- return fetchMcpResources(this.client, this.catalogFetchOptions());
660
- }
661
- async fetchPrompts() {
662
- return fetchMcpPrompts(this.client, this.catalogFetchOptions());
663
- }
664
- async fetchResourceTemplates() {
665
- return fetchMcpResourceTemplates(this.client, this.catalogFetchOptions());
666
- }
667
- /**
668
- * Handle elicitation request from server.
669
- *
670
- * Delegates to the `elicitationHandlers` connection option when provided.
671
- *
672
- * @deprecated Overriding or instance-patching this method directly is
673
- * deprecated — pass the `elicitationHandlers` connection option instead.
674
- */
675
- async handleElicitationRequest(request, signal) {
676
- const mode = request.params.mode === "url" ? "url" : "form";
677
- const handler = this.options.elicitationHandlers?.[mode];
678
- if (handler) return raceWithSignal(signal ? handler(request, signal) : handler(request), signal);
679
- if (this.options.elicitationHandlers) throw new Error(`No MCP ${mode}-mode elicitation handler configured for this connection.`);
680
- throw new Error("Elicitation handler must be implemented for your platform. Provide the MCPClientConnection elicitationHandlers option, or register handlers through the MCP client manager before connecting.");
681
- }
682
- isResumedStreamableHttpSession() {
683
- return this._transport instanceof StreamableHTTPClientTransport && typeof this._transport.sessionId === "string";
684
- }
685
- get sessionId() {
686
- if (this._transport instanceof StreamableHTTPClientTransport) return this._transport.sessionId;
687
- }
688
- /** @internal Clear a restored session before reconnecting. */
689
- clearResumedSession() {
690
- if ("sessionId" in this.options.transport) delete this.options.transport.sessionId;
691
- }
692
- get protocolVersion() {
693
- if (this._transport instanceof StreamableHTTPClientTransport) return this._transport.protocolVersion;
694
- }
695
- get discoverResult() {
696
- return this.client.getDiscoverResult();
697
- }
698
- async openRestoredListSubscription() {
699
- const capabilities = this.client.getServerCapabilities();
700
- const filter = {
701
- ...capabilities?.tools?.listChanged && { toolsListChanged: true },
702
- ...capabilities?.prompts?.listChanged && { promptsListChanged: true },
703
- ...capabilities?.resources?.listChanged && { resourcesListChanged: true }
704
- };
705
- if (Object.keys(filter).length === 0) return;
706
- try {
707
- this._restoredListSubscription = await this.client.listen(filter);
708
- } catch (error) {
709
- this.client.onerror?.(error instanceof Error ? error : new Error(String(error)));
710
- }
711
- }
712
- getTransportName(transport) {
713
- if (transport instanceof StreamableHTTPClientTransport) return "streamable-http";
714
- if (transport instanceof SSEClientTransport) return "sse";
715
- if (transport instanceof RPCClientTransport) return "rpc";
716
- return this.lastConnectedTransport;
717
- }
718
- async close() {
719
- const transport = this._transport;
720
- this._transport = void 0;
721
- await this._restoredListSubscription?.close().catch(() => {});
722
- this._restoredListSubscription = void 0;
723
- const url = this.url.toString();
724
- const transportName = this.getTransportName(transport);
725
- if (transport instanceof StreamableHTTPClientTransport && transport.sessionId) try {
726
- await transport.terminateSession();
727
- } catch (error) {
728
- this._onObservabilityEvent.fire({
729
- type: "mcp:client:close",
730
- payload: {
731
- url,
732
- transport: transportName,
733
- state: "error",
734
- error: toErrorMessage(error),
735
- phase: "terminate-session"
736
- },
737
- timestamp: Date.now()
738
- });
739
- }
740
- try {
741
- await this.client.close();
742
- } catch (error) {
743
- this._onObservabilityEvent.fire({
744
- type: "mcp:client:close",
745
- payload: {
746
- url,
747
- transport: transportName,
748
- state: "error",
749
- error: toErrorMessage(error),
750
- phase: "client-close"
751
- },
752
- timestamp: Date.now()
753
- });
754
- throw error;
755
- }
756
- this._onObservabilityEvent.fire({
757
- type: "mcp:client:close",
758
- payload: {
759
- url,
760
- transport: transportName,
761
- state: "closed"
762
- },
763
- timestamp: Date.now()
764
- });
765
- }
766
- /**
767
- * Get the transport for the client
768
- * @param transportType - The transport type to get
769
- * @returns The transport for the client
770
- */
771
- getTransport(transportType) {
772
- switch (transportType) {
773
- case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
774
- case "sse": return new SSEClientTransport(this.url, this.options.transport);
775
- case "rpc": return new RPCClientTransport(this.options.transport);
776
- default: throw new Error(`Unsupported transport type: ${transportType}`);
777
- }
778
- }
779
- async tryConnect(transportType) {
780
- const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
781
- for (const currentTransportType of transports) {
782
- const isLastTransport = currentTransportType === transports[transports.length - 1];
783
- const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
784
- const transport = this.getTransport(currentTransportType);
785
- try {
786
- const prior = transport instanceof StreamableHTTPClientTransport && transport.sessionId && this.options.discoverResult ? {
787
- kind: "modern",
788
- discover: this.options.discoverResult
789
- } : void 0;
790
- await this.client.connect(transport, prior ? { prior } : void 0);
791
- this._transport = transport;
792
- this._pendingAuthTransport = void 0;
793
- if (prior) await this.openRestoredListSubscription();
794
- return {
795
- state: MCPConnectionState.CONNECTED,
796
- transport: currentTransportType
797
- };
798
- } catch (e) {
799
- const error = e instanceof Error ? e : new Error(String(e));
800
- if (isUnauthorized(error)) {
801
- this._pendingAuthTransport = transport;
802
- return { state: MCPConnectionState.AUTHENTICATING };
803
- }
804
- if (isTransportNotImplemented(error) && hasFallback) continue;
805
- return {
806
- state: MCPConnectionState.FAILED,
807
- error
808
- };
809
- }
810
- }
811
- return {
812
- state: MCPConnectionState.FAILED,
813
- error: /* @__PURE__ */ new Error("No transports available")
814
- };
815
- }
816
- _capabilityErrorHandler(empty, method) {
817
- return (e) => {
818
- if (e.code === -32601) {
819
- const url = this.url.toString();
820
- this._onObservabilityEvent.fire({
821
- type: "mcp:client:discover",
822
- payload: {
823
- url,
824
- capability: method.split("/")[0],
825
- error: toErrorMessage(e)
826
- },
827
- timestamp: Date.now()
828
- });
829
- return empty;
830
- }
831
- throw e;
832
- };
833
- }
834
- };
835
- //#endregion
836
- //#region src/mcp/client/storage.ts
837
- /** Create the durable MCP server catalog table when it does not exist. */
838
- function ensureMcpServerTable(storage) {
839
- storage.sql.exec(`
840
- CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
841
- id TEXT PRIMARY KEY NOT NULL,
842
- name TEXT NOT NULL,
843
- server_url TEXT NOT NULL,
844
- callback_url TEXT NOT NULL,
845
- client_id TEXT,
846
- auth_url TEXT,
847
- server_options TEXT
848
- )
849
- `);
850
- }
851
- function persistClientOptions(client) {
852
- if (!client) return void 0;
853
- return {
854
- capabilities: client.capabilities,
855
- supportedProtocolVersions: client.supportedProtocolVersions,
856
- enforceStrictCapabilities: client.enforceStrictCapabilities,
857
- debouncedNotificationMethods: client.debouncedNotificationMethods,
858
- versionNegotiation: client.versionNegotiation,
859
- inputRequired: client.inputRequired,
860
- listMaxPages: client.listMaxPages,
861
- cachePartition: client.cachePartition,
862
- defaultCacheTtlMs: client.defaultCacheTtlMs
863
- };
864
- }
865
- function persistTransportOptions(value) {
866
- if (!value) return void 0;
867
- return {
868
- type: value.type,
869
- headers: value.headers,
870
- requestInit: value.requestInit,
871
- reconnectionOptions: value.reconnectionOptions,
872
- skipIssuerMetadataValidation: value.skipIssuerMetadataValidation,
873
- onInsufficientScope: value.onInsufficientScope,
874
- maxStepUpRetries: value.maxStepUpRetries,
875
- sessionId: value.sessionId,
876
- protocolVersion: value.protocolVersion
877
- };
878
- }
879
- function encodeMcpServerOptions(options) {
880
- return JSON.stringify({
881
- client: persistClientOptions(options.client),
882
- transport: persistTransportOptions(options.transport),
883
- discoverResult: options.discoverResult,
884
- retry: options.retry,
885
- bindingName: options.bindingName,
886
- props: options.props,
887
- capabilities: options.capabilities
888
- });
889
- }
890
- function decodeMcpServerOptions(value) {
891
- if (!value) return {};
892
- const parsed = JSON.parse(value);
893
- const transport = persistTransportOptions(parsed.transport);
894
- const statelessWithoutPrior = transport?.protocolVersion === "2026-07-28" && !parsed.discoverResult;
895
- if (transport?.sessionId && (!transport.protocolVersion || statelessWithoutPrior)) {
896
- delete transport.sessionId;
897
- delete transport.protocolVersion;
898
- delete parsed.discoverResult;
899
- }
900
- return {
901
- client: persistClientOptions(parsed.client),
902
- transport,
903
- discoverResult: parsed.discoverResult,
904
- retry: parsed.retry,
905
- ...parsed.bindingName !== void 0 && { bindingName: parsed.bindingName },
906
- ...parsed.props !== void 0 && { props: parsed.props },
907
- capabilities: parsed.capabilities
908
- };
909
- }
910
- function withMcpSession(options, session) {
911
- const transport = { ...options.transport ?? {} };
912
- if (!session) {
913
- delete transport.sessionId;
914
- delete transport.protocolVersion;
915
- const next = {
916
- ...options,
917
- transport
918
- };
919
- delete next.discoverResult;
920
- return next;
921
- }
922
- transport.sessionId = session.id;
923
- transport.protocolVersion = session.protocolVersion;
924
- return {
925
- ...options,
926
- transport,
927
- ...session.discoverResult ? { discoverResult: session.discoverResult } : { discoverResult: void 0 }
928
- };
929
- }
930
- //#endregion
931
- //#region src/mcp/client/rpc.ts
932
- /** Restore persisted RPC connections through a manager's public transport API. */
933
- async function restoreRpcConnections(manager, env, servers) {
934
- if (!env) {
935
- for (const server of servers) console.warn(`[MCPClientManager] Cannot restore RPC MCP server "${server.name}": no env was provided; pass { env } when constructing MCPClientManager`);
936
- return;
937
- }
938
- for (const server of servers) {
939
- if (manager.mcpConnections[server.id]) continue;
940
- const options = decodeMcpServerOptions(server.server_options);
941
- const binding = options.bindingName ? Object.entries(env).find(([name]) => name === options.bindingName)?.[1] : void 0;
942
- if (!isDurableObjectNamespace(binding)) {
943
- console.warn(`[MCPClientManager] Cannot restore RPC MCP server "${server.name}": binding "${options.bindingName ?? "<missing>"}" not found in env`);
944
- continue;
945
- }
946
- const normalizedName = server.server_url.replace(RPC_DO_PREFIX, "");
947
- try {
948
- await manager.connect(`${RPC_DO_PREFIX}${normalizedName}`, {
949
- reconnect: { id: server.id },
950
- transport: {
951
- type: "rpc",
952
- namespace: binding,
953
- name: normalizedName,
954
- props: options.props
955
- }
956
- });
957
- if (manager.mcpConnections[server.id]?.connectionState === MCPConnectionState.CONNECTED) await manager.discoverIfConnected(server.id);
958
- } catch (error) {
959
- console.error(`[MCPClientManager] Error restoring RPC MCP server "${server.name}":`, error);
960
- }
961
- }
962
- }
963
- //#endregion
964
- //#region src/mcp/client/index.ts
965
- /** Maximum length of a normalized MCP server id. */
966
- const MCP_SERVER_ID_MAX_LENGTH = 64;
967
- /**
968
- * Normalize a caller-supplied MCP server id into a stable, storage- and
969
- * tool-name-safe form.
970
- *
971
- * The id is surfaced in several places where the character set matters:
972
- * - as the primary key in the `cf_agents_mcp_servers` SQLite table
973
- * - embedded in AI SDK tool names as `` `tool_${id.replace(/-/g, "")}_${tool}` ``
974
- * (tool names must match `/^[A-Za-z0-9_]+$/`)
975
- * - as a key on the `mcpConnections` map and OAuth provider storage
976
- *
977
- * Rules:
978
- * 1. Lowercase.
979
- * 2. Replace any run of disallowed characters with a single `-`.
980
- * 3. Collapse repeated `-` and trim leading/trailing `-`/`_`.
981
- * 4. Prefix with `id-` if the result is empty or doesn't start with a letter.
982
- * 5. Truncate to {@link MCP_SERVER_ID_MAX_LENGTH} characters.
983
- *
984
- * @example
985
- * normalizeServerId("my-supplied-id"); // "my-supplied-id"
986
- * normalizeServerId("GitHub MCP!"); // "github-mcp"
987
- * normalizeServerId("42-things"); // "id-42-things"
988
- */
989
- function normalizeServerId(input) {
990
- if (typeof input !== "string") throw new TypeError(`normalizeServerId: expected string, got ${typeof input}`);
991
- let id = input.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, "");
992
- if (id.length === 0 || !/^[a-z]/.test(id)) id = `id-${id}`.replace(/-+$/g, "");
993
- if (id.length > 64) id = id.slice(0, 64).replace(/-+$/g, "");
994
- return id;
995
- }
996
- /**
997
- * Blocked hostname patterns for SSRF protection.
998
- * Prevents MCP client from connecting to internal/private network addresses
999
- * while allowing loopback hosts for local development.
1000
- */
1001
- const BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
1002
- "0.0.0.0",
1003
- "[::]",
1004
- "metadata.google.internal"
1005
- ]);
1006
- /**
1007
- * Check whether four IPv4 octets belong to a private/reserved range.
1008
- * Blocks RFC 1918, link-local, cloud metadata, and unspecified addresses.
1009
- */
1010
- function isPrivateIPv4(octets) {
1011
- const [a, b] = octets;
1012
- if (a === 10) return true;
1013
- if (a === 172 && b >= 16 && b <= 31) return true;
1014
- if (a === 192 && b === 168) return true;
1015
- if (a === 169 && b === 254) return true;
1016
- if (a === 0) return true;
1017
- return false;
1018
- }
1019
- /**
1020
- * fe80::/10 — IPv6 link-local (RFC 4291 §2.5.6).
1021
- *
1022
- * The /10 boundary fixes the first 10 bits (1111111010), which means valid
1023
- * first hextets range from fe80 through febf. Only hex digits 8, 9, a, b
1024
- * have high two bits "10" — anything else (e.g. fe7f, fec0) is out of range.
1025
- * The fourth hex digit is unconstrained by the /10 boundary.
1026
- *
1027
- * Historical bug: `startsWith("fe80")` only matched the narrower fe80::/16
1028
- * prefix and let fe81::/feab::/febf:: slip through. See issue #1325.
1029
- */
1030
- const IPV6_LINK_LOCAL = /^fe[89ab][0-9a-f]/;
1031
- /**
1032
- * Check whether a bracket-stripped, lowercased IPv6 address belongs to a
1033
- * private/reserved range. Also unwraps IPv4-mapped IPv6 (::ffff:...) and
1034
- * delegates to isPrivateIPv4 for those.
1035
- *
1036
- * Loopback (::1) and unspecified (::) are NOT blocked here:
1037
- * - ::1 is intentionally allowed (parallel to 127.x.x.x for local dev)
1038
- * - :: (== [::]) is blocked via BLOCKED_HOSTNAMES at the hostname level
1039
- */
1040
- function isPrivateIPv6(addr) {
1041
- if (addr.startsWith("fc") || addr.startsWith("fd")) return true;
1042
- if (IPV6_LINK_LOCAL.test(addr)) return true;
1043
- if (addr.startsWith("::ffff:")) {
1044
- const mapped = addr.slice(7);
1045
- const dotParts = mapped.split(".");
1046
- if (dotParts.length === 4 && dotParts.every((p) => /^\d{1,3}$/.test(p))) {
1047
- if (isPrivateIPv4(dotParts.map(Number))) return true;
1048
- } else {
1049
- const hexParts = mapped.split(":");
1050
- if (hexParts.length === 2) {
1051
- const hi = parseInt(hexParts[0], 16);
1052
- const lo = parseInt(hexParts[1], 16);
1053
- if (isPrivateIPv4([
1054
- hi >> 8 & 255,
1055
- hi & 255,
1056
- lo >> 8 & 255,
1057
- lo & 255
1058
- ])) return true;
1059
- }
1060
- }
1061
- }
1062
- return false;
1063
- }
1064
- /**
1065
- * Check whether a hostname looks like a private/internal IP address.
1066
- * Blocks RFC 1918, link-local, unique-local, unspecified,
1067
- * and cloud metadata endpoints. Also detects IPv4-mapped IPv6 addresses.
1068
- */
1069
- function isBlockedUrl(url) {
1070
- let parsed;
1071
- try {
1072
- parsed = new URL(url);
1073
- } catch {
1074
- return true;
1075
- }
1076
- const hostname = parsed.hostname;
1077
- if (BLOCKED_HOSTNAMES.has(hostname)) return true;
1078
- const ipv4Parts = hostname.split(".");
1079
- if (ipv4Parts.length === 4 && ipv4Parts.every((p) => /^\d{1,3}$/.test(p))) {
1080
- if (isPrivateIPv4(ipv4Parts.map(Number))) return true;
1081
- }
1082
- if (hostname.startsWith("[") && hostname.endsWith("]")) {
1083
- if (isPrivateIPv6(hostname.slice(1, -1).toLowerCase())) return true;
1084
- }
1085
- return false;
1086
- }
1087
- /** Converts a resolved connection failure into a retry signal. */
1088
- var ConnectRetryError = class extends Error {
1089
- constructor(result) {
1090
- super("MCP connection attempt failed");
1091
- this.result = result;
1092
- }
1093
- };
1094
- const MCP_SCHEMA_VERSION_KEY = "cf_agents:mcp_schema_version";
1095
- const CURRENT_MCP_SCHEMA_VERSION = 1;
1096
- /**
1097
- * A Durable Object capability that persists and aggregates MCP client
1098
- * connections. Install it on any Lifecycle, or use `agent.mcp` on an Agent.
1099
- */
1100
- var MCPClientManager = class extends LifecycleCapability {
1101
- /**
1102
- * Construct a reusable Durable Object MCP client capability.
1103
- *
1104
- * @param _name - MCP client implementation name sent during negotiation.
1105
- * @param _version - MCP client implementation version sent during negotiation.
1106
- * @param options - Optional runtime bindings and OAuth configuration.
1107
- */
1108
- constructor(_name, _version, options = {}) {
1109
- super("mcp");
1110
- this._name = _name;
1111
- this._version = _version;
1112
- this.mcpConnections = {};
1113
- this._aiToolSchemas = /* @__PURE__ */ new WeakMap();
1114
- this._didWarnAboutUnstableGetAITools = false;
1115
- this._connectionDisposables = /* @__PURE__ */ new Map();
1116
- this._isRestored = false;
1117
- this._pendingConnections = /* @__PURE__ */ new Map();
1118
- this._onObservabilityEvent = new Emitter();
1119
- this.onObservabilityEvent = this._onObservabilityEvent.event;
1120
- this._onServerStateChanged = new Emitter();
1121
- this.onServerStateChanged = this._onServerStateChanged.event;
1122
- this._env = options.env;
1123
- this._createAuthProviderFn = options.createAuthProvider;
1124
- }
1125
- /** Restore persisted HTTP and RPC connections before the host handles work. */
1126
- async onStart() {
1127
- if ((await this.lifecycle.storage.get(MCP_SCHEMA_VERSION_KEY) ?? 0) < CURRENT_MCP_SCHEMA_VERSION) {
1128
- ensureMcpServerTable(this.lifecycle.storage);
1129
- await this.lifecycle.storage.put(MCP_SCHEMA_VERSION_KEY, CURRENT_MCP_SCHEMA_VERSION);
1130
- }
1131
- await this.restoreConnectionsFromStorage(this._name);
1132
- await restoreRpcConnections(this, this._env, this.getRpcServersFromStorage());
1133
- this._onServerStateChanged.fire();
1134
- }
1135
- /** Intercept a registered MCP OAuth callback request. */
1136
- async onRequest(context) {
1137
- const { request } = context;
1138
- if (!this.isCallbackRequest(request)) return void 0;
1139
- const result = await this.handleCallbackRequest(request);
1140
- if (result.authSuccess) this.establishConnection(result.serverId).catch((error) => {
1141
- console.error("[MCPClientManager] Connection establishment after OAuth failed:", error);
1142
- });
1143
- return this.oauthCallbackResponse(result, request);
1144
- }
1145
- oauthCallbackResponse(result, request) {
1146
- const config = this.getOAuthCallbackConfig();
1147
- if (config?.customHandler) return config.customHandler(result);
1148
- const baseOrigin = new URL(request.url).origin;
1149
- const redirect = result.authSuccess ? config?.successRedirect : config?.errorRedirect;
1150
- if (!redirect) return Response.redirect(baseOrigin);
1151
- try {
1152
- const target = new URL(redirect, baseOrigin);
1153
- if (!result.authSuccess) target.searchParams.set("error", result.authError);
1154
- return Response.redirect(target);
1155
- } catch (error) {
1156
- console.error("Invalid OAuth callback redirect URL:", redirect, error);
1157
- return Response.redirect(baseOrigin);
1158
- }
1159
- }
1160
- /**
1161
- * Scope the manager-level elicitation handler to a single connection.
1162
- * Returns undefined when no handler is configured so the connection keeps
1163
- * its default throwing behavior.
1164
- */
1165
- scopedElicitationHandlers(serverId) {
1166
- const handlers = this._elicitationHandlers;
1167
- if (!handlers) return void 0;
1168
- const form = handlers.form;
1169
- const url = handlers.url;
1170
- return {
1171
- form: form ? (request, signal) => signal ? form(request, serverId, signal) : form(request, serverId) : void 0,
1172
- url: url ? (request, signal) => signal ? url(request, serverId, signal) : url(request, serverId) : void 0
1173
- };
1174
- }
1175
- sql(query, ...bindings) {
1176
- return [...this.lifecycle.storage.sql.exec(query, ...bindings)];
1177
- }
1178
- saveServerToStorage(server) {
1179
- this.sql(`INSERT OR REPLACE INTO cf_agents_mcp_servers (
1180
- id, name, server_url, client_id, auth_url, callback_url, server_options
1181
- ) VALUES (?, ?, ?, ?, ?, ?, ?)`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
1182
- }
1183
- removeServerFromStorage(serverId) {
1184
- this.sql("DELETE FROM cf_agents_mcp_servers WHERE id = ?", serverId);
1185
- }
1186
- /**
1187
- * Rename a server's id, in-place, across every place the id is used as a
1188
- * key. Used to JIT-migrate servers that were originally registered under an
1189
- * auto-generated nanoid to a caller-supplied stable id (see
1190
- * `Agent.addMcpServer`'s `{ id }` option).
1191
- *
1192
- * Migrates:
1193
- * - the `cf_agents_mcp_servers` row (primary key)
1194
- * - the in-memory `mcpConnections` map key
1195
- * - the connection disposables map key
1196
- * - the attached `authProvider.serverId`, if any
1197
- * - OAuth-related storage keys under `/{clientName}/{oldId}/...`
1198
- *
1199
- * Safe to call when no OAuth keys exist (RPC / bearer-token HTTP servers).
1200
- * If `oldId === newId` this is a no-op. If a row already exists under
1201
- * `newId`, throws — the caller is expected to have verified uniqueness.
1202
- *
1203
- * @internal Exposed for `Agent.addMcpServer` JIT-migration.
1204
- */
1205
- async migrateServerId(oldId, newId, clientName) {
1206
- if (oldId === newId) return;
1207
- while (true) {
1208
- const pending = this._pendingConnections.get(oldId);
1209
- if (!pending) break;
1210
- await pending.catch(() => {});
1211
- }
1212
- if (this.sql("SELECT id FROM cf_agents_mcp_servers WHERE id = ?", oldId).length === 0) {
1213
- this._renameInMemoryConnection(oldId, newId);
1214
- return;
1215
- }
1216
- if (this.sql("SELECT id FROM cf_agents_mcp_servers WHERE id = ?", newId).length > 0) throw new Error(`Cannot migrate MCP server id "${oldId}" → "${newId}": new id is already in use.`);
1217
- this.sql("UPDATE cf_agents_mcp_servers SET id = ? WHERE id = ?", newId, oldId);
1218
- const oldPrefix = `/${clientName}/${oldId}/`;
1219
- const newPrefix = `/${clientName}/${newId}/`;
1220
- try {
1221
- const keys = await this.lifecycle.storage.list({ prefix: oldPrefix });
1222
- if (keys.size > 0) {
1223
- const writes = {};
1224
- const deletes = [];
1225
- for (const [oldKey, value] of keys) {
1226
- const newKey = newPrefix + oldKey.slice(oldPrefix.length);
1227
- writes[newKey] = value;
1228
- deletes.push(oldKey);
1229
- }
1230
- await this.lifecycle.storage.put(writes);
1231
- await this.lifecycle.storage.delete(deletes);
1232
- }
1233
- } catch (error) {
1234
- console.warn(`[MCPClientManager] OAuth key migration ${oldPrefix} → ${newPrefix} failed:`, error);
1235
- }
1236
- this._renameInMemoryConnection(oldId, newId);
1237
- this._onServerStateChanged.fire();
1238
- }
1239
- _renameInMemoryConnection(oldId, newId) {
1240
- if (oldId === newId) return;
1241
- const conn = this.mcpConnections[oldId];
1242
- if (conn) {
1243
- this.mcpConnections[newId] = conn;
1244
- delete this.mcpConnections[oldId];
1245
- const authProvider = conn.options.transport.authProvider;
1246
- if (authProvider) authProvider.serverId = newId;
1247
- const scoped = this.scopedElicitationHandlers(newId);
1248
- if (scoped) conn.configureElicitationHandlers(scoped);
1249
- }
1250
- const disposables = this._connectionDisposables.get(oldId);
1251
- if (disposables) {
1252
- this._connectionDisposables.set(newId, disposables);
1253
- this._connectionDisposables.delete(oldId);
1254
- }
1255
- }
1256
- getServersFromStorage() {
1257
- return this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers");
1258
- }
1259
- filterConnections(filter) {
1260
- if (!filter) return this.mcpConnections;
1261
- const serverIds = filter.serverId ? Array.isArray(filter.serverId) ? filter.serverId : [filter.serverId] : void 0;
1262
- const serverNames = filter.serverName ? Array.isArray(filter.serverName) ? filter.serverName : [filter.serverName] : void 0;
1263
- const states = filter.state ? Array.isArray(filter.state) ? filter.state : [filter.state] : void 0;
1264
- let nameMatchedIds;
1265
- if (serverNames) {
1266
- const servers = this.getServersFromStorage();
1267
- nameMatchedIds = new Set(servers.filter((s) => serverNames.includes(s.name)).map((s) => s.id));
1268
- }
1269
- return Object.fromEntries(Object.entries(this.mcpConnections).filter(([id, conn]) => {
1270
- if (serverIds && !serverIds.includes(id)) return false;
1271
- if (nameMatchedIds && !nameMatchedIds.has(id)) return false;
1272
- if (states && !states.includes(conn.connectionState)) return false;
1273
- return true;
1274
- }));
1275
- }
1276
- /**
1277
- * Get the parsed server_options for a stored server, if any.
1278
- */
1279
- getStoredServerOptions(serverId) {
1280
- const rows = this.sql("SELECT server_options FROM cf_agents_mcp_servers WHERE id = ?", serverId);
1281
- if (!rows.length || !rows[0].server_options) return void 0;
1282
- return decodeMcpServerOptions(rows[0].server_options);
1283
- }
1284
- /**
1285
- * Clear the capabilities persisted on a stored server row. Called once a
1286
- * seeded connection's handshake completes (see `createConnection`): the
1287
- * stamp is valid for one successful restore — sessions that configure
1288
- * handlers re-stamp every row, so a deploy that stops configuring them
1289
- * stops advertising stale modes after its first connected wake instead of
1290
- * forever, while wakes that never handshake don't burn the stamp.
1291
- */
1292
- clearStoredCapabilities(serverId) {
1293
- const row = this.sql("SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers WHERE id = ?", serverId)[0];
1294
- if (!row?.server_options) return;
1295
- const options = decodeMcpServerOptions(row.server_options);
1296
- if (!options.capabilities) return;
1297
- options.capabilities = void 0;
1298
- this.saveServerToStorage({
1299
- ...row,
1300
- server_options: encodeMcpServerOptions(options)
1301
- });
1302
- }
1303
- /**
1304
- * Get the retry options for a server from stored server_options
1305
- */
1306
- getServerRetryOptions(serverId) {
1307
- return this.getStoredServerOptions(serverId)?.retry;
1308
- }
1309
- clearServerAuthUrl(serverId) {
1310
- this.sql("UPDATE cf_agents_mcp_servers SET auth_url = NULL WHERE id = ?", serverId);
1311
- }
1312
- updateStoredSession(id, sessionId, protocolVersion, discoverResult) {
1313
- const serverRow = this.getServersFromStorage().find((server) => server.id === id);
1314
- if (!serverRow) return;
1315
- const options = decodeMcpServerOptions(serverRow.server_options);
1316
- const next = sessionId && protocolVersion ? withMcpSession(options, {
1317
- id: sessionId,
1318
- protocolVersion,
1319
- discoverResult
1320
- }) : withMcpSession(options);
1321
- this.saveServerToStorage({
1322
- ...serverRow,
1323
- server_options: encodeMcpServerOptions(next)
1324
- });
1325
- }
1326
- failConnection(serverId, error) {
1327
- this.clearServerAuthUrl(serverId);
1328
- if (this.mcpConnections[serverId]) {
1329
- this.mcpConnections[serverId].connectionState = MCPConnectionState.FAILED;
1330
- this.mcpConnections[serverId].connectionError = error;
1331
- }
1332
- this._onServerStateChanged.fire();
1333
- return {
1334
- serverId,
1335
- authSuccess: false,
1336
- authError: error
1337
- };
1338
- }
1339
- isAuthAcceptedConnection(conn) {
1340
- return conn.connectionState === MCPConnectionState.READY || conn.connectionState === MCPConnectionState.CONNECTED || conn.connectionState === MCPConnectionState.CONNECTING || conn.connectionState === MCPConnectionState.DISCOVERING;
1341
- }
1342
- oauthCallbackSuccess(serverId, conn) {
1343
- this.clearServerAuthUrl(serverId);
1344
- conn.connectionError = null;
1345
- return {
1346
- serverId,
1347
- authSuccess: true
1348
- };
1349
- }
1350
- async runWithCodeVerifierState(authProvider, state, callback) {
1351
- if (authProvider.runWithCodeVerifierState) return authProvider.runWithCodeVerifierState(state, callback);
1352
- return callback();
1353
- }
1354
- async hasRedeemableOAuthState(serverId, authProvider, state) {
1355
- authProvider.serverId = serverId;
1356
- try {
1357
- return (await authProvider.checkState(state)).valid;
1358
- } catch {
1359
- return false;
1360
- }
1361
- }
1362
- ignoreUnverifiedCallback(serverId, error) {
1363
- console.warn(`[MCPClientManager] Ignoring OAuth callback with unverified state for server "${serverId}": ${error}`);
1364
- return {
1365
- serverId,
1366
- authSuccess: false,
1367
- authError: error
1368
- };
1369
- }
1370
- async consumeStaleOAuthState(serverId, authProvider, state) {
1371
- try {
1372
- const stateValidation = await authProvider.checkState(state);
1373
- if (!stateValidation.valid) {
1374
- console.warn(`[MCPClientManager] Ignoring stale OAuth callback with invalid state for server "${serverId}": ${stateValidation.error ?? "Invalid state"}`);
1375
- return;
1376
- }
1377
- await authProvider.consumeState(state);
1378
- } catch (cleanupError) {
1379
- console.warn(`[MCPClientManager] Failed to clean up stale OAuth callback state for server "${serverId}":`, cleanupError);
1380
- }
1381
- }
1382
- async completeAuthorizationAndCleanupVerifier(serverId, conn, authProvider, state, callbackParams) {
1383
- await this.runWithCodeVerifierState(authProvider, state, async () => {
1384
- let completeError;
1385
- let cleanupError;
1386
- try {
1387
- await conn.completeAuthorization(callbackParams, { alreadyAccepted: true });
1388
- } catch (error) {
1389
- completeError = error;
1390
- }
1391
- try {
1392
- await authProvider.deleteCodeVerifier();
1393
- } catch (deleteError) {
1394
- cleanupError = deleteError;
1395
- }
1396
- if (completeError) {
1397
- if (cleanupError) console.warn(`[MCPClientManager] Failed to clean up OAuth code verifier for server "${serverId}":`, cleanupError);
1398
- throw completeError;
1399
- }
1400
- if (cleanupError) throw cleanupError;
1401
- });
1402
- }
1403
- /**
1404
- * Create an auth provider for a server
1405
- * @internal
1406
- */
1407
- createAuthProvider(serverId, callbackUrl, clientName, clientId) {
1408
- const authProvider = new DurableObjectOAuthClientProvider(this.lifecycle.storage, clientName, callbackUrl);
1409
- authProvider.serverId = serverId;
1410
- if (clientId) authProvider.clientId = clientId;
1411
- return authProvider;
1412
- }
1413
- /** Get saved RPC servers from storage (servers with `rpc://` URLs). */
1414
- getRpcServersFromStorage() {
1415
- return this.getServersFromStorage().filter((s) => s.server_url.startsWith(RPC_DO_PREFIX));
1416
- }
1417
- /**
1418
- * Save an RPC server to storage for hibernation recovery.
1419
- * The binding name is stored so this manager can resolve the namespace from
1420
- * its runtime environment during restore.
1421
- */
1422
- saveRpcServerToStorage(id, name, normalizedName, bindingName, props) {
1423
- this.saveServerToStorage({
1424
- id,
1425
- name,
1426
- server_url: `${RPC_DO_PREFIX}${normalizedName}`,
1427
- client_id: null,
1428
- auth_url: null,
1429
- callback_url: "",
1430
- server_options: encodeMcpServerOptions({
1431
- bindingName,
1432
- props,
1433
- capabilities: this.advertisedHandlerCapabilities()
1434
- })
1435
- });
1436
- }
1437
- /**
1438
- * Restore persisted HTTP MCP connections.
1439
- *
1440
- * @param clientName - Durable Object identity used to scope OAuth state.
1441
- */
1442
- async restoreConnectionsFromStorage(clientName) {
1443
- if (this._isRestored) return;
1444
- const servers = this.getServersFromStorage();
1445
- if (!servers || servers.length === 0) {
1446
- this._isRestored = true;
1447
- return;
1448
- }
1449
- for (const server of servers) {
1450
- if (server.server_url.startsWith("rpc:")) continue;
1451
- const existingConn = this.mcpConnections[server.id];
1452
- if (existingConn) {
1453
- if (existingConn.connectionState === MCPConnectionState.READY) {
1454
- console.warn(`[MCPClientManager] Server ${server.id} already has a ready connection. Skipping recreation.`);
1455
- continue;
1456
- }
1457
- if (existingConn.connectionState === MCPConnectionState.AUTHENTICATING || existingConn.connectionState === MCPConnectionState.CONNECTING || existingConn.connectionState === MCPConnectionState.DISCOVERING) continue;
1458
- if (existingConn.connectionState === MCPConnectionState.FAILED) try {
1459
- await existingConn.close();
1460
- } catch (error) {
1461
- console.warn(`[MCPClientManager] Error closing failed connection ${server.id}:`, error);
1462
- } finally {
1463
- this.cleanupClosedConnection(server.id);
1464
- }
1465
- }
1466
- const parsedOptions = decodeMcpServerOptions(server.server_options);
1467
- let authProvider;
1468
- if (server.callback_url) {
1469
- authProvider = this._createAuthProviderFn ? this._createAuthProviderFn(server.callback_url) : this.createAuthProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0);
1470
- authProvider.serverId = server.id;
1471
- if (server.client_id) authProvider.clientId = server.client_id;
1472
- }
1473
- const conn = this.createConnection(server.id, server.server_url, {
1474
- client: parsedOptions?.client ?? {},
1475
- transport: {
1476
- ...parsedOptions?.transport ?? {},
1477
- type: parsedOptions?.transport?.type ?? "auto",
1478
- authProvider
1479
- },
1480
- discoverResult: parsedOptions?.discoverResult
1481
- });
1482
- if (server.auth_url) {
1483
- conn.connectionState = MCPConnectionState.AUTHENTICATING;
1484
- continue;
1485
- }
1486
- this._trackConnection(server.id, this._restoreServer(server.id, parsedOptions?.retry));
1487
- }
1488
- this._isRestored = true;
1489
- }
1490
- /**
1491
- * Track a pending connection promise for a server.
1492
- * The promise is removed from the map when it settles.
1493
- */
1494
- _trackConnection(serverId, promise) {
1495
- const tracked = promise.finally(() => {
1496
- if (this._pendingConnections.get(serverId) === tracked) this._pendingConnections.delete(serverId);
1497
- });
1498
- this._pendingConnections.set(serverId, tracked);
1499
- }
1500
- /**
1501
- * Wait for all in-flight connection and discovery operations to settle.
1502
- * This is useful when you need MCP tools to be available before proceeding,
1503
- * e.g. before calling getAITools() after the agent wakes from hibernation.
1504
- *
1505
- * Returns once every pending connection has either connected and discovered,
1506
- * failed, or timed out. Never rejects.
1507
- *
1508
- * @param options.timeout - Maximum time in milliseconds to wait.
1509
- * `0` returns immediately without waiting.
1510
- * `undefined` (default) waits indefinitely.
1511
- */
1512
- async waitForConnections(options) {
1513
- if (this._pendingConnections.size === 0) return;
1514
- if (options?.timeout != null && options.timeout <= 0) return;
1515
- const settled = Promise.allSettled(this._pendingConnections.values());
1516
- if (options?.timeout != null && options.timeout > 0) {
1517
- let timerId;
1518
- const timer = new Promise((resolve) => {
1519
- timerId = setTimeout(resolve, options.timeout);
1520
- });
1521
- await Promise.race([settled, timer]);
1522
- clearTimeout(timerId);
1523
- } else await settled;
1524
- }
1525
- async _connectWithRetry(serverId, retry) {
1526
- const maxAttempts = retry?.maxAttempts ?? 3;
1527
- const baseDelayMs = retry?.baseDelayMs ?? 500;
1528
- const maxDelayMs = retry?.maxDelayMs ?? 5e3;
1529
- try {
1530
- return await tryN(maxAttempts, async () => {
1531
- const result = await this.connectToServer(serverId);
1532
- if (result.state === MCPConnectionState.FAILED) throw new ConnectRetryError(result);
1533
- return result;
1534
- }, {
1535
- baseDelayMs,
1536
- maxDelayMs
1537
- });
1538
- } catch (error) {
1539
- if (error instanceof ConnectRetryError) return error.result;
1540
- throw error;
1541
- }
1542
- }
1543
- /**
1544
- * Internal method to restore a single server connection and discovery
1545
- */
1546
- async _restoreServer(serverId, retry) {
1547
- if ((await this._connectWithRetry(serverId, retry).catch((error) => {
1548
- console.error(`Error connecting to ${serverId}:`, error);
1549
- return null;
1550
- }))?.state === MCPConnectionState.CONNECTED) {
1551
- const discoverResult = await this.discoverIfConnected(serverId);
1552
- if (discoverResult && !discoverResult.success) console.error(`Error discovering ${serverId}:`, discoverResult.error);
1553
- }
1554
- }
1555
- /**
1556
- * Connect to and register an MCP server
1557
- *
1558
- * @deprecated This method is maintained for backward compatibility.
1559
- * For new code, use registerServer() and connectToServer() separately.
1560
- *
1561
- * @param url Server URL
1562
- * @param options Connection options
1563
- * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
1564
- */
1565
- async connect(url, options = {}) {
1566
- const id = options.reconnect?.id ?? nanoid(8);
1567
- if (options.transport?.authProvider) {
1568
- options.transport.authProvider.serverId = id;
1569
- if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
1570
- }
1571
- if (isBlockedUrl(url)) throw new Error(`Blocked URL: ${url} — MCP client connections to private/internal addresses are not allowed`);
1572
- if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
1573
- const replaced = this.mcpConnections[id];
1574
- if (replaced) {
1575
- delete this.mcpConnections[id];
1576
- await replaced.close().catch(() => {});
1577
- this.updateStoredSession(id, void 0);
1578
- }
1579
- this.createConnection(id, url, {
1580
- client: options.client,
1581
- transport: options.transport ?? {}
1582
- });
1583
- }
1584
- await this.mcpConnections[id].init();
1585
- if (options.reconnect?.oauthCode) try {
1586
- const authProvider = this.mcpConnections[id].options.transport.authProvider;
1587
- let completeError;
1588
- try {
1589
- await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
1590
- } catch (error) {
1591
- completeError = error;
1592
- }
1593
- try {
1594
- await authProvider?.deleteCodeVerifier();
1595
- } catch (cleanupError) {
1596
- console.warn(`[MCPClientManager] Failed to clean up OAuth code verifier for server "${id}":`, cleanupError);
1597
- }
1598
- if (completeError) throw completeError;
1599
- await this.mcpConnections[id].init();
1600
- } catch (error) {
1601
- this._onObservabilityEvent.fire({
1602
- type: "mcp:client:connect",
1603
- payload: {
1604
- url,
1605
- transport: options.transport?.type ?? "auto",
1606
- state: this.mcpConnections[id].connectionState,
1607
- error: toErrorMessage(error)
1608
- },
1609
- timestamp: Date.now()
1610
- });
1611
- throw error;
1612
- }
1613
- const authUrl = options.transport?.authProvider?.authUrl;
1614
- if (this.mcpConnections[id].connectionState === MCPConnectionState.AUTHENTICATING && authUrl && options.transport?.authProvider?.redirectUrl) return {
1615
- authUrl,
1616
- clientId: options.transport?.authProvider?.clientId,
1617
- id
1618
- };
1619
- const discoverResult = await this.discoverIfConnected(id);
1620
- if (discoverResult && !discoverResult.success) throw new Error(`Failed to discover server capabilities: ${discoverResult.error}`);
1621
- return { id };
1622
- }
1623
- /**
1624
- * Create an in-memory connection object and set up observability
1625
- * Does NOT save to storage - use registerServer() for that
1626
- * @returns The connection object (existing or newly created)
1627
- */
1628
- createConnection(id, url, options) {
1629
- if (this.mcpConnections[id]) return this.mcpConnections[id];
1630
- const normalizedTransport = {
1631
- ...options.transport,
1632
- type: options.transport?.type ?? "auto"
1633
- };
1634
- const capabilitySeed = this.getStoredServerOptions(id)?.capabilities;
1635
- this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
1636
- name: this._name,
1637
- version: this._version
1638
- }, {
1639
- client: options.client ?? {},
1640
- transport: normalizedTransport,
1641
- elicitationHandlers: this.scopedElicitationHandlers(id),
1642
- capabilitySeed,
1643
- discoverResult: options.discoverResult
1644
- });
1645
- const store = new DisposableStore();
1646
- const existing = this._connectionDisposables.get(id);
1647
- if (existing) existing.dispose();
1648
- this._connectionDisposables.set(id, store);
1649
- store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
1650
- this._onObservabilityEvent.fire(event);
1651
- }));
1652
- store.add(this.mcpConnections[id].onListChanged(() => {
1653
- this._onServerStateChanged.fire();
1654
- }));
1655
- if (capabilitySeed) {
1656
- const conn = this.mcpConnections[id];
1657
- const seedClear = conn.onObservabilityEvent((event) => {
1658
- if (event.type !== "mcp:client:connect" || event.payload.state !== MCPConnectionState.CONNECTED) return;
1659
- seedClear.dispose();
1660
- if (this._elicitationHandlers || !conn.options.capabilitySeed) return;
1661
- const currentId = Object.keys(this.mcpConnections).find((key) => this.mcpConnections[key] === conn);
1662
- if (currentId) this.clearStoredCapabilities(currentId);
1663
- });
1664
- store.add(seedClear);
1665
- }
1666
- return this.mcpConnections[id];
1667
- }
1668
- /**
1669
- * Register an MCP server connection without connecting
1670
- * Creates the connection object, sets up observability, and saves to storage
1671
- *
1672
- * @param id Server ID
1673
- * @param options Registration options including URL, name, callback URL, and connection config
1674
- * @returns Server ID
1675
- */
1676
- async registerServer(id, options) {
1677
- if (isBlockedUrl(options.url)) throw new Error(`Blocked URL: ${options.url} — MCP client connections to private/internal addresses are not allowed`);
1678
- const authProvider = options.transport?.authProvider ?? (options.callbackUrl ? this._createAuthProviderFn?.(options.callbackUrl) ?? this.createAuthProvider(id, options.callbackUrl, this._name, options.clientId) : void 0);
1679
- if (authProvider) {
1680
- authProvider.serverId = id;
1681
- if (options.clientId) authProvider.clientId = options.clientId;
1682
- }
1683
- this.createConnection(id, options.url, {
1684
- client: options.client,
1685
- transport: {
1686
- ...options.transport,
1687
- authProvider,
1688
- type: options.transport?.type ?? "auto"
1689
- }
1690
- });
1691
- this.saveServerToStorage({
1692
- id,
1693
- name: options.name,
1694
- server_url: options.url,
1695
- callback_url: options.callbackUrl ?? "",
1696
- client_id: options.clientId ?? null,
1697
- auth_url: options.authUrl ?? null,
1698
- server_options: encodeMcpServerOptions({
1699
- client: options.client,
1700
- transport: options.transport,
1701
- retry: options.retry,
1702
- capabilities: this.advertisedHandlerCapabilities()
1703
- })
1704
- });
1705
- this._onServerStateChanged.fire();
1706
- return id;
1707
- }
1708
- /** Persist and emit an OAuth continuation produced by connect or discovery. */
1709
- persistAuthContinuation(id, conn) {
1710
- const authProvider = conn.options.transport.authProvider;
1711
- const authUrl = authProvider?.authUrl;
1712
- if (!authUrl || !authProvider.redirectUrl) return void 0;
1713
- const clientId = authProvider.clientId;
1714
- const serverRow = this.getServersFromStorage().find((s) => s.id === id);
1715
- if (serverRow) this.saveServerToStorage({
1716
- ...serverRow,
1717
- auth_url: authUrl,
1718
- client_id: clientId ?? null
1719
- });
1720
- this._onObservabilityEvent.fire({
1721
- type: "mcp:client:authorize",
1722
- payload: {
1723
- serverId: id,
1724
- authUrl,
1725
- clientId
1726
- },
1727
- timestamp: Date.now()
1728
- });
1729
- return {
1730
- authUrl,
1731
- clientId
1732
- };
1733
- }
1734
- /**
1735
- * Connect to an already registered MCP server and initialize the connection.
1736
- *
1737
- * For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
1738
- * The user must complete the OAuth flow via the authUrl, which triggers a
1739
- * callback handled by `handleCallbackRequest()`.
1740
- *
1741
- * For non-OAuth servers, establishes the transport connection and returns
1742
- * `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
1743
- * discover capabilities and transition to "ready" state.
1744
- *
1745
- * @param id Server ID (must be registered first via registerServer())
1746
- * @returns Connection result with current state and OAuth info (if applicable)
1747
- */
1748
- async connectToServer(id) {
1749
- const conn = this.mcpConnections[id];
1750
- if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
1751
- const error = await conn.init();
1752
- this.updateStoredSession(id, conn.sessionId, conn.protocolVersion, conn.discoverResult);
1753
- this._onServerStateChanged.fire();
1754
- switch (conn.connectionState) {
1755
- case MCPConnectionState.FAILED: return {
1756
- state: conn.connectionState,
1757
- error: error ?? "Unknown connection error"
1758
- };
1759
- case MCPConnectionState.AUTHENTICATING: {
1760
- const auth = this.persistAuthContinuation(id, conn);
1761
- if (!auth) {
1762
- const provider = conn.options.transport.authProvider;
1763
- return {
1764
- state: MCPConnectionState.FAILED,
1765
- error: `OAuth configuration incomplete: missing ${!provider?.authUrl ? "authUrl" : "redirectUrl"}`
1766
- };
1767
- }
1768
- this._onServerStateChanged.fire();
1769
- return {
1770
- state: conn.connectionState,
1771
- ...auth
1772
- };
1773
- }
1774
- case MCPConnectionState.CONNECTED: return { state: conn.connectionState };
1775
- default: return {
1776
- state: MCPConnectionState.FAILED,
1777
- error: `Unexpected connection state after init: ${conn.connectionState}`
1778
- };
1779
- }
1780
- }
1781
- extractServerIdFromState(state) {
1782
- if (!state) return null;
1783
- const parts = state.split(".");
1784
- return parts.length === 2 ? parts[1] : null;
1785
- }
1786
- isCallbackRequest(req) {
1787
- if (req.method !== "GET") return false;
1788
- const url = new URL(req.url);
1789
- const state = url.searchParams.get("state");
1790
- const serverId = this.extractServerIdFromState(state);
1791
- if (!serverId) return false;
1792
- return this.getServersFromStorage().some((server) => {
1793
- if (server.id !== serverId) return false;
1794
- try {
1795
- const storedUrl = new URL(server.callback_url);
1796
- return storedUrl.origin === url.origin && storedUrl.pathname === url.pathname;
1797
- } catch {
1798
- return false;
1799
- }
1800
- });
1801
- }
1802
- validateCallbackRequest(req) {
1803
- const url = new URL(req.url);
1804
- const code = url.searchParams.get("code");
1805
- const state = url.searchParams.get("state");
1806
- const error = url.searchParams.get("error");
1807
- if (!state) return {
1808
- valid: false,
1809
- error: "Unauthorized: no state provided"
1810
- };
1811
- const serverId = this.extractServerIdFromState(state);
1812
- if (!serverId) return {
1813
- valid: false,
1814
- error: "No serverId found in state parameter. Expected format: {nonce}.{serverId}"
1815
- };
1816
- if (!code && !error) return {
1817
- serverId,
1818
- state,
1819
- valid: false,
1820
- error: "Unauthorized: no code provided"
1821
- };
1822
- if (!this.getServersFromStorage().some((server) => server.id === serverId)) return {
1823
- serverId,
1824
- valid: false,
1825
- error: `No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`
1826
- };
1827
- if (this.mcpConnections[serverId] === void 0) return {
1828
- serverId,
1829
- valid: false,
1830
- error: `No connection found for serverId "${serverId}".`
1831
- };
1832
- return {
1833
- valid: true,
1834
- serverId,
1835
- state,
1836
- callbackParams: url.searchParams
1837
- };
1838
- }
1839
- async handleCallbackRequest(req) {
1840
- const validation = this.validateCallbackRequest(req);
1841
- if (!validation.valid) {
1842
- const conn = validation.serverId ? this.mcpConnections[validation.serverId] : void 0;
1843
- if (validation.serverId && conn) {
1844
- if (this.isAuthAcceptedConnection(conn)) {
1845
- const authProvider = conn.options.transport.authProvider;
1846
- if (validation.state && authProvider) {
1847
- authProvider.serverId = validation.serverId;
1848
- await this.consumeStaleOAuthState(validation.serverId, authProvider, validation.state);
1849
- }
1850
- return this.oauthCallbackSuccess(validation.serverId, conn);
1851
- }
1852
- const authProvider = conn.options.transport.authProvider;
1853
- if (validation.state && authProvider && !await this.hasRedeemableOAuthState(validation.serverId, authProvider, validation.state)) return this.ignoreUnverifiedCallback(validation.serverId, validation.error);
1854
- return this.failConnection(validation.serverId, validation.error);
1855
- }
1856
- return {
1857
- serverId: validation.serverId,
1858
- authSuccess: false,
1859
- authError: validation.error
1860
- };
1861
- }
1862
- const { serverId, state, callbackParams } = validation;
1863
- const conn = this.mcpConnections[serverId];
1864
- try {
1865
- if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
1866
- const authProvider = conn.options.transport.authProvider;
1867
- authProvider.serverId = serverId;
1868
- const stateValidation = await authProvider.checkState(state);
1869
- if (!stateValidation.valid) {
1870
- if (this.isAuthAcceptedConnection(conn)) {
1871
- await this.consumeStaleOAuthState(serverId, authProvider, state);
1872
- return this.oauthCallbackSuccess(serverId, conn);
1873
- }
1874
- return this.ignoreUnverifiedCallback(serverId, callbackParams.get("error_description") ?? callbackParams.get("error") ?? stateValidation.error ?? "Invalid state");
1875
- }
1876
- if (this.isAuthAcceptedConnection(conn)) {
1877
- await this.consumeStaleOAuthState(serverId, authProvider, state);
1878
- return this.oauthCallbackSuccess(serverId, conn);
1879
- }
1880
- if (conn.connectionState !== MCPConnectionState.AUTHENTICATING && conn.connectionState !== MCPConnectionState.FAILED) throw new Error(`Failed to authenticate from "${conn.connectionState}" state`);
1881
- conn.connectionState = MCPConnectionState.CONNECTING;
1882
- await authProvider.consumeState(state);
1883
- await this.completeAuthorizationAndCleanupVerifier(serverId, conn, authProvider, state, callbackParams);
1884
- this.updateStoredSession(serverId, conn.sessionId, conn.protocolVersion, conn.discoverResult);
1885
- const result = this.oauthCallbackSuccess(serverId, conn);
1886
- this._onServerStateChanged.fire();
1887
- return result;
1888
- } catch (err) {
1889
- const message = err instanceof Error ? err.message : String(err);
1890
- return this.failConnection(serverId, message);
1891
- }
1892
- }
1893
- /**
1894
- * Discover server capabilities if connection is in CONNECTED or READY state.
1895
- * Transitions to DISCOVERING then READY (or CONNECTED on error).
1896
- * Can be called to refresh server capabilities (e.g., from a UI refresh button).
1897
- *
1898
- * If called while a previous discovery is in-flight for the same server,
1899
- * the previous discovery will be aborted.
1900
- *
1901
- * @param serverId The server ID to discover
1902
- * @param options Optional configuration
1903
- * @param options.timeoutMs Timeout in milliseconds (default: 30000)
1904
- * @returns Result with current state and optional error, or undefined if connection not found
1905
- */
1906
- async discoverIfConnected(serverId, options = {}) {
1907
- const conn = this.mcpConnections[serverId];
1908
- if (!conn) {
1909
- this._onObservabilityEvent.fire({
1910
- type: "mcp:client:discover",
1911
- payload: {},
1912
- timestamp: Date.now()
1913
- });
1914
- return;
1915
- }
1916
- const result = await conn.discover(options);
1917
- if (!result.success && result.reason === "stale-session") return this._recoverStaleSession(conn, serverId, options);
1918
- if (conn.connectionState === MCPConnectionState.AUTHENTICATING) this.persistAuthContinuation(serverId, conn);
1919
- this._onServerStateChanged.fire();
1920
- return this._toDiscoverResult(conn, result);
1921
- }
1922
- _toDiscoverResult(conn, result) {
1923
- return result.success ? {
1924
- success: true,
1925
- state: conn.connectionState
1926
- } : {
1927
- success: false,
1928
- error: result.error,
1929
- state: conn.connectionState
1930
- };
1931
- }
1932
- async _recoverStaleSession(conn, serverId, options) {
1933
- conn.clearResumedSession();
1934
- this.updateStoredSession(serverId, void 0);
1935
- let connectResult;
1936
- try {
1937
- connectResult = await this.connectToServer(serverId);
1938
- } catch (error) {
1939
- return {
1940
- success: false,
1941
- error: toErrorMessage(error),
1942
- state: conn.connectionState
1943
- };
1944
- }
1945
- if (connectResult.state !== MCPConnectionState.CONNECTED) return {
1946
- success: false,
1947
- error: connectResult.state === MCPConnectionState.FAILED ? connectResult.error : `Connection in ${connectResult.state} state after session re-initialization`,
1948
- state: conn.connectionState
1949
- };
1950
- const result = await conn.discover(options);
1951
- this._onServerStateChanged.fire();
1952
- return this._toDiscoverResult(conn, result);
1953
- }
1954
- /**
1955
- * Establish connection in the background after OAuth completion.
1956
- * This method connects to the server and discovers its capabilities.
1957
- * The connection is automatically tracked so that `waitForConnections()`
1958
- * will include it.
1959
- * @param serverId The server ID to establish connection for
1960
- */
1961
- async establishConnection(serverId) {
1962
- const promise = this._doEstablishConnection(serverId);
1963
- this._trackConnection(serverId, promise);
1964
- return promise;
1965
- }
1966
- async _doEstablishConnection(serverId) {
1967
- const conn = this.mcpConnections[serverId];
1968
- if (!conn) {
1969
- this._onObservabilityEvent.fire({
1970
- type: "mcp:client:preconnect",
1971
- payload: { serverId },
1972
- timestamp: Date.now()
1973
- });
1974
- return;
1975
- }
1976
- if (conn.connectionState === MCPConnectionState.DISCOVERING || conn.connectionState === MCPConnectionState.READY) {
1977
- this._onObservabilityEvent.fire({
1978
- type: "mcp:client:connect",
1979
- payload: {
1980
- url: conn.url.toString(),
1981
- transport: conn.options.transport.type || "unknown",
1982
- state: conn.connectionState
1983
- },
1984
- timestamp: Date.now()
1985
- });
1986
- return;
1987
- }
1988
- const retry = this.getServerRetryOptions(serverId);
1989
- const connectResult = await this._connectWithRetry(serverId, retry);
1990
- this._onServerStateChanged.fire();
1991
- if (connectResult.state === MCPConnectionState.CONNECTED) await this.discoverIfConnected(serverId);
1992
- this._onObservabilityEvent.fire({
1993
- type: "mcp:client:connect",
1994
- payload: {
1995
- url: conn.url.toString(),
1996
- transport: conn.options.transport.type || "unknown",
1997
- state: conn.connectionState
1998
- },
1999
- timestamp: Date.now()
2000
- });
2001
- }
2002
- /**
2003
- * Configure OAuth callback handling
2004
- * @param config OAuth callback configuration
2005
- */
2006
- configureOAuthCallback(config) {
2007
- this._oauthCallbackConfig = config;
2008
- }
2009
- /**
2010
- * Configure handling for server-initiated `elicitation/create` requests.
2011
- *
2012
- * The handler is held in memory only and applied to every MCP connection
2013
- * created or restored by this manager. Call this before registering
2014
- * connections when you want the initial MCP handshake to advertise
2015
- * handler-driven form- and url-mode elicitation. Existing active connections
2016
- * keep their negotiated capabilities until they reconnect.
2017
- *
2018
- * The advertised modes are persisted with each stored server, so
2019
- * connections restored after hibernation re-advertise them at the handshake
2020
- * even when this is called later in the wake-up (e.g. from onStart) — the
2021
- * handlers attach to the live connections as soon as this runs.
2022
- *
2023
- * Pass undefined to clear the handler.
2024
- *
2025
- * @param handlers Elicitation handlers keyed by mode, each scoped with the server id that sent the request
2026
- */
2027
- configureElicitationHandlers(handlers) {
2028
- this._elicitationHandlers = handlers && (handlers.form || handlers.url) ? handlers : void 0;
2029
- this.persistAdvertisedCapabilities();
2030
- for (const [id, connection] of Object.entries(this.mcpConnections)) connection.configureElicitationHandlers(this.scopedElicitationHandlers(id));
2031
- }
2032
- /** Client capabilities advertised from the currently configured handlers. */
2033
- advertisedHandlerCapabilities() {
2034
- const elicitation = elicitationCapabilitiesFromHandlers(this._elicitationHandlers);
2035
- return elicitation ? { elicitation } : void 0;
2036
- }
2037
- /**
2038
- * Record the handler-derived capabilities on every stored server row so a
2039
- * restore after hibernation re-advertises them before the handlers
2040
- * themselves are reconfigured.
2041
- */
2042
- persistAdvertisedCapabilities() {
2043
- const capabilities = this.advertisedHandlerCapabilities();
2044
- for (const server of this.getServersFromStorage()) {
2045
- const options = decodeMcpServerOptions(server.server_options);
2046
- if (JSON.stringify(options.capabilities) === JSON.stringify(capabilities)) continue;
2047
- options.capabilities = capabilities;
2048
- this.saveServerToStorage({
2049
- ...server,
2050
- server_options: encodeMcpServerOptions(options)
2051
- });
2052
- }
2053
- }
2054
- /**
2055
- * Get the current OAuth callback configuration
2056
- * @returns The current OAuth callback configuration
2057
- */
2058
- getOAuthCallbackConfig() {
2059
- return this._oauthCallbackConfig;
2060
- }
2061
- /**
2062
- * @param filter - Optional filter to scope results to specific servers
2063
- * @returns namespaced list of tools
2064
- */
2065
- listTools(filter) {
2066
- return getNamespacedData(this.filterConnections(filter), "tools");
2067
- }
2068
- /**
2069
- * Convert connected MCP tools for the AI SDK. Converted schemas are reused
2070
- * while a live connection retains the same catalog array and schema-source
2071
- * identities; tool records and execute closures are rebuilt on every call.
2072
- *
2073
- * @param filter - Optional filter to scope results to specific servers
2074
- * @returns a set of tools that you can use with the AI SDK
2075
- */
2076
- getAITools(filter) {
2077
- const connections = this.filterConnections(filter);
2078
- const entries = [];
2079
- for (const [serverId, conn] of Object.entries(connections)) {
2080
- if (conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) console.warn(`[getAITools] WARNING: Reading tools from connection ${serverId} in state "${conn.connectionState}". Tools may not be loaded yet.`);
2081
- const catalog = conn.tools;
2082
- let cache = this._aiToolSchemas.get(conn);
2083
- if (!cache || cache.catalog !== catalog) {
2084
- cache = {
2085
- catalog,
2086
- converted: []
2087
- };
2088
- this._aiToolSchemas.set(conn, cache);
2089
- }
2090
- for (const [index, tool] of catalog.entries()) {
2091
- const toolName = tool.name;
2092
- try {
2093
- const sourceInputSchema = tool.inputSchema;
2094
- const sourceOutputSchema = tool.outputSchema;
2095
- let slot = cache.converted[index];
2096
- if (!slot || slot.tool !== tool || slot.inputSchema !== sourceInputSchema || slot.outputSchema !== sourceOutputSchema) {
2097
- try {
2098
- slot = {
2099
- status: "converted",
2100
- tool,
2101
- inputSchema: sourceInputSchema,
2102
- outputSchema: sourceOutputSchema,
2103
- converted: {
2104
- inputSchema: sourceInputSchema ? z.fromJSONSchema(sourceInputSchema) : z.fromJSONSchema({ type: "object" }),
2105
- outputSchema: sourceOutputSchema ? z.fromJSONSchema(sourceOutputSchema) : void 0
2106
- }
2107
- };
2108
- } catch (error) {
2109
- const errorText = String(error);
2110
- cache.converted[index] = {
2111
- status: "failed",
2112
- tool,
2113
- inputSchema: sourceInputSchema,
2114
- outputSchema: sourceOutputSchema,
2115
- error: errorText
2116
- };
2117
- console.warn(`[getAITools] Skipping tool "${toolName}" from "${serverId}": ${errorText}`);
2118
- continue;
2119
- }
2120
- cache.converted[index] = slot;
2121
- }
2122
- if (slot.status === "failed") continue;
2123
- const toolKey = `tool_${serverId.replace(/-/g, "")}_${toolName}`;
2124
- const title = tool.title ?? tool.annotations?.title;
2125
- const description = tool.description;
2126
- entries.push([toolKey, {
2127
- description,
2128
- title,
2129
- execute: async (args) => {
2130
- const result = await this.callTool({
2131
- arguments: args,
2132
- name: toolName,
2133
- serverId
2134
- });
2135
- if (result.isError) {
2136
- const textContent = result.content?.[0];
2137
- const message = textContent?.type === "text" && textContent.text ? textContent.text : "Tool call failed";
2138
- throw new Error(message);
2139
- }
2140
- return result;
2141
- },
2142
- inputSchema: slot.converted.inputSchema,
2143
- outputSchema: slot.converted.outputSchema
2144
- }]);
2145
- } catch (error) {
2146
- console.warn(`[getAITools] Skipping tool "${toolName}" from "${serverId}": ${error}`);
2147
- }
2148
- }
2149
- cache.converted.length = catalog.length;
2150
- }
2151
- return Object.fromEntries(entries);
2152
- }
2153
- /**
2154
- * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
2155
- * @param filter - Optional filter to scope results to specific servers
2156
- * @returns a set of tools that you can use with the AI SDK
2157
- */
2158
- unstable_getAITools(filter) {
2159
- if (!this._didWarnAboutUnstableGetAITools) {
2160
- this._didWarnAboutUnstableGetAITools = true;
2161
- console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
2162
- }
2163
- return this.getAITools(filter);
2164
- }
2165
- /**
2166
- * Closes all active in-memory connections to MCP servers.
2167
- *
2168
- * Note: This only closes the transport connections - it does NOT remove
2169
- * servers from storage. Servers will still be listed and their callback
2170
- * URLs will still match incoming OAuth requests.
2171
- *
2172
- * Use removeServer() instead if you want to fully clean up a server
2173
- * (closes connection AND removes from storage).
2174
- */
2175
- cleanupClosedConnection(id) {
2176
- this.updateStoredSession(id, void 0);
2177
- const store = this._connectionDisposables.get(id);
2178
- if (store) store.dispose();
2179
- this._connectionDisposables.delete(id);
2180
- delete this.mcpConnections[id];
2181
- }
2182
- async closeAllConnections() {
2183
- const ids = Object.keys(this.mcpConnections);
2184
- this._pendingConnections.clear();
2185
- for (const id of ids) this.mcpConnections[id].cancelDiscovery();
2186
- const errors = (await Promise.allSettled(ids.map(async (id) => {
2187
- try {
2188
- await this.mcpConnections[id].close();
2189
- } finally {
2190
- this.cleanupClosedConnection(id);
2191
- }
2192
- }))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2193
- if (errors.length === 1) throw errors[0];
2194
- if (errors.length > 1) throw new AggregateError(errors, "Failed to close one or more MCP connections");
2195
- }
2196
- /**
2197
- * Closes a connection to an MCP server
2198
- * @param id The id of the connection to close
2199
- */
2200
- async closeConnection(id) {
2201
- const connection = this.mcpConnections[id];
2202
- if (!connection) throw new Error(`Connection with id "${id}" does not exist.`);
2203
- connection.cancelDiscovery();
2204
- this._pendingConnections.delete(id);
2205
- try {
2206
- await connection.close();
2207
- } finally {
2208
- this.cleanupClosedConnection(id);
2209
- }
2210
- }
2211
- /**
2212
- * Remove an MCP server - closes connection if active and removes from storage.
2213
- */
2214
- async removeServer(serverId) {
2215
- const connection = this.mcpConnections[serverId];
2216
- let authProvider = connection?.options.transport.authProvider;
2217
- if (!authProvider) try {
2218
- authProvider = this.authProviderFromStorage(serverId);
2219
- } catch (error) {
2220
- console.warn(`[MCPClientManager] Failed to create auth provider for ${serverId}:`, error);
2221
- }
2222
- if (connection) try {
2223
- await this.closeConnection(serverId);
2224
- } catch (_e) {}
2225
- try {
2226
- if (authProvider instanceof DurableObjectOAuthClientProvider) await authProvider.clearServerStorage();
2227
- else await authProvider?.invalidateCredentials?.("all");
2228
- } catch (error) {
2229
- console.warn(`[MCPClientManager] Failed to clear OAuth credentials for ${serverId}:`, error);
2230
- }
2231
- this.removeServerFromStorage(serverId);
2232
- this._onServerStateChanged.fire();
2233
- }
2234
- /**
2235
- * Rebuild a server's auth provider from its stored row, as restore does,
2236
- * for a server with no live connection.
2237
- */
2238
- authProviderFromStorage(serverId) {
2239
- const server = this.getServersFromStorage().find((s) => s.id === serverId);
2240
- if (!server?.callback_url) return void 0;
2241
- const authProvider = this._createAuthProviderFn ? this._createAuthProviderFn(server.callback_url) : this.createAuthProvider(server.id, server.callback_url, this._name, server.client_id ?? void 0);
2242
- authProvider.serverId = server.id;
2243
- if (server.client_id) authProvider.clientId = server.client_id;
2244
- return authProvider;
2245
- }
2246
- /**
2247
- * List all MCP servers from storage
2248
- */
2249
- listServers() {
2250
- return this.getServersFromStorage();
2251
- }
2252
- /**
2253
- * Dispose the manager and all resources.
2254
- */
2255
- async dispose() {
2256
- try {
2257
- await this.closeAllConnections();
2258
- } finally {
2259
- this._onServerStateChanged.dispose();
2260
- this._onObservabilityEvent.dispose();
2261
- }
2262
- }
2263
- /**
2264
- * @param filter - Optional filter to scope results to specific servers
2265
- * @returns namespaced list of prompts
2266
- */
2267
- listPrompts(filter) {
2268
- return getNamespacedData(this.filterConnections(filter), "prompts");
2269
- }
2270
- /**
2271
- * @param filter - Optional filter to scope results to specific servers
2272
- * @returns namespaced list of resources
2273
- */
2274
- listResources(filter) {
2275
- return getNamespacedData(this.filterConnections(filter), "resources");
2276
- }
2277
- /**
2278
- * @param filter - Optional filter to scope results to specific servers
2279
- * @returns namespaced list of resource templates
2280
- */
2281
- listResourceTemplates(filter) {
2282
- return getNamespacedData(this.filterConnections(filter), "resourceTemplates");
2283
- }
2284
- async callTool(params, schemaOrOptions, options) {
2285
- const { serverId, ...mcpParams } = params;
2286
- const unqualifiedName = mcpParams.name.replace(`${serverId}.`, "");
2287
- return callV2Tool(this.mcpConnections[serverId].client, {
2288
- ...mcpParams,
2289
- name: unqualifiedName
2290
- }, schemaOrOptions, options);
2291
- }
2292
- /**
2293
- * Namespaced version of readResource
2294
- */
2295
- readResource(params, options) {
2296
- const { serverId, ...mcpParams } = params;
2297
- return this.mcpConnections[serverId].client.readResource(mcpParams, options);
2298
- }
2299
- /**
2300
- * Namespaced version of getPrompt
2301
- */
2302
- getPrompt(params, options) {
2303
- const { serverId, ...mcpParams } = params;
2304
- return this.mcpConnections[serverId].client.getPrompt(mcpParams, options);
2305
- }
2306
- };
2307
- function getNamespacedData(mcpClients, type) {
2308
- return Object.entries(mcpClients).map(([name, conn]) => {
2309
- return {
2310
- data: conn[type],
2311
- name
2312
- };
2313
- }).flatMap(({ name: serverId, data }) => {
2314
- return data.map((item) => {
2315
- return {
2316
- ...item,
2317
- serverId
2318
- };
2319
- });
2320
- });
2321
- }
2322
- //#endregion
2323
- export { ensureMcpServerTable as a, RPCClientTransport as c, normalizeServerId as i, RPC_DO_PREFIX as l, MCP_SERVER_ID_MAX_LENGTH as n, MCPConnectionState as o, getNamespacedData as r, DisposableStore as s, MCPClientManager as t, isDurableObjectNamespace as u };
2324
-
2325
- //# sourceMappingURL=client-DMWujQJ1.js.map