agents 0.0.0-fb503ba → 0.0.0-fb62d22

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 (69) hide show
  1. package/README.md +255 -27
  2. package/dist/_esm-LV5FJ3HK.js +3922 -0
  3. package/dist/_esm-LV5FJ3HK.js.map +1 -0
  4. package/dist/ai-chat-agent.d.ts +12 -8
  5. package/dist/ai-chat-agent.js +482 -60
  6. package/dist/ai-chat-agent.js.map +1 -1
  7. package/dist/ai-chat-v5-migration.d.ts +152 -0
  8. package/dist/ai-chat-v5-migration.js +20 -0
  9. package/dist/ai-chat-v5-migration.js.map +1 -0
  10. package/dist/ai-react.d.ts +69 -72
  11. package/dist/ai-react.js +260 -107
  12. package/dist/ai-react.js.map +1 -1
  13. package/dist/ai-types.d.ts +37 -19
  14. package/dist/ai-types.js +7 -0
  15. package/dist/ccip-CMBYN64O.js +15 -0
  16. package/dist/ccip-CMBYN64O.js.map +1 -0
  17. package/dist/chunk-5Y6BEZDY.js +276 -0
  18. package/dist/chunk-5Y6BEZDY.js.map +1 -0
  19. package/dist/chunk-BER7KXUJ.js +18 -0
  20. package/dist/chunk-BER7KXUJ.js.map +1 -0
  21. package/dist/chunk-JJBFIGUC.js +5202 -0
  22. package/dist/chunk-JJBFIGUC.js.map +1 -0
  23. package/dist/chunk-PR4QN5HX.js +43 -0
  24. package/dist/chunk-PR4QN5HX.js.map +1 -0
  25. package/dist/{chunk-OYJXQRRH.js → chunk-QEPGNUG6.js} +230 -45
  26. package/dist/chunk-QEPGNUG6.js.map +1 -0
  27. package/dist/{chunk-VCSB47AK.js → chunk-QEVM4BVL.js} +10 -10
  28. package/dist/chunk-QEVM4BVL.js.map +1 -0
  29. package/dist/chunk-RS5OCNEQ.js +1323 -0
  30. package/dist/chunk-RS5OCNEQ.js.map +1 -0
  31. package/dist/chunk-TYAY6AU6.js +159 -0
  32. package/dist/chunk-TYAY6AU6.js.map +1 -0
  33. package/dist/chunk-UJVEAURM.js +150 -0
  34. package/dist/chunk-UJVEAURM.js.map +1 -0
  35. package/dist/{chunk-BZXOAZUX.js → chunk-XFS5ERG3.js} +27 -6
  36. package/dist/chunk-XFS5ERG3.js.map +1 -0
  37. package/dist/client-DNEb-lf3.d.ts +5041 -0
  38. package/dist/client.d.ts +2 -2
  39. package/dist/client.js +3 -1
  40. package/dist/index.d.ts +186 -26
  41. package/dist/index.js +14 -4
  42. package/dist/mcp/client.d.ts +9 -781
  43. package/dist/mcp/client.js +2 -1
  44. package/dist/mcp/do-oauth-client-provider.d.ts +9 -0
  45. package/dist/mcp/do-oauth-client-provider.js +2 -1
  46. package/dist/mcp/index.d.ts +58 -64
  47. package/dist/mcp/index.js +956 -639
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/x402.d.ts +39 -0
  50. package/dist/mcp/x402.js +3195 -0
  51. package/dist/mcp/x402.js.map +1 -0
  52. package/dist/observability/index.d.ts +46 -0
  53. package/dist/observability/index.js +12 -0
  54. package/dist/observability/index.js.map +1 -0
  55. package/dist/react.d.ts +12 -8
  56. package/dist/react.js +13 -10
  57. package/dist/react.js.map +1 -1
  58. package/dist/schedule.d.ts +81 -7
  59. package/dist/schedule.js +21 -6
  60. package/dist/schedule.js.map +1 -1
  61. package/dist/secp256k1-M22GZP2U.js +2193 -0
  62. package/dist/secp256k1-M22GZP2U.js.map +1 -0
  63. package/package.json +91 -70
  64. package/src/index.ts +923 -190
  65. package/dist/chunk-BZXOAZUX.js.map +0 -1
  66. package/dist/chunk-MXJNY43J.js +0 -785
  67. package/dist/chunk-MXJNY43J.js.map +0 -1
  68. package/dist/chunk-OYJXQRRH.js.map +0 -1
  69. package/dist/chunk-VCSB47AK.js.map +0 -1
