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