agents 0.2.9 → 0.2.11

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 (94) hide show
  1. package/dist/ai-chat-agent.d.ts +15 -18
  2. package/dist/ai-chat-agent.js +544 -656
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  6. package/dist/ai-chat-v5-migration.d.ts +7 -4
  7. package/dist/ai-chat-v5-migration.js +3 -20
  8. package/dist/ai-react.d.ts +14 -24
  9. package/dist/ai-react.js +257 -343
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-B0GBFDwi.js +20 -0
  12. package/dist/ai-types-B0GBFDwi.js.map +1 -0
  13. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  14. package/dist/ai-types.d.ts +6 -92
  15. package/dist/ai-types.js +3 -8
  16. package/dist/client-C-u-lCFT.d.ts +5311 -0
  17. package/dist/client-CmMi85Sj.d.ts +104 -0
  18. package/dist/client-WbaRgKYN.js +788 -0
  19. package/dist/client-WbaRgKYN.js.map +1 -0
  20. package/dist/client-zS-OCVJA.js +117 -0
  21. package/dist/client-zS-OCVJA.js.map +1 -0
  22. package/dist/client.d.ts +11 -92
  23. package/dist/client.js +4 -13
  24. package/dist/codemode/ai.d.ts +19 -17
  25. package/dist/codemode/ai.js +90 -5139
  26. package/dist/codemode/ai.js.map +1 -1
  27. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  29. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  30. package/dist/index-DWcUTPtX.d.ts +558 -0
  31. package/dist/index-W4JUkafc.d.ts +54 -0
  32. package/dist/index.d.ts +55 -542
  33. package/dist/index.js +7 -32
  34. package/dist/mcp/client.d.ts +4 -12
  35. package/dist/mcp/client.js +3 -10
  36. package/dist/mcp/do-oauth-client-provider.d.ts +2 -42
  37. package/dist/mcp/do-oauth-client-provider.js +3 -8
  38. package/dist/mcp/index.d.ts +72 -76
  39. package/dist/mcp/index.js +830 -1082
  40. package/dist/mcp/index.js.map +1 -1
  41. package/dist/mcp/x402.d.ts +22 -27
  42. package/dist/mcp/x402.js +186 -3187
  43. package/dist/mcp/x402.js.map +1 -1
  44. package/dist/{mcp-BH1fJeiU.d.ts → mcp-BEwaCsxO.d.ts} +6 -3
  45. package/dist/observability/index.d.ts +3 -34
  46. package/dist/observability/index.js +7 -12
  47. package/dist/react-B8BT6PYZ.d.ts +113 -0
  48. package/dist/react.d.ts +10 -127
  49. package/dist/react.js +173 -200
  50. package/dist/react.js.map +1 -1
  51. package/dist/schedule.d.ts +13 -10
  52. package/dist/schedule.js +43 -33
  53. package/dist/schedule.js.map +1 -1
  54. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  55. package/dist/serializable.d.ts +7 -32
  56. package/dist/serializable.js +1 -1
  57. package/dist/src-C9xZ0CrH.js +1179 -0
  58. package/dist/src-C9xZ0CrH.js.map +1 -0
  59. package/package.json +9 -3
  60. package/dist/_esm-LV5FJ3HK.js +0 -3922
  61. package/dist/_esm-LV5FJ3HK.js.map +0 -1
  62. package/dist/ai-chat-v5-migration.js.map +0 -1
  63. package/dist/ai-types.js.map +0 -1
  64. package/dist/ccip-CMBYN64O.js +0 -15
  65. package/dist/ccip-CMBYN64O.js.map +0 -1
  66. package/dist/chunk-5Y6BEZDY.js +0 -276
  67. package/dist/chunk-5Y6BEZDY.js.map +0 -1
  68. package/dist/chunk-BER7KXUJ.js +0 -18
  69. package/dist/chunk-BER7KXUJ.js.map +0 -1
  70. package/dist/chunk-C2OEBJZ2.js +0 -113
  71. package/dist/chunk-C2OEBJZ2.js.map +0 -1
  72. package/dist/chunk-JJBFIGUC.js +0 -5202
  73. package/dist/chunk-JJBFIGUC.js.map +0 -1
  74. package/dist/chunk-PR4QN5HX.js +0 -43
  75. package/dist/chunk-PR4QN5HX.js.map +0 -1
  76. package/dist/chunk-QEVM4BVL.js +0 -116
  77. package/dist/chunk-QEVM4BVL.js.map +0 -1
  78. package/dist/chunk-TYAY6AU6.js +0 -159
  79. package/dist/chunk-TYAY6AU6.js.map +0 -1
  80. package/dist/chunk-UJVEAURM.js +0 -150
  81. package/dist/chunk-UJVEAURM.js.map +0 -1
  82. package/dist/chunk-XGMKNUJA.js +0 -1343
  83. package/dist/chunk-XGMKNUJA.js.map +0 -1
  84. package/dist/chunk-ZMMHNOMZ.js +0 -942
  85. package/dist/chunk-ZMMHNOMZ.js.map +0 -1
  86. package/dist/client-C8tswVoM.d.ts +0 -5248
  87. package/dist/client.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/mcp/client.js.map +0 -1
  90. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  91. package/dist/observability/index.js.map +0 -1
  92. package/dist/secp256k1-M22GZP2U.js +0 -2193
  93. package/dist/secp256k1-M22GZP2U.js.map +0 -1
  94. package/dist/serializable.js.map +0 -1
