mcp-use 1.11.0-canary.8 → 1.11.0

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 (91) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/{chunk-5RTMAOZ6.js → chunk-A4QJRN7Z.js} +5 -1041
  3. package/dist/{chunk-4LZSXUFM.js → chunk-B7AGEK7F.js} +1 -1
  4. package/dist/{chunk-TAEHPLGV.js → chunk-GN5HOAV3.js} +664 -136
  5. package/dist/chunk-QPIDKGV4.js +1246 -0
  6. package/dist/chunk-UWWLWLS2.js +62 -0
  7. package/dist/{chunk-ZFZPZ4GE.js → chunk-V77WS6CS.js} +9 -0
  8. package/dist/{chunk-EBSNALCB.js → chunk-VRHAF2WT.js} +10 -4
  9. package/dist/{chunk-X7JKFBPN.js → chunk-Y2HHHJQB.js} +159 -8
  10. package/dist/{chunk-JPKFN73V.js → chunk-ZLZOOXMJ.js} +96 -43
  11. package/dist/index.cjs +316 -53
  12. package/dist/index.js +22 -24
  13. package/dist/notifications-FLGIFS56.js +9 -0
  14. package/dist/src/agents/index.cjs +153 -47
  15. package/dist/src/agents/index.d.ts +1 -1
  16. package/dist/src/agents/index.d.ts.map +1 -1
  17. package/dist/src/agents/index.js +7 -10
  18. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  19. package/dist/src/{client/prompts.d.ts → agents/prompts/index.d.ts} +3 -3
  20. package/dist/src/agents/prompts/index.d.ts.map +1 -0
  21. package/dist/src/browser.cjs +160 -48
  22. package/dist/src/browser.js +10 -12
  23. package/dist/src/client/browser.d.ts.map +1 -1
  24. package/dist/src/client.cjs +3852 -0
  25. package/dist/src/client.d.ts +2 -0
  26. package/dist/src/client.d.ts.map +1 -1
  27. package/dist/src/client.js +21 -0
  28. package/dist/src/config.d.ts.map +1 -1
  29. package/dist/src/connectors/http.d.ts +2 -0
  30. package/dist/src/connectors/http.d.ts.map +1 -1
  31. package/dist/src/react/index.cjs +313 -52
  32. package/dist/src/react/index.js +7 -8
  33. package/dist/src/react/types.d.ts +41 -1
  34. package/dist/src/react/types.d.ts.map +1 -1
  35. package/dist/src/react/useMcp.d.ts.map +1 -1
  36. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  37. package/dist/src/server/index.cjs +1339 -256
  38. package/dist/src/server/index.d.ts +2 -0
  39. package/dist/src/server/index.d.ts.map +1 -1
  40. package/dist/src/server/index.js +1119 -156
  41. package/dist/src/server/mcp-server.d.ts +4 -1
  42. package/dist/src/server/mcp-server.d.ts.map +1 -1
  43. package/dist/src/server/notifications/index.d.ts +1 -1
  44. package/dist/src/server/notifications/index.d.ts.map +1 -1
  45. package/dist/src/server/notifications/notification-registration.d.ts +51 -0
  46. package/dist/src/server/notifications/notification-registration.d.ts.map +1 -1
  47. package/dist/src/server/sessions/index.d.ts +3 -1
  48. package/dist/src/server/sessions/index.d.ts.map +1 -1
  49. package/dist/src/server/sessions/session-manager.d.ts +30 -16
  50. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  51. package/dist/src/server/sessions/stores/filesystem.d.ts +121 -0
  52. package/dist/src/server/sessions/stores/filesystem.d.ts.map +1 -0
  53. package/dist/src/server/sessions/stores/index.d.ts +94 -0
  54. package/dist/src/server/sessions/stores/index.d.ts.map +1 -0
  55. package/dist/src/server/sessions/stores/memory.d.ts +82 -0
  56. package/dist/src/server/sessions/stores/memory.d.ts.map +1 -0
  57. package/dist/src/server/sessions/stores/redis.d.ts +164 -0
  58. package/dist/src/server/sessions/stores/redis.d.ts.map +1 -0
  59. package/dist/src/server/sessions/streams/index.d.ts +77 -0
  60. package/dist/src/server/sessions/streams/index.d.ts.map +1 -0
  61. package/dist/src/server/sessions/streams/memory.d.ts +76 -0
  62. package/dist/src/server/sessions/streams/memory.d.ts.map +1 -0
  63. package/dist/src/server/sessions/streams/redis.d.ts +146 -0
  64. package/dist/src/server/sessions/streams/redis.d.ts.map +1 -0
  65. package/dist/src/server/types/common.d.ts +82 -28
  66. package/dist/src/server/types/common.d.ts.map +1 -1
  67. package/dist/src/server/types/widget.d.ts +2 -2
  68. package/dist/src/server/types/widget.d.ts.map +1 -1
  69. package/dist/src/server/utils/response-helpers.d.ts +4 -2
  70. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  71. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  72. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  73. package/dist/src/task_managers/index.d.ts +10 -0
  74. package/dist/src/task_managers/index.d.ts.map +1 -1
  75. package/dist/src/task_managers/sse.d.ts +34 -1
  76. package/dist/src/task_managers/sse.d.ts.map +1 -1
  77. package/dist/src/task_managers/streamable_http.d.ts +8 -2
  78. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  79. package/dist/src/telemetry/telemetry.d.ts +1 -0
  80. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  81. package/dist/src/version.d.ts +1 -1
  82. package/dist/src/version.d.ts.map +1 -1
  83. package/dist/{tool-execution-helpers-EYAIJERC.js → tool-execution-helpers-ZUA5D5IO.js} +2 -2
  84. package/dist/tsup.config.d.ts.map +1 -1
  85. package/package.json +62 -52
  86. package/dist/chunk-GVU7C2ZD.js +0 -12
  87. package/dist/chunk-JZNXOM7C.js +0 -204
  88. package/dist/chunk-XKTBHYNM.js +0 -491
  89. package/dist/src/client/prompts.cjs +0 -407
  90. package/dist/src/client/prompts.d.ts.map +0 -1
  91. package/dist/src/client/prompts.js +0 -11
