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
@@ -1,2087 +1,23 @@
1
1
  import {
2
- BaseMCPClient,
3
- ConnectionManager,
4
- HttpConnector,
5
- MCPSession
6
- } from "./chunk-QP7MQ2UJ.js";
2
+ MCPClient
3
+ } from "./chunk-WW3A2EKQ.js";
7
4
  import {
8
- CodeModeConnector
9
- } from "./chunk-REX2YTWF.js";
5
+ LangChainAdapter
6
+ } from "./chunk-MFSO5PUW.js";
10
7
  import {
11
- BaseConnector
12
- } from "./chunk-CHHWJQVC.js";
13
- import {
14
- Tel,
15
- Telemetry,
16
- extractModelInfo,
17
- getPackageVersion
18
- } from "./chunk-3QVRNWW7.js";
19
- import {
20
- logger
21
- } from "./chunk-FRUZDWXH.js";
22
- import {
23
- __name,
24
- __require
25
- } from "./chunk-3GQAWCBQ.js";
26
-
27
- // src/adapters/base.ts
28
- var BaseAdapter = class {
29
- static {
30
- __name(this, "BaseAdapter");
31
- }
32
- /**
33
- * List of tool names that should not be available.
34
- */
35
- disallowedTools;
36
- /**
37
- * Internal cache that maps a connector instance to the list of tools
38
- * generated for it.
39
- */
40
- connectorToolMap = /* @__PURE__ */ new Map();
41
- constructor(disallowedTools) {
42
- this.disallowedTools = disallowedTools ?? [];
43
- }
44
- /**
45
- * Create tools from an MCPClient instance.
46
- *
47
- * This is the recommended way to create tools from an MCPClient, as it handles
48
- * session creation and connector extraction automatically.
49
- *
50
- * @param client The MCPClient to extract tools from.
51
- * @param disallowedTools Optional list of tool names to exclude.
52
- * @returns A promise that resolves with a list of converted tools.
53
- */
54
- static async createTools(client, disallowedTools) {
55
- const adapter = new this(disallowedTools);
56
- if (!client.activeSessions || Object.keys(client.activeSessions).length === 0) {
57
- logger.info("No active sessions found, creating new ones...");
58
- await client.createAllSessions();
59
- }
60
- const sessions = client.getAllActiveSessions();
61
- const connectors = Object.values(sessions).map(
62
- (session) => session.connector
63
- );
64
- return adapter.createToolsFromConnectors(connectors);
65
- }
66
- /**
67
- * Dynamically load tools for a specific connector.
68
- *
69
- * @param connector The connector to load tools for.
70
- * @returns The list of tools that were loaded in the target framework's format.
71
- */
72
- async loadToolsForConnector(connector) {
73
- if (this.connectorToolMap.has(connector)) {
74
- const cached = this.connectorToolMap.get(connector);
75
- logger.debug(`Returning ${cached.length} existing tools for connector`);
76
- return cached;
77
- }
78
- const connectorTools = [];
79
- const success = await this.ensureConnectorInitialized(connector);
80
- if (!success) {
81
- return [];
82
- }
83
- for (const tool of connector.tools) {
84
- const converted = this.convertTool(tool, connector);
85
- if (converted) {
86
- connectorTools.push(converted);
87
- }
88
- }
89
- this.connectorToolMap.set(connector, connectorTools);
90
- logger.debug(
91
- `Loaded ${connectorTools.length} new tools for connector: ${connectorTools.map((t) => t?.name ?? String(t)).join(", ")}`
92
- );
93
- return connectorTools;
94
- }
95
- /**
96
- * Create tools from MCP tools in all provided connectors.
97
- *
98
- * @param connectors List of MCP connectors to create tools from.
99
- * @returns A promise that resolves with all converted tools.
100
- */
101
- async createToolsFromConnectors(connectors) {
102
- const tools = [];
103
- for (const connector of connectors) {
104
- const connectorTools = await this.loadToolsForConnector(connector);
105
- tools.push(...connectorTools);
106
- }
107
- logger.debug(`Available tools: ${tools.length}`);
108
- return tools;
109
- }
110
- /**
111
- * Dynamically load resources for a specific connector.
112
- *
113
- * @param connector The connector to load resources for.
114
- * @returns The list of resources that were loaded in the target framework's format.
115
- */
116
- async loadResourcesForConnector(connector) {
117
- const connectorResources = [];
118
- const success = await this.ensureConnectorInitialized(connector);
119
- if (!success) {
120
- return [];
121
- }
122
- try {
123
- const resourcesResult = await connector.listAllResources();
124
- const resources = resourcesResult?.resources || [];
125
- if (this.convertResource) {
126
- for (const resource of resources) {
127
- const converted = this.convertResource(resource, connector);
128
- if (converted) {
129
- connectorResources.push(converted);
130
- }
131
- }
132
- }
133
- logger.debug(
134
- `Loaded ${connectorResources.length} new resources for connector: ${connectorResources.map((r) => r?.name ?? String(r)).join(", ")}`
135
- );
136
- } catch (err) {
137
- logger.warn(`Error loading resources for connector: ${err}`);
138
- }
139
- return connectorResources;
140
- }
141
- /**
142
- * Dynamically load prompts for a specific connector.
143
- *
144
- * @param connector The connector to load prompts for.
145
- * @returns The list of prompts that were loaded in the target framework's format.
146
- */
147
- async loadPromptsForConnector(connector) {
148
- const connectorPrompts = [];
149
- const success = await this.ensureConnectorInitialized(connector);
150
- if (!success) {
151
- return [];
152
- }
153
- try {
154
- const promptsResult = await connector.listPrompts();
155
- const prompts = promptsResult?.prompts || [];
156
- if (this.convertPrompt) {
157
- for (const prompt of prompts) {
158
- const converted = this.convertPrompt(prompt, connector);
159
- if (converted) {
160
- connectorPrompts.push(converted);
161
- }
162
- }
163
- }
164
- logger.debug(
165
- `Loaded ${connectorPrompts.length} new prompts for connector: ${connectorPrompts.map((p) => p?.name ?? String(p)).join(", ")}`
166
- );
167
- } catch (err) {
168
- logger.warn(`Error loading prompts for connector: ${err}`);
169
- }
170
- return connectorPrompts;
171
- }
172
- /**
173
- * Create resources from MCP resources in all provided connectors.
174
- *
175
- * @param connectors List of MCP connectors to create resources from.
176
- * @returns A promise that resolves with all converted resources.
177
- */
178
- async createResourcesFromConnectors(connectors) {
179
- const resources = [];
180
- for (const connector of connectors) {
181
- const connectorResources = await this.loadResourcesForConnector(connector);
182
- resources.push(...connectorResources);
183
- }
184
- logger.debug(`Available resources: ${resources.length}`);
185
- return resources;
186
- }
187
- /**
188
- * Create prompts from MCP prompts in all provided connectors.
189
- *
190
- * @param connectors List of MCP connectors to create prompts from.
191
- * @returns A promise that resolves with all converted prompts.
192
- */
193
- async createPromptsFromConnectors(connectors) {
194
- const prompts = [];
195
- for (const connector of connectors) {
196
- const connectorPrompts = await this.loadPromptsForConnector(connector);
197
- prompts.push(...connectorPrompts);
198
- }
199
- logger.debug(`Available prompts: ${prompts.length}`);
200
- return prompts;
201
- }
202
- /**
203
- * Check if a connector is initialized and has tools.
204
- *
205
- * @param connector The connector to check.
206
- * @returns True if the connector is initialized and has tools, false otherwise.
207
- */
208
- checkConnectorInitialized(connector) {
209
- return Boolean(connector.tools && connector.tools.length);
210
- }
211
- /**
212
- * Ensure a connector is initialized.
213
- *
214
- * @param connector The connector to initialize.
215
- * @returns True if initialization succeeded, false otherwise.
216
- */
217
- async ensureConnectorInitialized(connector) {
218
- if (!this.checkConnectorInitialized(connector)) {
219
- logger.debug("Connector doesn't have tools, initializing it");
220
- try {
221
- await connector.initialize();
222
- return true;
223
- } catch (err) {
224
- logger.error(`Error initializing connector: ${err}`);
225
- return false;
226
- }
227
- }
228
- return true;
229
- }
230
- };
231
-
232
- // src/utils/json-schema-to-zod/JSONSchemaToZod.ts
233
- import { z } from "zod";
234
- var JSONSchemaToZod = class {
235
- static {
236
- __name(this, "JSONSchemaToZod");
237
- }
238
- /**
239
- * Converts a JSON schema to a Zod schema.
240
- *
241
- * @param {JSONSchema} schema - The JSON schema.
242
- * @returns {ZodSchema} - The Zod schema.
243
- */
244
- static convert(schema) {
245
- return this.parseSchema(schema);
246
- }
247
- /**
248
- * Checks if data matches a condition schema.
249
- *
250
- * @param {JSONValue} data - The data to check.
251
- * @param {JSONSchema} condition - The condition schema.
252
- * @returns {boolean} - Whether the data matches the condition.
253
- */
254
- static matchesCondition(data, condition) {
255
- if (!condition.properties) {
256
- return true;
257
- }
258
- if (typeof data !== "object" || data === null || Array.isArray(data)) {
259
- return false;
260
- }
261
- const objectData = data;
262
- for (const [key, propCondition] of Object.entries(condition.properties)) {
263
- if (!(key in objectData)) {
264
- if ("const" in propCondition) {
265
- return false;
266
- }
267
- continue;
268
- }
269
- const value = objectData[key];
270
- if ("const" in propCondition && value !== propCondition["const"]) {
271
- return false;
272
- }
273
- if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
274
- return false;
275
- }
276
- if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
277
- return false;
278
- }
279
- }
280
- return true;
281
- }
282
- /**
283
- * Validates data against a conditional schema and adds issues to context if validation fails.
284
- *
285
- * @param {JSONValue} data - The data to validate.
286
- * @param {JSONSchema} schema - The conditional schema.
287
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
288
- */
289
- static validateConditionalSchema(data, schema, ctx) {
290
- this.validateRequiredProperties(data, schema, ctx);
291
- this.validatePropertyPatterns(data, schema, ctx);
292
- this.validateNestedConditions(data, schema, ctx);
293
- }
294
- /**
295
- * Validates that all required properties are present in the data.
296
- *
297
- * @param {JSONValue} data - The data to validate.
298
- * @param {JSONSchema} schema - The schema containing required properties.
299
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
300
- */
301
- static validateRequiredProperties(data, schema, ctx) {
302
- if (!schema.required) {
303
- return;
304
- }
305
- if (typeof data !== "object" || data === null) {
306
- for (const requiredProp of schema.required) {
307
- ctx.addIssue({
308
- code: z.ZodIssueCode.custom,
309
- message: `Required property '${requiredProp}' is missing`,
310
- path: [requiredProp]
311
- });
312
- }
313
- return;
314
- }
315
- for (const requiredProp of schema.required) {
316
- if (!(requiredProp in data)) {
317
- ctx.addIssue({
318
- code: z.ZodIssueCode.custom,
319
- message: `Required property '${requiredProp}' is missing`,
320
- path: [requiredProp]
321
- });
322
- }
323
- }
324
- }
325
- /**
326
- * Validates property patterns for string properties.
327
- *
328
- * @param {JSONValue} data - The data to validate.
329
- * @param {JSONSchema} schema - The schema containing property patterns.
330
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
331
- */
332
- static validatePropertyPatterns(data, schema, ctx) {
333
- if (!schema.properties) {
334
- return;
335
- }
336
- if (typeof data !== "object" || data === null) {
337
- return;
338
- }
339
- if (Array.isArray(data)) {
340
- return;
341
- }
342
- const objectData = data;
343
- for (const [key, propSchema] of Object.entries(schema.properties)) {
344
- if (!(key in objectData)) {
345
- continue;
346
- }
347
- const value = objectData[key];
348
- if (propSchema["pattern"] && typeof value === "string") {
349
- const regex = new RegExp(propSchema["pattern"]);
350
- if (!regex.test(value)) {
351
- ctx.addIssue({
352
- code: z.ZodIssueCode.custom,
353
- message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
354
- path: [key]
355
- });
356
- }
357
- }
358
- }
359
- }
360
- /**
361
- * Validates nested if-then-else conditions.
362
- *
363
- * @param {JSONValue} data - The data to validate.
364
- * @param {JSONSchema} schema - The schema containing if-then-else conditions.
365
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
366
- */
367
- static validateNestedConditions(data, schema, ctx) {
368
- if (!schema["if"] || !schema["then"]) {
369
- return;
370
- }
371
- const matchesIf = this.matchesCondition(data, schema["if"]);
372
- if (matchesIf) {
373
- this.validateConditionalSchema(data, schema["then"], ctx);
374
- } else if (schema["else"]) {
375
- this.validateConditionalSchema(data, schema["else"], ctx);
376
- }
377
- }
378
- /**
379
- * Parses a JSON schema and returns the corresponding Zod schema.
380
- * This is the main entry point for schema conversion.
381
- *
382
- * @param {JSONSchema} schema - The JSON schema.
383
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
384
- */
385
- static parseSchema(schema) {
386
- if (Array.isArray(schema.type)) {
387
- return this.handleTypeArray(schema);
388
- }
389
- if (schema.oneOf || schema.anyOf || schema.allOf) {
390
- return this.parseCombinator(schema);
391
- }
392
- if (schema["if"] && schema["then"]) {
393
- return this.parseObject(schema);
394
- }
395
- if (schema.properties && (!schema.type || schema.type === "object")) {
396
- return this.parseObject(schema);
397
- }
398
- return this.handleSingleType(schema);
399
- }
400
- /**
401
- * Handles schemas with an array of types.
402
- *
403
- * @param {JSONSchema} schema - The JSON schema with type array.
404
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
405
- */
406
- static handleTypeArray(schema) {
407
- if (!Array.isArray(schema.type)) {
408
- throw new Error("Expected schema.type to be an array");
409
- }
410
- if (schema.type.includes("null")) {
411
- return this.handleNullableType(schema);
412
- }
413
- return this.createUnionFromTypes(schema.type, schema);
414
- }
415
- /**
416
- * Handles nullable types by creating a nullable schema.
417
- *
418
- * @param {JSONSchema} schema - The JSON schema with nullable type.
419
- * @returns {ZodTypeAny} - The nullable Zod schema.
420
- */
421
- static handleNullableType(schema) {
422
- if (!Array.isArray(schema.type)) {
423
- throw new Error("Expected schema.type to be an array");
424
- }
425
- const nonNullSchema = { ...schema };
426
- nonNullSchema.type = schema.type.filter((t) => t !== "null");
427
- if (nonNullSchema.type.length === 1) {
428
- const singleTypeSchema = this.handleSingleType({
429
- ...schema,
430
- type: nonNullSchema.type[0]
431
- });
432
- return singleTypeSchema.nullable();
433
- }
434
- const unionSchema = this.parseSchema(nonNullSchema);
435
- return unionSchema.nullable();
436
- }
437
- /**
438
- * Creates a union type from an array of types.
439
- *
440
- * @param {string[]} types - Array of type strings.
441
- * @param {JSONSchema} baseSchema - The base schema to apply to each type.
442
- * @returns {ZodTypeAny} - The union Zod schema.
443
- */
444
- static createUnionFromTypes(types, baseSchema) {
445
- const schemas = types.map((type) => {
446
- const singleTypeSchema = { ...baseSchema, type };
447
- return this.parseSchema(singleTypeSchema);
448
- });
449
- return z.union(schemas);
450
- }
451
- /**
452
- * Handles schemas with a single type.
453
- *
454
- * @param {JSONSchema} schema - The JSON schema with single type.
455
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
456
- */
457
- static handleSingleType(schema) {
458
- if (schema.type === void 0) {
459
- if (schema.oneOf || schema.anyOf || schema.allOf) {
460
- return this.parseCombinator(schema);
461
- }
462
- if (schema.properties) {
463
- return this.parseObject(schema);
464
- }
465
- return z.any();
466
- }
467
- switch (schema.type) {
468
- case "string":
469
- return this.parseString(schema);
470
- case "number":
471
- case "integer":
472
- return this.parseNumberSchema(schema);
473
- case "boolean":
474
- return z.boolean();
475
- case "array":
476
- return this.parseArray(schema);
477
- case "object":
478
- return this.parseObject(schema);
479
- default:
480
- throw new Error("Unsupported schema type");
481
- }
482
- }
483
- /**
484
- * Parses a number schema.
485
- *
486
- * @param {JSONSchema} schema - The JSON schema for a number.
487
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
488
- */
489
- static parseNumberSchema(schema) {
490
- const numberSchema = z.number();
491
- let result = numberSchema;
492
- result = this.applyNumberBounds(numberSchema, schema);
493
- result = this.applyNumberMultipleOf(numberSchema, schema);
494
- result = this.applyNumberEnum(numberSchema, schema);
495
- result = this.applyIntegerConstraint(numberSchema, schema);
496
- return result;
497
- }
498
- /**
499
- * Applies bounds validation to a number schema.
500
- *
501
- * @param {z.ZodNumber} numberSchema - The base number schema.
502
- * @param {JSONSchema} schema - The JSON schema with bounds.
503
- * @returns {z.ZodNumber} - The updated schema with bounds validation.
504
- */
505
- static applyNumberBounds(numberSchema, schema) {
506
- let result = numberSchema;
507
- if (schema["minimum"] !== void 0) {
508
- result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
509
- }
510
- if (schema["maximum"] !== void 0) {
511
- result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
512
- }
513
- return result;
514
- }
515
- /**
516
- * Applies multipleOf validation to a number schema.
517
- *
518
- * @param {z.ZodNumber} numberSchema - The base number schema.
519
- * @param {JSONSchema} schema - The JSON schema with multipleOf.
520
- * @returns {z.ZodNumber} - The updated schema with multipleOf validation.
521
- */
522
- static applyNumberMultipleOf(numberSchema, schema) {
523
- if (schema["multipleOf"] === void 0) {
524
- return numberSchema;
525
- }
526
- return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
527
- message: `Number must be a multiple of ${schema["multipleOf"]}`
528
- });
529
- }
530
- /**
531
- * Applies enum validation to a number schema.
532
- *
533
- * @param {z.ZodNumber} numberSchema - The base number schema.
534
- * @param {JSONSchema} schema - The JSON schema with enum.
535
- * @returns {z.ZodNumber} - The updated schema with enum validation.
536
- */
537
- static applyNumberEnum(numberSchema, schema) {
538
- if (!schema.enum) {
539
- return numberSchema;
540
- }
541
- const numberEnums = schema.enum.filter(
542
- (val) => typeof val === "number"
543
- );
544
- if (numberEnums.length === 0) {
545
- return numberSchema;
546
- }
547
- return numberSchema.refine((val) => numberEnums.includes(val), {
548
- message: `Number must be one of: ${numberEnums.join(", ")}`
549
- });
550
- }
551
- /**
552
- * Applies integer constraint to a number schema if needed.
553
- *
554
- * @param {z.ZodNumber} numberSchema - The base number schema.
555
- * @param {JSONSchema} schema - The JSON schema.
556
- * @returns {z.ZodNumber} - The updated schema with integer validation if needed.
557
- */
558
- static applyIntegerConstraint(numberSchema, schema) {
559
- if (schema.type !== "integer") {
560
- return numberSchema;
561
- }
562
- return numberSchema.refine((val) => Number.isInteger(val), {
563
- message: "Number must be an integer"
564
- });
565
- }
566
- /**
567
- * Parses a string schema.
568
- *
569
- * @param {JSONSchema} schema - The JSON schema for a string.
570
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
571
- */
572
- static parseString(schema) {
573
- const stringSchema = z.string();
574
- let result = stringSchema;
575
- if (schema.format) {
576
- return this.applyStringFormat(stringSchema, schema);
577
- } else {
578
- result = this.applyStringPattern(stringSchema, schema);
579
- result = this.applyStringLength(stringSchema, schema);
580
- result = this.applyStringEnum(stringSchema, schema);
581
- }
582
- return result;
583
- }
584
- /**
585
- * Applies format validation to a string schema.
586
- *
587
- * @param {z.ZodString} stringSchema - The base string schema.
588
- * @param {JSONSchema} schema - The JSON schema with format.
589
- * @returns {ZodTypeAny} - The updated schema with format validation.
590
- */
591
- static applyStringFormat(stringSchema, schema) {
592
- if (!schema.format) {
593
- return stringSchema;
594
- }
595
- switch (schema.format) {
596
- case "email":
597
- return stringSchema.email();
598
- case "date-time":
599
- return stringSchema.datetime();
600
- case "uri":
601
- return stringSchema.url();
602
- case "uuid":
603
- return stringSchema.uuid();
604
- case "date":
605
- return stringSchema.date();
606
- default:
607
- return stringSchema;
608
- }
609
- }
610
- /**
611
- * Applies pattern validation to a string schema.
612
- *
613
- * @param {z.ZodString} stringSchema - The base string schema.
614
- * @param {JSONSchema} schema - The JSON schema with pattern.
615
- * @returns {z.ZodString} - The updated schema with pattern validation.
616
- */
617
- static applyStringPattern(stringSchema, schema) {
618
- if (!schema["pattern"]) {
619
- return stringSchema;
620
- }
621
- const regex = new RegExp(schema["pattern"]);
622
- return stringSchema.regex(regex, {
623
- message: `String must match pattern: ${schema["pattern"]}`
624
- });
625
- }
626
- /**
627
- * Applies length constraints to a string schema.
628
- *
629
- * @param {z.ZodString} stringSchema - The base string schema.
630
- * @param {JSONSchema} schema - The JSON schema with length constraints.
631
- * @returns {z.ZodString} - The updated schema with length validation.
632
- */
633
- static applyStringLength(stringSchema, schema) {
634
- const result = stringSchema;
635
- if (schema["minLength"] !== void 0) {
636
- stringSchema = stringSchema.min(schema["minLength"]);
637
- }
638
- if (schema["maxLength"] !== void 0) {
639
- stringSchema = stringSchema.max(schema["maxLength"]);
640
- }
641
- return result;
642
- }
643
- /**
644
- * Applies enum validation to a string schema.
645
- *
646
- * @param {z.ZodString} stringSchema - The base string schema.
647
- * @param {JSONSchema} schema - The JSON schema with enum.
648
- * @returns {ZodTypeAny} - The updated schema with enum validation.
649
- */
650
- static applyStringEnum(stringSchema, schema) {
651
- if (!schema.enum) {
652
- return stringSchema;
653
- }
654
- return stringSchema.refine((val) => schema.enum?.includes(val), {
655
- message: `Value must be one of: ${schema.enum?.join(", ")}`
656
- });
657
- }
658
- /**
659
- * Parses a JSON schema of type array and returns the corresponding Zod schema.
660
- *
661
- * @param {JSONSchema} schema - The JSON schema.
662
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
663
- */
664
- static parseArray(schema) {
665
- if (Array.isArray(schema.items)) {
666
- const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
667
- return z.union(tupleSchemas);
668
- }
669
- const itemSchema = schema.items ? this.parseSchema(schema.items) : z.any();
670
- const arraySchema = z.array(itemSchema);
671
- let result = arraySchema;
672
- result = this.applyArrayConstraints(arraySchema, schema);
673
- return result;
674
- }
675
- /**
676
- * Applies constraints to an array schema.
677
- *
678
- * @param {z.ZodArray<any>} arraySchema - The base array schema.
679
- * @param {JSONSchema} schema - The JSON schema with array constraints.
680
- * @returns {z.ZodTypeAny} - The updated array schema with constraints.
681
- */
682
- static applyArrayConstraints(arraySchema, schema) {
683
- if (schema["minItems"] !== void 0) {
684
- arraySchema = arraySchema.min(schema["minItems"]);
685
- }
686
- if (schema["maxItems"] !== void 0) {
687
- arraySchema = arraySchema.max(schema["maxItems"]);
688
- }
689
- if (schema["uniqueItems"]) {
690
- return arraySchema.refine(
691
- (items) => new Set(items).size === items.length,
692
- { message: "Array items must be unique" }
693
- );
694
- }
695
- return arraySchema;
696
- }
697
- /**
698
- * Parses an object schema.
699
- *
700
- * @param {JSONSchema} schema - The JSON schema for an object.
701
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
702
- */
703
- static parseObject(schema) {
704
- if (schema["if"] && schema["then"]) {
705
- return this.parseConditional(schema);
706
- }
707
- const shape = {};
708
- this.processObjectProperties(schema, shape);
709
- return this.processAdditionalProperties(schema, z.object(shape));
710
- }
711
- /**
712
- * Processes object properties and builds the shape object.
713
- *
714
- * @param {JSONSchema} schema - The JSON schema for an object.
715
- * @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
716
- */
717
- static processObjectProperties(schema, shape) {
718
- const required = new Set(schema.required || []);
719
- if (!schema.properties) {
720
- return;
721
- }
722
- for (const [key, propSchema] of Object.entries(schema.properties)) {
723
- const zodSchema = this.parseSchema(propSchema);
724
- shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
725
- }
726
- }
727
- /**
728
- * Processes additionalProperties configuration.
729
- *
730
- * @param {JSONSchema} schema - The JSON schema for an object.
731
- * @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
732
- * @returns {z.ZodObject<any, any>} - The updated Zod object schema.
733
- */
734
- static processAdditionalProperties(schema, objectSchema) {
735
- if (schema.additionalProperties === true) {
736
- return objectSchema.passthrough();
737
- } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
738
- const additionalPropSchema = this.parseSchema(
739
- schema.additionalProperties
740
- );
741
- return objectSchema.catchall(additionalPropSchema);
742
- } else {
743
- return objectSchema.strict();
744
- }
745
- }
746
- /**
747
- * Parses a conditional schema with if-then-else.
748
- *
749
- * @param {JSONSchema} schema - The JSON schema with conditional validation.
750
- * @returns {ZodTypeAny} - The conditional Zod schema.
751
- */
752
- static parseConditional(schema) {
753
- const zodObject = this.createBaseObjectSchema(schema);
754
- const ifCondition = schema["if"];
755
- const thenSchema = schema["then"];
756
- const elseSchema = schema["else"];
757
- return zodObject.superRefine((data, ctx) => {
758
- const dataWithDefaults = this.applyDefaultValues(
759
- data,
760
- schema
761
- );
762
- if (this.matchesCondition(dataWithDefaults, ifCondition)) {
763
- this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
764
- } else if (elseSchema) {
765
- this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
766
- }
767
- });
768
- }
769
- /**
770
- * Creates a base object schema from the given JSON schema.
771
- *
772
- * @param {JSONSchema} schema - The JSON schema.
773
- * @returns {z.ZodObject<any, any>} - The base Zod object schema.
774
- */
775
- static createBaseObjectSchema(schema) {
776
- const shape = {};
777
- const required = new Set(schema.required || []);
778
- for (const [key, value] of Object.entries(schema.properties || {})) {
779
- const zodSchema = this.parseSchema(value);
780
- shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
781
- }
782
- const zodObject = z.object(shape);
783
- return this.processAdditionalProperties(schema, zodObject);
784
- }
785
- /**
786
- * Applies default values from schema properties to data object.
787
- *
788
- * @param {JSONValue} data - The original data object.
789
- * @param {JSONSchema} schema - The schema with default values.
790
- * @returns {JSONValue} - The data object with defaults applied.
791
- */
792
- static applyDefaultValues(data, schema) {
793
- if (typeof data !== "object" || data === null) {
794
- return data;
795
- }
796
- if (Array.isArray(data)) {
797
- return data;
798
- }
799
- const objectData = data;
800
- const dataWithDefaults = { ...objectData };
801
- if (!schema.properties) {
802
- return dataWithDefaults;
803
- }
804
- for (const [key, propSchema] of Object.entries(schema.properties)) {
805
- if (!(key in dataWithDefaults) && "default" in propSchema) {
806
- dataWithDefaults[key] = propSchema["default"];
807
- }
808
- }
809
- return dataWithDefaults;
810
- }
811
- /**
812
- * Parses a schema with combinators (oneOf, anyOf, allOf).
813
- * Delegates to the appropriate combinator parser based on which combinator is present.
814
- *
815
- * @param {JSONSchema} schema - The JSON schema with combinators.
816
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
817
- */
818
- static parseCombinator(schema) {
819
- if (schema.oneOf) {
820
- return this.parseOneOf(schema.oneOf);
821
- }
822
- if (schema.anyOf) {
823
- return this.parseAnyOf(schema.anyOf);
824
- }
825
- if (schema.allOf) {
826
- return this.parseAllOf(schema.allOf);
827
- }
828
- throw new Error("Unsupported schema type");
829
- }
830
- /**
831
- * Parses a oneOf combinator schema.
832
- *
833
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
834
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
835
- */
836
- static parseOneOf(schemas) {
837
- return this.createUnionFromSchemas(schemas);
838
- }
839
- /**
840
- * Parses an anyOf combinator schema.
841
- *
842
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
843
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
844
- */
845
- static parseAnyOf(schemas) {
846
- return this.createUnionFromSchemas(schemas);
847
- }
848
- /**
849
- * Creates a union from an array of schemas, handling special cases.
850
- *
851
- * @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
852
- * @returns {ZodTypeAny} - The union Zod schema.
853
- */
854
- static createUnionFromSchemas(schemas) {
855
- if (schemas.length === 0) {
856
- return z.any();
857
- }
858
- if (schemas.length === 1) {
859
- return this.parseSchema(schemas[0]);
860
- }
861
- const zodSchemas = [];
862
- for (const subSchema of schemas) {
863
- if (subSchema.type === "null") {
864
- zodSchemas.push(z.null());
865
- } else {
866
- zodSchemas.push(this.parseSchema(subSchema));
867
- }
868
- }
869
- if (zodSchemas.length >= 2) {
870
- return z.union(zodSchemas);
871
- } else if (zodSchemas.length === 1) {
872
- return zodSchemas[0];
873
- }
874
- return z.any();
875
- }
876
- /**
877
- * Parses an allOf combinator schema by merging all schemas.
878
- *
879
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
880
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
881
- */
882
- static parseAllOf(schemas) {
883
- if (schemas.length === 0) {
884
- return z.any();
885
- }
886
- if (schemas.length === 1) {
887
- return this.parseSchema(schemas[0]);
888
- }
889
- const mergedSchema = schemas.reduce(
890
- (acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
891
- );
892
- return this.parseSchema(mergedSchema);
893
- }
894
- /**
895
- * Merges two JSON schemas together.
896
- *
897
- * @param {JSONSchema} baseSchema - The base JSON schema.
898
- * @param {JSONSchema} addSchema - The JSON schema to add.
899
- * @returns {JSONSchema} - The merged JSON schema
900
- */
901
- static mergeSchemas(baseSchema, addSchema) {
902
- const merged = { ...baseSchema, ...addSchema };
903
- if (baseSchema.properties && addSchema.properties) {
904
- const mergedProperties = {
905
- ...baseSchema.properties,
906
- ...addSchema.properties
907
- };
908
- merged.properties = mergedProperties;
909
- }
910
- if (baseSchema.required && addSchema.required) {
911
- const mergedRequired = [
912
- .../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
913
- ];
914
- merged.required = mergedRequired;
915
- }
916
- return merged;
917
- }
918
- };
919
-
920
- // src/adapters/langchain_adapter.ts
921
- import { DynamicStructuredTool } from "@langchain/core/tools";
922
- import { z as z2 } from "zod";
923
- function schemaToZod(schema) {
924
- try {
925
- return JSONSchemaToZod.convert(schema);
926
- } catch (err) {
927
- logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
928
- return z2.any();
929
- }
930
- }
931
- __name(schemaToZod, "schemaToZod");
932
- var LangChainAdapter = class extends BaseAdapter {
933
- static {
934
- __name(this, "LangChainAdapter");
935
- }
936
- constructor(disallowedTools = []) {
937
- super(disallowedTools);
938
- }
939
- /**
940
- * Convert a single MCP tool specification into a LangChainJS structured tool.
941
- */
942
- convertTool(mcpTool, connector) {
943
- if (this.disallowedTools.includes(mcpTool.name)) {
944
- return null;
945
- }
946
- const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : z2.object({}).optional();
947
- const tool = new DynamicStructuredTool({
948
- name: mcpTool.name ?? "NO NAME",
949
- description: mcpTool.description ?? "",
950
- // Blank is acceptable but discouraged.
951
- schema: argsSchema,
952
- func: /* @__PURE__ */ __name(async (input) => {
953
- logger.debug(
954
- `MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
955
- );
956
- try {
957
- const result = await connector.callTool(
958
- mcpTool.name,
959
- input
960
- );
961
- return JSON.stringify(result);
962
- } catch (err) {
963
- logger.error(`Error executing MCP tool: ${err.message}`);
964
- return `Error executing MCP tool: ${String(err)}`;
965
- }
966
- }, "func")
967
- });
968
- return tool;
969
- }
970
- /**
971
- * Convert a single MCP resource into a LangChainJS structured tool.
972
- * Each resource becomes an async tool that returns its content when called.
973
- */
974
- convertResource(mcpResource, connector) {
975
- const sanitizeName = /* @__PURE__ */ __name((name) => {
976
- return name.replace(/[^A-Za-z0-9_]+/g, "_").toLowerCase().replace(/^_+|_+$/g, "");
977
- }, "sanitizeName");
978
- const resourceName = sanitizeName(
979
- mcpResource.name || `resource_${mcpResource.uri}`
980
- );
981
- const resourceUri = mcpResource.uri;
982
- const tool = new DynamicStructuredTool({
983
- name: resourceName,
984
- description: mcpResource.description || `Return the content of the resource located at URI ${resourceUri}.`,
985
- schema: z2.object({}).optional(),
986
- // Resources take no arguments
987
- func: /* @__PURE__ */ __name(async () => {
988
- logger.debug(`Resource tool: "${resourceName}" called`);
989
- try {
990
- const result = await connector.readResource(resourceUri);
991
- if (result.contents && result.contents.length > 0) {
992
- return result.contents.map((content) => {
993
- if (typeof content === "string") {
994
- return content;
995
- }
996
- if (content.text) {
997
- return content.text;
998
- }
999
- if (content.uri) {
1000
- return content.uri;
1001
- }
1002
- return JSON.stringify(content);
1003
- }).join("\n");
1004
- }
1005
- return "Resource is empty or unavailable";
1006
- } catch (err) {
1007
- logger.error(`Error reading resource: ${err.message}`);
1008
- return `Error reading resource: ${String(err)}`;
1009
- }
1010
- }, "func")
1011
- });
1012
- return tool;
1013
- }
1014
- /**
1015
- * Convert a single MCP prompt into a LangChainJS structured tool.
1016
- * The resulting tool executes getPrompt on the connector with the prompt's name
1017
- * and the user-provided arguments (if any).
1018
- */
1019
- convertPrompt(mcpPrompt, connector) {
1020
- let argsSchema = z2.object({}).optional();
1021
- if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {
1022
- const schemaFields = {};
1023
- for (const arg of mcpPrompt.arguments) {
1024
- const zodType = z2.string();
1025
- if (arg.required !== false) {
1026
- schemaFields[arg.name] = zodType;
1027
- } else {
1028
- schemaFields[arg.name] = zodType.optional();
1029
- }
1030
- }
1031
- argsSchema = Object.keys(schemaFields).length > 0 ? z2.object(schemaFields) : z2.object({}).optional();
1032
- }
1033
- const tool = new DynamicStructuredTool({
1034
- name: mcpPrompt.name,
1035
- description: mcpPrompt.description || "",
1036
- schema: argsSchema,
1037
- func: /* @__PURE__ */ __name(async (input) => {
1038
- logger.debug(
1039
- `Prompt tool: "${mcpPrompt.name}" called with args: ${JSON.stringify(input)}`
1040
- );
1041
- try {
1042
- const result = await connector.getPrompt(mcpPrompt.name, input);
1043
- if (result.messages && result.messages.length > 0) {
1044
- return result.messages.map((msg) => {
1045
- if (typeof msg === "string") {
1046
- return msg;
1047
- }
1048
- if (msg.content) {
1049
- return typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1050
- }
1051
- return JSON.stringify(msg);
1052
- }).join("\n");
1053
- }
1054
- return "Prompt returned no messages";
1055
- } catch (err) {
1056
- logger.error(`Error getting prompt: ${err.message}`);
1057
- return `Error getting prompt: ${String(err)}`;
1058
- }
1059
- }, "func")
1060
- });
1061
- return tool;
1062
- }
1063
- };
1064
-
1065
- // src/client/executors/base.ts
1066
- var BaseCodeExecutor = class {
1067
- static {
1068
- __name(this, "BaseCodeExecutor");
1069
- }
1070
- client;
1071
- _connecting = false;
1072
- constructor(client) {
1073
- this.client = client;
1074
- }
1075
- /**
1076
- * Ensure all configured MCP servers are connected before execution.
1077
- * Prevents race conditions with a connection lock.
1078
- */
1079
- async ensureServersConnected() {
1080
- const configuredServers = this.client.getServerNames();
1081
- const activeSessions = Object.keys(this.client.getAllActiveSessions());
1082
- const missingServers = configuredServers.filter(
1083
- (s) => !activeSessions.includes(s)
1084
- );
1085
- if (missingServers.length > 0 && !this._connecting) {
1086
- this._connecting = true;
1087
- try {
1088
- logger.debug(
1089
- `Connecting to configured servers for code execution: ${missingServers.join(", ")}`
1090
- );
1091
- await this.client.createAllSessions();
1092
- } finally {
1093
- this._connecting = false;
1094
- }
1095
- } else if (missingServers.length > 0 && this._connecting) {
1096
- logger.debug("Waiting for ongoing server connection...");
1097
- const startWait = Date.now();
1098
- while (this._connecting && Date.now() - startWait < 5e3) {
1099
- await new Promise((resolve) => setTimeout(resolve, 100));
1100
- }
1101
- }
1102
- }
1103
- /**
1104
- * Get tool namespace information from all active MCP sessions.
1105
- * Filters out the internal code_mode server.
1106
- */
1107
- getToolNamespaces() {
1108
- const namespaces = [];
1109
- const activeSessions = this.client.getAllActiveSessions();
1110
- for (const [serverName, session] of Object.entries(activeSessions)) {
1111
- if (serverName === "code_mode") continue;
1112
- try {
1113
- const connector = session.connector;
1114
- let tools;
1115
- try {
1116
- tools = connector.tools;
1117
- } catch (e) {
1118
- logger.warn(`Tools not available for server ${serverName}: ${e}`);
1119
- continue;
1120
- }
1121
- if (!tools || tools.length === 0) continue;
1122
- namespaces.push({ serverName, tools, session });
1123
- } catch (e) {
1124
- logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
1125
- }
1126
- }
1127
- return namespaces;
1128
- }
1129
- /**
1130
- * Create a search function for discovering available MCP tools.
1131
- * Used by code execution environments to find tools at runtime.
1132
- */
1133
- createSearchToolsFunction() {
1134
- return async (query = "", detailLevel = "full") => {
1135
- const allTools = [];
1136
- const allNamespaces = /* @__PURE__ */ new Set();
1137
- const queryLower = query.toLowerCase();
1138
- const activeSessions = this.client.getAllActiveSessions();
1139
- for (const [serverName, session] of Object.entries(activeSessions)) {
1140
- if (serverName === "code_mode") continue;
1141
- try {
1142
- const tools = session.connector.tools;
1143
- if (tools && tools.length > 0) {
1144
- allNamespaces.add(serverName);
1145
- }
1146
- for (const tool of tools) {
1147
- if (detailLevel === "names") {
1148
- allTools.push({ name: tool.name, server: serverName });
1149
- } else if (detailLevel === "descriptions") {
1150
- allTools.push({
1151
- name: tool.name,
1152
- server: serverName,
1153
- description: tool.description
1154
- });
1155
- } else {
1156
- allTools.push({
1157
- name: tool.name,
1158
- server: serverName,
1159
- description: tool.description,
1160
- input_schema: tool.inputSchema
1161
- });
1162
- }
1163
- }
1164
- } catch (e) {
1165
- logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
1166
- }
1167
- }
1168
- let filteredTools = allTools;
1169
- if (query) {
1170
- filteredTools = allTools.filter((tool) => {
1171
- const nameMatch = tool.name.toLowerCase().includes(queryLower);
1172
- const descMatch = tool.description?.toLowerCase().includes(queryLower);
1173
- const serverMatch = tool.server.toLowerCase().includes(queryLower);
1174
- return nameMatch || descMatch || serverMatch;
1175
- });
1176
- }
1177
- return {
1178
- meta: {
1179
- total_tools: allTools.length,
1180
- namespaces: Array.from(allNamespaces).sort(),
1181
- result_count: filteredTools.length
1182
- },
1183
- results: filteredTools
1184
- };
1185
- };
1186
- }
1187
- };
1188
-
1189
- // src/client/executors/e2b.ts
1190
- var E2BCodeExecutor = class extends BaseCodeExecutor {
1191
- static {
1192
- __name(this, "E2BCodeExecutor");
1193
- }
1194
- e2bApiKey;
1195
- codeExecSandbox = null;
1196
- SandboxClass = null;
1197
- timeoutMs;
1198
- constructor(client, options) {
1199
- super(client);
1200
- this.e2bApiKey = options.apiKey;
1201
- this.timeoutMs = options.timeoutMs ?? 3e5;
1202
- }
1203
- /**
1204
- * Lazy load E2B Sandbox class.
1205
- * This allows the library to work without E2B installed.
1206
- */
1207
- async ensureSandboxClass() {
1208
- if (this.SandboxClass) return;
1209
- try {
1210
- const e2b = await import("@e2b/code-interpreter");
1211
- this.SandboxClass = e2b.Sandbox;
1212
- } catch (error) {
1213
- throw new Error(
1214
- "@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
1215
- );
1216
- }
1217
- }
1218
- /**
1219
- * Get or create a dedicated sandbox for code execution.
1220
- */
1221
- async getOrCreateCodeExecSandbox() {
1222
- if (this.codeExecSandbox) return this.codeExecSandbox;
1223
- await this.ensureSandboxClass();
1224
- logger.debug("Starting E2B sandbox for code execution...");
1225
- this.codeExecSandbox = await this.SandboxClass.create("base", {
1226
- apiKey: this.e2bApiKey,
1227
- timeoutMs: this.timeoutMs
1228
- });
1229
- return this.codeExecSandbox;
1230
- }
1231
- /**
1232
- * Generate the shim code that exposes tools to the sandbox environment.
1233
- * Creates a bridge that intercepts tool calls and sends them back to host.
1234
- */
1235
- generateShim(tools) {
1236
- let shim = `
1237
- // MCP Bridge Shim
1238
- global.__callMcpTool = async (server, tool, args) => {
1239
- const id = Math.random().toString(36).substring(7);
1240
- console.log(JSON.stringify({
1241
- type: '__MCP_TOOL_CALL__',
1242
- id,
1243
- server,
1244
- tool,
1245
- args
1246
- }));
1247
-
1248
- const resultPath = \`/tmp/mcp_result_\${id}.json\`;
1249
- const fs = require('fs');
1250
-
1251
- // Poll for result file
1252
- let attempts = 0;
1253
- while (attempts < 300) { // 30 seconds timeout
1254
- if (fs.existsSync(resultPath)) {
1255
- const content = fs.readFileSync(resultPath, 'utf8');
1256
- const result = JSON.parse(content);
1257
- fs.unlinkSync(resultPath); // Clean up
1258
-
1259
- if (result.error) {
1260
- throw new Error(result.error);
1261
- }
1262
- return result.data;
1263
- }
1264
- await new Promise(resolve => setTimeout(resolve, 100));
1265
- attempts++;
1266
- }
1267
- throw new Error('Tool execution timed out');
1268
- };
1269
-
1270
- // Global search_tools helper
1271
- global.search_tools = async (query, detailLevel = 'full') => {
1272
- const allTools = ${JSON.stringify(
1273
- Object.entries(tools).flatMap(
1274
- ([server, serverTools]) => serverTools.map((tool) => ({
1275
- name: tool.name,
1276
- description: tool.description,
1277
- server,
1278
- input_schema: tool.inputSchema
1279
- }))
1280
- )
1281
- )};
1282
-
1283
- const filtered = allTools.filter(tool => {
1284
- if (!query) return true;
1285
- const q = query.toLowerCase();
1286
- return tool.name.toLowerCase().includes(q) ||
1287
- (tool.description && tool.description.toLowerCase().includes(q));
1288
- });
1289
-
1290
- if (detailLevel === 'names') {
1291
- return filtered.map(t => ({ name: t.name, server: t.server }));
1292
- } else if (detailLevel === 'descriptions') {
1293
- return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
1294
- }
1295
- return filtered;
1296
- };
1297
- `;
1298
- for (const [serverName, serverTools] of Object.entries(tools)) {
1299
- if (!serverTools || serverTools.length === 0) continue;
1300
- const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
1301
- shim += `
1302
- global['${serverName}'] = {`;
1303
- for (const tool of serverTools) {
1304
- shim += `
1305
- '${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
1306
- }
1307
- shim += `
1308
- };
1309
-
1310
- // Also expose as safe name if different
1311
- if ('${safeServerName}' !== '${serverName}') {
1312
- global['${safeServerName}'] = global['${serverName}'];
1313
- }
1314
- `;
1315
- }
1316
- return shim;
1317
- }
1318
- /**
1319
- * Build the tool catalog for the shim.
1320
- * Returns a map of server names to their available tools.
1321
- */
1322
- buildToolCatalog() {
1323
- const catalog = {};
1324
- const namespaces = this.getToolNamespaces();
1325
- for (const { serverName, tools } of namespaces) {
1326
- catalog[serverName] = tools;
1327
- }
1328
- return catalog;
1329
- }
1330
- /**
1331
- * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
1332
- * Tool calls are proxied back to the host via the bridge pattern.
1333
- *
1334
- * @param code - Code to execute
1335
- * @param timeout - Execution timeout in milliseconds (default: 30000)
1336
- */
1337
- async execute(code, timeout = 3e4) {
1338
- const startTime = Date.now();
1339
- let result = null;
1340
- let error = null;
1341
- let logs = [];
1342
- try {
1343
- await this.ensureServersConnected();
1344
- const sandbox = await this.getOrCreateCodeExecSandbox();
1345
- const toolCatalog = this.buildToolCatalog();
1346
- const shim = this.generateShim(toolCatalog);
1347
- const wrappedCode = `
1348
- ${shim}
1349
-
1350
- (async () => {
1351
- try {
1352
- const func = async () => {
1353
- ${code}
1354
- };
1355
- const result = await func();
1356
- console.log('__MCP_RESULT_START__');
1357
- console.log(JSON.stringify(result));
1358
- console.log('__MCP_RESULT_END__');
1359
- } catch (e) {
1360
- console.error(e);
1361
- process.exit(1);
1362
- }
1363
- })();
1364
- `;
1365
- const filename = `exec_${Date.now()}.js`;
1366
- await sandbox.files.write(filename, wrappedCode);
1367
- const execution = await sandbox.commands.run(`node ${filename}`, {
1368
- timeoutMs: timeout,
1369
- onStdout: /* @__PURE__ */ __name(async (data) => {
1370
- try {
1371
- const lines = data.split("\n");
1372
- for (const line of lines) {
1373
- if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
1374
- const call = JSON.parse(line);
1375
- if (call.type === "__MCP_TOOL_CALL__") {
1376
- try {
1377
- logger.debug(
1378
- `[E2B Bridge] Calling tool ${call.server}.${call.tool}`
1379
- );
1380
- const activeSessions = this.client.getAllActiveSessions();
1381
- const session = activeSessions[call.server];
1382
- if (!session) {
1383
- throw new Error(`Server ${call.server} not found`);
1384
- }
1385
- const toolResult = await session.connector.callTool(
1386
- call.tool,
1387
- call.args
1388
- );
1389
- let extractedResult = toolResult;
1390
- if (toolResult.content && toolResult.content.length > 0) {
1391
- const item = toolResult.content[0];
1392
- if (item.type === "text") {
1393
- try {
1394
- extractedResult = JSON.parse(item.text);
1395
- } catch {
1396
- extractedResult = item.text;
1397
- }
1398
- } else {
1399
- extractedResult = item;
1400
- }
1401
- }
1402
- const resultPath = `/tmp/mcp_result_${call.id}.json`;
1403
- await sandbox.files.write(
1404
- resultPath,
1405
- JSON.stringify({ data: extractedResult })
1406
- );
1407
- } catch (err) {
1408
- logger.error(
1409
- `[E2B Bridge] Tool execution failed: ${err.message}`
1410
- );
1411
- const resultPath = `/tmp/mcp_result_${call.id}.json`;
1412
- await sandbox.files.write(
1413
- resultPath,
1414
- JSON.stringify({
1415
- error: err.message || String(err)
1416
- })
1417
- );
1418
- }
1419
- }
1420
- }
1421
- }
1422
- } catch (e) {
1423
- }
1424
- }, "onStdout")
1425
- });
1426
- logs = [execution.stdout, execution.stderr].filter(Boolean);
1427
- if (execution.exitCode !== 0) {
1428
- error = execution.stderr || "Execution failed";
1429
- } else {
1430
- const stdout = execution.stdout;
1431
- const startMarker = "__MCP_RESULT_START__";
1432
- const endMarker = "__MCP_RESULT_END__";
1433
- const startIndex = stdout.indexOf(startMarker);
1434
- const endIndex = stdout.indexOf(endMarker);
1435
- if (startIndex !== -1 && endIndex !== -1) {
1436
- const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
1437
- try {
1438
- result = JSON.parse(jsonStr);
1439
- } catch (e) {
1440
- result = jsonStr;
1441
- }
1442
- logs = logs.map((log) => {
1443
- let cleaned = log.replace(
1444
- new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
1445
- "[Result captured]"
1446
- );
1447
- cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
1448
- return cleaned;
1449
- });
1450
- }
1451
- }
1452
- } catch (e) {
1453
- error = e.message || String(e);
1454
- if (error && (error.includes("timeout") || error.includes("timed out"))) {
1455
- error = "Script execution timed out";
1456
- }
1457
- }
1458
- return {
1459
- result,
1460
- logs,
1461
- error,
1462
- execution_time: (Date.now() - startTime) / 1e3
1463
- };
1464
- }
1465
- /**
1466
- * Clean up the E2B sandbox.
1467
- * Should be called when the executor is no longer needed.
1468
- */
1469
- async cleanup() {
1470
- if (this.codeExecSandbox) {
1471
- try {
1472
- await this.codeExecSandbox.kill();
1473
- this.codeExecSandbox = null;
1474
- logger.debug("E2B code execution sandbox stopped");
1475
- } catch (error) {
1476
- logger.error("Failed to stop E2B code execution sandbox:", error);
1477
- }
1478
- }
1479
- }
1480
- };
1481
-
1482
- // src/client/executors/vm.ts
1483
- var vm = null;
1484
- var vmCheckAttempted = false;
1485
- function getVMModuleName() {
1486
- return ["node", "vm"].join(":");
1487
- }
1488
- __name(getVMModuleName, "getVMModuleName");
1489
- function tryLoadVM() {
1490
- if (vmCheckAttempted) {
1491
- return vm !== null;
1492
- }
1493
- vmCheckAttempted = true;
1494
- try {
1495
- const nodeRequire = typeof __require !== "undefined" ? __require : null;
1496
- if (nodeRequire) {
1497
- vm = nodeRequire(getVMModuleName());
1498
- return true;
1499
- }
1500
- } catch (error) {
1501
- logger.debug("node:vm module not available via require");
1502
- }
1503
- return false;
1504
- }
1505
- __name(tryLoadVM, "tryLoadVM");
1506
- async function tryLoadVMAsync() {
1507
- if (vm !== null) {
1508
- return true;
1509
- }
1510
- if (!vmCheckAttempted) {
1511
- if (tryLoadVM()) {
1512
- return true;
1513
- }
1514
- }
1515
- try {
1516
- vm = await import(
1517
- /* @vite-ignore */
1518
- getVMModuleName()
1519
- );
1520
- return true;
1521
- } catch (error) {
1522
- logger.debug(
1523
- "node:vm module not available in this environment (e.g., Deno)"
1524
- );
1525
- return false;
1526
- }
1527
- }
1528
- __name(tryLoadVMAsync, "tryLoadVMAsync");
1529
- function isVMAvailable() {
1530
- tryLoadVM();
1531
- return vm !== null;
1532
- }
1533
- __name(isVMAvailable, "isVMAvailable");
1534
- var VMCodeExecutor = class extends BaseCodeExecutor {
1535
- static {
1536
- __name(this, "VMCodeExecutor");
1537
- }
1538
- defaultTimeout;
1539
- memoryLimitMb;
1540
- constructor(client, options) {
1541
- super(client);
1542
- this.defaultTimeout = options?.timeoutMs ?? 3e4;
1543
- this.memoryLimitMb = options?.memoryLimitMb;
1544
- tryLoadVM();
1545
- }
1546
- /**
1547
- * Ensure VM module is loaded before execution
1548
- */
1549
- async ensureVMLoaded() {
1550
- if (vm !== null) {
1551
- return;
1552
- }
1553
- const loaded = await tryLoadVMAsync();
1554
- if (!loaded) {
1555
- throw new Error(
1556
- "node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment."
1557
- );
1558
- }
1559
- }
1560
- /**
1561
- * Execute JavaScript/TypeScript code with access to MCP tools.
1562
- *
1563
- * @param code - Code to execute
1564
- * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
1565
- */
1566
- async execute(code, timeout) {
1567
- const effectiveTimeout = timeout ?? this.defaultTimeout;
1568
- await this.ensureVMLoaded();
1569
- await this.ensureServersConnected();
1570
- const logs = [];
1571
- const startTime = Date.now();
1572
- let result = null;
1573
- let error = null;
1574
- try {
1575
- const context = await this._buildContext(logs);
1576
- const wrappedCode = `
1577
- (async () => {
1578
- try {
1579
- ${code}
1580
- } catch (e) {
1581
- throw e;
1582
- }
1583
- })()
1584
- `;
1585
- const script = new vm.Script(wrappedCode, {
1586
- filename: "agent_code.js"
1587
- });
1588
- const promise = script.runInNewContext(context, {
1589
- timeout: effectiveTimeout,
1590
- displayErrors: true
1591
- });
1592
- result = await promise;
1593
- } catch (e) {
1594
- error = e.message || String(e);
1595
- if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
1596
- error = "Script execution timed out";
1597
- }
1598
- if (e.stack) {
1599
- logger.debug(`Code execution error stack: ${e.stack}`);
1600
- }
1601
- }
1602
- const executionTime = (Date.now() - startTime) / 1e3;
1603
- return {
1604
- result,
1605
- logs,
1606
- error,
1607
- execution_time: executionTime
1608
- };
1609
- }
1610
- /**
1611
- * Build the VM execution context with MCP tools and standard globals.
1612
- *
1613
- * @param logs - Array to capture console output
1614
- */
1615
- async _buildContext(logs) {
1616
- const logHandler = /* @__PURE__ */ __name((...args) => {
1617
- logs.push(
1618
- args.map(
1619
- (arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
1620
- ).join(" ")
1621
- );
1622
- }, "logHandler");
1623
- const sandbox = {
1624
- console: {
1625
- log: logHandler,
1626
- error: /* @__PURE__ */ __name((...args) => {
1627
- logHandler("[ERROR]", ...args);
1628
- }, "error"),
1629
- warn: /* @__PURE__ */ __name((...args) => {
1630
- logHandler("[WARN]", ...args);
1631
- }, "warn"),
1632
- info: logHandler,
1633
- debug: logHandler
1634
- },
1635
- // Standard globals
1636
- Object,
1637
- Array,
1638
- String,
1639
- Number,
1640
- Boolean,
1641
- Date,
1642
- Math,
1643
- JSON,
1644
- RegExp,
1645
- Map,
1646
- Set,
1647
- Promise,
1648
- parseInt,
1649
- parseFloat,
1650
- isNaN,
1651
- isFinite,
1652
- encodeURI,
1653
- decodeURI,
1654
- encodeURIComponent,
1655
- decodeURIComponent,
1656
- setTimeout,
1657
- clearTimeout,
1658
- // Helper for tools
1659
- search_tools: this.createSearchToolsFunction(),
1660
- __tool_namespaces: []
1661
- };
1662
- const toolNamespaces = {};
1663
- const namespaceInfos = this.getToolNamespaces();
1664
- for (const { serverName, tools, session } of namespaceInfos) {
1665
- const serverNamespace = {};
1666
- for (const tool of tools) {
1667
- const toolName = tool.name;
1668
- serverNamespace[toolName] = async (args) => {
1669
- const result = await session.connector.callTool(toolName, args || {});
1670
- if (result.content && result.content.length > 0) {
1671
- const item = result.content[0];
1672
- if (item.type === "text") {
1673
- try {
1674
- return JSON.parse(item.text);
1675
- } catch {
1676
- return item.text;
1677
- }
1678
- }
1679
- return item;
1680
- }
1681
- return result;
1682
- };
1683
- }
1684
- sandbox[serverName] = serverNamespace;
1685
- toolNamespaces[serverName] = true;
1686
- }
1687
- sandbox.__tool_namespaces = Object.keys(toolNamespaces);
1688
- return vm.createContext(sandbox);
1689
- }
1690
- /**
1691
- * Clean up resources.
1692
- * VM executor doesn't need cleanup, but method kept for interface consistency.
1693
- */
1694
- async cleanup() {
1695
- }
1696
- };
1697
-
1698
- // src/connectors/stdio.ts
1699
- import process2 from "process";
1700
- import { Client } from "@mcp-use/modelcontextprotocol-sdk/client/index.js";
1701
-
1702
- // src/task_managers/stdio.ts
1703
- import { StdioClientTransport } from "@mcp-use/modelcontextprotocol-sdk/client/stdio.js";
1704
- var StdioConnectionManager = class extends ConnectionManager {
1705
- static {
1706
- __name(this, "StdioConnectionManager");
1707
- }
1708
- serverParams;
1709
- errlog;
1710
- _transport = null;
1711
- /**
1712
- * Create a new stdio connection manager.
1713
- *
1714
- * @param serverParams Parameters for the stdio server process.
1715
- * @param errlog Stream to which the server's stderr should be piped.
1716
- * Defaults to `process.stderr`.
1717
- */
1718
- constructor(serverParams, errlog = process.stderr) {
1719
- super();
1720
- this.serverParams = serverParams;
1721
- this.errlog = errlog;
1722
- }
1723
- /**
1724
- * Establish the stdio connection by spawning the server process and starting
1725
- * the SDK's transport. Returns the live `StdioClientTransport` instance.
1726
- */
1727
- async establishConnection() {
1728
- this._transport = new StdioClientTransport(this.serverParams);
1729
- if (this._transport.stderr && typeof this._transport.stderr.pipe === "function") {
1730
- this._transport.stderr.pipe(
1731
- this.errlog
1732
- );
1733
- }
1734
- logger.debug(`${this.constructor.name} connected successfully`);
1735
- return this._transport;
1736
- }
1737
- /**
1738
- * Close the stdio connection, making sure the transport cleans up the child
1739
- * process and associated resources.
1740
- */
1741
- async closeConnection(_connection) {
1742
- if (this._transport) {
1743
- try {
1744
- await this._transport.close();
1745
- } catch (e) {
1746
- logger.warn(`Error closing stdio transport: ${e}`);
1747
- } finally {
1748
- this._transport = null;
1749
- }
1750
- }
1751
- }
1752
- };
1753
-
1754
- // src/connectors/stdio.ts
1755
- var StdioConnector = class extends BaseConnector {
1756
- static {
1757
- __name(this, "StdioConnector");
1758
- }
1759
- command;
1760
- args;
1761
- env;
1762
- errlog;
1763
- clientInfo;
1764
- constructor({
1765
- command = "npx",
1766
- args = [],
1767
- env,
1768
- errlog = process2.stderr,
1769
- ...rest
1770
- } = {}) {
1771
- super(rest);
1772
- this.command = command;
1773
- this.args = args;
1774
- this.env = env;
1775
- this.errlog = errlog;
1776
- this.clientInfo = rest.clientInfo ?? {
1777
- name: "stdio-connector",
1778
- version: "1.0.0"
1779
- };
1780
- }
1781
- /** Establish connection to the MCP implementation. */
1782
- async connect() {
1783
- if (this.connected) {
1784
- logger.debug("Already connected to MCP implementation");
1785
- return;
1786
- }
1787
- logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
1788
- try {
1789
- let mergedEnv;
1790
- if (this.env) {
1791
- mergedEnv = {};
1792
- for (const [key, value] of Object.entries(process2.env)) {
1793
- if (value !== void 0) {
1794
- mergedEnv[key] = value;
1795
- }
1796
- }
1797
- Object.assign(mergedEnv, this.env);
1798
- }
1799
- const serverParams = {
1800
- command: this.command,
1801
- args: this.args,
1802
- env: mergedEnv
1803
- };
1804
- this.connectionManager = new StdioConnectionManager(
1805
- serverParams,
1806
- this.errlog
1807
- );
1808
- const transport = await this.connectionManager.start();
1809
- const clientOptions = {
1810
- ...this.opts.clientOptions || {},
1811
- capabilities: {
1812
- ...this.opts.clientOptions?.capabilities || {},
1813
- roots: { listChanged: true },
1814
- // Always advertise roots capability
1815
- // Add sampling capability if callback is provided
1816
- ...this.opts.samplingCallback ? { sampling: {} } : {},
1817
- // Add elicitation capability if callback is provided
1818
- ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
1819
- }
1820
- };
1821
- this.client = new Client(this.clientInfo, clientOptions);
1822
- await this.client.connect(transport);
1823
- this.connected = true;
1824
- this.setupNotificationHandler();
1825
- this.setupRootsHandler();
1826
- this.setupSamplingHandler();
1827
- this.setupElicitationHandler();
1828
- logger.debug(
1829
- `Successfully connected to MCP implementation: ${this.command}`
1830
- );
1831
- this.trackConnectorInit({
1832
- serverCommand: this.command,
1833
- serverArgs: this.args,
1834
- publicIdentifier: `${this.command} ${this.args.join(" ")}`
1835
- });
1836
- } catch (err) {
1837
- logger.error(`Failed to connect to MCP implementation: ${err}`);
1838
- await this.cleanupResources();
1839
- throw err;
1840
- }
1841
- }
1842
- get publicIdentifier() {
1843
- return {
1844
- type: "stdio",
1845
- "command&args": `${this.command} ${this.args.join(" ")}`
1846
- };
1847
- }
1848
- };
1849
-
1850
- // src/config.ts
1851
- import { readFileSync } from "fs";
1852
- function loadConfigFile(filepath) {
1853
- const raw = readFileSync(filepath, "utf-8");
1854
- return JSON.parse(raw);
1855
- }
1856
- __name(loadConfigFile, "loadConfigFile");
1857
- function createConnectorFromConfig(serverConfig, connectorOptions) {
1858
- if ("command" in serverConfig && "args" in serverConfig) {
1859
- return new StdioConnector({
1860
- command: serverConfig.command,
1861
- args: serverConfig.args,
1862
- env: serverConfig.env,
1863
- ...connectorOptions
1864
- });
1865
- }
1866
- if ("url" in serverConfig) {
1867
- const transport = serverConfig.transport || "http";
1868
- return new HttpConnector(serverConfig.url, {
1869
- headers: serverConfig.headers,
1870
- authToken: serverConfig.auth_token || serverConfig.authToken,
1871
- // Only force SSE if explicitly requested
1872
- preferSse: serverConfig.preferSse || transport === "sse",
1873
- ...connectorOptions
1874
- });
1875
- }
1876
- throw new Error("Cannot determine connector type from config");
1877
- }
1878
- __name(createConnectorFromConfig, "createConnectorFromConfig");
1879
-
1880
- // src/client.ts
1881
- import fs from "fs";
1882
- import path from "path";
1883
- var MCPClient = class _MCPClient extends BaseMCPClient {
1884
- static {
1885
- __name(this, "MCPClient");
1886
- }
1887
- /**
1888
- * Get the mcp-use package version.
1889
- * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
1890
- */
1891
- static getPackageVersion() {
1892
- return getPackageVersion();
1893
- }
1894
- codeMode = false;
1895
- _codeExecutor = null;
1896
- _customCodeExecutor = null;
1897
- _codeExecutorConfig = "vm";
1898
- _executorOptions;
1899
- _samplingCallback;
1900
- _elicitationCallback;
1901
- constructor(config, options) {
1902
- if (config) {
1903
- if (typeof config === "string") {
1904
- super(loadConfigFile(config));
1905
- } else {
1906
- super(config);
1907
- }
1908
- } else {
1909
- super();
1910
- }
1911
- let codeModeEnabled = false;
1912
- let executorConfig = "vm";
1913
- let executorOptions;
1914
- if (options?.codeMode) {
1915
- if (typeof options.codeMode === "boolean") {
1916
- codeModeEnabled = options.codeMode;
1917
- } else {
1918
- codeModeEnabled = options.codeMode.enabled;
1919
- executorConfig = options.codeMode.executor ?? "vm";
1920
- executorOptions = options.codeMode.executorOptions;
1921
- }
1922
- }
1923
- this.codeMode = codeModeEnabled;
1924
- this._codeExecutorConfig = executorConfig;
1925
- this._executorOptions = executorOptions;
1926
- this._samplingCallback = options?.samplingCallback;
1927
- this._elicitationCallback = options?.elicitationCallback;
1928
- if (this.codeMode) {
1929
- this._setupCodeModeConnector();
1930
- }
1931
- this._trackClientInit();
1932
- }
1933
- _trackClientInit() {
1934
- const servers = Object.keys(this.config.mcpServers ?? {});
1935
- const hasSamplingCallback = !!this._samplingCallback;
1936
- const hasElicitationCallback = !!this._elicitationCallback;
1937
- Tel.getInstance().trackMCPClientInit({
1938
- codeMode: this.codeMode,
1939
- sandbox: false,
1940
- // Sandbox not supported in TS yet
1941
- allCallbacks: hasSamplingCallback && hasElicitationCallback,
1942
- verify: false,
1943
- // No verify option in TS client
1944
- servers,
1945
- numServers: servers.length,
1946
- isBrowser: false
1947
- // Node.js MCPClient
1948
- }).catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));
1949
- }
1950
- static fromDict(cfg, options) {
1951
- return new _MCPClient(cfg, options);
1952
- }
1953
- static fromConfigFile(path2, options) {
1954
- return new _MCPClient(loadConfigFile(path2), options);
1955
- }
1956
- /**
1957
- * Save configuration to a file (Node.js only)
1958
- */
1959
- saveConfig(filepath) {
1960
- const dir = path.dirname(filepath);
1961
- if (!fs.existsSync(dir)) {
1962
- fs.mkdirSync(dir, { recursive: true });
1963
- }
1964
- fs.writeFileSync(filepath, JSON.stringify(this.config, null, 2), "utf-8");
1965
- }
1966
- /**
1967
- * Create a connector from server configuration (Node.js version)
1968
- * Supports all connector types including StdioConnector
1969
- */
1970
- createConnectorFromConfig(serverConfig) {
1971
- return createConnectorFromConfig(serverConfig, {
1972
- samplingCallback: this._samplingCallback,
1973
- elicitationCallback: this._elicitationCallback
1974
- });
1975
- }
1976
- _setupCodeModeConnector() {
1977
- logger.debug("Code mode connector initialized as internal meta server");
1978
- const connector = new CodeModeConnector(this);
1979
- const session = new MCPSession(connector);
1980
- this.sessions["code_mode"] = session;
1981
- this.activeSessions.push("code_mode");
1982
- }
1983
- _ensureCodeExecutor() {
1984
- if (!this._codeExecutor) {
1985
- const config = this._codeExecutorConfig;
1986
- if (config instanceof BaseCodeExecutor) {
1987
- this._codeExecutor = config;
1988
- } else if (typeof config === "function") {
1989
- this._customCodeExecutor = config;
1990
- throw new Error(
1991
- "Custom executor function should be handled in executeCode"
1992
- );
1993
- } else if (config === "e2b") {
1994
- const opts = this._executorOptions;
1995
- if (!opts?.apiKey) {
1996
- logger.warn("E2B executor requires apiKey. Falling back to VM.");
1997
- try {
1998
- this._codeExecutor = new VMCodeExecutor(
1999
- this,
2000
- this._executorOptions
2001
- );
2002
- } catch (error) {
2003
- throw new Error(
2004
- "VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment."
2005
- );
2006
- }
2007
- } else {
2008
- this._codeExecutor = new E2BCodeExecutor(this, opts);
2009
- }
2010
- } else {
2011
- try {
2012
- this._codeExecutor = new VMCodeExecutor(
2013
- this,
2014
- this._executorOptions
2015
- );
2016
- } catch (error) {
2017
- const e2bOpts = this._executorOptions;
2018
- const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;
2019
- if (e2bApiKey) {
2020
- logger.info(
2021
- "VM executor not available in this environment. Falling back to E2B."
2022
- );
2023
- this._codeExecutor = new E2BCodeExecutor(this, {
2024
- ...e2bOpts,
2025
- apiKey: e2bApiKey
2026
- });
2027
- } else {
2028
- throw new Error(
2029
- "VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment."
2030
- );
2031
- }
2032
- }
2033
- }
2034
- }
2035
- return this._codeExecutor;
2036
- }
2037
- /**
2038
- * Execute code in code mode
2039
- */
2040
- async executeCode(code, timeout) {
2041
- if (!this.codeMode) {
2042
- throw new Error("Code execution mode is not enabled");
2043
- }
2044
- if (this._customCodeExecutor) {
2045
- return this._customCodeExecutor(code, timeout);
2046
- }
2047
- return this._ensureCodeExecutor().execute(code, timeout);
2048
- }
2049
- /**
2050
- * Search available tools (used by code mode)
2051
- */
2052
- async searchTools(query = "", detailLevel = "full") {
2053
- if (!this.codeMode) {
2054
- throw new Error("Code execution mode is not enabled");
2055
- }
2056
- return this._ensureCodeExecutor().createSearchToolsFunction()(
2057
- query,
2058
- detailLevel
2059
- );
2060
- }
2061
- /**
2062
- * Override getServerNames to exclude internal code_mode server
2063
- */
2064
- getServerNames() {
2065
- const isCodeModeEnabled = this.codeMode;
2066
- return super.getServerNames().filter((name) => {
2067
- return !isCodeModeEnabled || name !== "code_mode";
2068
- });
2069
- }
2070
- /**
2071
- * Close the client and clean up resources including code executors.
2072
- * This ensures E2B sandboxes and other resources are properly released.
2073
- */
2074
- async close() {
2075
- if (this._codeExecutor) {
2076
- await this._codeExecutor.cleanup();
2077
- this._codeExecutor = null;
2078
- }
2079
- await this.closeAllSessions();
2080
- }
2081
- };
8
+ Telemetry,
9
+ extractModelInfo,
10
+ getPackageVersion
11
+ } from "./chunk-Q5LZL6BH.js";
12
+ import {
13
+ logger
14
+ } from "./chunk-FRUZDWXH.js";
15
+ import {
16
+ __name
17
+ } from "./chunk-3GQAWCBQ.js";
2082
18
 
2083
19
  // src/managers/tools/acquire_active_mcp_server.ts
2084
- import { z as z3 } from "zod";
20
+ import { z } from "zod";
2085
21
 
2086
22
  // src/managers/tools/base.ts
2087
23
  import { StructuredTool } from "@langchain/core/tools";
@@ -2106,7 +42,7 @@ var MCPServerTool = class extends StructuredTool {
2106
42
  };
2107
43
 
2108
44
  // src/managers/tools/acquire_active_mcp_server.ts
2109
- var PresentActiveServerSchema = z3.object({});
45
+ var PresentActiveServerSchema = z.object({});
2110
46
  var AcquireActiveMCPServerTool = class extends MCPServerTool {
2111
47
  static {
2112
48
  __name(this, "AcquireActiveMCPServerTool");
@@ -2127,16 +63,16 @@ var AcquireActiveMCPServerTool = class extends MCPServerTool {
2127
63
 
2128
64
  // src/managers/tools/add_server_from_config.ts
2129
65
  import { StructuredTool as StructuredTool2 } from "@langchain/core/tools";
2130
- import { z as z4 } from "zod";
66
+ import { z as z2 } from "zod";
2131
67
  var AddMCPServerFromConfigTool = class extends StructuredTool2 {
2132
68
  static {
2133
69
  __name(this, "AddMCPServerFromConfigTool");
2134
70
  }
2135
71
  name = "add_mcp_server_from_config";
2136
72
  description = "Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";
2137
- schema = z4.object({
2138
- serverName: z4.string().describe("The name for the new MCP server."),
2139
- serverConfig: z4.any().describe(
73
+ schema = z2.object({
74
+ serverName: z2.string().describe("The name for the new MCP server."),
75
+ serverConfig: z2.any().describe(
2140
76
  'The configuration object for the server. This should not include the top-level "mcpServers" key.'
2141
77
  )
2142
78
  });
@@ -2178,9 +114,9 @@ ${tools.map((t) => t.name).join("\n")}`;
2178
114
  };
2179
115
 
2180
116
  // src/managers/tools/connect_mcp_server.ts
2181
- import { z as z5 } from "zod";
2182
- var ConnectMCPServerSchema = z5.object({
2183
- serverName: z5.string().describe("The name of the MCP server.")
117
+ import { z as z3 } from "zod";
118
+ var ConnectMCPServerSchema = z3.object({
119
+ serverName: z3.string().describe("The name of the MCP server.")
2184
120
  });
2185
121
  var ConnectMCPServerTool = class extends MCPServerTool {
2186
122
  static {
@@ -2234,8 +170,8 @@ var ConnectMCPServerTool = class extends MCPServerTool {
2234
170
  };
2235
171
 
2236
172
  // src/managers/tools/list_mcp_servers.ts
2237
- import { z as z6 } from "zod";
2238
- var EnumerateServersSchema = z6.object({});
173
+ import { z as z4 } from "zod";
174
+ var EnumerateServersSchema = z4.object({});
2239
175
  var ListMCPServersTool = class extends MCPServerTool {
2240
176
  static {
2241
177
  __name(this, "ListMCPServersTool");
@@ -2272,8 +208,8 @@ var ListMCPServersTool = class extends MCPServerTool {
2272
208
  };
2273
209
 
2274
210
  // src/managers/tools/release_mcp_server_connection.ts
2275
- import { z as z7 } from "zod";
2276
- var ReleaseConnectionSchema = z7.object({});
211
+ import { z as z5 } from "zod";
212
+ var ReleaseConnectionSchema = z5.object({});
2277
213
  var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
2278
214
  static {
2279
215
  __name(this, "ReleaseMCPServerConnectionTool");
@@ -4686,15 +2622,6 @@ ${formatPrompt}`
4686
2622
  };
4687
2623
 
4688
2624
  export {
4689
- BaseAdapter,
4690
- LangChainAdapter,
4691
- BaseCodeExecutor,
4692
- E2BCodeExecutor,
4693
- isVMAvailable,
4694
- VMCodeExecutor,
4695
- StdioConnector,
4696
- loadConfigFile,
4697
- MCPClient,
4698
2625
  AcquireActiveMCPServerTool,
4699
2626
  AddMCPServerFromConfigTool,
4700
2627
  ConnectMCPServerTool,