mcp-use 1.10.6 → 1.11.0-canary.4

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