mcp-use 1.11.0-canary.7 → 1.11.0-canary.9

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 (98) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-REYY7LSD.js → chunk-5QFJZ7H3.js} +2 -2
  3. package/dist/chunk-D3CNYAYE.js +1055 -0
  4. package/dist/{chunk-OD6B7KGQ.js → chunk-ESMOFYJ6.js} +27 -2100
  5. package/dist/{chunk-WTGUJLTR.js → chunk-F3BZFJCD.js} +167 -7
  6. package/dist/chunk-GXNAXUDI.js +0 -0
  7. package/dist/{chunk-QP7MQ2UJ.js → chunk-HU2DGJ5J.js} +175 -133
  8. package/dist/{chunk-REX2YTWF.js → chunk-M7WATKYM.js} +1 -1
  9. package/dist/chunk-MFSO5PUW.js +1049 -0
  10. package/dist/{chunk-5LBXMCKC.js → chunk-N3DO4P2L.js} +27 -2100
  11. package/dist/{chunk-M7CHBY4S.js → chunk-OWPXM4QQ.js} +1 -1
  12. package/dist/{chunk-3QVRNWW7.js → chunk-Q5LZL6BH.js} +1 -1
  13. package/dist/{chunk-ZN3MKSKM.js → chunk-UCPSHMNO.js} +1 -1
  14. package/dist/chunk-UWWLWLS2.js +62 -0
  15. package/dist/chunk-WW3A2EKQ.js +1055 -0
  16. package/dist/{chunk-CHHWJQVC.js → chunk-XEFWIBQF.js} +1 -1
  17. package/dist/index.cjs +211 -10
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +31 -28
  21. package/dist/notifications-FLGIFS56.js +9 -0
  22. package/dist/src/adapters/index.cjs +1346 -0
  23. package/dist/src/adapters/index.js +11 -0
  24. package/dist/src/agents/index.cjs +46 -4
  25. package/dist/src/agents/index.js +8 -6
  26. package/dist/src/browser.cjs +46 -5
  27. package/dist/src/browser.d.ts +1 -1
  28. package/dist/src/browser.d.ts.map +1 -1
  29. package/dist/src/browser.js +15 -13
  30. package/dist/src/client/prompts.js +4 -4
  31. package/dist/src/client.cjs +3787 -0
  32. package/dist/src/client.js +20 -0
  33. package/dist/src/react/index.cjs +211 -9
  34. package/dist/src/react/index.js +5 -5
  35. package/dist/src/react/types.d.ts +41 -1
  36. package/dist/src/react/types.d.ts.map +1 -1
  37. package/dist/src/react/useMcp.d.ts.map +1 -1
  38. package/dist/src/react/useWidget.d.ts +11 -7
  39. package/dist/src/react/useWidget.d.ts.map +1 -1
  40. package/dist/src/react/widget-types.d.ts +6 -2
  41. package/dist/src/react/widget-types.d.ts.map +1 -1
  42. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  43. package/dist/src/server/index.cjs +1269 -144
  44. package/dist/src/server/index.d.ts +2 -0
  45. package/dist/src/server/index.d.ts.map +1 -1
  46. package/dist/src/server/index.js +1158 -100
  47. package/dist/src/server/mcp-server.d.ts +5 -1
  48. package/dist/src/server/mcp-server.d.ts.map +1 -1
  49. package/dist/src/server/notifications/index.d.ts +1 -1
  50. package/dist/src/server/notifications/index.d.ts.map +1 -1
  51. package/dist/src/server/notifications/notification-registration.d.ts +51 -0
  52. package/dist/src/server/notifications/notification-registration.d.ts.map +1 -1
  53. package/dist/src/server/sessions/index.d.ts +3 -1
  54. package/dist/src/server/sessions/index.d.ts.map +1 -1
  55. package/dist/src/server/sessions/session-manager.d.ts +30 -16
  56. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  57. package/dist/src/server/sessions/stores/filesystem.d.ts +121 -0
  58. package/dist/src/server/sessions/stores/filesystem.d.ts.map +1 -0
  59. package/dist/src/server/sessions/stores/index.d.ts +94 -0
  60. package/dist/src/server/sessions/stores/index.d.ts.map +1 -0
  61. package/dist/src/server/sessions/stores/memory.d.ts +82 -0
  62. package/dist/src/server/sessions/stores/memory.d.ts.map +1 -0
  63. package/dist/src/server/sessions/stores/redis.d.ts +164 -0
  64. package/dist/src/server/sessions/stores/redis.d.ts.map +1 -0
  65. package/dist/src/server/sessions/streams/index.d.ts +77 -0
  66. package/dist/src/server/sessions/streams/index.d.ts.map +1 -0
  67. package/dist/src/server/sessions/streams/memory.d.ts +76 -0
  68. package/dist/src/server/sessions/streams/memory.d.ts.map +1 -0
  69. package/dist/src/server/sessions/streams/redis.d.ts +146 -0
  70. package/dist/src/server/sessions/streams/redis.d.ts.map +1 -0
  71. package/dist/src/server/types/common.d.ts +105 -28
  72. package/dist/src/server/types/common.d.ts.map +1 -1
  73. package/dist/src/server/types/resource.d.ts +16 -0
  74. package/dist/src/server/types/resource.d.ts.map +1 -1
  75. package/dist/src/server/types/widget.d.ts +21 -2
  76. package/dist/src/server/types/widget.d.ts.map +1 -1
  77. package/dist/src/server/utils/response-helpers.d.ts +12 -6
  78. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  79. package/dist/src/server/widgets/index.d.ts +1 -1
  80. package/dist/src/server/widgets/index.d.ts.map +1 -1
  81. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  82. package/dist/src/server/widgets/setup-widget-routes.d.ts.map +1 -1
  83. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  84. package/dist/src/server/widgets/widget-helpers.d.ts +22 -0
  85. package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
  86. package/dist/src/server/widgets/widget-types.d.ts +2 -0
  87. package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
  88. package/dist/src/task_managers/index.d.ts +10 -0
  89. package/dist/src/task_managers/index.d.ts.map +1 -1
  90. package/dist/src/task_managers/sse.d.ts +34 -1
  91. package/dist/src/task_managers/sse.d.ts.map +1 -1
  92. package/dist/src/task_managers/streamable_http.d.ts +8 -2
  93. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  94. package/dist/src/version.d.ts +1 -1
  95. package/dist/{tool-execution-helpers-PAFGGAGL.js → tool-execution-helpers-MXVN6YNU.js} +2 -2
  96. package/dist/tsup.config.d.ts.map +1 -1
  97. package/package.json +29 -5
  98. /package/dist/{chunk-H4BZVTGK.js → chunk-LGDFGYRL.js} +0 -0
