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