@@ -1,1050 +1,21 @@
1
+ import {
2
+ MCPClient
3
+ } from "./chunk-QPIDKGV4.js";
1
4
  import {
2
5
  LangChainAdapter
3
6
  } from "./chunk-MFSO5PUW.js";
4
7
  import {
5
- CodeModeConnector
6
- } from "./chunk-JZNXOM7C.js";
7
- import {
8
- BaseMCPClient,
9
- ConnectionManager,
10
- HttpConnector,
11
- MCPSession
12
- } from "./chunk-TAEHPLGV.js";
13
- import {
14
- BaseConnector
15
- } from "./chunk-XKTBHYNM.js";
16
- import {
17
- Tel,
18
8
  Telemetry,
19
9
  extractModelInfo,
20
10
  getPackageVersion
21
- } from "./chunk-JPKFN73V.js";
11
+ } from "./chunk-ZLZOOXMJ.js";
22
12
  import {
23
13
  logger
24
14
  } from "./chunk-FRUZDWXH.js";
25
15
  import {
26
- __name,
27
- __require
16
+ __name
28
17
  } from "./chunk-3GQAWCBQ.js";
29
18
 
30
- // src/client/executors/base.ts
31
- var BaseCodeExecutor = class {
32
- static {
33
- __name(this, "BaseCodeExecutor");
34
- }
35
- client;
36
- _connecting = false;
37
- constructor(client) {
38
- this.client = client;
39
- }
40
- /**
41
- * Ensure all configured MCP servers are connected before execution.
42
- * Prevents race conditions with a connection lock.
43
- */
44
- async ensureServersConnected() {
45
- const configuredServers = this.client.getServerNames();
46
- const activeSessions = Object.keys(this.client.getAllActiveSessions());
47
- const missingServers = configuredServers.filter(
48
- (s) => !activeSessions.includes(s)
49
- );
50
- if (missingServers.length > 0 && !this._connecting) {
51
- this._connecting = true;
52
- try {
53
- logger.debug(
54
- `Connecting to configured servers for code execution: ${missingServers.join(", ")}`
55
- );
56
- await this.client.createAllSessions();
57
- } finally {
58
- this._connecting = false;
59
- }
60
- } else if (missingServers.length > 0 && this._connecting) {
61
- logger.debug("Waiting for ongoing server connection...");
62
- const startWait = Date.now();
63
- while (this._connecting && Date.now() - startWait < 5e3) {
64
- await new Promise((resolve) => setTimeout(resolve, 100));
65
- }
66
- }
67
- }
68
- /**
69
- * Get tool namespace information from all active MCP sessions.
70
- * Filters out the internal code_mode server.
71
- */
72
- getToolNamespaces() {
73
- const namespaces = [];
74
- const activeSessions = this.client.getAllActiveSessions();
75
- for (const [serverName, session] of Object.entries(activeSessions)) {
76
- if (serverName === "code_mode") continue;
77
- try {
78
- const connector = session.connector;
79
- let tools;
80
- try {
81
- tools = connector.tools;
82
- } catch (e) {
83
- logger.warn(`Tools not available for server ${serverName}: ${e}`);
84
- continue;
85
- }
86
- if (!tools || tools.length === 0) continue;
87
- namespaces.push({ serverName, tools, session });
88
- } catch (e) {
89
- logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
90
- }
91
- }
92
- return namespaces;
93
- }
94
- /**
95
- * Create a search function for discovering available MCP tools.
96
- * Used by code execution environments to find tools at runtime.
97
- */
98
- createSearchToolsFunction() {
99
- return async (query = "", detailLevel = "full") => {
100
- const allTools = [];
101
- const allNamespaces = /* @__PURE__ */ new Set();
102
- const queryLower = query.toLowerCase();
103
- const activeSessions = this.client.getAllActiveSessions();
104
- for (const [serverName, session] of Object.entries(activeSessions)) {
105
- if (serverName === "code_mode") continue;
106
- try {
107
- const tools = session.connector.tools;
108
- if (tools && tools.length > 0) {
109
- allNamespaces.add(serverName);
110
- }
111
- for (const tool of tools) {
112
- if (detailLevel === "names") {
113
- allTools.push({ name: tool.name, server: serverName });
114
- } else if (detailLevel === "descriptions") {
115
- allTools.push({
116
- name: tool.name,
117
- server: serverName,
118
- description: tool.description
119
- });
120
- } else {
121
- allTools.push({
122
- name: tool.name,
123
- server: serverName,
124
- description: tool.description,
125
- input_schema: tool.inputSchema
126
- });
127
- }
128
- }
129
- } catch (e) {
130
- logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
131
- }
132
- }
133
- let filteredTools = allTools;
134
- if (query) {
135
- filteredTools = allTools.filter((tool) => {
136
- const nameMatch = tool.name.toLowerCase().includes(queryLower);
137
- const descMatch = tool.description?.toLowerCase().includes(queryLower);
138
- const serverMatch = tool.server.toLowerCase().includes(queryLower);
139
- return nameMatch || descMatch || serverMatch;
140
- });
141
- }
142
- return {
143
- meta: {
144
- total_tools: allTools.length,
145
- namespaces: Array.from(allNamespaces).sort(),
146
- result_count: filteredTools.length
147
- },
148
- results: filteredTools
149
- };
150
- };
151
- }
152
- };
153
-
154
- // src/client/executors/e2b.ts
155
- var E2BCodeExecutor = class extends BaseCodeExecutor {
156
- static {
157
- __name(this, "E2BCodeExecutor");
158
- }
159
- e2bApiKey;
160
- codeExecSandbox = null;
161
- SandboxClass = null;
162
- timeoutMs;
163
- constructor(client, options) {
164
- super(client);
165
- this.e2bApiKey = options.apiKey;
166
- this.timeoutMs = options.timeoutMs ?? 3e5;
167
- }
168
- /**
169
- * Lazy load E2B Sandbox class.
170
- * This allows the library to work without E2B installed.
171
- */
172
- async ensureSandboxClass() {
173
- if (this.SandboxClass) return;
174
- try {
175
- const e2b = await import("@e2b/code-interpreter");
176
- this.SandboxClass = e2b.Sandbox;
177
- } catch (error) {
178
- throw new Error(
179
- "@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
180
- );
181
- }
182
- }
183
- /**
184
- * Get or create a dedicated sandbox for code execution.
185
- */
186
- async getOrCreateCodeExecSandbox() {
187
- if (this.codeExecSandbox) return this.codeExecSandbox;
188
- await this.ensureSandboxClass();
189
- logger.debug("Starting E2B sandbox for code execution...");
190
- this.codeExecSandbox = await this.SandboxClass.create("base", {
191
- apiKey: this.e2bApiKey,
192
- timeoutMs: this.timeoutMs
193
- });
194
- return this.codeExecSandbox;
195
- }
196
- /**
197
- * Generate the shim code that exposes tools to the sandbox environment.
198
- * Creates a bridge that intercepts tool calls and sends them back to host.
199
- */
200
- generateShim(tools) {
201
- let shim = `
202
- // MCP Bridge Shim
203
- global.__callMcpTool = async (server, tool, args) => {
204
- const id = Math.random().toString(36).substring(7);
205
- console.log(JSON.stringify({
206
- type: '__MCP_TOOL_CALL__',
207
- id,
208
- server,
209
- tool,
210
- args
211
- }));
212
-
213
- const resultPath = \`/tmp/mcp_result_\${id}.json\`;
214
- const fs = require('fs');
215
-
216
- // Poll for result file
217
- let attempts = 0;
218
- while (attempts < 300) { // 30 seconds timeout
219
- if (fs.existsSync(resultPath)) {
220
- const content = fs.readFileSync(resultPath, 'utf8');
221
- const result = JSON.parse(content);
222
- fs.unlinkSync(resultPath); // Clean up
223
-
224
- if (result.error) {
225
- throw new Error(result.error);
226
- }
227
- return result.data;
228
- }
229
- await new Promise(resolve => setTimeout(resolve, 100));
230
- attempts++;
231
- }
232
- throw new Error('Tool execution timed out');
233
- };
234
-
235
- // Global search_tools helper
236
- global.search_tools = async (query, detailLevel = 'full') => {
237
- const allTools = ${JSON.stringify(
238
- Object.entries(tools).flatMap(
239
- ([server, serverTools]) => serverTools.map((tool) => ({
240
- name: tool.name,
241
- description: tool.description,
242
- server,
243
- input_schema: tool.inputSchema
244
- }))
245
- )
246
- )};
247
-
248
- const filtered = allTools.filter(tool => {
249
- if (!query) return true;
250
- const q = query.toLowerCase();
251
- return tool.name.toLowerCase().includes(q) ||
252
- (tool.description && tool.description.toLowerCase().includes(q));
253
- });
254
-
255
- if (detailLevel === 'names') {
256
- return filtered.map(t => ({ name: t.name, server: t.server }));
257
- } else if (detailLevel === 'descriptions') {
258
- return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
259
- }
260
- return filtered;
261
- };
262
- `;
263
- for (const [serverName, serverTools] of Object.entries(tools)) {
264
- if (!serverTools || serverTools.length === 0) continue;
265
- const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
266
- shim += `
267
- global['${serverName}'] = {`;
268
- for (const tool of serverTools) {
269
- shim += `
270
- '${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
271
- }
272
- shim += `
273
- };
274
-
275
- // Also expose as safe name if different
276
- if ('${safeServerName}' !== '${serverName}') {
277
- global['${safeServerName}'] = global['${serverName}'];
278
- }
279
- `;
280
- }
281
- return shim;
282
- }
283
- /**
284
- * Build the tool catalog for the shim.
285
- * Returns a map of server names to their available tools.
286
- */
287
- buildToolCatalog() {
288
- const catalog = {};
289
- const namespaces = this.getToolNamespaces();
290
- for (const { serverName, tools } of namespaces) {
291
- catalog[serverName] = tools;
292
- }
293
- return catalog;
294
- }
295
- /**
296
- * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
297
- * Tool calls are proxied back to the host via the bridge pattern.
298
- *
299
- * @param code - Code to execute
300
- * @param timeout - Execution timeout in milliseconds (default: 30000)
301
- */
302
- async execute(code, timeout = 3e4) {
303
- const startTime = Date.now();
304
- let result = null;
305
- let error = null;
306
- let logs = [];
307
- try {
308
- await this.ensureServersConnected();
309
- const sandbox = await this.getOrCreateCodeExecSandbox();
310
- const toolCatalog = this.buildToolCatalog();
311
- const shim = this.generateShim(toolCatalog);
312
- const wrappedCode = `
313
- ${shim}
314
-
315
- (async () => {
316
- try {
317
- const func = async () => {
318
- ${code}
319
- };
320
- const result = await func();
321
- console.log('__MCP_RESULT_START__');
322
- console.log(JSON.stringify(result));
323
- console.log('__MCP_RESULT_END__');
324
- } catch (e) {
325
- console.error(e);
326
- process.exit(1);
327
- }
328
- })();
329
- `;
330
- const filename = `exec_${Date.now()}.js`;
331
- await sandbox.files.write(filename, wrappedCode);
332
- const execution = await sandbox.commands.run(`node ${filename}`, {
333
- timeoutMs: timeout,
334
- onStdout: /* @__PURE__ */ __name(async (data) => {
335
- try {
336
- const lines = data.split("\n");
337
- for (const line of lines) {
338
- if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
339
- const call = JSON.parse(line);
340
- if (call.type === "__MCP_TOOL_CALL__") {
341
- try {
342
- logger.debug(
343
- `[E2B Bridge] Calling tool ${call.server}.${call.tool}`
344
- );
345
- const activeSessions = this.client.getAllActiveSessions();
346
- const session = activeSessions[call.server];
347
- if (!session) {
348
- throw new Error(`Server ${call.server} not found`);
349
- }
350
- const toolResult = await session.connector.callTool(
351
- call.tool,
352
- call.args
353
- );
354
- let extractedResult = toolResult;
355
- if (toolResult.content && toolResult.content.length > 0) {
356
- const item = toolResult.content[0];
357
- if (item.type === "text") {
358
- try {
359
- extractedResult = JSON.parse(item.text);
360
- } catch {
361
- extractedResult = item.text;
362
- }
363
- } else {
364
- extractedResult = item;
365
- }
366
- }
367
- const resultPath = `/tmp/mcp_result_${call.id}.json`;
368
- await sandbox.files.write(
369
- resultPath,
370
- JSON.stringify({ data: extractedResult })
371
- );
372
- } catch (err) {
373
- logger.error(
374
- `[E2B Bridge] Tool execution failed: ${err.message}`
375
- );
376
- const resultPath = `/tmp/mcp_result_${call.id}.json`;
377
- await sandbox.files.write(
378
- resultPath,
379
- JSON.stringify({
380
- error: err.message || String(err)
381
- })
382
- );
383
- }
384
- }
385
- }
386
- }
387
- } catch (e) {
388
- }
389
- }, "onStdout")
390
- });
391
- logs = [execution.stdout, execution.stderr].filter(Boolean);
392
- if (execution.exitCode !== 0) {
393
- error = execution.stderr || "Execution failed";
394
- } else {
395
- const stdout = execution.stdout;
396
- const startMarker = "__MCP_RESULT_START__";
397
- const endMarker = "__MCP_RESULT_END__";
398
- const startIndex = stdout.indexOf(startMarker);
399
- const endIndex = stdout.indexOf(endMarker);
400
- if (startIndex !== -1 && endIndex !== -1) {
401
- const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
402
- try {
403
- result = JSON.parse(jsonStr);
404
- } catch (e) {
405
- result = jsonStr;
406
- }
407
- logs = logs.map((log) => {
408
- let cleaned = log.replace(
409
- new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
410
- "[Result captured]"
411
- );
412
- cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
413
- return cleaned;
414
- });
415
- }
416
- }
417
- } catch (e) {
418
- error = e.message || String(e);
419
- if (error && (error.includes("timeout") || error.includes("timed out"))) {
420
- error = "Script execution timed out";
421
- }
422
- }
423
- return {
424
- result,
425
- logs,
426
- error,
427
- execution_time: (Date.now() - startTime) / 1e3
428
- };
429
- }
430
- /**
431
- * Clean up the E2B sandbox.
432
- * Should be called when the executor is no longer needed.
433
- */
434
- async cleanup() {
435
- if (this.codeExecSandbox) {
436
- try {
437
- await this.codeExecSandbox.kill();
438
- this.codeExecSandbox = null;
439
- logger.debug("E2B code execution sandbox stopped");
440
- } catch (error) {
441
- logger.error("Failed to stop E2B code execution sandbox:", error);
442
- }
443
- }
444
- }
445
- };
446
-
447
- // src/client/executors/vm.ts
448
- var vm = null;
449
- var vmCheckAttempted = false;
450
- function getVMModuleName() {
451
- return ["node", "vm"].join(":");
452
- }
453
- __name(getVMModuleName, "getVMModuleName");
454
- function tryLoadVM() {
455
- if (vmCheckAttempted) {
456
- return vm !== null;
457
- }
458
- vmCheckAttempted = true;
459
- try {
460
- const nodeRequire = typeof __require !== "undefined" ? __require : null;
461
- if (nodeRequire) {
462
- vm = nodeRequire(getVMModuleName());
463
- return true;
464
- }
465
- } catch (error) {
466
- logger.debug("node:vm module not available via require");
467
- }
468
- return false;
469
- }
470
- __name(tryLoadVM, "tryLoadVM");
471
- async function tryLoadVMAsync() {
472
- if (vm !== null) {
473
- return true;
474
- }
475
- if (!vmCheckAttempted) {
476
- if (tryLoadVM()) {
477
- return true;
478
- }
479
- }
480
- try {
481
- vm = await import(
482
- /* @vite-ignore */
483
- getVMModuleName()
484
- );
485
- return true;
486
- } catch (error) {
487
- logger.debug(
488
- "node:vm module not available in this environment (e.g., Deno)"
489
- );
490
- return false;
491
- }
492
- }
493
- __name(tryLoadVMAsync, "tryLoadVMAsync");
494
- function isVMAvailable() {
495
- tryLoadVM();
496
- return vm !== null;
497
- }
498
- __name(isVMAvailable, "isVMAvailable");
499
- var VMCodeExecutor = class extends BaseCodeExecutor {
500
- static {
501
- __name(this, "VMCodeExecutor");
502
- }
503
- defaultTimeout;
504
- memoryLimitMb;
505
- constructor(client, options) {
506
- super(client);
507
- this.defaultTimeout = options?.timeoutMs ?? 3e4;
508
- this.memoryLimitMb = options?.memoryLimitMb;
509
- tryLoadVM();
510
- }
511
- /**
512
- * Ensure VM module is loaded before execution
513
- */
514
- async ensureVMLoaded() {
515
- if (vm !== null) {
516
- return;
517
- }
518
- const loaded = await tryLoadVMAsync();
519
- if (!loaded) {
520
- throw new Error(
521
- "node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment."
522
- );
523
- }
524
- }
525
- /**
526
- * Execute JavaScript/TypeScript code with access to MCP tools.
527
- *
528
- * @param code - Code to execute
529
- * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
530
- */
531
- async execute(code, timeout) {
532
- const effectiveTimeout = timeout ?? this.defaultTimeout;
533
- await this.ensureVMLoaded();
534
- await this.ensureServersConnected();
535
- const logs = [];
536
- const startTime = Date.now();
537
- let result = null;
538
- let error = null;
539
- try {
540
- const context = await this._buildContext(logs);
541
- const wrappedCode = `
542
- (async () => {
543
- try {
544
- ${code}
545
- } catch (e) {
546
- throw e;
547
- }
548
- })()
549
- `;
550
- const script = new vm.Script(wrappedCode, {
551
- filename: "agent_code.js"
552
- });
553
- const promise = script.runInNewContext(context, {
554
- timeout: effectiveTimeout,
555
- displayErrors: true
556
- });
557
- result = await promise;
558
- } catch (e) {
559
- error = e.message || String(e);
560
- if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
561
- error = "Script execution timed out";
562
- }
563
- if (e.stack) {
564
- logger.debug(`Code execution error stack: ${e.stack}`);
565
- }
566
- }
567
- const executionTime = (Date.now() - startTime) / 1e3;
568
- return {
569
- result,
570
- logs,
571
- error,
572
- execution_time: executionTime
573
- };
574
- }
575
- /**
576
- * Build the VM execution context with MCP tools and standard globals.
577
- *
578
- * @param logs - Array to capture console output
579
- */
580
- async _buildContext(logs) {
581
- const logHandler = /* @__PURE__ */ __name((...args) => {
582
- logs.push(
583
- args.map(
584
- (arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
585
- ).join(" ")
586
- );
587
- }, "logHandler");
588
- const sandbox = {
589
- console: {
590
- log: logHandler,
591
- error: /* @__PURE__ */ __name((...args) => {
592
- logHandler("[ERROR]", ...args);
593
- }, "error"),
594
- warn: /* @__PURE__ */ __name((...args) => {
595
- logHandler("[WARN]", ...args);
596
- }, "warn"),
597
- info: logHandler,
598
- debug: logHandler
599
- },
600
- // Standard globals
601
- Object,
602
- Array,
603
- String,
604
- Number,
605
- Boolean,
606
- Date,
607
- Math,
608
- JSON,
609
- RegExp,
610
- Map,
611
- Set,
612
- Promise,
613
- parseInt,
614
- parseFloat,
615
- isNaN,
616
- isFinite,
617
- encodeURI,
618
- decodeURI,
619
- encodeURIComponent,
620
- decodeURIComponent,
621
- setTimeout,
622
- clearTimeout,
623
- // Helper for tools
624
- search_tools: this.createSearchToolsFunction(),
625
- __tool_namespaces: []
626
- };
627
- const toolNamespaces = {};
628
- const namespaceInfos = this.getToolNamespaces();
629
- for (const { serverName, tools, session } of namespaceInfos) {
630
- const serverNamespace = {};
631
- for (const tool of tools) {
632
- const toolName = tool.name;
633
- serverNamespace[toolName] = async (args) => {
634
- const result = await session.connector.callTool(toolName, args || {});
635
- if (result.content && result.content.length > 0) {
636
- const item = result.content[0];
637
- if (item.type === "text") {
638
- try {
639
- return JSON.parse(item.text);
640
- } catch {
641
- return item.text;
642
- }
643
- }
644
- return item;
645
- }
646
- return result;
647
- };
648
- }
649
- sandbox[serverName] = serverNamespace;
650
- toolNamespaces[serverName] = true;
651
- }
652
- sandbox.__tool_namespaces = Object.keys(toolNamespaces);
653
- return vm.createContext(sandbox);
654
- }
655
- /**
656
- * Clean up resources.
657
- * VM executor doesn't need cleanup, but method kept for interface consistency.
658
- */
659
- async cleanup() {
660
- }
661
- };
662
-
663
- // src/connectors/stdio.ts
664
- import process2 from "process";
665
- import { Client } from "@mcp-use/modelcontextprotocol-sdk/client/index.js";
666
-
667
- // src/task_managers/stdio.ts
668
- import { StdioClientTransport } from "@mcp-use/modelcontextprotocol-sdk/client/stdio.js";
669
- var StdioConnectionManager = class extends ConnectionManager {
670
- static {
671
- __name(this, "StdioConnectionManager");
672
- }
673
- serverParams;
674
- errlog;
675
- _transport = null;
676
- /**
677
- * Create a new stdio connection manager.
678
- *
679
- * @param serverParams Parameters for the stdio server process.
680
- * @param errlog Stream to which the server's stderr should be piped.
681
- * Defaults to `process.stderr`.
682
- */
683
- constructor(serverParams, errlog = process.stderr) {
684
- super();
685
- this.serverParams = serverParams;
686
- this.errlog = errlog;
687
- }
688
- /**
689
- * Establish the stdio connection by spawning the server process and starting
690
- * the SDK's transport. Returns the live `StdioClientTransport` instance.
691
- */
692
- async establishConnection() {
693
- this._transport = new StdioClientTransport(this.serverParams);
694
- if (this._transport.stderr && typeof this._transport.stderr.pipe === "function") {
695
- this._transport.stderr.pipe(
696
- this.errlog
697
- );
698
- }
699
- logger.debug(`${this.constructor.name} connected successfully`);
700
- return this._transport;
701
- }
702
- /**
703
- * Close the stdio connection, making sure the transport cleans up the child
704
- * process and associated resources.
705
- */
706
- async closeConnection(_connection) {
707
- if (this._transport) {
708
- try {
709
- await this._transport.close();
710
- } catch (e) {
711
- logger.warn(`Error closing stdio transport: ${e}`);
712
- } finally {
713
- this._transport = null;
714
- }
715
- }
716
- }
717
- };
718
-
719
- // src/connectors/stdio.ts
720
- var StdioConnector = class extends BaseConnector {
721
- static {
722
- __name(this, "StdioConnector");
723
- }
724
- command;
725
- args;
726
- env;
727
- errlog;
728
- clientInfo;
729
- constructor({
730
- command = "npx",
731
- args = [],
732
- env,
733
- errlog = process2.stderr,
734
- ...rest
735
- } = {}) {
736
- super(rest);
737
- this.command = command;
738
- this.args = args;
739
- this.env = env;
740
- this.errlog = errlog;
741
- this.clientInfo = rest.clientInfo ?? {
742
- name: "stdio-connector",
743
- version: "1.0.0"
744
- };
745
- }
746
- /** Establish connection to the MCP implementation. */
747
- async connect() {
748
- if (this.connected) {
749
- logger.debug("Already connected to MCP implementation");
750
- return;
751
- }
752
- logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
753
- try {
754
- let mergedEnv;
755
- if (this.env) {
756
- mergedEnv = {};
757
- for (const [key, value] of Object.entries(process2.env)) {
758
- if (value !== void 0) {
759
- mergedEnv[key] = value;
760
- }
761
- }
762
- Object.assign(mergedEnv, this.env);
763
- }
764
- const serverParams = {
765
- command: this.command,
766
- args: this.args,
767
- env: mergedEnv
768
- };
769
- this.connectionManager = new StdioConnectionManager(
770
- serverParams,
771
- this.errlog
772
- );
773
- const transport = await this.connectionManager.start();
774
- const clientOptions = {
775
- ...this.opts.clientOptions || {},
776
- capabilities: {
777
- ...this.opts.clientOptions?.capabilities || {},
778
- roots: { listChanged: true },
779
- // Always advertise roots capability
780
- // Add sampling capability if callback is provided
781
- ...this.opts.samplingCallback ? { sampling: {} } : {},
782
- // Add elicitation capability if callback is provided
783
- ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
784
- }
785
- };
786
- this.client = new Client(this.clientInfo, clientOptions);
787
- await this.client.connect(transport);
788
- this.connected = true;
789
- this.setupNotificationHandler();
790
- this.setupRootsHandler();
791
- this.setupSamplingHandler();
792
- this.setupElicitationHandler();
793
- logger.debug(
794
- `Successfully connected to MCP implementation: ${this.command}`
795
- );
796
- this.trackConnectorInit({
797
- serverCommand: this.command,
798
- serverArgs: this.args,
799
- publicIdentifier: `${this.command} ${this.args.join(" ")}`
800
- });
801
- } catch (err) {
802
- logger.error(`Failed to connect to MCP implementation: ${err}`);
803
- await this.cleanupResources();
804
- throw err;
805
- }
806
- }
807
- get publicIdentifier() {
808
- return {
809
- type: "stdio",
810
- "command&args": `${this.command} ${this.args.join(" ")}`
811
- };
812
- }
813
- };
814
-
815
- // src/config.ts
816
- import { readFileSync } from "fs";
817
- function loadConfigFile(filepath) {
818
- const raw = readFileSync(filepath, "utf-8");
819
- return JSON.parse(raw);
820
- }
821
- __name(loadConfigFile, "loadConfigFile");
822
- function createConnectorFromConfig(serverConfig, connectorOptions) {
823
- if ("command" in serverConfig && "args" in serverConfig) {
824
- return new StdioConnector({
825
- command: serverConfig.command,
826
- args: serverConfig.args,
827
- env: serverConfig.env,
828
- ...connectorOptions
829
- });
830
- }
831
- if ("url" in serverConfig) {
832
- const transport = serverConfig.transport || "http";
833
- return new HttpConnector(serverConfig.url, {
834
- headers: serverConfig.headers,
835
- authToken: serverConfig.auth_token || serverConfig.authToken,
836
- // Only force SSE if explicitly requested
837
- preferSse: serverConfig.preferSse || transport === "sse",
838
- ...connectorOptions
839
- });
840
- }
841
- throw new Error("Cannot determine connector type from config");
842
- }
843
- __name(createConnectorFromConfig, "createConnectorFromConfig");
844
-
845
- // src/client.ts
846
- import fs from "fs";
847
- import path from "path";
848
- var MCPClient = class _MCPClient extends BaseMCPClient {
849
- static {
850
- __name(this, "MCPClient");
851
- }
852
- /**
853
- * Get the mcp-use package version.
854
- * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
855
- */
856
- static getPackageVersion() {
857
- return getPackageVersion();
858
- }
859
- codeMode = false;
860
- _codeExecutor = null;
861
- _customCodeExecutor = null;
862
- _codeExecutorConfig = "vm";
863
- _executorOptions;
864
- _samplingCallback;
865
- _elicitationCallback;
866
- constructor(config, options) {
867
- if (config) {
868
- if (typeof config === "string") {
869
- super(loadConfigFile(config));
870
- } else {
871
- super(config);
872
- }
873
- } else {
874
- super();
875
- }
876
- let codeModeEnabled = false;
877
- let executorConfig = "vm";
878
- let executorOptions;
879
- if (options?.codeMode) {
880
- if (typeof options.codeMode === "boolean") {
881
- codeModeEnabled = options.codeMode;
882
- } else {
883
- codeModeEnabled = options.codeMode.enabled;
884
- executorConfig = options.codeMode.executor ?? "vm";
885
- executorOptions = options.codeMode.executorOptions;
886
- }
887
- }
888
- this.codeMode = codeModeEnabled;
889
- this._codeExecutorConfig = executorConfig;
890
- this._executorOptions = executorOptions;
891
- this._samplingCallback = options?.samplingCallback;
892
- this._elicitationCallback = options?.elicitationCallback;
893
- if (this.codeMode) {
894
- this._setupCodeModeConnector();
895
- }
896
- this._trackClientInit();
897
- }
898
- _trackClientInit() {
899
- const servers = Object.keys(this.config.mcpServers ?? {});
900
- const hasSamplingCallback = !!this._samplingCallback;
901
- const hasElicitationCallback = !!this._elicitationCallback;
902
- Tel.getInstance().trackMCPClientInit({
903
- codeMode: this.codeMode,
904
- sandbox: false,
905
- // Sandbox not supported in TS yet
906
- allCallbacks: hasSamplingCallback && hasElicitationCallback,
907
- verify: false,
908
- // No verify option in TS client
909
- servers,
910
- numServers: servers.length,
911
- isBrowser: false
912
- // Node.js MCPClient
913
- }).catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));
914
- }
915
- static fromDict(cfg, options) {
916
- return new _MCPClient(cfg, options);
917
- }
918
- static fromConfigFile(path2, options) {
919
- return new _MCPClient(loadConfigFile(path2), options);
920
- }
921
- /**
922
- * Save configuration to a file (Node.js only)
923
- */
924
- saveConfig(filepath) {
925
- const dir = path.dirname(filepath);
926
- if (!fs.existsSync(dir)) {
927
- fs.mkdirSync(dir, { recursive: true });
928
- }
929
- fs.writeFileSync(filepath, JSON.stringify(this.config, null, 2), "utf-8");
930
- }
931
- /**
932
- * Create a connector from server configuration (Node.js version)
933
- * Supports all connector types including StdioConnector
934
- */
935
- createConnectorFromConfig(serverConfig) {
936
- return createConnectorFromConfig(serverConfig, {
937
- samplingCallback: this._samplingCallback,
938
- elicitationCallback: this._elicitationCallback
939
- });
940
- }
941
- _setupCodeModeConnector() {
942
- logger.debug("Code mode connector initialized as internal meta server");
943
- const connector = new CodeModeConnector(this);
944
- const session = new MCPSession(connector);
945
- this.sessions["code_mode"] = session;
946
- this.activeSessions.push("code_mode");
947
- }
948
- _ensureCodeExecutor() {
949
- if (!this._codeExecutor) {
950
- const config = this._codeExecutorConfig;
951
- if (config instanceof BaseCodeExecutor) {
952
- this._codeExecutor = config;
953
- } else if (typeof config === "function") {
954
- this._customCodeExecutor = config;
955
- throw new Error(
956
- "Custom executor function should be handled in executeCode"
957
- );
958
- } else if (config === "e2b") {
959
- const opts = this._executorOptions;
960
- if (!opts?.apiKey) {
961
- logger.warn("E2B executor requires apiKey. Falling back to VM.");
962
- try {
963
- this._codeExecutor = new VMCodeExecutor(
964
- this,
965
- this._executorOptions
966
- );
967
- } catch (error) {
968
- throw new Error(
969
- "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."
970
- );
971
- }
972
- } else {
973
- this._codeExecutor = new E2BCodeExecutor(this, opts);
974
- }
975
- } else {
976
- try {
977
- this._codeExecutor = new VMCodeExecutor(
978
- this,
979
- this._executorOptions
980
- );
981
- } catch (error) {
982
- const e2bOpts = this._executorOptions;
983
- const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;
984
- if (e2bApiKey) {
985
- logger.info(
986
- "VM executor not available in this environment. Falling back to E2B."
987
- );
988
- this._codeExecutor = new E2BCodeExecutor(this, {
989
- ...e2bOpts,
990
- apiKey: e2bApiKey
991
- });
992
- } else {
993
- throw new Error(
994
- "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."
995
- );
996
- }
997
- }
998
- }
999
- }
1000
- return this._codeExecutor;
1001
- }
1002
- /**
1003
- * Execute code in code mode
1004
- */
1005
- async executeCode(code, timeout) {
1006
- if (!this.codeMode) {
1007
- throw new Error("Code execution mode is not enabled");
1008
- }
1009
- if (this._customCodeExecutor) {
1010
- return this._customCodeExecutor(code, timeout);
1011
- }
1012
- return this._ensureCodeExecutor().execute(code, timeout);
1013
- }
1014
- /**
1015
- * Search available tools (used by code mode)
1016
- */
1017
- async searchTools(query = "", detailLevel = "full") {
1018
- if (!this.codeMode) {
1019
- throw new Error("Code execution mode is not enabled");
1020
- }
1021
- return this._ensureCodeExecutor().createSearchToolsFunction()(
1022
- query,
1023
- detailLevel
1024
- );
1025
- }
1026
- /**
1027
- * Override getServerNames to exclude internal code_mode server
1028
- */
1029
- getServerNames() {
1030
- const isCodeModeEnabled = this.codeMode;
1031
- return super.getServerNames().filter((name) => {
1032
- return !isCodeModeEnabled || name !== "code_mode";
1033
- });
1034
- }
1035
- /**
1036
- * Close the client and clean up resources including code executors.
1037
- * This ensures E2B sandboxes and other resources are properly released.
1038
- */
1039
- async close() {
1040
- if (this._codeExecutor) {
1041
- await this._codeExecutor.cleanup();
1042
- this._codeExecutor = null;
1043
- }
1044
- await this.closeAllSessions();
1045
- }
1046
- };
1047
-
1048
19
  // src/managers/tools/acquire_active_mcp_server.ts
1049
20
  import { z } from "zod";
1050
21
 
@@ -3651,13 +2622,6 @@ ${formatPrompt}`
3651
2622
  };
3652
2623
 
3653
2624
  export {
3654
- BaseCodeExecutor,
3655
- E2BCodeExecutor,
3656
- isVMAvailable,
3657
- VMCodeExecutor,
3658
- StdioConnector,
3659
- loadConfigFile,
3660
- MCPClient,
3661
2625
  AcquireActiveMCPServerTool,
3662
2626
  AddMCPServerFromConfigTool,
3663
2627
  ConnectMCPServerTool,