@@ -0,0 +1,1346 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/adapters/index.ts
32
+ var adapters_exports = {};
33
+ __export(adapters_exports, {
34
+ BaseAdapter: () => BaseAdapter,
35
+ LangChainAdapter: () => LangChainAdapter
36
+ });
37
+ module.exports = __toCommonJS(adapters_exports);
38
+
39
+ // src/logging.ts
40
+ async function getNodeModules() {
41
+ if (typeof process !== "undefined" && process.platform) {
42
+ try {
43
+ const fs = await import("fs");
44
+ const path = await import("path");
45
+ return { fs: fs.default, path: path.default };
46
+ } catch {
47
+ return { fs: null, path: null };
48
+ }
49
+ }
50
+ return { fs: null, path: null };
51
+ }
52
+ __name(getNodeModules, "getNodeModules");
53
+ var winston = null;
54
+ function loadWinstonSync() {
55
+ if (typeof require !== "undefined") {
56
+ try {
57
+ winston = require("winston");
58
+ } catch {
59
+ }
60
+ }
61
+ }
62
+ __name(loadWinstonSync, "loadWinstonSync");
63
+ async function getWinston() {
64
+ if (!winston) {
65
+ winston = await import("winston");
66
+ }
67
+ return winston;
68
+ }
69
+ __name(getWinston, "getWinston");
70
+ var DEFAULT_LOGGER_NAME = "mcp-use";
71
+ function isNodeJSEnvironment() {
72
+ try {
73
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
74
+ return false;
75
+ }
76
+ if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
77
+ return false;
78
+ }
79
+ const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
80
+ return hasNodeGlobals;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+ __name(isNodeJSEnvironment, "isNodeJSEnvironment");
86
+ var SimpleConsoleLogger = class {
87
+ static {
88
+ __name(this, "SimpleConsoleLogger");
89
+ }
90
+ _level;
91
+ name;
92
+ constructor(name = DEFAULT_LOGGER_NAME, level = "info") {
93
+ this.name = name;
94
+ this._level = level;
95
+ }
96
+ shouldLog(level) {
97
+ const levels = [
98
+ "error",
99
+ "warn",
100
+ "info",
101
+ "http",
102
+ "verbose",
103
+ "debug",
104
+ "silly"
105
+ ];
106
+ const currentIndex = levels.indexOf(this._level);
107
+ const messageIndex = levels.indexOf(level);
108
+ return messageIndex <= currentIndex;
109
+ }
110
+ formatMessage(level, message) {
111
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
112
+ return `${timestamp} [${this.name}] ${level}: ${message}`;
113
+ }
114
+ error(message) {
115
+ if (this.shouldLog("error")) {
116
+ console.error(this.formatMessage("error", message));
117
+ }
118
+ }
119
+ warn(message) {
120
+ if (this.shouldLog("warn")) {
121
+ console.warn(this.formatMessage("warn", message));
122
+ }
123
+ }
124
+ info(message) {
125
+ if (this.shouldLog("info")) {
126
+ console.info(this.formatMessage("info", message));
127
+ }
128
+ }
129
+ debug(message) {
130
+ if (this.shouldLog("debug")) {
131
+ console.debug(this.formatMessage("debug", message));
132
+ }
133
+ }
134
+ http(message) {
135
+ if (this.shouldLog("http")) {
136
+ console.log(this.formatMessage("http", message));
137
+ }
138
+ }
139
+ verbose(message) {
140
+ if (this.shouldLog("verbose")) {
141
+ console.log(this.formatMessage("verbose", message));
142
+ }
143
+ }
144
+ silly(message) {
145
+ if (this.shouldLog("silly")) {
146
+ console.log(this.formatMessage("silly", message));
147
+ }
148
+ }
149
+ // Make it compatible with Winston interface
150
+ get level() {
151
+ return this._level;
152
+ }
153
+ set level(newLevel) {
154
+ this._level = newLevel;
155
+ }
156
+ };
157
+ function resolveLevel(env) {
158
+ const envValue = typeof process !== "undefined" && process.env ? env : void 0;
159
+ switch (envValue?.trim()) {
160
+ case "2":
161
+ return "debug";
162
+ case "1":
163
+ return "info";
164
+ default:
165
+ return "info";
166
+ }
167
+ }
168
+ __name(resolveLevel, "resolveLevel");
169
+ var Logger = class {
170
+ static {
171
+ __name(this, "Logger");
172
+ }
173
+ static instances = {};
174
+ static simpleInstances = {};
175
+ static currentFormat = "minimal";
176
+ static get(name = DEFAULT_LOGGER_NAME) {
177
+ if (!isNodeJSEnvironment()) {
178
+ if (!this.simpleInstances[name]) {
179
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
180
+ this.simpleInstances[name] = new SimpleConsoleLogger(
181
+ name,
182
+ resolveLevel(debugEnv)
183
+ );
184
+ }
185
+ return this.simpleInstances[name];
186
+ }
187
+ if (!this.instances[name]) {
188
+ if (!winston) {
189
+ throw new Error("Winston not loaded - call Logger.configure() first");
190
+ }
191
+ const { createLogger, format } = winston;
192
+ const { combine, timestamp, label, colorize, splat } = format;
193
+ this.instances[name] = createLogger({
194
+ level: resolveLevel(process.env.DEBUG),
195
+ format: combine(
196
+ colorize(),
197
+ splat(),
198
+ label({ label: name }),
199
+ timestamp({ format: "HH:mm:ss" }),
200
+ this.getFormatter()
201
+ ),
202
+ transports: [new winston.transports.Console()]
203
+ });
204
+ }
205
+ return this.instances[name];
206
+ }
207
+ static getFormatter() {
208
+ if (!winston) {
209
+ throw new Error("Winston not loaded");
210
+ }
211
+ const { format } = winston;
212
+ const { printf } = format;
213
+ const minimalFormatter = printf(({ level, message, label, timestamp }) => {
214
+ return `${timestamp} [${label}] ${level}: ${message}`;
215
+ });
216
+ const detailedFormatter = printf(({ level, message, label, timestamp }) => {
217
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
218
+ });
219
+ const emojiFormatter = printf(({ level, message, label, timestamp }) => {
220
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
221
+ });
222
+ switch (this.currentFormat) {
223
+ case "minimal":
224
+ return minimalFormatter;
225
+ case "detailed":
226
+ return detailedFormatter;
227
+ case "emoji":
228
+ return emojiFormatter;
229
+ default:
230
+ return minimalFormatter;
231
+ }
232
+ }
233
+ static async configure(options = {}) {
234
+ const { level, console: console2 = true, file, format = "minimal" } = options;
235
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
236
+ const resolvedLevel = level ?? resolveLevel(debugEnv);
237
+ this.currentFormat = format;
238
+ if (!isNodeJSEnvironment()) {
239
+ Object.values(this.simpleInstances).forEach((logger2) => {
240
+ logger2.level = resolvedLevel;
241
+ });
242
+ return;
243
+ }
244
+ await getWinston();
245
+ if (!winston) {
246
+ throw new Error("Failed to load winston");
247
+ }
248
+ const root = this.get();
249
+ root.level = resolvedLevel;
250
+ const winstonRoot = root;
251
+ winstonRoot.clear();
252
+ if (console2) {
253
+ winstonRoot.add(new winston.transports.Console());
254
+ }
255
+ if (file) {
256
+ const { fs: nodeFs, path: nodePath } = await getNodeModules();
257
+ if (nodeFs && nodePath) {
258
+ const dir = nodePath.dirname(nodePath.resolve(file));
259
+ if (!nodeFs.existsSync(dir)) {
260
+ nodeFs.mkdirSync(dir, { recursive: true });
261
+ }
262
+ winstonRoot.add(new winston.transports.File({ filename: file }));
263
+ }
264
+ }
265
+ const { format: winstonFormat } = winston;
266
+ const { combine, timestamp, label, colorize, splat } = winstonFormat;
267
+ Object.values(this.instances).forEach((logger2) => {
268
+ if (logger2 && "format" in logger2) {
269
+ logger2.level = resolvedLevel;
270
+ logger2.format = combine(
271
+ colorize(),
272
+ splat(),
273
+ label({ label: DEFAULT_LOGGER_NAME }),
274
+ timestamp({ format: "HH:mm:ss" }),
275
+ this.getFormatter()
276
+ );
277
+ }
278
+ });
279
+ }
280
+ static setDebug(enabled) {
281
+ let level;
282
+ if (enabled === 2 || enabled === true) level = "debug";
283
+ else if (enabled === 1) level = "info";
284
+ else level = "info";
285
+ Object.values(this.simpleInstances).forEach((logger2) => {
286
+ logger2.level = level;
287
+ });
288
+ Object.values(this.instances).forEach((logger2) => {
289
+ if (logger2) {
290
+ logger2.level = level;
291
+ }
292
+ });
293
+ if (typeof process !== "undefined" && process.env) {
294
+ process.env.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
295
+ }
296
+ }
297
+ static setFormat(format) {
298
+ this.currentFormat = format;
299
+ this.configure({ format });
300
+ }
301
+ };
302
+ if (isNodeJSEnvironment()) {
303
+ loadWinstonSync();
304
+ if (winston) {
305
+ Logger.configure();
306
+ }
307
+ }
308
+ var logger = Logger.get();
309
+
310
+ // src/adapters/base.ts
311
+ var BaseAdapter = class {
312
+ static {
313
+ __name(this, "BaseAdapter");
314
+ }
315
+ /**
316
+ * List of tool names that should not be available.
317
+ */
318
+ disallowedTools;
319
+ /**
320
+ * Internal cache that maps a connector instance to the list of tools
321
+ * generated for it.
322
+ */
323
+ connectorToolMap = /* @__PURE__ */ new Map();
324
+ constructor(disallowedTools) {
325
+ this.disallowedTools = disallowedTools ?? [];
326
+ }
327
+ /**
328
+ * Create tools from an MCPClient instance.
329
+ *
330
+ * This is the recommended way to create tools from an MCPClient, as it handles
331
+ * session creation and connector extraction automatically.
332
+ *
333
+ * @param client The MCPClient to extract tools from.
334
+ * @param disallowedTools Optional list of tool names to exclude.
335
+ * @returns A promise that resolves with a list of converted tools.
336
+ */
337
+ static async createTools(client, disallowedTools) {
338
+ const adapter = new this(disallowedTools);
339
+ if (!client.activeSessions || Object.keys(client.activeSessions).length === 0) {
340
+ logger.info("No active sessions found, creating new ones...");
341
+ await client.createAllSessions();
342
+ }
343
+ const sessions = client.getAllActiveSessions();
344
+ const connectors = Object.values(sessions).map(
345
+ (session) => session.connector
346
+ );
347
+ return adapter.createToolsFromConnectors(connectors);
348
+ }
349
+ /**
350
+ * Dynamically load tools for a specific connector.
351
+ *
352
+ * @param connector The connector to load tools for.
353
+ * @returns The list of tools that were loaded in the target framework's format.
354
+ */
355
+ async loadToolsForConnector(connector) {
356
+ if (this.connectorToolMap.has(connector)) {
357
+ const cached = this.connectorToolMap.get(connector);
358
+ logger.debug(`Returning ${cached.length} existing tools for connector`);
359
+ return cached;
360
+ }
361
+ const connectorTools = [];
362
+ const success = await this.ensureConnectorInitialized(connector);
363
+ if (!success) {
364
+ return [];
365
+ }
366
+ for (const tool of connector.tools) {
367
+ const converted = this.convertTool(tool, connector);
368
+ if (converted) {
369
+ connectorTools.push(converted);
370
+ }
371
+ }
372
+ this.connectorToolMap.set(connector, connectorTools);
373
+ logger.debug(
374
+ `Loaded ${connectorTools.length} new tools for connector: ${connectorTools.map((t) => t?.name ?? String(t)).join(", ")}`
375
+ );
376
+ return connectorTools;
377
+ }
378
+ /**
379
+ * Create tools from MCP tools in all provided connectors.
380
+ *
381
+ * @param connectors List of MCP connectors to create tools from.
382
+ * @returns A promise that resolves with all converted tools.
383
+ */
384
+ async createToolsFromConnectors(connectors) {
385
+ const tools = [];
386
+ for (const connector of connectors) {
387
+ const connectorTools = await this.loadToolsForConnector(connector);
388
+ tools.push(...connectorTools);
389
+ }
390
+ logger.debug(`Available tools: ${tools.length}`);
391
+ return tools;
392
+ }
393
+ /**
394
+ * Dynamically load resources for a specific connector.
395
+ *
396
+ * @param connector The connector to load resources for.
397
+ * @returns The list of resources that were loaded in the target framework's format.
398
+ */
399
+ async loadResourcesForConnector(connector) {
400
+ const connectorResources = [];
401
+ const success = await this.ensureConnectorInitialized(connector);
402
+ if (!success) {
403
+ return [];
404
+ }
405
+ try {
406
+ const resourcesResult = await connector.listAllResources();
407
+ const resources = resourcesResult?.resources || [];
408
+ if (this.convertResource) {
409
+ for (const resource of resources) {
410
+ const converted = this.convertResource(resource, connector);
411
+ if (converted) {
412
+ connectorResources.push(converted);
413
+ }
414
+ }
415
+ }
416
+ logger.debug(
417
+ `Loaded ${connectorResources.length} new resources for connector: ${connectorResources.map((r) => r?.name ?? String(r)).join(", ")}`
418
+ );
419
+ } catch (err) {
420
+ logger.warn(`Error loading resources for connector: ${err}`);
421
+ }
422
+ return connectorResources;
423
+ }
424
+ /**
425
+ * Dynamically load prompts for a specific connector.
426
+ *
427
+ * @param connector The connector to load prompts for.
428
+ * @returns The list of prompts that were loaded in the target framework's format.
429
+ */
430
+ async loadPromptsForConnector(connector) {
431
+ const connectorPrompts = [];
432
+ const success = await this.ensureConnectorInitialized(connector);
433
+ if (!success) {
434
+ return [];
435
+ }
436
+ try {
437
+ const promptsResult = await connector.listPrompts();
438
+ const prompts = promptsResult?.prompts || [];
439
+ if (this.convertPrompt) {
440
+ for (const prompt of prompts) {
441
+ const converted = this.convertPrompt(prompt, connector);
442
+ if (converted) {
443
+ connectorPrompts.push(converted);
444
+ }
445
+ }
446
+ }
447
+ logger.debug(
448
+ `Loaded ${connectorPrompts.length} new prompts for connector: ${connectorPrompts.map((p) => p?.name ?? String(p)).join(", ")}`
449
+ );
450
+ } catch (err) {
451
+ logger.warn(`Error loading prompts for connector: ${err}`);
452
+ }
453
+ return connectorPrompts;
454
+ }
455
+ /**
456
+ * Create resources from MCP resources in all provided connectors.
457
+ *
458
+ * @param connectors List of MCP connectors to create resources from.
459
+ * @returns A promise that resolves with all converted resources.
460
+ */
461
+ async createResourcesFromConnectors(connectors) {
462
+ const resources = [];
463
+ for (const connector of connectors) {
464
+ const connectorResources = await this.loadResourcesForConnector(connector);
465
+ resources.push(...connectorResources);
466
+ }
467
+ logger.debug(`Available resources: ${resources.length}`);
468
+ return resources;
469
+ }
470
+ /**
471
+ * Create prompts from MCP prompts in all provided connectors.
472
+ *
473
+ * @param connectors List of MCP connectors to create prompts from.
474
+ * @returns A promise that resolves with all converted prompts.
475
+ */
476
+ async createPromptsFromConnectors(connectors) {
477
+ const prompts = [];
478
+ for (const connector of connectors) {
479
+ const connectorPrompts = await this.loadPromptsForConnector(connector);
480
+ prompts.push(...connectorPrompts);
481
+ }
482
+ logger.debug(`Available prompts: ${prompts.length}`);
483
+ return prompts;
484
+ }
485
+ /**
486
+ * Check if a connector is initialized and has tools.
487
+ *
488
+ * @param connector The connector to check.
489
+ * @returns True if the connector is initialized and has tools, false otherwise.
490
+ */
491
+ checkConnectorInitialized(connector) {
492
+ return Boolean(connector.tools && connector.tools.length);
493
+ }
494
+ /**
495
+ * Ensure a connector is initialized.
496
+ *
497
+ * @param connector The connector to initialize.
498
+ * @returns True if initialization succeeded, false otherwise.
499
+ */
500
+ async ensureConnectorInitialized(connector) {
501
+ if (!this.checkConnectorInitialized(connector)) {
502
+ logger.debug("Connector doesn't have tools, initializing it");
503
+ try {
504
+ await connector.initialize();
505
+ return true;
506
+ } catch (err) {
507
+ logger.error(`Error initializing connector: ${err}`);
508
+ return false;
509
+ }
510
+ }
511
+ return true;
512
+ }
513
+ };
514
+
515
+ // src/utils/json-schema-to-zod/JSONSchemaToZod.ts
516
+ var import_zod = require("zod");
517
+ var JSONSchemaToZod = class {
518
+ static {
519
+ __name(this, "JSONSchemaToZod");
520
+ }
521
+ /**
522
+ * Converts a JSON schema to a Zod schema.
523
+ *
524
+ * @param {JSONSchema} schema - The JSON schema.
525
+ * @returns {ZodSchema} - The Zod schema.
526
+ */
527
+ static convert(schema) {
528
+ return this.parseSchema(schema);
529
+ }
530
+ /**
531
+ * Checks if data matches a condition schema.
532
+ *
533
+ * @param {JSONValue} data - The data to check.
534
+ * @param {JSONSchema} condition - The condition schema.
535
+ * @returns {boolean} - Whether the data matches the condition.
536
+ */
537
+ static matchesCondition(data, condition) {
538
+ if (!condition.properties) {
539
+ return true;
540
+ }
541
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
542
+ return false;
543
+ }
544
+ const objectData = data;
545
+ for (const [key, propCondition] of Object.entries(condition.properties)) {
546
+ if (!(key in objectData)) {
547
+ if ("const" in propCondition) {
548
+ return false;
549
+ }
550
+ continue;
551
+ }
552
+ const value = objectData[key];
553
+ if ("const" in propCondition && value !== propCondition["const"]) {
554
+ return false;
555
+ }
556
+ if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
557
+ return false;
558
+ }
559
+ if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
560
+ return false;
561
+ }
562
+ }
563
+ return true;
564
+ }
565
+ /**
566
+ * Validates data against a conditional schema and adds issues to context if validation fails.
567
+ *
568
+ * @param {JSONValue} data - The data to validate.
569
+ * @param {JSONSchema} schema - The conditional schema.
570
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
571
+ */
572
+ static validateConditionalSchema(data, schema, ctx) {
573
+ this.validateRequiredProperties(data, schema, ctx);
574
+ this.validatePropertyPatterns(data, schema, ctx);
575
+ this.validateNestedConditions(data, schema, ctx);
576
+ }
577
+ /**
578
+ * Validates that all required properties are present in the data.
579
+ *
580
+ * @param {JSONValue} data - The data to validate.
581
+ * @param {JSONSchema} schema - The schema containing required properties.
582
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
583
+ */
584
+ static validateRequiredProperties(data, schema, ctx) {
585
+ if (!schema.required) {
586
+ return;
587
+ }
588
+ if (typeof data !== "object" || data === null) {
589
+ for (const requiredProp of schema.required) {
590
+ ctx.addIssue({
591
+ code: import_zod.z.ZodIssueCode.custom,
592
+ message: `Required property '${requiredProp}' is missing`,
593
+ path: [requiredProp]
594
+ });
595
+ }
596
+ return;
597
+ }
598
+ for (const requiredProp of schema.required) {
599
+ if (!(requiredProp in data)) {
600
+ ctx.addIssue({
601
+ code: import_zod.z.ZodIssueCode.custom,
602
+ message: `Required property '${requiredProp}' is missing`,
603
+ path: [requiredProp]
604
+ });
605
+ }
606
+ }
607
+ }
608
+ /**
609
+ * Validates property patterns for string properties.
610
+ *
611
+ * @param {JSONValue} data - The data to validate.
612
+ * @param {JSONSchema} schema - The schema containing property patterns.
613
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
614
+ */
615
+ static validatePropertyPatterns(data, schema, ctx) {
616
+ if (!schema.properties) {
617
+ return;
618
+ }
619
+ if (typeof data !== "object" || data === null) {
620
+ return;
621
+ }
622
+ if (Array.isArray(data)) {
623
+ return;
624
+ }
625
+ const objectData = data;
626
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
627
+ if (!(key in objectData)) {
628
+ continue;
629
+ }
630
+ const value = objectData[key];
631
+ if (propSchema["pattern"] && typeof value === "string") {
632
+ const regex = new RegExp(propSchema["pattern"]);
633
+ if (!regex.test(value)) {
634
+ ctx.addIssue({
635
+ code: import_zod.z.ZodIssueCode.custom,
636
+ message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
637
+ path: [key]
638
+ });
639
+ }
640
+ }
641
+ }
642
+ }
643
+ /**
644
+ * Validates nested if-then-else conditions.
645
+ *
646
+ * @param {JSONValue} data - The data to validate.
647
+ * @param {JSONSchema} schema - The schema containing if-then-else conditions.
648
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
649
+ */
650
+ static validateNestedConditions(data, schema, ctx) {
651
+ if (!schema["if"] || !schema["then"]) {
652
+ return;
653
+ }
654
+ const matchesIf = this.matchesCondition(data, schema["if"]);
655
+ if (matchesIf) {
656
+ this.validateConditionalSchema(data, schema["then"], ctx);
657
+ } else if (schema["else"]) {
658
+ this.validateConditionalSchema(data, schema["else"], ctx);
659
+ }
660
+ }
661
+ /**
662
+ * Parses a JSON schema and returns the corresponding Zod schema.
663
+ * This is the main entry point for schema conversion.
664
+ *
665
+ * @param {JSONSchema} schema - The JSON schema.
666
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
667
+ */
668
+ static parseSchema(schema) {
669
+ if (Array.isArray(schema.type)) {
670
+ return this.handleTypeArray(schema);
671
+ }
672
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
673
+ return this.parseCombinator(schema);
674
+ }
675
+ if (schema["if"] && schema["then"]) {
676
+ return this.parseObject(schema);
677
+ }
678
+ if (schema.properties && (!schema.type || schema.type === "object")) {
679
+ return this.parseObject(schema);
680
+ }
681
+ return this.handleSingleType(schema);
682
+ }
683
+ /**
684
+ * Handles schemas with an array of types.
685
+ *
686
+ * @param {JSONSchema} schema - The JSON schema with type array.
687
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
688
+ */
689
+ static handleTypeArray(schema) {
690
+ if (!Array.isArray(schema.type)) {
691
+ throw new Error("Expected schema.type to be an array");
692
+ }
693
+ if (schema.type.includes("null")) {
694
+ return this.handleNullableType(schema);
695
+ }
696
+ return this.createUnionFromTypes(schema.type, schema);
697
+ }
698
+ /**
699
+ * Handles nullable types by creating a nullable schema.
700
+ *
701
+ * @param {JSONSchema} schema - The JSON schema with nullable type.
702
+ * @returns {ZodTypeAny} - The nullable Zod schema.
703
+ */
704
+ static handleNullableType(schema) {
705
+ if (!Array.isArray(schema.type)) {
706
+ throw new Error("Expected schema.type to be an array");
707
+ }
708
+ const nonNullSchema = { ...schema };
709
+ nonNullSchema.type = schema.type.filter((t) => t !== "null");
710
+ if (nonNullSchema.type.length === 1) {
711
+ const singleTypeSchema = this.handleSingleType({
712
+ ...schema,
713
+ type: nonNullSchema.type[0]
714
+ });
715
+ return singleTypeSchema.nullable();
716
+ }
717
+ const unionSchema = this.parseSchema(nonNullSchema);
718
+ return unionSchema.nullable();
719
+ }
720
+ /**
721
+ * Creates a union type from an array of types.
722
+ *
723
+ * @param {string[]} types - Array of type strings.
724
+ * @param {JSONSchema} baseSchema - The base schema to apply to each type.
725
+ * @returns {ZodTypeAny} - The union Zod schema.
726
+ */
727
+ static createUnionFromTypes(types, baseSchema) {
728
+ const schemas = types.map((type) => {
729
+ const singleTypeSchema = { ...baseSchema, type };
730
+ return this.parseSchema(singleTypeSchema);
731
+ });
732
+ return import_zod.z.union(schemas);
733
+ }
734
+ /**
735
+ * Handles schemas with a single type.
736
+ *
737
+ * @param {JSONSchema} schema - The JSON schema with single type.
738
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
739
+ */
740
+ static handleSingleType(schema) {
741
+ if (schema.type === void 0) {
742
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
743
+ return this.parseCombinator(schema);
744
+ }
745
+ if (schema.properties) {
746
+ return this.parseObject(schema);
747
+ }
748
+ return import_zod.z.any();
749
+ }
750
+ switch (schema.type) {
751
+ case "string":
752
+ return this.parseString(schema);
753
+ case "number":
754
+ case "integer":
755
+ return this.parseNumberSchema(schema);
756
+ case "boolean":
757
+ return import_zod.z.boolean();
758
+ case "array":
759
+ return this.parseArray(schema);
760
+ case "object":
761
+ return this.parseObject(schema);
762
+ default:
763
+ throw new Error("Unsupported schema type");
764
+ }
765
+ }
766
+ /**
767
+ * Parses a number schema.
768
+ *
769
+ * @param {JSONSchema} schema - The JSON schema for a number.
770
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
771
+ */
772
+ static parseNumberSchema(schema) {
773
+ const numberSchema = import_zod.z.number();
774
+ let result = numberSchema;
775
+ result = this.applyNumberBounds(numberSchema, schema);
776
+ result = this.applyNumberMultipleOf(numberSchema, schema);
777
+ result = this.applyNumberEnum(numberSchema, schema);
778
+ result = this.applyIntegerConstraint(numberSchema, schema);
779
+ return result;
780
+ }
781
+ /**
782
+ * Applies bounds validation to a number schema.
783
+ *
784
+ * @param {z.ZodNumber} numberSchema - The base number schema.
785
+ * @param {JSONSchema} schema - The JSON schema with bounds.
786
+ * @returns {z.ZodNumber} - The updated schema with bounds validation.
787
+ */
788
+ static applyNumberBounds(numberSchema, schema) {
789
+ let result = numberSchema;
790
+ if (schema["minimum"] !== void 0) {
791
+ result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
792
+ }
793
+ if (schema["maximum"] !== void 0) {
794
+ result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
795
+ }
796
+ return result;
797
+ }
798
+ /**
799
+ * Applies multipleOf validation to a number schema.
800
+ *
801
+ * @param {z.ZodNumber} numberSchema - The base number schema.
802
+ * @param {JSONSchema} schema - The JSON schema with multipleOf.
803
+ * @returns {z.ZodNumber} - The updated schema with multipleOf validation.
804
+ */
805
+ static applyNumberMultipleOf(numberSchema, schema) {
806
+ if (schema["multipleOf"] === void 0) {
807
+ return numberSchema;
808
+ }
809
+ return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
810
+ message: `Number must be a multiple of ${schema["multipleOf"]}`
811
+ });
812
+ }
813
+ /**
814
+ * Applies enum validation to a number schema.
815
+ *
816
+ * @param {z.ZodNumber} numberSchema - The base number schema.
817
+ * @param {JSONSchema} schema - The JSON schema with enum.
818
+ * @returns {z.ZodNumber} - The updated schema with enum validation.
819
+ */
820
+ static applyNumberEnum(numberSchema, schema) {
821
+ if (!schema.enum) {
822
+ return numberSchema;
823
+ }
824
+ const numberEnums = schema.enum.filter(
825
+ (val) => typeof val === "number"
826
+ );
827
+ if (numberEnums.length === 0) {
828
+ return numberSchema;
829
+ }
830
+ return numberSchema.refine((val) => numberEnums.includes(val), {
831
+ message: `Number must be one of: ${numberEnums.join(", ")}`
832
+ });
833
+ }
834
+ /**
835
+ * Applies integer constraint to a number schema if needed.
836
+ *
837
+ * @param {z.ZodNumber} numberSchema - The base number schema.
838
+ * @param {JSONSchema} schema - The JSON schema.
839
+ * @returns {z.ZodNumber} - The updated schema with integer validation if needed.
840
+ */
841
+ static applyIntegerConstraint(numberSchema, schema) {
842
+ if (schema.type !== "integer") {
843
+ return numberSchema;
844
+ }
845
+ return numberSchema.refine((val) => Number.isInteger(val), {
846
+ message: "Number must be an integer"
847
+ });
848
+ }
849
+ /**
850
+ * Parses a string schema.
851
+ *
852
+ * @param {JSONSchema} schema - The JSON schema for a string.
853
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
854
+ */
855
+ static parseString(schema) {
856
+ const stringSchema = import_zod.z.string();
857
+ let result = stringSchema;
858
+ if (schema.format) {
859
+ return this.applyStringFormat(stringSchema, schema);
860
+ } else {
861
+ result = this.applyStringPattern(stringSchema, schema);
862
+ result = this.applyStringLength(stringSchema, schema);
863
+ result = this.applyStringEnum(stringSchema, schema);
864
+ }
865
+ return result;
866
+ }
867
+ /**
868
+ * Applies format validation to a string schema.
869
+ *
870
+ * @param {z.ZodString} stringSchema - The base string schema.
871
+ * @param {JSONSchema} schema - The JSON schema with format.
872
+ * @returns {ZodTypeAny} - The updated schema with format validation.
873
+ */
874
+ static applyStringFormat(stringSchema, schema) {
875
+ if (!schema.format) {
876
+ return stringSchema;
877
+ }
878
+ switch (schema.format) {
879
+ case "email":
880
+ return stringSchema.email();
881
+ case "date-time":
882
+ return stringSchema.datetime();
883
+ case "uri":
884
+ return stringSchema.url();
885
+ case "uuid":
886
+ return stringSchema.uuid();
887
+ case "date":
888
+ return stringSchema.date();
889
+ default:
890
+ return stringSchema;
891
+ }
892
+ }
893
+ /**
894
+ * Applies pattern validation to a string schema.
895
+ *
896
+ * @param {z.ZodString} stringSchema - The base string schema.
897
+ * @param {JSONSchema} schema - The JSON schema with pattern.
898
+ * @returns {z.ZodString} - The updated schema with pattern validation.
899
+ */
900
+ static applyStringPattern(stringSchema, schema) {
901
+ if (!schema["pattern"]) {
902
+ return stringSchema;
903
+ }
904
+ const regex = new RegExp(schema["pattern"]);
905
+ return stringSchema.regex(regex, {
906
+ message: `String must match pattern: ${schema["pattern"]}`
907
+ });
908
+ }
909
+ /**
910
+ * Applies length constraints to a string schema.
911
+ *
912
+ * @param {z.ZodString} stringSchema - The base string schema.
913
+ * @param {JSONSchema} schema - The JSON schema with length constraints.
914
+ * @returns {z.ZodString} - The updated schema with length validation.
915
+ */
916
+ static applyStringLength(stringSchema, schema) {
917
+ const result = stringSchema;
918
+ if (schema["minLength"] !== void 0) {
919
+ stringSchema = stringSchema.min(schema["minLength"]);
920
+ }
921
+ if (schema["maxLength"] !== void 0) {
922
+ stringSchema = stringSchema.max(schema["maxLength"]);
923
+ }
924
+ return result;
925
+ }
926
+ /**
927
+ * Applies enum validation to a string schema.
928
+ *
929
+ * @param {z.ZodString} stringSchema - The base string schema.
930
+ * @param {JSONSchema} schema - The JSON schema with enum.
931
+ * @returns {ZodTypeAny} - The updated schema with enum validation.
932
+ */
933
+ static applyStringEnum(stringSchema, schema) {
934
+ if (!schema.enum) {
935
+ return stringSchema;
936
+ }
937
+ return stringSchema.refine((val) => schema.enum?.includes(val), {
938
+ message: `Value must be one of: ${schema.enum?.join(", ")}`
939
+ });
940
+ }
941
+ /**
942
+ * Parses a JSON schema of type array and returns the corresponding Zod schema.
943
+ *
944
+ * @param {JSONSchema} schema - The JSON schema.
945
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
946
+ */
947
+ static parseArray(schema) {
948
+ if (Array.isArray(schema.items)) {
949
+ const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
950
+ return import_zod.z.union(tupleSchemas);
951
+ }
952
+ const itemSchema = schema.items ? this.parseSchema(schema.items) : import_zod.z.any();
953
+ const arraySchema = import_zod.z.array(itemSchema);
954
+ let result = arraySchema;
955
+ result = this.applyArrayConstraints(arraySchema, schema);
956
+ return result;
957
+ }
958
+ /**
959
+ * Applies constraints to an array schema.
960
+ *
961
+ * @param {z.ZodArray<any>} arraySchema - The base array schema.
962
+ * @param {JSONSchema} schema - The JSON schema with array constraints.
963
+ * @returns {z.ZodTypeAny} - The updated array schema with constraints.
964
+ */
965
+ static applyArrayConstraints(arraySchema, schema) {
966
+ if (schema["minItems"] !== void 0) {
967
+ arraySchema = arraySchema.min(schema["minItems"]);
968
+ }
969
+ if (schema["maxItems"] !== void 0) {
970
+ arraySchema = arraySchema.max(schema["maxItems"]);
971
+ }
972
+ if (schema["uniqueItems"]) {
973
+ return arraySchema.refine(
974
+ (items) => new Set(items).size === items.length,
975
+ { message: "Array items must be unique" }
976
+ );
977
+ }
978
+ return arraySchema;
979
+ }
980
+ /**
981
+ * Parses an object schema.
982
+ *
983
+ * @param {JSONSchema} schema - The JSON schema for an object.
984
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
985
+ */
986
+ static parseObject(schema) {
987
+ if (schema["if"] && schema["then"]) {
988
+ return this.parseConditional(schema);
989
+ }
990
+ const shape = {};
991
+ this.processObjectProperties(schema, shape);
992
+ return this.processAdditionalProperties(schema, import_zod.z.object(shape));
993
+ }
994
+ /**
995
+ * Processes object properties and builds the shape object.
996
+ *
997
+ * @param {JSONSchema} schema - The JSON schema for an object.
998
+ * @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
999
+ */
1000
+ static processObjectProperties(schema, shape) {
1001
+ const required = new Set(schema.required || []);
1002
+ if (!schema.properties) {
1003
+ return;
1004
+ }
1005
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
1006
+ const zodSchema = this.parseSchema(propSchema);
1007
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
1008
+ }
1009
+ }
1010
+ /**
1011
+ * Processes additionalProperties configuration.
1012
+ *
1013
+ * @param {JSONSchema} schema - The JSON schema for an object.
1014
+ * @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
1015
+ * @returns {z.ZodObject<any, any>} - The updated Zod object schema.
1016
+ */
1017
+ static processAdditionalProperties(schema, objectSchema) {
1018
+ if (schema.additionalProperties === true) {
1019
+ return objectSchema.passthrough();
1020
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
1021
+ const additionalPropSchema = this.parseSchema(
1022
+ schema.additionalProperties
1023
+ );
1024
+ return objectSchema.catchall(additionalPropSchema);
1025
+ } else {
1026
+ return objectSchema.strict();
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Parses a conditional schema with if-then-else.
1031
+ *
1032
+ * @param {JSONSchema} schema - The JSON schema with conditional validation.
1033
+ * @returns {ZodTypeAny} - The conditional Zod schema.
1034
+ */
1035
+ static parseConditional(schema) {
1036
+ const zodObject = this.createBaseObjectSchema(schema);
1037
+ const ifCondition = schema["if"];
1038
+ const thenSchema = schema["then"];
1039
+ const elseSchema = schema["else"];
1040
+ return zodObject.superRefine((data, ctx) => {
1041
+ const dataWithDefaults = this.applyDefaultValues(
1042
+ data,
1043
+ schema
1044
+ );
1045
+ if (this.matchesCondition(dataWithDefaults, ifCondition)) {
1046
+ this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
1047
+ } else if (elseSchema) {
1048
+ this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
1049
+ }
1050
+ });
1051
+ }
1052
+ /**
1053
+ * Creates a base object schema from the given JSON schema.
1054
+ *
1055
+ * @param {JSONSchema} schema - The JSON schema.
1056
+ * @returns {z.ZodObject<any, any>} - The base Zod object schema.
1057
+ */
1058
+ static createBaseObjectSchema(schema) {
1059
+ const shape = {};
1060
+ const required = new Set(schema.required || []);
1061
+ for (const [key, value] of Object.entries(schema.properties || {})) {
1062
+ const zodSchema = this.parseSchema(value);
1063
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
1064
+ }
1065
+ const zodObject = import_zod.z.object(shape);
1066
+ return this.processAdditionalProperties(schema, zodObject);
1067
+ }
1068
+ /**
1069
+ * Applies default values from schema properties to data object.
1070
+ *
1071
+ * @param {JSONValue} data - The original data object.
1072
+ * @param {JSONSchema} schema - The schema with default values.
1073
+ * @returns {JSONValue} - The data object with defaults applied.
1074
+ */
1075
+ static applyDefaultValues(data, schema) {
1076
+ if (typeof data !== "object" || data === null) {
1077
+ return data;
1078
+ }
1079
+ if (Array.isArray(data)) {
1080
+ return data;
1081
+ }
1082
+ const objectData = data;
1083
+ const dataWithDefaults = { ...objectData };
1084
+ if (!schema.properties) {
1085
+ return dataWithDefaults;
1086
+ }
1087
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
1088
+ if (!(key in dataWithDefaults) && "default" in propSchema) {
1089
+ dataWithDefaults[key] = propSchema["default"];
1090
+ }
1091
+ }
1092
+ return dataWithDefaults;
1093
+ }
1094
+ /**
1095
+ * Parses a schema with combinators (oneOf, anyOf, allOf).
1096
+ * Delegates to the appropriate combinator parser based on which combinator is present.
1097
+ *
1098
+ * @param {JSONSchema} schema - The JSON schema with combinators.
1099
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
1100
+ */
1101
+ static parseCombinator(schema) {
1102
+ if (schema.oneOf) {
1103
+ return this.parseOneOf(schema.oneOf);
1104
+ }
1105
+ if (schema.anyOf) {
1106
+ return this.parseAnyOf(schema.anyOf);
1107
+ }
1108
+ if (schema.allOf) {
1109
+ return this.parseAllOf(schema.allOf);
1110
+ }
1111
+ throw new Error("Unsupported schema type");
1112
+ }
1113
+ /**
1114
+ * Parses a oneOf combinator schema.
1115
+ *
1116
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
1117
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
1118
+ */
1119
+ static parseOneOf(schemas) {
1120
+ return this.createUnionFromSchemas(schemas);
1121
+ }
1122
+ /**
1123
+ * Parses an anyOf combinator schema.
1124
+ *
1125
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
1126
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
1127
+ */
1128
+ static parseAnyOf(schemas) {
1129
+ return this.createUnionFromSchemas(schemas);
1130
+ }
1131
+ /**
1132
+ * Creates a union from an array of schemas, handling special cases.
1133
+ *
1134
+ * @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
1135
+ * @returns {ZodTypeAny} - The union Zod schema.
1136
+ */
1137
+ static createUnionFromSchemas(schemas) {
1138
+ if (schemas.length === 0) {
1139
+ return import_zod.z.any();
1140
+ }
1141
+ if (schemas.length === 1) {
1142
+ return this.parseSchema(schemas[0]);
1143
+ }
1144
+ const zodSchemas = [];
1145
+ for (const subSchema of schemas) {
1146
+ if (subSchema.type === "null") {
1147
+ zodSchemas.push(import_zod.z.null());
1148
+ } else {
1149
+ zodSchemas.push(this.parseSchema(subSchema));
1150
+ }
1151
+ }
1152
+ if (zodSchemas.length >= 2) {
1153
+ return import_zod.z.union(zodSchemas);
1154
+ } else if (zodSchemas.length === 1) {
1155
+ return zodSchemas[0];
1156
+ }
1157
+ return import_zod.z.any();
1158
+ }
1159
+ /**
1160
+ * Parses an allOf combinator schema by merging all schemas.
1161
+ *
1162
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
1163
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
1164
+ */
1165
+ static parseAllOf(schemas) {
1166
+ if (schemas.length === 0) {
1167
+ return import_zod.z.any();
1168
+ }
1169
+ if (schemas.length === 1) {
1170
+ return this.parseSchema(schemas[0]);
1171
+ }
1172
+ const mergedSchema = schemas.reduce(
1173
+ (acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
1174
+ );
1175
+ return this.parseSchema(mergedSchema);
1176
+ }
1177
+ /**
1178
+ * Merges two JSON schemas together.
1179
+ *
1180
+ * @param {JSONSchema} baseSchema - The base JSON schema.
1181
+ * @param {JSONSchema} addSchema - The JSON schema to add.
1182
+ * @returns {JSONSchema} - The merged JSON schema
1183
+ */
1184
+ static mergeSchemas(baseSchema, addSchema) {
1185
+ const merged = { ...baseSchema, ...addSchema };
1186
+ if (baseSchema.properties && addSchema.properties) {
1187
+ const mergedProperties = {
1188
+ ...baseSchema.properties,
1189
+ ...addSchema.properties
1190
+ };
1191
+ merged.properties = mergedProperties;
1192
+ }
1193
+ if (baseSchema.required && addSchema.required) {
1194
+ const mergedRequired = [
1195
+ .../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
1196
+ ];
1197
+ merged.required = mergedRequired;
1198
+ }
1199
+ return merged;
1200
+ }
1201
+ };
1202
+
1203
+ // src/adapters/langchain_adapter.ts
1204
+ var import_tools = require("@langchain/core/tools");
1205
+ var import_zod2 = require("zod");
1206
+ function schemaToZod(schema) {
1207
+ try {
1208
+ return JSONSchemaToZod.convert(schema);
1209
+ } catch (err) {
1210
+ logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
1211
+ return import_zod2.z.any();
1212
+ }
1213
+ }
1214
+ __name(schemaToZod, "schemaToZod");
1215
+ var LangChainAdapter = class extends BaseAdapter {
1216
+ static {
1217
+ __name(this, "LangChainAdapter");
1218
+ }
1219
+ constructor(disallowedTools = []) {
1220
+ super(disallowedTools);
1221
+ }
1222
+ /**
1223
+ * Convert a single MCP tool specification into a LangChainJS structured tool.
1224
+ */
1225
+ convertTool(mcpTool, connector) {
1226
+ if (this.disallowedTools.includes(mcpTool.name)) {
1227
+ return null;
1228
+ }
1229
+ const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : import_zod2.z.object({}).optional();
1230
+ const tool = new import_tools.DynamicStructuredTool({
1231
+ name: mcpTool.name ?? "NO NAME",
1232
+ description: mcpTool.description ?? "",
1233
+ // Blank is acceptable but discouraged.
1234
+ schema: argsSchema,
1235
+ func: /* @__PURE__ */ __name(async (input) => {
1236
+ logger.debug(
1237
+ `MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
1238
+ );
1239
+ try {
1240
+ const result = await connector.callTool(
1241
+ mcpTool.name,
1242
+ input
1243
+ );
1244
+ return JSON.stringify(result);
1245
+ } catch (err) {
1246
+ logger.error(`Error executing MCP tool: ${err.message}`);
1247
+ return `Error executing MCP tool: ${String(err)}`;
1248
+ }
1249
+ }, "func")
1250
+ });
1251
+ return tool;
1252
+ }
1253
+ /**
1254
+ * Convert a single MCP resource into a LangChainJS structured tool.
1255
+ * Each resource becomes an async tool that returns its content when called.
1256
+ */
1257
+ convertResource(mcpResource, connector) {
1258
+ const sanitizeName = /* @__PURE__ */ __name((name) => {
1259
+ return name.replace(/[^A-Za-z0-9_]+/g, "_").toLowerCase().replace(/^_+|_+$/g, "");
1260
+ }, "sanitizeName");
1261
+ const resourceName = sanitizeName(
1262
+ mcpResource.name || `resource_${mcpResource.uri}`
1263
+ );
1264
+ const resourceUri = mcpResource.uri;
1265
+ const tool = new import_tools.DynamicStructuredTool({
1266
+ name: resourceName,
1267
+ description: mcpResource.description || `Return the content of the resource located at URI ${resourceUri}.`,
1268
+ schema: import_zod2.z.object({}).optional(),
1269
+ // Resources take no arguments
1270
+ func: /* @__PURE__ */ __name(async () => {
1271
+ logger.debug(`Resource tool: "${resourceName}" called`);
1272
+ try {
1273
+ const result = await connector.readResource(resourceUri);
1274
+ if (result.contents && result.contents.length > 0) {
1275
+ return result.contents.map((content) => {
1276
+ if (typeof content === "string") {
1277
+ return content;
1278
+ }
1279
+ if (content.text) {
1280
+ return content.text;
1281
+ }
1282
+ if (content.uri) {
1283
+ return content.uri;
1284
+ }
1285
+ return JSON.stringify(content);
1286
+ }).join("\n");
1287
+ }
1288
+ return "Resource is empty or unavailable";
1289
+ } catch (err) {
1290
+ logger.error(`Error reading resource: ${err.message}`);
1291
+ return `Error reading resource: ${String(err)}`;
1292
+ }
1293
+ }, "func")
1294
+ });
1295
+ return tool;
1296
+ }
1297
+ /**
1298
+ * Convert a single MCP prompt into a LangChainJS structured tool.
1299
+ * The resulting tool executes getPrompt on the connector with the prompt's name
1300
+ * and the user-provided arguments (if any).
1301
+ */
1302
+ convertPrompt(mcpPrompt, connector) {
1303
+ let argsSchema = import_zod2.z.object({}).optional();
1304
+ if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {
1305
+ const schemaFields = {};
1306
+ for (const arg of mcpPrompt.arguments) {
1307
+ const zodType = import_zod2.z.string();
1308
+ if (arg.required !== false) {
1309
+ schemaFields[arg.name] = zodType;
1310
+ } else {
1311
+ schemaFields[arg.name] = zodType.optional();
1312
+ }
1313
+ }
1314
+ argsSchema = Object.keys(schemaFields).length > 0 ? import_zod2.z.object(schemaFields) : import_zod2.z.object({}).optional();
1315
+ }
1316
+ const tool = new import_tools.DynamicStructuredTool({
1317
+ name: mcpPrompt.name,
1318
+ description: mcpPrompt.description || "",
1319
+ schema: argsSchema,
1320
+ func: /* @__PURE__ */ __name(async (input) => {
1321
+ logger.debug(
1322
+ `Prompt tool: "${mcpPrompt.name}" called with args: ${JSON.stringify(input)}`
1323
+ );
1324
+ try {
1325
+ const result = await connector.getPrompt(mcpPrompt.name, input);
1326
+ if (result.messages && result.messages.length > 0) {
1327
+ return result.messages.map((msg) => {
1328
+ if (typeof msg === "string") {
1329
+ return msg;
1330
+ }
1331
+ if (msg.content) {
1332
+ return typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1333
+ }
1334
+ return JSON.stringify(msg);
1335
+ }).join("\n");
1336
+ }
1337
+ return "Prompt returned no messages";
1338
+ } catch (err) {
1339
+ logger.error(`Error getting prompt: ${err.message}`);
1340
+ return `Error getting prompt: ${String(err)}`;
1341
+ }
1342
+ }, "func")
1343
+ });
1344
+ return tool;
1345
+ }
1346
+ };