@@ -1,942 +0,0 @@
1
- // src/mcp/client.ts
2
- import { jsonSchema } from "ai";
3
- import { nanoid as nanoid2 } from "nanoid";
4
-
5
- // src/core/events.ts
6
- function toDisposable(fn) {
7
- return { dispose: fn };
8
- }
9
- var DisposableStore = class {
10
- constructor() {
11
- this._items = [];
12
- }
13
- add(d) {
14
- this._items.push(d);
15
- return d;
16
- }
17
- dispose() {
18
- while (this._items.length) {
19
- try {
20
- this._items.pop().dispose();
21
- } catch {
22
- }
23
- }
24
- }
25
- };
26
- var Emitter = class {
27
- constructor() {
28
- this._listeners = /* @__PURE__ */ new Set();
29
- this.event = (listener) => {
30
- this._listeners.add(listener);
31
- return toDisposable(() => this._listeners.delete(listener));
32
- };
33
- }
34
- fire(data) {
35
- for (const listener of [...this._listeners]) {
36
- try {
37
- listener(data);
38
- } catch (err) {
39
- console.error("Emitter listener error:", err);
40
- }
41
- }
42
- }
43
- dispose() {
44
- this._listeners.clear();
45
- }
46
- };
47
-
48
- // src/mcp/client-connection.ts
49
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
50
- import {
51
- ElicitRequestSchema,
52
- PromptListChangedNotificationSchema,
53
- ResourceListChangedNotificationSchema,
54
- ToolListChangedNotificationSchema
55
- } from "@modelcontextprotocol/sdk/types.js";
56
- import { nanoid } from "nanoid";
57
-
58
- // src/mcp/errors.ts
59
- function toErrorMessage(error) {
60
- return error instanceof Error ? error.message : String(error);
61
- }
62
- function isUnauthorized(error) {
63
- const msg = toErrorMessage(error);
64
- return msg.includes("Unauthorized") || msg.includes("401");
65
- }
66
- function isTransportNotImplemented(error) {
67
- const msg = toErrorMessage(error);
68
- return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
69
- }
70
-
71
- // src/mcp/sse-edge.ts
72
- import {
73
- SSEClientTransport
74
- } from "@modelcontextprotocol/sdk/client/sse.js";
75
- var SSEEdgeClientTransport = class extends SSEClientTransport {
76
- /**
77
- * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
78
- */
79
- constructor(url, options) {
80
- const fetchOverride = async (fetchUrl, fetchInit = {}) => {
81
- const headers = await this.authHeaders();
82
- const workerOptions = {
83
- ...fetchInit,
84
- headers: {
85
- ...options.requestInit?.headers,
86
- ...fetchInit?.headers,
87
- ...headers
88
- }
89
- };
90
- delete workerOptions.mode;
91
- return options.eventSourceInit?.fetch?.(
92
- fetchUrl,
93
- // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit
94
- workerOptions
95
- ) || fetch(fetchUrl, workerOptions);
96
- };
97
- super(url, {
98
- ...options,
99
- eventSourceInit: {
100
- ...options.eventSourceInit,
101
- fetch: fetchOverride
102
- }
103
- });
104
- this.authProvider = options.authProvider;
105
- }
106
- async authHeaders() {
107
- if (this.authProvider) {
108
- const tokens = await this.authProvider.tokens();
109
- if (tokens) {
110
- return {
111
- Authorization: `Bearer ${tokens.access_token}`
112
- };
113
- }
114
- }
115
- }
116
- };
117
-
118
- // src/mcp/streamable-http-edge.ts
119
- import {
120
- StreamableHTTPClientTransport
121
- } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
122
- var StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {
123
- /**
124
- * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
125
- */
126
- constructor(url, options) {
127
- const fetchOverride = async (fetchUrl, fetchInit = {}) => {
128
- const headers = await this.authHeaders();
129
- const workerOptions = {
130
- ...fetchInit,
131
- headers: {
132
- ...options.requestInit?.headers,
133
- ...fetchInit?.headers,
134
- ...headers
135
- }
136
- };
137
- delete workerOptions.mode;
138
- return (
139
- // @ts-expect-error Custom fetch function for Cloudflare Workers compatibility
140
- options.requestInit?.fetch?.(
141
- fetchUrl,
142
- workerOptions
143
- ) || fetch(fetchUrl, workerOptions)
144
- );
145
- };
146
- super(url, {
147
- ...options,
148
- requestInit: {
149
- ...options.requestInit,
150
- // @ts-expect-error Custom fetch override for Cloudflare Workers
151
- fetch: fetchOverride
152
- }
153
- });
154
- this.authProvider = options.authProvider;
155
- }
156
- async authHeaders() {
157
- if (this.authProvider) {
158
- const tokens = await this.authProvider.tokens();
159
- if (tokens) {
160
- return {
161
- Authorization: `Bearer ${tokens.access_token}`
162
- };
163
- }
164
- }
165
- }
166
- };
167
-
168
- // src/mcp/client-connection.ts
169
- var MCPClientConnection = class {
170
- constructor(url, info, options = { client: {}, transport: {} }) {
171
- this.url = url;
172
- this.options = options;
173
- this.connectionState = "connecting";
174
- this.tools = [];
175
- this.prompts = [];
176
- this.resources = [];
177
- this.resourceTemplates = [];
178
- this._onObservabilityEvent = new Emitter();
179
- this.onObservabilityEvent = this._onObservabilityEvent.event;
180
- const clientOptions = {
181
- ...options.client,
182
- capabilities: {
183
- ...options.client?.capabilities,
184
- elicitation: {}
185
- }
186
- };
187
- this.client = new Client(info, clientOptions);
188
- }
189
- /**
190
- * Initialize a client connection
191
- *
192
- * @returns
193
- */
194
- async init() {
195
- const transportType = this.options.transport.type;
196
- if (!transportType) {
197
- throw new Error("Transport type must be specified");
198
- }
199
- try {
200
- await this.tryConnect(transportType);
201
- } catch (e) {
202
- if (isUnauthorized(e)) {
203
- this.connectionState = "authenticating";
204
- return;
205
- }
206
- this._onObservabilityEvent.fire({
207
- type: "mcp:client:connect",
208
- displayMessage: `Connection initialization failed for ${this.url.toString()}`,
209
- payload: {
210
- url: this.url.toString(),
211
- transport: transportType,
212
- state: this.connectionState,
213
- error: toErrorMessage(e)
214
- },
215
- timestamp: Date.now(),
216
- id: nanoid()
217
- });
218
- this.connectionState = "failed";
219
- return;
220
- }
221
- await this.discoverAndRegister();
222
- }
223
- /**
224
- * Finish OAuth by probing transports based on configured type.
225
- * - Explicit: finish on that transport
226
- * - Auto: try streamable-http, then sse on 404/405/Not Implemented
227
- */
228
- async finishAuthProbe(code) {
229
- if (!this.options.transport.authProvider) {
230
- throw new Error("No auth provider configured");
231
- }
232
- const configuredType = this.options.transport.type;
233
- if (!configuredType) {
234
- throw new Error("Transport type must be specified");
235
- }
236
- const finishAuth = async (base) => {
237
- const transport = this.getTransport(base);
238
- await transport.finishAuth(code);
239
- };
240
- if (configuredType === "sse" || configuredType === "streamable-http") {
241
- await finishAuth(configuredType);
242
- return;
243
- }
244
- try {
245
- await finishAuth("streamable-http");
246
- } catch (e) {
247
- if (isTransportNotImplemented(e)) {
248
- await finishAuth("sse");
249
- return;
250
- }
251
- throw e;
252
- }
253
- }
254
- /**
255
- * Complete OAuth authorization
256
- */
257
- async completeAuthorization(code) {
258
- if (this.connectionState !== "authenticating") {
259
- throw new Error(
260
- "Connection must be in authenticating state to complete authorization"
261
- );
262
- }
263
- try {
264
- await this.finishAuthProbe(code);
265
- this.connectionState = "connecting";
266
- } catch (error) {
267
- this.connectionState = "failed";
268
- throw error;
269
- }
270
- }
271
- /**
272
- * Establish connection after successful authorization
273
- */
274
- async establishConnection() {
275
- if (this.connectionState !== "connecting") {
276
- throw new Error(
277
- "Connection must be in connecting state to establish connection"
278
- );
279
- }
280
- try {
281
- const transportType = this.options.transport.type;
282
- if (!transportType) {
283
- throw new Error("Transport type must be specified");
284
- }
285
- await this.tryConnect(transportType);
286
- await this.discoverAndRegister();
287
- } catch (error) {
288
- this.connectionState = "failed";
289
- throw error;
290
- }
291
- }
292
- /**
293
- * Discover server capabilities and register tools, resources, prompts, and templates
294
- */
295
- async discoverAndRegister() {
296
- this.connectionState = "discovering";
297
- this.serverCapabilities = this.client.getServerCapabilities();
298
- if (!this.serverCapabilities) {
299
- throw new Error("The MCP Server failed to return server capabilities");
300
- }
301
- const [
302
- instructionsResult,
303
- toolsResult,
304
- resourcesResult,
305
- promptsResult,
306
- resourceTemplatesResult
307
- ] = await Promise.allSettled([
308
- this.client.getInstructions(),
309
- this.registerTools(),
310
- this.registerResources(),
311
- this.registerPrompts(),
312
- this.registerResourceTemplates()
313
- ]);
314
- const operations = [
315
- { name: "instructions", result: instructionsResult },
316
- { name: "tools", result: toolsResult },
317
- { name: "resources", result: resourcesResult },
318
- { name: "prompts", result: promptsResult },
319
- { name: "resource templates", result: resourceTemplatesResult }
320
- ];
321
- for (const { name, result } of operations) {
322
- if (result.status === "rejected") {
323
- const url = this.url.toString();
324
- this._onObservabilityEvent.fire({
325
- type: "mcp:client:discover",
326
- displayMessage: `Failed to discover ${name} for ${url}`,
327
- payload: {
328
- url,
329
- capability: name,
330
- error: result.reason
331
- },
332
- timestamp: Date.now(),
333
- id: nanoid()
334
- });
335
- }
336
- }
337
- this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
338
- this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
339
- this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
340
- this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
341
- this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
342
- this.connectionState = "ready";
343
- }
344
- /**
345
- * Notification handler registration
346
- */
347
- async registerTools() {
348
- if (!this.serverCapabilities || !this.serverCapabilities.tools) {
349
- return [];
350
- }
351
- if (this.serverCapabilities.tools.listChanged) {
352
- this.client.setNotificationHandler(
353
- ToolListChangedNotificationSchema,
354
- async (_notification) => {
355
- this.tools = await this.fetchTools();
356
- }
357
- );
358
- }
359
- return this.fetchTools();
360
- }
361
- async registerResources() {
362
- if (!this.serverCapabilities || !this.serverCapabilities.resources) {
363
- return [];
364
- }
365
- if (this.serverCapabilities.resources.listChanged) {
366
- this.client.setNotificationHandler(
367
- ResourceListChangedNotificationSchema,
368
- async (_notification) => {
369
- this.resources = await this.fetchResources();
370
- }
371
- );
372
- }
373
- return this.fetchResources();
374
- }
375
- async registerPrompts() {
376
- if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
377
- return [];
378
- }
379
- if (this.serverCapabilities.prompts.listChanged) {
380
- this.client.setNotificationHandler(
381
- PromptListChangedNotificationSchema,
382
- async (_notification) => {
383
- this.prompts = await this.fetchPrompts();
384
- }
385
- );
386
- }
387
- return this.fetchPrompts();
388
- }
389
- async registerResourceTemplates() {
390
- if (!this.serverCapabilities || !this.serverCapabilities.resources) {
391
- return [];
392
- }
393
- return this.fetchResourceTemplates();
394
- }
395
- async fetchTools() {
396
- let toolsAgg = [];
397
- let toolsResult = { tools: [] };
398
- do {
399
- toolsResult = await this.client.listTools({
400
- cursor: toolsResult.nextCursor
401
- }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
402
- toolsAgg = toolsAgg.concat(toolsResult.tools);
403
- } while (toolsResult.nextCursor);
404
- return toolsAgg;
405
- }
406
- async fetchResources() {
407
- let resourcesAgg = [];
408
- let resourcesResult = { resources: [] };
409
- do {
410
- resourcesResult = await this.client.listResources({
411
- cursor: resourcesResult.nextCursor
412
- }).catch(
413
- this._capabilityErrorHandler({ resources: [] }, "resources/list")
414
- );
415
- resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
416
- } while (resourcesResult.nextCursor);
417
- return resourcesAgg;
418
- }
419
- async fetchPrompts() {
420
- let promptsAgg = [];
421
- let promptsResult = { prompts: [] };
422
- do {
423
- promptsResult = await this.client.listPrompts({
424
- cursor: promptsResult.nextCursor
425
- }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
426
- promptsAgg = promptsAgg.concat(promptsResult.prompts);
427
- } while (promptsResult.nextCursor);
428
- return promptsAgg;
429
- }
430
- async fetchResourceTemplates() {
431
- let templatesAgg = [];
432
- let templatesResult = {
433
- resourceTemplates: []
434
- };
435
- do {
436
- templatesResult = await this.client.listResourceTemplates({
437
- cursor: templatesResult.nextCursor
438
- }).catch(
439
- this._capabilityErrorHandler(
440
- { resourceTemplates: [] },
441
- "resources/templates/list"
442
- )
443
- );
444
- templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
445
- } while (templatesResult.nextCursor);
446
- return templatesAgg;
447
- }
448
- /**
449
- * Handle elicitation request from server
450
- * Automatically uses the Agent's built-in elicitation handling if available
451
- */
452
- async handleElicitationRequest(_request) {
453
- throw new Error(
454
- "Elicitation handler must be implemented for your platform. Override handleElicitationRequest method."
455
- );
456
- }
457
- /**
458
- * Get the transport for the client
459
- * @param transportType - The transport type to get
460
- * @returns The transport for the client
461
- */
462
- getTransport(transportType) {
463
- switch (transportType) {
464
- case "streamable-http":
465
- return new StreamableHTTPEdgeClientTransport(
466
- this.url,
467
- this.options.transport
468
- );
469
- case "sse":
470
- return new SSEEdgeClientTransport(
471
- this.url,
472
- this.options.transport
473
- );
474
- default:
475
- throw new Error(`Unsupported transport type: ${transportType}`);
476
- }
477
- }
478
- async tryConnect(transportType) {
479
- const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
480
- for (const currentTransportType of transports) {
481
- const isLastTransport = currentTransportType === transports[transports.length - 1];
482
- const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
483
- const transport = this.getTransport(currentTransportType);
484
- try {
485
- await this.client.connect(transport);
486
- this.lastConnectedTransport = currentTransportType;
487
- const url = this.url.toString();
488
- this._onObservabilityEvent.fire({
489
- type: "mcp:client:connect",
490
- displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,
491
- payload: {
492
- url,
493
- transport: currentTransportType,
494
- state: this.connectionState
495
- },
496
- timestamp: Date.now(),
497
- id: nanoid()
498
- });
499
- break;
500
- } catch (e) {
501
- const error = e instanceof Error ? e : new Error(String(e));
502
- if (isUnauthorized(error)) {
503
- throw e;
504
- }
505
- if (hasFallback && isTransportNotImplemented(error)) {
506
- const url = this.url.toString();
507
- this._onObservabilityEvent.fire({
508
- type: "mcp:client:connect",
509
- displayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,
510
- payload: {
511
- url,
512
- transport: currentTransportType,
513
- state: this.connectionState
514
- },
515
- timestamp: Date.now(),
516
- id: nanoid()
517
- });
518
- continue;
519
- }
520
- throw e;
521
- }
522
- }
523
- this.client.setRequestHandler(
524
- ElicitRequestSchema,
525
- async (request) => {
526
- return await this.handleElicitationRequest(request);
527
- }
528
- );
529
- }
530
- _capabilityErrorHandler(empty, method) {
531
- return (e) => {
532
- if (e.code === -32601) {
533
- const url = this.url.toString();
534
- this._onObservabilityEvent.fire({
535
- type: "mcp:client:discover",
536
- displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
537
- payload: {
538
- url,
539
- capability: method.split("/")[0],
540
- error: toErrorMessage(e)
541
- },
542
- timestamp: Date.now(),
543
- id: nanoid()
544
- });
545
- return empty;
546
- }
547
- throw e;
548
- };
549
- }
550
- };
551
-
552
- // src/mcp/client.ts
553
- var MCPClientManager = class {
554
- /**
555
- * @param _name Name of the MCP client
556
- * @param _version Version of the MCP Client
557
- * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
558
- */
559
- constructor(_name, _version) {
560
- this._name = _name;
561
- this._version = _version;
562
- this.mcpConnections = {};
563
- this._callbackUrls = [];
564
- this._didWarnAboutUnstableGetAITools = false;
565
- this._connectionDisposables = /* @__PURE__ */ new Map();
566
- this._onObservabilityEvent = new Emitter();
567
- this.onObservabilityEvent = this._onObservabilityEvent.event;
568
- this._onConnected = new Emitter();
569
- this.onConnected = this._onConnected.event;
570
- }
571
- /**
572
- * Connect to and register an MCP server
573
- *
574
- * @param transportConfig Transport config
575
- * @param clientConfig Client config
576
- * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
577
- */
578
- async connect(url, options = {}) {
579
- const id = options.reconnect?.id ?? nanoid2(8);
580
- if (options.transport?.authProvider) {
581
- options.transport.authProvider.serverId = id;
582
- if (options.reconnect?.oauthClientId) {
583
- options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
584
- }
585
- }
586
- if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
587
- const normalizedTransport = {
588
- ...options.transport,
589
- type: options.transport?.type ?? "auto"
590
- };
591
- this.mcpConnections[id] = new MCPClientConnection(
592
- new URL(url),
593
- {
594
- name: this._name,
595
- version: this._version
596
- },
597
- {
598
- client: options.client ?? {},
599
- transport: normalizedTransport
600
- }
601
- );
602
- const store = new DisposableStore();
603
- const existing = this._connectionDisposables.get(id);
604
- if (existing) existing.dispose();
605
- this._connectionDisposables.set(id, store);
606
- store.add(
607
- this.mcpConnections[id].onObservabilityEvent((event) => {
608
- this._onObservabilityEvent.fire(event);
609
- })
610
- );
611
- }
612
- await this.mcpConnections[id].init();
613
- if (options.reconnect?.oauthCode) {
614
- try {
615
- await this.mcpConnections[id].completeAuthorization(
616
- options.reconnect.oauthCode
617
- );
618
- await this.mcpConnections[id].establishConnection();
619
- } catch (error) {
620
- this._onObservabilityEvent.fire({
621
- type: "mcp:client:connect",
622
- displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
623
- payload: {
624
- url,
625
- transport: options.transport?.type ?? "auto",
626
- state: this.mcpConnections[id].connectionState,
627
- error: toErrorMessage(error)
628
- },
629
- timestamp: Date.now(),
630
- id
631
- });
632
- throw error;
633
- }
634
- }
635
- const authUrl = options.transport?.authProvider?.authUrl;
636
- if (this.mcpConnections[id].connectionState === "authenticating" && authUrl && options.transport?.authProvider?.redirectUrl) {
637
- this._callbackUrls.push(
638
- options.transport.authProvider.redirectUrl.toString()
639
- );
640
- return {
641
- authUrl,
642
- clientId: options.transport?.authProvider?.clientId,
643
- id
644
- };
645
- }
646
- return {
647
- id
648
- };
649
- }
650
- isCallbackRequest(req) {
651
- return req.method === "GET" && !!this._callbackUrls.find((url) => {
652
- return req.url.startsWith(url);
653
- });
654
- }
655
- async handleCallbackRequest(req) {
656
- const url = new URL(req.url);
657
- const urlMatch = this._callbackUrls.find((url2) => {
658
- return req.url.startsWith(url2);
659
- });
660
- if (!urlMatch) {
661
- throw new Error(
662
- `No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`
663
- );
664
- }
665
- const code = url.searchParams.get("code");
666
- const state = url.searchParams.get("state");
667
- const urlParams = urlMatch.split("/");
668
- const serverId = urlParams[urlParams.length - 1];
669
- if (!code) {
670
- throw new Error("Unauthorized: no code provided");
671
- }
672
- if (!state) {
673
- throw new Error("Unauthorized: no state provided");
674
- }
675
- if (this.mcpConnections[serverId] === void 0) {
676
- throw new Error(`Could not find serverId: ${serverId}`);
677
- }
678
- if (this.mcpConnections[serverId].connectionState !== "authenticating") {
679
- throw new Error(
680
- "Failed to authenticate: the client isn't in the `authenticating` state"
681
- );
682
- }
683
- const conn = this.mcpConnections[serverId];
684
- if (!conn.options.transport.authProvider) {
685
- throw new Error(
686
- "Trying to finalize authentication for a server connection without an authProvider"
687
- );
688
- }
689
- const clientId = conn.options.transport.authProvider.clientId || state;
690
- conn.options.transport.authProvider.clientId = clientId;
691
- conn.options.transport.authProvider.serverId = serverId;
692
- try {
693
- await conn.completeAuthorization(code);
694
- return {
695
- serverId,
696
- authSuccess: true
697
- };
698
- } catch (error) {
699
- const errorMessage = error instanceof Error ? error.message : String(error);
700
- return {
701
- serverId,
702
- authSuccess: false,
703
- authError: errorMessage
704
- };
705
- }
706
- }
707
- /**
708
- * Establish connection in the background after OAuth completion
709
- * This method is called asynchronously and doesn't block the OAuth callback response
710
- * @param serverId The server ID to establish connection for
711
- */
712
- async establishConnection(serverId) {
713
- const conn = this.mcpConnections[serverId];
714
- if (!conn) {
715
- this._onObservabilityEvent.fire({
716
- type: "mcp:client:preconnect",
717
- displayMessage: `Connection not found for serverId: ${serverId}`,
718
- payload: { serverId },
719
- timestamp: Date.now(),
720
- id: nanoid2()
721
- });
722
- return;
723
- }
724
- try {
725
- await conn.establishConnection();
726
- this._onConnected.fire(serverId);
727
- } catch (error) {
728
- const url = conn.url.toString();
729
- this._onObservabilityEvent.fire({
730
- type: "mcp:client:connect",
731
- displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,
732
- payload: {
733
- url,
734
- transport: conn.options.transport.type ?? "auto",
735
- state: conn.connectionState,
736
- error: toErrorMessage(error)
737
- },
738
- timestamp: Date.now(),
739
- id: nanoid2()
740
- });
741
- }
742
- }
743
- /**
744
- * Register a callback URL for OAuth handling
745
- * @param url The callback URL to register
746
- */
747
- registerCallbackUrl(url) {
748
- if (!this._callbackUrls.includes(url)) {
749
- this._callbackUrls.push(url);
750
- }
751
- }
752
- /**
753
- * Unregister a callback URL
754
- * @param serverId The server ID whose callback URL should be removed
755
- */
756
- unregisterCallbackUrl(serverId) {
757
- this._callbackUrls = this._callbackUrls.filter(
758
- (url) => !url.endsWith(`/${serverId}`)
759
- );
760
- }
761
- /**
762
- * Configure OAuth callback handling
763
- * @param config OAuth callback configuration
764
- */
765
- configureOAuthCallback(config) {
766
- this._oauthCallbackConfig = config;
767
- }
768
- /**
769
- * Get the current OAuth callback configuration
770
- * @returns The current OAuth callback configuration
771
- */
772
- getOAuthCallbackConfig() {
773
- return this._oauthCallbackConfig;
774
- }
775
- /**
776
- * @returns namespaced list of tools
777
- */
778
- listTools() {
779
- return getNamespacedData(this.mcpConnections, "tools");
780
- }
781
- /**
782
- * @returns a set of tools that you can use with the AI SDK
783
- */
784
- getAITools() {
785
- return Object.fromEntries(
786
- getNamespacedData(this.mcpConnections, "tools").map((tool) => {
787
- return [
788
- `tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`,
789
- {
790
- description: tool.description,
791
- execute: async (args) => {
792
- const result = await this.callTool({
793
- arguments: args,
794
- name: tool.name,
795
- serverId: tool.serverId
796
- });
797
- if (result.isError) {
798
- throw new Error(result.content[0].text);
799
- }
800
- return result;
801
- },
802
- // @ts-expect-error drift between ai and mcp types
803
- inputSchema: jsonSchema(tool.inputSchema),
804
- outputSchema: tool.outputSchema ? (
805
- // @ts-expect-error drift between ai and mcp types
806
- jsonSchema(tool.outputSchema)
807
- ) : void 0
808
- }
809
- ];
810
- })
811
- );
812
- }
813
- /**
814
- * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
815
- * @returns a set of tools that you can use with the AI SDK
816
- */
817
- unstable_getAITools() {
818
- if (!this._didWarnAboutUnstableGetAITools) {
819
- this._didWarnAboutUnstableGetAITools = true;
820
- console.warn(
821
- "unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version."
822
- );
823
- }
824
- return this.getAITools();
825
- }
826
- /**
827
- * Closes all connections to MCP servers
828
- */
829
- async closeAllConnections() {
830
- const ids = Object.keys(this.mcpConnections);
831
- await Promise.all(
832
- ids.map(async (id) => {
833
- await this.mcpConnections[id].client.close();
834
- })
835
- );
836
- for (const id of ids) {
837
- const store = this._connectionDisposables.get(id);
838
- if (store) store.dispose();
839
- this._connectionDisposables.delete(id);
840
- delete this.mcpConnections[id];
841
- }
842
- }
843
- /**
844
- * Closes a connection to an MCP server
845
- * @param id The id of the connection to close
846
- */
847
- async closeConnection(id) {
848
- if (!this.mcpConnections[id]) {
849
- throw new Error(`Connection with id "${id}" does not exist.`);
850
- }
851
- await this.mcpConnections[id].client.close();
852
- delete this.mcpConnections[id];
853
- const store = this._connectionDisposables.get(id);
854
- if (store) store.dispose();
855
- this._connectionDisposables.delete(id);
856
- }
857
- /**
858
- * Dispose the manager and all resources.
859
- */
860
- async dispose() {
861
- try {
862
- await this.closeAllConnections();
863
- } finally {
864
- this._onConnected.dispose();
865
- this._onObservabilityEvent.dispose();
866
- }
867
- }
868
- /**
869
- * @returns namespaced list of prompts
870
- */
871
- listPrompts() {
872
- return getNamespacedData(this.mcpConnections, "prompts");
873
- }
874
- /**
875
- * @returns namespaced list of tools
876
- */
877
- listResources() {
878
- return getNamespacedData(this.mcpConnections, "resources");
879
- }
880
- /**
881
- * @returns namespaced list of resource templates
882
- */
883
- listResourceTemplates() {
884
- return getNamespacedData(this.mcpConnections, "resourceTemplates");
885
- }
886
- /**
887
- * Namespaced version of callTool
888
- */
889
- async callTool(params, resultSchema, options) {
890
- const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
891
- return this.mcpConnections[params.serverId].client.callTool(
892
- {
893
- ...params,
894
- name: unqualifiedName
895
- },
896
- resultSchema,
897
- options
898
- );
899
- }
900
- /**
901
- * Namespaced version of readResource
902
- */
903
- readResource(params, options) {
904
- return this.mcpConnections[params.serverId].client.readResource(
905
- params,
906
- options
907
- );
908
- }
909
- /**
910
- * Namespaced version of getPrompt
911
- */
912
- getPrompt(params, options) {
913
- return this.mcpConnections[params.serverId].client.getPrompt(
914
- params,
915
- options
916
- );
917
- }
918
- };
919
- function getNamespacedData(mcpClients, type) {
920
- const sets = Object.entries(mcpClients).map(([name, conn]) => {
921
- return { data: conn[type], name };
922
- });
923
- const namespacedData = sets.flatMap(({ name: serverId, data }) => {
924
- return data.map((item) => {
925
- return {
926
- ...item,
927
- // we add a serverId so we can easily pull it out and send the tool call to the right server
928
- serverId
929
- };
930
- });
931
- });
932
- return namespacedData;
933
- }
934
-
935
- export {
936
- DisposableStore,
937
- SSEEdgeClientTransport,
938
- StreamableHTTPEdgeClientTransport,
939
- MCPClientManager,
940
- getNamespacedData
941
- };
942
- //# sourceMappingURL=chunk-ZMMHNOMZ.js.map