@@ -0,0 +1,43 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+
37
+ export {
38
+ __require,
39
+ __commonJS,
40
+ __export,
41
+ __toESM
42
+ };
43
+ //# sourceMappingURL=chunk-PR4QN5HX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,3 +1,16 @@
1
+ // src/mcp/client.ts
2
+ import { jsonSchema } from "ai";
3
+ import { nanoid } from "nanoid";
4
+
5
+ // src/mcp/client-connection.ts
6
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
7
+ import {
8
+ PromptListChangedNotificationSchema,
9
+ ResourceListChangedNotificationSchema,
10
+ ToolListChangedNotificationSchema,
11
+ ElicitRequestSchema
12
+ } from "@modelcontextprotocol/sdk/types.js";
13
+
1
14
  // src/mcp/sse-edge.ts
2
15
  import {
3
16
  SSEClientTransport
@@ -45,15 +58,59 @@ var SSEEdgeClientTransport = class extends SSEClientTransport {
45
58
  }
46
59
  };
47
60
 
48
- // src/mcp/client-connection.ts
61
+ // src/mcp/streamable-http-edge.ts
49
62
  import {
50
- ToolListChangedNotificationSchema,
51
- ResourceListChangedNotificationSchema,
52
- PromptListChangedNotificationSchema
53
- } from "@modelcontextprotocol/sdk/types.js";
54
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
63
+ StreamableHTTPClientTransport
64
+ } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
65
+ var StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {
66
+ /**
67
+ * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment
68
+ */
69
+ constructor(url, options) {
70
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
71
+ const headers = await this.authHeaders();
72
+ const workerOptions = {
73
+ ...fetchInit,
74
+ headers: {
75
+ ...options.requestInit?.headers,
76
+ ...fetchInit?.headers,
77
+ ...headers
78
+ }
79
+ };
80
+ delete workerOptions.mode;
81
+ return (
82
+ // @ts-expect-error Custom fetch function for Cloudflare Workers compatibility
83
+ options.requestInit?.fetch?.(
84
+ fetchUrl,
85
+ workerOptions
86
+ ) || fetch(fetchUrl, workerOptions)
87
+ );
88
+ };
89
+ super(url, {
90
+ ...options,
91
+ requestInit: {
92
+ ...options.requestInit,
93
+ // @ts-expect-error Custom fetch override for Cloudflare Workers
94
+ fetch: fetchOverride
95
+ }
96
+ });
97
+ this.authProvider = options.authProvider;
98
+ }
99
+ async authHeaders() {
100
+ if (this.authProvider) {
101
+ const tokens = await this.authProvider.tokens();
102
+ if (tokens) {
103
+ return {
104
+ Authorization: `Bearer ${tokens.access_token}`
105
+ };
106
+ }
107
+ }
108
+ }
109
+ };
110
+
111
+ // src/mcp/client-connection.ts
55
112
  var MCPClientConnection = class {
56
- constructor(url, info, options = { transport: {}, client: {} }) {
113
+ constructor(url, info, options = { client: {}, transport: {} }) {
57
114
  this.url = url;
58
115
  this.options = options;
59
116
  this.connectionState = "connecting";
@@ -61,7 +118,15 @@ var MCPClientConnection = class {
61
118
  this.prompts = [];
62
119
  this.resources = [];
63
120
  this.resourceTemplates = [];
64
- this.client = new Client(info, options.client);
121
+ this.url = url;
122
+ const clientOptions = {
123
+ ...options.client,
124
+ capabilities: {
125
+ ...options.client?.capabilities,
126
+ elicitation: {}
127
+ }
128
+ };
129
+ this.client = new Client(info, clientOptions);
65
130
  }
66
131
  /**
67
132
  * Initialize a client connection
@@ -71,14 +136,8 @@ var MCPClientConnection = class {
71
136
  */
72
137
  async init(code) {
73
138
  try {
74
- const transport = new SSEEdgeClientTransport(
75
- this.url,
76
- this.options.transport
77
- );
78
- if (code) {
79
- await transport.finishAuth(code);
80
- }
81
- await this.client.connect(transport);
139
+ const transportType = this.options.transport.type || "streamable-http";
140
+ await this.tryConnect(transportType, code);
82
141
  } catch (e) {
83
142
  if (e.toString().includes("Unauthorized")) {
84
143
  this.connectionState = "authenticating";
@@ -92,18 +151,36 @@ var MCPClientConnection = class {
92
151
  if (!this.serverCapabilities) {
93
152
  throw new Error("The MCP Server failed to return server capabilities");
94
153
  }
95
- const [instructions, tools, resources, prompts, resourceTemplates] = await Promise.all([
154
+ const [
155
+ instructionsResult,
156
+ toolsResult,
157
+ resourcesResult,
158
+ promptsResult,
159
+ resourceTemplatesResult
160
+ ] = await Promise.allSettled([
96
161
  this.client.getInstructions(),
97
162
  this.registerTools(),
98
163
  this.registerResources(),
99
164
  this.registerPrompts(),
100
165
  this.registerResourceTemplates()
101
166
  ]);
102
- this.instructions = instructions;
103
- this.tools = tools;
104
- this.resources = resources;
105
- this.prompts = prompts;
106
- this.resourceTemplates = resourceTemplates;
167
+ const operations = [
168
+ { name: "instructions", result: instructionsResult },
169
+ { name: "tools", result: toolsResult },
170
+ { name: "resources", result: resourcesResult },
171
+ { name: "prompts", result: promptsResult },
172
+ { name: "resource templates", result: resourceTemplatesResult }
173
+ ];
174
+ for (const { name, result } of operations) {
175
+ if (result.status === "rejected") {
176
+ console.error(`Failed to initialize ${name}:`, result.reason);
177
+ }
178
+ }
179
+ this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
180
+ this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
181
+ this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
182
+ this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
183
+ this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
107
184
  this.connectionState = "ready";
108
185
  }
109
186
  /**
@@ -208,6 +285,79 @@ var MCPClientConnection = class {
208
285
  } while (templatesResult.nextCursor);
209
286
  return templatesAgg;
210
287
  }
288
+ /**
289
+ * Handle elicitation request from server
290
+ * Automatically uses the Agent's built-in elicitation handling if available
291
+ */
292
+ async handleElicitationRequest(_request) {
293
+ throw new Error(
294
+ "Elicitation handler must be implemented for your platform. Override handleElicitationRequest method."
295
+ );
296
+ }
297
+ /**
298
+ * Get the transport for the client
299
+ * @param transportType - The transport type to get
300
+ * @returns The transport for the client
301
+ */
302
+ getTransport(transportType) {
303
+ switch (transportType) {
304
+ case "streamable-http":
305
+ return new StreamableHTTPEdgeClientTransport(
306
+ this.url,
307
+ this.options.transport
308
+ );
309
+ case "sse":
310
+ return new SSEEdgeClientTransport(
311
+ this.url,
312
+ this.options.transport
313
+ );
314
+ default:
315
+ throw new Error(`Unsupported transport type: ${transportType}`);
316
+ }
317
+ }
318
+ async tryConnect(transportType, code) {
319
+ let effectiveTransportType = transportType;
320
+ if (code && this.options.transport.authProvider) {
321
+ const savedTransport = await this.options.transport.authProvider.getOAuthTransport();
322
+ if (savedTransport) {
323
+ effectiveTransportType = savedTransport;
324
+ }
325
+ }
326
+ const transports = effectiveTransportType === "auto" ? ["streamable-http", "sse"] : [effectiveTransportType];
327
+ for (const currentTransportType of transports) {
328
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
329
+ const hasFallback = effectiveTransportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
330
+ const transport = this.getTransport(currentTransportType);
331
+ if (code) {
332
+ await transport.finishAuth(code);
333
+ }
334
+ try {
335
+ await this.client.connect(transport);
336
+ if (code && this.options.transport.authProvider) {
337
+ await this.options.transport.authProvider.clearOAuthTransport();
338
+ }
339
+ break;
340
+ } catch (e) {
341
+ const error = e instanceof Error ? e : new Error(String(e));
342
+ if (!code && error.message.includes("Unauthorized") && this.options.transport.authProvider && currentTransportType) {
343
+ await this.options.transport.authProvider.saveOAuthTransport(
344
+ currentTransportType
345
+ );
346
+ throw e;
347
+ }
348
+ if (hasFallback && (error.message.includes("404") || error.message.includes("405"))) {
349
+ continue;
350
+ }
351
+ throw e;
352
+ }
353
+ }
354
+ this.client.setRequestHandler(
355
+ ElicitRequestSchema,
356
+ async (request) => {
357
+ return await this.handleElicitationRequest(request);
358
+ }
359
+ );
360
+ }
211
361
  };
212
362
  function capabilityErrorHandler(empty, method) {
213
363
  return (e) => {
@@ -222,8 +372,6 @@ function capabilityErrorHandler(empty, method) {
222
372
  }
223
373
 
224
374
  // src/mcp/client.ts
225
- import { jsonSchema } from "ai";
226
- import { nanoid } from "nanoid";
227
375
  var MCPClientManager = class {
228
376
  /**
229
377
  * @param _name Name of the MCP client
@@ -235,6 +383,7 @@ var MCPClientManager = class {
235
383
  this._version = _version;
236
384
  this.mcpConnections = {};
237
385
  this._callbackUrls = [];
386
+ this._didWarnAboutUnstableGetAITools = false;
238
387
  }
239
388
  /**
240
389
  * Connect to and register an MCP server
@@ -255,17 +404,19 @@ var MCPClientManager = class {
255
404
  options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
256
405
  }
257
406
  }
258
- this.mcpConnections[id] = new MCPClientConnection(
259
- new URL(url),
260
- {
261
- name: this._name,
262
- version: this._version
263
- },
264
- {
265
- transport: options.transport ?? {},
266
- client: options.client ?? {}
267
- }
268
- );
407
+ if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
408
+ this.mcpConnections[id] = new MCPClientConnection(
409
+ new URL(url),
410
+ {
411
+ name: this._name,
412
+ version: this._version
413
+ },
414
+ {
415
+ client: options.client ?? {},
416
+ transport: options.transport ?? {}
417
+ }
418
+ );
419
+ }
269
420
  await this.mcpConnections[id].init(options.reconnect?.oauthCode);
270
421
  const authUrl = options.transport?.authProvider?.authUrl;
271
422
  if (authUrl && options.transport?.authProvider?.redirectUrl) {
@@ -273,9 +424,9 @@ var MCPClientManager = class {
273
424
  options.transport.authProvider.redirectUrl.toString()
274
425
  );
275
426
  return {
276
- id,
277
427
  authUrl,
278
- clientId: options.transport?.authProvider?.clientId
428
+ clientId: options.transport?.authProvider?.clientId,
429
+ id
279
430
  };
280
431
  }
281
432
  return {
@@ -337,6 +488,24 @@ var MCPClientManager = class {
337
488
  }
338
489
  return { serverId };
339
490
  }
491
+ /**
492
+ * Register a callback URL for OAuth handling
493
+ * @param url The callback URL to register
494
+ */
495
+ registerCallbackUrl(url) {
496
+ if (!this._callbackUrls.includes(url)) {
497
+ this._callbackUrls.push(url);
498
+ }
499
+ }
500
+ /**
501
+ * Unregister a callback URL
502
+ * @param serverId The server ID whose callback URL should be removed
503
+ */
504
+ unregisterCallbackUrl(serverId) {
505
+ this._callbackUrls = this._callbackUrls.filter(
506
+ (url) => !url.endsWith(`/${serverId}`)
507
+ );
508
+ }
340
509
  /**
341
510
  * @returns namespaced list of tools
342
511
  */
@@ -346,30 +515,44 @@ var MCPClientManager = class {
346
515
  /**
347
516
  * @returns a set of tools that you can use with the AI SDK
348
517
  */
349
- unstable_getAITools() {
518
+ getAITools() {
350
519
  return Object.fromEntries(
351
520
  getNamespacedData(this.mcpConnections, "tools").map((tool) => {
352
521
  return [
353
- `${tool.serverId}_${tool.name}`,
522
+ `tool_${tool.serverId}_${tool.name}`,
354
523
  {
355
- parameters: jsonSchema(tool.inputSchema),
356
524
  description: tool.description,
357
525
  execute: async (args) => {
358
526
  const result = await this.callTool({
359
- name: tool.name,
360
527
  arguments: args,
528
+ name: tool.name,
361
529
  serverId: tool.serverId
362
530
  });
363
531
  if (result.isError) {
364
532
  throw new Error(result.content[0].text);
365
533
  }
366
534
  return result;
367
- }
535
+ },
536
+ inputSchema: jsonSchema(tool.inputSchema),
537
+ outputSchema: tool.outputSchema ? jsonSchema(tool.outputSchema) : void 0
368
538
  }
369
539
  ];
370
540
  })
371
541
  );
372
542
  }
543
+ /**
544
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
545
+ * @returns a set of tools that you can use with the AI SDK
546
+ */
547
+ unstable_getAITools() {
548
+ if (!this._didWarnAboutUnstableGetAITools) {
549
+ this._didWarnAboutUnstableGetAITools = true;
550
+ console.warn(
551
+ "unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version."
552
+ );
553
+ }
554
+ return this.getAITools();
555
+ }
373
556
  /**
374
557
  * Closes all connections to MCP servers
375
558
  */
@@ -412,7 +595,7 @@ var MCPClientManager = class {
412
595
  /**
413
596
  * Namespaced version of callTool
414
597
  */
415
- callTool(params, resultSchema, options) {
598
+ async callTool(params, resultSchema, options) {
416
599
  const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
417
600
  return this.mcpConnections[params.serverId].client.callTool(
418
601
  {
@@ -444,7 +627,7 @@ var MCPClientManager = class {
444
627
  };
445
628
  function getNamespacedData(mcpClients, type) {
446
629
  const sets = Object.entries(mcpClients).map(([name, conn]) => {
447
- return { name, data: conn[type] };
630
+ return { data: conn[type], name };
448
631
  });
449
632
  const namespacedData = sets.flatMap(({ name: serverId, data }) => {
450
633
  return data.map((item) => {
@@ -459,7 +642,9 @@ function getNamespacedData(mcpClients, type) {
459
642
  }
460
643
 
461
644
  export {
645
+ SSEEdgeClientTransport,
646
+ StreamableHTTPEdgeClientTransport,
462
647
  MCPClientManager,
463
648
  getNamespacedData
464
649
  };
465
- //# sourceMappingURL=chunk-OYJXQRRH.js.map
650
+ //# sourceMappingURL=chunk-QEPGNUG6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/client.ts","../src/mcp/client-connection.ts","../src/mcp/sse-edge.ts","../src/mcp/streamable-http-edge.ts"],"sourcesContent":["import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n CallToolResultSchema,\n CallToolRequest,\n CompatibilityCallToolResultSchema,\n GetPromptRequest,\n Prompt,\n ReadResourceRequest,\n Resource,\n ResourceTemplate,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { type ToolSet, jsonSchema } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport {\n MCPClientConnection,\n type MCPTransportOptions\n} from \"./client-connection\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private _callbackUrls: string[] = [];\n private _didWarnAboutUnstableGetAITools = false;\n\n /**\n * @param _name Name of the MCP client\n * @param _version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private _name: string,\n private _version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of an auth reconnect)\n reconnect?: {\n // server id\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: MCPTransportOptions;\n client?: ConstructorParameters<typeof Client>[1];\n } = {}\n ): Promise<{\n id: string;\n authUrl?: string;\n clientId?: string;\n }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n options.transport.authProvider.serverId = id;\n // reconnect with auth\n if (options.reconnect?.oauthClientId) {\n options.transport.authProvider.clientId =\n options.reconnect?.oauthClientId;\n }\n }\n\n // During OAuth reconnect, reuse existing connection to preserve state\n if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this._name,\n version: this._version\n },\n {\n client: options.client ?? {},\n transport: options.transport ?? {}\n }\n );\n }\n\n await this.mcpConnections[id].init(options.reconnect?.oauthCode);\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this._callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n return {\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n id\n };\n }\n\n return {\n id\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code\n },\n ...conn.options\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * Register a callback URL for OAuth handling\n * @param url The callback URL to register\n */\n registerCallbackUrl(url: string): void {\n if (!this._callbackUrls.includes(url)) {\n this._callbackUrls.push(url);\n }\n }\n\n /**\n * Unregister a callback URL\n * @param serverId The server ID whose callback URL should be removed\n */\n unregisterCallbackUrl(serverId: string): void {\n // Remove callback URLs that end with this serverId\n this._callbackUrls = this._callbackUrls.filter(\n (url) => !url.endsWith(`/${serverId}`)\n );\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `tool_${tool.serverId}_${tool.name}`,\n {\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n arguments: args,\n name: tool.name,\n serverId: tool.serverId\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n inputSchema: jsonSchema(tool.inputSchema),\n outputSchema: tool.outputSchema\n ? jsonSchema(tool.outputSchema)\n : undefined\n }\n ];\n })\n );\n }\n\n /**\n * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n if (!this._didWarnAboutUnstableGetAITools) {\n this._didWarnAboutUnstableGetAITools = true;\n console.warn(\n \"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\"\n );\n }\n return this.getAITools();\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n delete this.mcpConnections[id];\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n async callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { data: conn[type], name };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport {\n type ClientCapabilities,\n type ListPromptsResult,\n type ListResourceTemplatesResult,\n type ListResourcesResult,\n type ListToolsResult,\n PromptListChangedNotificationSchema,\n ResourceListChangedNotificationSchema,\n type ResourceTemplate,\n type ServerCapabilities,\n ToolListChangedNotificationSchema,\n ElicitRequestSchema,\n type ElicitRequest,\n type ElicitResult\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { SSEEdgeClientTransport } from \"./sse-edge\";\nimport type { BaseTransportType, TransportType } from \"./types\";\nimport { StreamableHTTPEdgeClientTransport } from \"./streamable-http-edge\";\n// Import types directly from MCP SDK\nimport type {\n Tool,\n Resource,\n Prompt\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type MCPTransportOptions = (\n | SSEClientTransportOptions\n | StreamableHTTPClientTransportOptions\n) & {\n authProvider?: AgentsOAuthProvider;\n type?: TransportType;\n};\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: MCPTransportOptions;\n client: ConstructorParameters<typeof Client>[1];\n } = { client: {}, transport: {} }\n ) {\n this.url = url;\n\n const clientOptions = {\n ...options.client,\n capabilities: {\n ...options.client?.capabilities,\n elicitation: {}\n } as ClientCapabilities\n };\n\n this.client = new Client(info, clientOptions);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string) {\n try {\n const transportType = this.options.transport.type || \"streamable-http\";\n await this.tryConnect(transportType, code);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [\n instructionsResult,\n toolsResult,\n resourcesResult,\n promptsResult,\n resourceTemplatesResult\n ] = await Promise.allSettled([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates()\n ]);\n\n const operations = [\n { name: \"instructions\", result: instructionsResult },\n { name: \"tools\", result: toolsResult },\n { name: \"resources\", result: resourcesResult },\n { name: \"prompts\", result: promptsResult },\n { name: \"resource templates\", result: resourceTemplatesResult }\n ];\n\n for (const { name, result } of operations) {\n if (result.status === \"rejected\") {\n console.error(`Failed to initialize ${name}:`, result.reason);\n }\n }\n\n this.instructions =\n instructionsResult.status === \"fulfilled\"\n ? instructionsResult.value\n : undefined;\n this.tools = toolsResult.status === \"fulfilled\" ? toolsResult.value : [];\n this.resources =\n resourcesResult.status === \"fulfilled\" ? resourcesResult.value : [];\n this.prompts =\n promptsResult.status === \"fulfilled\" ? promptsResult.value : [];\n this.resourceTemplates =\n resourceTemplatesResult.status === \"fulfilled\"\n ? resourceTemplatesResult.value\n : [];\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: []\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n\n /**\n * Handle elicitation request from server\n * Automatically uses the Agent's built-in elicitation handling if available\n */\n async handleElicitationRequest(\n _request: ElicitRequest\n ): Promise<ElicitResult> {\n // Elicitation handling must be implemented by the platform\n // For MCP servers, this should be handled by McpAgent.elicitInput()\n throw new Error(\n \"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\"\n );\n }\n /**\n * Get the transport for the client\n * @param transportType - The transport type to get\n * @returns The transport for the client\n */\n getTransport(transportType: BaseTransportType) {\n switch (transportType) {\n case \"streamable-http\":\n return new StreamableHTTPEdgeClientTransport(\n this.url,\n this.options.transport as StreamableHTTPClientTransportOptions\n );\n case \"sse\":\n return new SSEEdgeClientTransport(\n this.url,\n this.options.transport as SSEClientTransportOptions\n );\n default:\n throw new Error(`Unsupported transport type: ${transportType}`);\n }\n }\n\n private async tryConnect(transportType: TransportType, code?: string) {\n // When completing OAuth (with code), use the transport that initiated OAuth\n let effectiveTransportType = transportType;\n if (code && this.options.transport.authProvider) {\n const savedTransport =\n await this.options.transport.authProvider.getOAuthTransport();\n if (savedTransport) {\n effectiveTransportType = savedTransport as TransportType;\n }\n }\n\n const transports: BaseTransportType[] =\n effectiveTransportType === \"auto\"\n ? [\"streamable-http\", \"sse\"]\n : [effectiveTransportType];\n\n for (const currentTransportType of transports) {\n const isLastTransport =\n currentTransportType === transports[transports.length - 1];\n const hasFallback =\n effectiveTransportType === \"auto\" &&\n currentTransportType === \"streamable-http\" &&\n !isLastTransport;\n\n const transport = this.getTransport(currentTransportType);\n\n if (code) {\n await transport.finishAuth(code);\n }\n\n try {\n await this.client.connect(transport);\n\n // Clear saved transport after successful OAuth completion\n if (code && this.options.transport.authProvider) {\n await this.options.transport.authProvider.clearOAuthTransport();\n }\n\n break;\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n\n // Save transport type when OAuth is needed (Unauthorized error)\n // This must happen BEFORE we throw or continue\n if (\n !code &&\n error.message.includes(\"Unauthorized\") &&\n this.options.transport.authProvider &&\n currentTransportType\n ) {\n await this.options.transport.authProvider.saveOAuthTransport(\n currentTransportType\n );\n throw e; // Re-throw after storing transport\n }\n\n if (\n hasFallback &&\n (error.message.includes(\"404\") || error.message.includes(\"405\"))\n ) {\n // try the next transport if we have a fallback\n continue;\n }\n\n throw e;\n }\n }\n\n // Set up elicitation request handler\n this.client.setRequestHandler(\n ElicitRequestSchema,\n async (request: ElicitRequest) => {\n return await this.handleElicitationRequest(request);\n }\n );\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n SSEClientTransport,\n type SSEClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.eventSourceInit,\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport {\n StreamableHTTPClientTransport,\n type StreamableHTTPClientTransportOptions\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\nexport class StreamableHTTPEdgeClientTransport extends StreamableHTTPClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n\n /**\n * Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: StreamableHTTPClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers\n }\n };\n\n // Remove unsupported properties\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n // @ts-expect-error Custom fetch function for Cloudflare Workers compatibility\n (options.requestInit?.fetch?.(\n fetchUrl as URL | string,\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n requestInit: {\n ...options.requestInit,\n // @ts-expect-error Custom fetch override for Cloudflare Workers\n fetch: fetchOverride\n }\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`\n };\n }\n }\n }\n}\n"],"mappings":";AAaA,SAAuB,kBAAkB;AACzC,SAAS,cAAc;;;ACdvB,SAAS,cAAc;AAGvB;AAAA,EAME;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OAGK;;;AChBP;AAAA,EACE;AAAA,OAEK;AAEA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAAY;AACvC,YAAM,gBAAgB;AAAA,QACpB,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,QAAQ,aAAa;AAAA,UACxB,GAAG,WAAW;AAAA,UACd,GAAG;AAAA,QACL;AAAA,MACF;AAGA,aAAO,cAAc;AAGrB,aACG,QAAQ,iBAAiB;AAAA,QACxB;AAAA;AAAA,QAEA;AAAA,MACF,KAA2B,MAAM,UAAU,aAAa;AAAA,IAE5D;AAEA,UA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QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,QACE,GAAG;AAAA,QACH,MAAM;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,KAAK,IAAI,GAAG,KAAK;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url"]}
@@ -17,8 +17,8 @@ var AgentClient = class extends PartySocket {
17
17
  constructor(options) {
18
18
  const agentNamespace = camelCaseToKebabCase(options.agent);
19
19
  super({
20
- prefix: "agents",
21
20
  party: agentNamespace,
21
+ prefix: "agents",
22
22
  room: options.name || "default",
23
23
  ...options
24
24
  });
@@ -31,14 +31,14 @@ var AgentClient = class extends PartySocket {
31
31
  let parsedMessage;
32
32
  try {
33
33
  parsedMessage = JSON.parse(event.data);
34
- } catch (error) {
34
+ } catch (_error) {
35
35
  return;
36
36
  }
37
- if (parsedMessage.type === "cf_agent_state") {
37
+ if (parsedMessage.type === "cf_agent_state" /* CF_AGENT_STATE */) {
38
38
  this.options.onStateUpdate?.(parsedMessage.state, "server");
39
39
  return;
40
40
  }
41
- if (parsedMessage.type === "rpc") {
41
+ if (parsedMessage.type === "rpc" /* RPC */) {
42
42
  const response = parsedMessage;
43
43
  const pending = this._pendingCalls.get(response.id);
44
44
  if (!pending) return;
@@ -73,23 +73,23 @@ var AgentClient = class extends PartySocket {
73
73
  );
74
74
  }
75
75
  setState(state) {
76
- this.send(JSON.stringify({ type: "cf_agent_state", state }));
76
+ this.send(JSON.stringify({ state, type: "cf_agent_state" /* CF_AGENT_STATE */ }));
77
77
  this.options.onStateUpdate?.(state, "client");
78
78
  }
79
79
  async call(method, args = [], streamOptions) {
80
80
  return new Promise((resolve, reject) => {
81
81
  const id = Math.random().toString(36).slice(2);
82
82
  this._pendingCalls.set(id, {
83
- resolve: (value) => resolve(value),
84
83
  reject,
84
+ resolve: (value) => resolve(value),
85
85
  stream: streamOptions,
86
86
  type: null
87
87
  });
88
88
  const request = {
89
- type: "rpc",
89
+ args,
90
90
  id,
91
91
  method,
92
- args
92
+ type: "rpc" /* RPC */
93
93
  };
94
94
  this.send(JSON.stringify(request));
95
95
  });
@@ -99,8 +99,8 @@ function agentFetch(opts, init) {
99
99
  const agentNamespace = camelCaseToKebabCase(opts.agent);
100
100
  return PartySocket.fetch(
101
101
  {
102
- prefix: "agents",
103
102
  party: agentNamespace,
103
+ prefix: "agents",
104
104
  room: opts.name || "default",
105
105
  ...opts
106
106
  },
@@ -113,4 +113,4 @@ export {
113
113
  AgentClient,
114
114
  agentFetch
115
115
  };
116
- //# sourceMappingURL=chunk-VCSB47AK.js.map
116
+ //# sourceMappingURL=chunk-QEVM4BVL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import {\n type PartyFetchOptions,\n PartySocket,\n type PartySocketOptions\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\nimport type {\n SerializableReturnValue,\n SerializableValue\n} from \"./serializable\";\nimport { MessageType } from \"./ai-types\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nexport function camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n private options: AgentClientOptions<State>;\n private _pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n party: agentNamespace,\n prefix: \"agents\",\n room: options.name || \"default\",\n ...options\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n this.options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === MessageType.RPC) {\n const response = parsedMessage as RPCResponse;\n const pending = this._pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this._pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ state, type: MessageType.CF_AGENT_STATE }));\n this.options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n call<T extends SerializableReturnValue>(\n method: string,\n args?: SerializableValue[],\n streamOptions?: StreamOptions\n ): Promise<T>;\n call<T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ): Promise<T>;\n async call<T>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this._pendingCalls.set(id, {\n reject,\n resolve: (value: unknown) => resolve(value as T),\n stream: streamOptions,\n type: null as T\n });\n\n const request: RPCRequest = {\n args,\n id,\n method,\n type: MessageType.RPC\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n party: agentNamespace,\n prefix: \"agents\",\n room: opts.name || \"default\",\n ...opts\n },\n init\n );\n}\n"],"mappings":";AAAA;AAAA,EAEE;AAAA,OAEK;AAqDA,SAAS,qBAAqB,KAAqB;AAExD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,EAAE;AACvD;AAKO,IAAM,cAAN,cAA2C,YAAY;AAAA,EAsB5D,YAAY,SAAoC;AAC9C,UAAM,iBAAiB,qBAAqB,QAAQ,KAAK;AACzD,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,MAAM,QAAQ,QAAQ;AAAA,MACtB,GAAG;AAAA,IACL,CAAC;AAjBH,SAAQ,gBAAgB,oBAAI,IAQ1B;AAUA,SAAK,QAAQ;AACb,SAAK,OAAO,QAAQ,QAAQ;AAC5B,SAAK,UAAU;AAEf,SAAK,iBAAiB,WAAW,CAAC,UAAU;AAC1C,UAAI,OAAO,MAAM,SAAS,UAAU;AAClC,YAAI;AACJ,YAAI;AACF,0B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