agents 0.0.0-f641104 → 0.0.0-f7bd395

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 (59) hide show
  1. package/README.md +159 -33
  2. package/dist/ai-chat-agent.d.ts +56 -6
  3. package/dist/ai-chat-agent.js +278 -94
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-react.d.ts +71 -67
  8. package/dist/ai-react.js +193 -72
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +40 -18
  11. package/dist/ai-types.js +6 -0
  12. package/dist/chunk-AVYJQSLW.js +17 -0
  13. package/dist/chunk-AVYJQSLW.js.map +1 -0
  14. package/dist/chunk-IJPBZOSS.js +1296 -0
  15. package/dist/chunk-IJPBZOSS.js.map +1 -0
  16. package/dist/chunk-LL2AFX7V.js +109 -0
  17. package/dist/chunk-LL2AFX7V.js.map +1 -0
  18. package/dist/chunk-QEVM4BVL.js +116 -0
  19. package/dist/chunk-QEVM4BVL.js.map +1 -0
  20. package/dist/chunk-UJVEAURM.js +150 -0
  21. package/dist/chunk-UJVEAURM.js.map +1 -0
  22. package/dist/chunk-VYENMKFS.js +612 -0
  23. package/dist/chunk-VYENMKFS.js.map +1 -0
  24. package/dist/client-CcIORE73.d.ts +4607 -0
  25. package/dist/client.d.ts +16 -2
  26. package/dist/client.js +7 -133
  27. package/dist/client.js.map +1 -1
  28. package/dist/index.d.ts +284 -22
  29. package/dist/index.js +15 -4
  30. package/dist/mcp/client.d.ts +11 -0
  31. package/dist/mcp/client.js +9 -0
  32. package/dist/mcp/client.js.map +1 -0
  33. package/dist/mcp/do-oauth-client-provider.d.ts +42 -0
  34. package/dist/mcp/do-oauth-client-provider.js +7 -0
  35. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  36. package/dist/mcp/index.d.ts +97 -0
  37. package/dist/mcp/index.js +1029 -0
  38. package/dist/mcp/index.js.map +1 -0
  39. package/dist/observability/index.d.ts +46 -0
  40. package/dist/observability/index.js +11 -0
  41. package/dist/observability/index.js.map +1 -0
  42. package/dist/react.d.ts +89 -5
  43. package/dist/react.js +53 -32
  44. package/dist/react.js.map +1 -1
  45. package/dist/schedule.d.ts +81 -7
  46. package/dist/schedule.js +19 -8
  47. package/dist/schedule.js.map +1 -1
  48. package/dist/serializable.d.ts +32 -0
  49. package/dist/serializable.js +1 -0
  50. package/dist/serializable.js.map +1 -0
  51. package/package.json +95 -52
  52. package/src/index.ts +1243 -184
  53. package/dist/chunk-HMLY7DHA.js +0 -16
  54. package/dist/chunk-X6BBKLSC.js +0 -568
  55. package/dist/chunk-X6BBKLSC.js.map +0 -1
  56. package/dist/mcp.d.ts +0 -58
  57. package/dist/mcp.js +0 -945
  58. package/dist/mcp.js.map +0 -1
  59. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility)\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n */\nexport function needsMigration(messages: unknown[]): boolean {\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";AAkFA,IAAM,YAAY;AAAA,EAChB,gBAAgB;AAAA,EAChB,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACT;AAKO,SAAS,YAAY,SAAwC;AAClE,SACE,OAAO,YAAY,YACnB,YAAY,QACZ,WAAW,WACX,MAAM,QAAS,QAA+B,KAAK;AAEvD;AAKA,SAAS,gBAAgB,SAA4C;AACnE,SACE,OAAO,YAAY,YACnB,YAAY,QACZ,UAAU,WACV,aAAa,WACb,OAAQ,QAA8B,SAAS,YAC/C,OAAQ,QAAiC,YAAY;AAEzD;AAMA,SAAS,sBACP,SACgC;AAChC,SACE,OAAO,YAAY,YACnB,YAAY,QACZ,UAAU,WACV,aAAa,WACb,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;AACH;AAOO,SAAS,kBAAkB,UAWhC;AACA,QAAM,QAAQ;AAAA,IACZ,OAAO,SAAS;AAAA,IAChB,OAAO;AAAA,IACP,cAAc;AAAA,IACd,cAAc;AAAA,IACd,SAAS;AAAA,IACT,UAAU,CAAC;AAAA,EAKb;AAEA,aAAW,WAAW,UAAU;AAC9B,QAAI,YAAY,OAAO,GAAG;AACxB,YAAM;AAAA,IACR,WAAW,sBAAsB,OAAO,GAAG;AACzC,YAAM;AACN,UAAI,CAAC,MAAM,SAAS,cAAc;AAChC,cAAM,SAAS,eAAe;AAAA,MAChC;AAAA,IACF,WAAW,gBAAgB,OAAO,GAAG;AACnC,YAAM;AACN,UAAI,CAAC,MAAM,SAAS,cAAc;AAChC,cAAM,SAAS,eAAe;AAAA,MAChC;AAAA,IACF,OAAO;AACL,YAAM;AACN,UAAI,CAAC,MAAM,SAAS,SAAS;AAC3B,cAAM,SAAS,UAAU;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,612 @@
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
+
14
+ // src/mcp/sse-edge.ts
15
+ import {
16
+ SSEClientTransport
17
+ } from "@modelcontextprotocol/sdk/client/sse.js";
18
+ var SSEEdgeClientTransport = class extends SSEClientTransport {
19
+ /**
20
+ * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment
21
+ */
22
+ constructor(url, options) {
23
+ const fetchOverride = async (fetchUrl, fetchInit = {}) => {
24
+ const headers = await this.authHeaders();
25
+ const workerOptions = {
26
+ ...fetchInit,
27
+ headers: {
28
+ ...options.requestInit?.headers,
29
+ ...fetchInit?.headers,
30
+ ...headers
31
+ }
32
+ };
33
+ delete workerOptions.mode;
34
+ return options.eventSourceInit?.fetch?.(
35
+ fetchUrl,
36
+ // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit
37
+ workerOptions
38
+ ) || fetch(fetchUrl, workerOptions);
39
+ };
40
+ super(url, {
41
+ ...options,
42
+ eventSourceInit: {
43
+ ...options.eventSourceInit,
44
+ fetch: fetchOverride
45
+ }
46
+ });
47
+ this.authProvider = options.authProvider;
48
+ }
49
+ async authHeaders() {
50
+ if (this.authProvider) {
51
+ const tokens = await this.authProvider.tokens();
52
+ if (tokens) {
53
+ return {
54
+ Authorization: `Bearer ${tokens.access_token}`
55
+ };
56
+ }
57
+ }
58
+ }
59
+ };
60
+
61
+ // src/mcp/streamable-http-edge.ts
62
+ import {
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
112
+ var MCPClientConnection = class {
113
+ constructor(url, info, options = { client: {}, transport: {} }) {
114
+ this.url = url;
115
+ this.options = options;
116
+ this.connectionState = "connecting";
117
+ this.tools = [];
118
+ this.prompts = [];
119
+ this.resources = [];
120
+ this.resourceTemplates = [];
121
+ const clientOptions = {
122
+ ...options.client,
123
+ capabilities: {
124
+ ...options.client?.capabilities,
125
+ elicitation: {}
126
+ }
127
+ };
128
+ this.client = new Client(info, clientOptions);
129
+ }
130
+ /**
131
+ * Initialize a client connection
132
+ *
133
+ * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
134
+ * @returns
135
+ */
136
+ async init(code) {
137
+ try {
138
+ const transportType = this.options.transport.type || "streamable-http";
139
+ await this.tryConnect(transportType, code);
140
+ } catch (e) {
141
+ if (e.toString().includes("Unauthorized")) {
142
+ this.connectionState = "authenticating";
143
+ return;
144
+ }
145
+ this.connectionState = "failed";
146
+ throw e;
147
+ }
148
+ this.connectionState = "discovering";
149
+ this.serverCapabilities = await this.client.getServerCapabilities();
150
+ if (!this.serverCapabilities) {
151
+ throw new Error("The MCP Server failed to return server capabilities");
152
+ }
153
+ const [
154
+ instructionsResult,
155
+ toolsResult,
156
+ resourcesResult,
157
+ promptsResult,
158
+ resourceTemplatesResult
159
+ ] = await Promise.allSettled([
160
+ this.client.getInstructions(),
161
+ this.registerTools(),
162
+ this.registerResources(),
163
+ this.registerPrompts(),
164
+ this.registerResourceTemplates()
165
+ ]);
166
+ const operations = [
167
+ { name: "instructions", result: instructionsResult },
168
+ { name: "tools", result: toolsResult },
169
+ { name: "resources", result: resourcesResult },
170
+ { name: "prompts", result: promptsResult },
171
+ { name: "resource templates", result: resourceTemplatesResult }
172
+ ];
173
+ for (const { name, result } of operations) {
174
+ if (result.status === "rejected") {
175
+ console.error(`Failed to initialize ${name}:`, result.reason);
176
+ }
177
+ }
178
+ this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
179
+ this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
180
+ this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
181
+ this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
182
+ this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
183
+ this.connectionState = "ready";
184
+ }
185
+ /**
186
+ * Notification handler registration
187
+ */
188
+ async registerTools() {
189
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) {
190
+ return [];
191
+ }
192
+ if (this.serverCapabilities.tools.listChanged) {
193
+ this.client.setNotificationHandler(
194
+ ToolListChangedNotificationSchema,
195
+ async (_notification) => {
196
+ this.tools = await this.fetchTools();
197
+ }
198
+ );
199
+ }
200
+ return this.fetchTools();
201
+ }
202
+ async registerResources() {
203
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
204
+ return [];
205
+ }
206
+ if (this.serverCapabilities.resources.listChanged) {
207
+ this.client.setNotificationHandler(
208
+ ResourceListChangedNotificationSchema,
209
+ async (_notification) => {
210
+ this.resources = await this.fetchResources();
211
+ }
212
+ );
213
+ }
214
+ return this.fetchResources();
215
+ }
216
+ async registerPrompts() {
217
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) {
218
+ return [];
219
+ }
220
+ if (this.serverCapabilities.prompts.listChanged) {
221
+ this.client.setNotificationHandler(
222
+ PromptListChangedNotificationSchema,
223
+ async (_notification) => {
224
+ this.prompts = await this.fetchPrompts();
225
+ }
226
+ );
227
+ }
228
+ return this.fetchPrompts();
229
+ }
230
+ async registerResourceTemplates() {
231
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) {
232
+ return [];
233
+ }
234
+ return this.fetchResourceTemplates();
235
+ }
236
+ async fetchTools() {
237
+ let toolsAgg = [];
238
+ let toolsResult = { tools: [] };
239
+ do {
240
+ toolsResult = await this.client.listTools({
241
+ cursor: toolsResult.nextCursor
242
+ }).catch(capabilityErrorHandler({ tools: [] }, "tools/list"));
243
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
244
+ } while (toolsResult.nextCursor);
245
+ return toolsAgg;
246
+ }
247
+ async fetchResources() {
248
+ let resourcesAgg = [];
249
+ let resourcesResult = { resources: [] };
250
+ do {
251
+ resourcesResult = await this.client.listResources({
252
+ cursor: resourcesResult.nextCursor
253
+ }).catch(capabilityErrorHandler({ resources: [] }, "resources/list"));
254
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
255
+ } while (resourcesResult.nextCursor);
256
+ return resourcesAgg;
257
+ }
258
+ async fetchPrompts() {
259
+ let promptsAgg = [];
260
+ let promptsResult = { prompts: [] };
261
+ do {
262
+ promptsResult = await this.client.listPrompts({
263
+ cursor: promptsResult.nextCursor
264
+ }).catch(capabilityErrorHandler({ prompts: [] }, "prompts/list"));
265
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
266
+ } while (promptsResult.nextCursor);
267
+ return promptsAgg;
268
+ }
269
+ async fetchResourceTemplates() {
270
+ let templatesAgg = [];
271
+ let templatesResult = {
272
+ resourceTemplates: []
273
+ };
274
+ do {
275
+ templatesResult = await this.client.listResourceTemplates({
276
+ cursor: templatesResult.nextCursor
277
+ }).catch(
278
+ capabilityErrorHandler(
279
+ { resourceTemplates: [] },
280
+ "resources/templates/list"
281
+ )
282
+ );
283
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
284
+ } while (templatesResult.nextCursor);
285
+ return templatesAgg;
286
+ }
287
+ /**
288
+ * Handle elicitation request from server
289
+ * Automatically uses the Agent's built-in elicitation handling if available
290
+ */
291
+ async handleElicitationRequest(_request) {
292
+ throw new Error(
293
+ "Elicitation handler must be implemented for your platform. Override handleElicitationRequest method."
294
+ );
295
+ }
296
+ /**
297
+ * Get the transport for the client
298
+ * @param transportType - The transport type to get
299
+ * @returns The transport for the client
300
+ */
301
+ getTransport(transportType) {
302
+ switch (transportType) {
303
+ case "streamable-http":
304
+ return new StreamableHTTPEdgeClientTransport(
305
+ this.url,
306
+ this.options.transport
307
+ );
308
+ case "sse":
309
+ return new SSEEdgeClientTransport(
310
+ this.url,
311
+ this.options.transport
312
+ );
313
+ default:
314
+ throw new Error(`Unsupported transport type: ${transportType}`);
315
+ }
316
+ }
317
+ async tryConnect(transportType, code) {
318
+ const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
319
+ for (const currentTransportType of transports) {
320
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
321
+ const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
322
+ const transport = await this.getTransport(currentTransportType);
323
+ if (code) {
324
+ await transport.finishAuth(code);
325
+ }
326
+ try {
327
+ await this.client.connect(transport);
328
+ break;
329
+ } catch (e) {
330
+ const error = e instanceof Error ? e : new Error(String(e));
331
+ if (hasFallback && (error.message.includes("404") || error.message.includes("405"))) {
332
+ continue;
333
+ }
334
+ throw e;
335
+ }
336
+ }
337
+ this.client.setRequestHandler(
338
+ ElicitRequestSchema,
339
+ async (request) => {
340
+ return await this.handleElicitationRequest(request);
341
+ }
342
+ );
343
+ }
344
+ };
345
+ function capabilityErrorHandler(empty, method) {
346
+ return (e) => {
347
+ if (e.code === -32601) {
348
+ console.error(
349
+ `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}'.`
350
+ );
351
+ return empty;
352
+ }
353
+ throw e;
354
+ };
355
+ }
356
+
357
+ // src/mcp/client.ts
358
+ var MCPClientManager = class {
359
+ /**
360
+ * @param _name Name of the MCP client
361
+ * @param _version Version of the MCP Client
362
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
363
+ */
364
+ constructor(_name, _version) {
365
+ this._name = _name;
366
+ this._version = _version;
367
+ this.mcpConnections = {};
368
+ this._callbackUrls = [];
369
+ this._didWarnAboutUnstableGetAITools = false;
370
+ }
371
+ /**
372
+ * Connect to and register an MCP server
373
+ *
374
+ * @param transportConfig Transport config
375
+ * @param clientConfig Client config
376
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
377
+ */
378
+ async connect(url, options = {}) {
379
+ const id = options.reconnect?.id ?? nanoid(8);
380
+ if (!options.transport?.authProvider) {
381
+ console.warn(
382
+ "No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers"
383
+ );
384
+ } else {
385
+ options.transport.authProvider.serverId = id;
386
+ if (options.reconnect?.oauthClientId) {
387
+ options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
388
+ }
389
+ }
390
+ this.mcpConnections[id] = new MCPClientConnection(
391
+ new URL(url),
392
+ {
393
+ name: this._name,
394
+ version: this._version
395
+ },
396
+ {
397
+ client: options.client ?? {},
398
+ transport: options.transport ?? {}
399
+ }
400
+ );
401
+ await this.mcpConnections[id].init(options.reconnect?.oauthCode);
402
+ const authUrl = options.transport?.authProvider?.authUrl;
403
+ if (authUrl && options.transport?.authProvider?.redirectUrl) {
404
+ this._callbackUrls.push(
405
+ options.transport.authProvider.redirectUrl.toString()
406
+ );
407
+ return {
408
+ authUrl,
409
+ clientId: options.transport?.authProvider?.clientId,
410
+ id
411
+ };
412
+ }
413
+ return {
414
+ id
415
+ };
416
+ }
417
+ isCallbackRequest(req) {
418
+ return req.method === "GET" && !!this._callbackUrls.find((url) => {
419
+ return req.url.startsWith(url);
420
+ });
421
+ }
422
+ async handleCallbackRequest(req) {
423
+ const url = new URL(req.url);
424
+ const urlMatch = this._callbackUrls.find((url2) => {
425
+ return req.url.startsWith(url2);
426
+ });
427
+ if (!urlMatch) {
428
+ throw new Error(
429
+ `No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`
430
+ );
431
+ }
432
+ const code = url.searchParams.get("code");
433
+ const clientId = url.searchParams.get("state");
434
+ const urlParams = urlMatch.split("/");
435
+ const serverId = urlParams[urlParams.length - 1];
436
+ if (!code) {
437
+ throw new Error("Unauthorized: no code provided");
438
+ }
439
+ if (!clientId) {
440
+ throw new Error("Unauthorized: no state provided");
441
+ }
442
+ if (this.mcpConnections[serverId] === void 0) {
443
+ throw new Error(`Could not find serverId: ${serverId}`);
444
+ }
445
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") {
446
+ throw new Error(
447
+ "Failed to authenticate: the client isn't in the `authenticating` state"
448
+ );
449
+ }
450
+ const conn = this.mcpConnections[serverId];
451
+ if (!conn.options.transport.authProvider) {
452
+ throw new Error(
453
+ "Trying to finalize authentication for a server connection without an authProvider"
454
+ );
455
+ }
456
+ conn.options.transport.authProvider.clientId = clientId;
457
+ conn.options.transport.authProvider.serverId = serverId;
458
+ const serverUrl = conn.url.toString();
459
+ await this.connect(serverUrl, {
460
+ reconnect: {
461
+ id: serverId,
462
+ oauthClientId: clientId,
463
+ oauthCode: code
464
+ },
465
+ ...conn.options
466
+ });
467
+ if (this.mcpConnections[serverId].connectionState === "authenticating") {
468
+ throw new Error("Failed to authenticate: client failed to initialize");
469
+ }
470
+ return { serverId };
471
+ }
472
+ /**
473
+ * @returns namespaced list of tools
474
+ */
475
+ listTools() {
476
+ return getNamespacedData(this.mcpConnections, "tools");
477
+ }
478
+ /**
479
+ * @returns a set of tools that you can use with the AI SDK
480
+ */
481
+ getAITools() {
482
+ return Object.fromEntries(
483
+ getNamespacedData(this.mcpConnections, "tools").map((tool) => {
484
+ return [
485
+ `tool_${tool.serverId}_${tool.name}`,
486
+ {
487
+ description: tool.description,
488
+ execute: async (args) => {
489
+ const result = await this.callTool({
490
+ arguments: args,
491
+ name: tool.name,
492
+ serverId: tool.serverId
493
+ });
494
+ if (result.isError) {
495
+ throw new Error(result.content[0].text);
496
+ }
497
+ return result;
498
+ },
499
+ inputSchema: jsonSchema(tool.inputSchema)
500
+ }
501
+ ];
502
+ })
503
+ );
504
+ }
505
+ /**
506
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
507
+ * @returns a set of tools that you can use with the AI SDK
508
+ */
509
+ unstable_getAITools() {
510
+ if (!this._didWarnAboutUnstableGetAITools) {
511
+ this._didWarnAboutUnstableGetAITools = true;
512
+ console.warn(
513
+ "unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version."
514
+ );
515
+ }
516
+ return this.getAITools();
517
+ }
518
+ /**
519
+ * Closes all connections to MCP servers
520
+ */
521
+ async closeAllConnections() {
522
+ return Promise.all(
523
+ Object.values(this.mcpConnections).map(async (connection) => {
524
+ await connection.client.close();
525
+ })
526
+ );
527
+ }
528
+ /**
529
+ * Closes a connection to an MCP server
530
+ * @param id The id of the connection to close
531
+ */
532
+ async closeConnection(id) {
533
+ if (!this.mcpConnections[id]) {
534
+ throw new Error(`Connection with id "${id}" does not exist.`);
535
+ }
536
+ await this.mcpConnections[id].client.close();
537
+ delete this.mcpConnections[id];
538
+ }
539
+ /**
540
+ * @returns namespaced list of prompts
541
+ */
542
+ listPrompts() {
543
+ return getNamespacedData(this.mcpConnections, "prompts");
544
+ }
545
+ /**
546
+ * @returns namespaced list of tools
547
+ */
548
+ listResources() {
549
+ return getNamespacedData(this.mcpConnections, "resources");
550
+ }
551
+ /**
552
+ * @returns namespaced list of resource templates
553
+ */
554
+ listResourceTemplates() {
555
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
556
+ }
557
+ /**
558
+ * Namespaced version of callTool
559
+ */
560
+ callTool(params, resultSchema, options) {
561
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
562
+ return this.mcpConnections[params.serverId].client.callTool(
563
+ {
564
+ ...params,
565
+ name: unqualifiedName
566
+ },
567
+ resultSchema,
568
+ options
569
+ );
570
+ }
571
+ /**
572
+ * Namespaced version of readResource
573
+ */
574
+ readResource(params, options) {
575
+ return this.mcpConnections[params.serverId].client.readResource(
576
+ params,
577
+ options
578
+ );
579
+ }
580
+ /**
581
+ * Namespaced version of getPrompt
582
+ */
583
+ getPrompt(params, options) {
584
+ return this.mcpConnections[params.serverId].client.getPrompt(
585
+ params,
586
+ options
587
+ );
588
+ }
589
+ };
590
+ function getNamespacedData(mcpClients, type) {
591
+ const sets = Object.entries(mcpClients).map(([name, conn]) => {
592
+ return { data: conn[type], name };
593
+ });
594
+ const namespacedData = sets.flatMap(({ name: serverId, data }) => {
595
+ return data.map((item) => {
596
+ return {
597
+ ...item,
598
+ // we add a serverId so we can easily pull it out and send the tool call to the right server
599
+ serverId
600
+ };
601
+ });
602
+ });
603
+ return namespacedData;
604
+ }
605
+
606
+ export {
607
+ SSEEdgeClientTransport,
608
+ StreamableHTTPEdgeClientTransport,
609
+ MCPClientManager,
610
+ getNamespacedData
611
+ };
612
+ //# sourceMappingURL=chunk-VYENMKFS.js.map