mcp-use 1.3.4-canary.2 → 1.4.0-canary.3

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-6EHM3S3M.js → chunk-35A6O3YH.js} +52 -10
  3. package/dist/chunk-DSBKVAWD.js +263 -0
  4. package/dist/{chunk-TIUSJAAE.js → chunk-GRLCLVAK.js} +3 -254
  5. package/dist/{chunk-QKPVHYJU.js → chunk-RE7EYFDV.js} +1 -1
  6. package/dist/chunk-WERYJ6PF.js +209 -0
  7. package/dist/chunk-ZFZPZ4GE.js +21 -0
  8. package/dist/display-LIYVTGEU.js +350 -0
  9. package/dist/index.cjs +1539 -284
  10. package/dist/index.d.ts +5 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +686 -22
  13. package/dist/src/agents/display.d.ts +54 -0
  14. package/dist/src/agents/display.d.ts.map +1 -0
  15. package/dist/src/agents/index.cjs +504 -10
  16. package/dist/src/agents/index.d.ts +1 -0
  17. package/dist/src/agents/index.d.ts.map +1 -1
  18. package/dist/src/agents/index.js +10 -18
  19. package/dist/src/agents/mcp_agent.d.ts +5 -0
  20. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  21. package/dist/src/browser.cjs +406 -10
  22. package/dist/src/browser.js +10 -8
  23. package/dist/src/client/codeExecutor.d.ts +6 -0
  24. package/dist/src/client/codeExecutor.d.ts.map +1 -0
  25. package/dist/src/client/connectors/codeMode.d.ts +27 -0
  26. package/dist/src/client/connectors/codeMode.d.ts.map +1 -0
  27. package/dist/src/client/executors/base.d.ts +56 -0
  28. package/dist/src/client/executors/base.d.ts.map +1 -0
  29. package/dist/src/client/executors/e2b.d.ts +46 -0
  30. package/dist/src/client/executors/e2b.d.ts.map +1 -0
  31. package/dist/src/client/executors/vm.d.ts +30 -0
  32. package/dist/src/client/executors/vm.d.ts.map +1 -0
  33. package/dist/src/client/prompts.cjs +401 -0
  34. package/dist/src/client/prompts.d.ts +13 -0
  35. package/dist/src/client/prompts.d.ts.map +1 -0
  36. package/dist/src/client/prompts.js +9 -0
  37. package/dist/src/client.d.ts +51 -4
  38. package/dist/src/client.d.ts.map +1 -1
  39. package/dist/src/react/index.js +3 -2
  40. package/dist/tsup.config.d.ts.map +1 -1
  41. package/package.json +14 -4
package/dist/index.js CHANGED
@@ -3,6 +3,26 @@ import {
3
3
  streamEventsToAISDK,
4
4
  streamEventsToAISDKWithTools
5
5
  } from "./chunk-EW4MJSHA.js";
6
+ import "./chunk-ZFZPZ4GE.js";
7
+ import {
8
+ AcquireActiveMCPServerTool,
9
+ AddMCPServerFromConfigTool,
10
+ BaseAdapter,
11
+ ConnectMCPServerTool,
12
+ LangChainAdapter,
13
+ ListMCPServersTool,
14
+ MCPAgent,
15
+ ObservabilityManager,
16
+ ReleaseMCPServerConnectionTool,
17
+ RemoteAgent,
18
+ ServerManager,
19
+ Telemetry,
20
+ setTelemetrySource
21
+ } from "./chunk-35A6O3YH.js";
22
+ import {
23
+ CodeModeConnector,
24
+ PROMPTS
25
+ } from "./chunk-WERYJ6PF.js";
6
26
  import {
7
27
  WidgetDebugger,
8
28
  WidgetFullscreenWrapper,
@@ -11,9 +31,8 @@ import {
11
31
  useWidgetProps,
12
32
  useWidgetState,
13
33
  useWidgetTheme
14
- } from "./chunk-QKPVHYJU.js";
34
+ } from "./chunk-RE7EYFDV.js";
15
35
  import {
16
- BaseConnector,
17
36
  BaseMCPClient,
18
37
  BrowserOAuthClientProvider,
19
38
  ConnectionManager,
@@ -21,22 +40,10 @@ import {
21
40
  MCPSession,
22
41
  WebSocketConnector,
23
42
  onMcpAuthorization
24
- } from "./chunk-TIUSJAAE.js";
43
+ } from "./chunk-GRLCLVAK.js";
25
44
  import {
26
- AcquireActiveMCPServerTool,
27
- AddMCPServerFromConfigTool,
28
- BaseAdapter,
29
- ConnectMCPServerTool,
30
- LangChainAdapter,
31
- ListMCPServersTool,
32
- MCPAgent,
33
- ObservabilityManager,
34
- ReleaseMCPServerConnectionTool,
35
- RemoteAgent,
36
- ServerManager,
37
- Telemetry,
38
- setTelemetrySource
39
- } from "./chunk-6EHM3S3M.js";
45
+ BaseConnector
46
+ } from "./chunk-DSBKVAWD.js";
40
47
  import "./chunk-YURRUCIM.js";
41
48
  import {
42
49
  Logger,
@@ -50,6 +57,558 @@ import {
50
57
  import fs from "fs";
51
58
  import path from "path";
52
59
 
60
+ // src/client/executors/base.ts
61
+ var BaseCodeExecutor = class {
62
+ static {
63
+ __name(this, "BaseCodeExecutor");
64
+ }
65
+ client;
66
+ _connecting = false;
67
+ constructor(client) {
68
+ this.client = client;
69
+ }
70
+ /**
71
+ * Ensure all configured MCP servers are connected before execution.
72
+ * Prevents race conditions with a connection lock.
73
+ */
74
+ async ensureServersConnected() {
75
+ const configuredServers = this.client.getServerNames();
76
+ const activeSessions = Object.keys(this.client.getAllActiveSessions());
77
+ const missingServers = configuredServers.filter(
78
+ (s) => !activeSessions.includes(s)
79
+ );
80
+ if (missingServers.length > 0 && !this._connecting) {
81
+ this._connecting = true;
82
+ try {
83
+ logger.debug(
84
+ `Connecting to configured servers for code execution: ${missingServers.join(", ")}`
85
+ );
86
+ await this.client.createAllSessions();
87
+ } finally {
88
+ this._connecting = false;
89
+ }
90
+ } else if (missingServers.length > 0 && this._connecting) {
91
+ logger.debug("Waiting for ongoing server connection...");
92
+ const startWait = Date.now();
93
+ while (this._connecting && Date.now() - startWait < 5e3) {
94
+ await new Promise((resolve) => setTimeout(resolve, 100));
95
+ }
96
+ }
97
+ }
98
+ /**
99
+ * Get tool namespace information from all active MCP sessions.
100
+ * Filters out the internal code_mode server.
101
+ */
102
+ getToolNamespaces() {
103
+ const namespaces = [];
104
+ const activeSessions = this.client.getAllActiveSessions();
105
+ for (const [serverName, session] of Object.entries(activeSessions)) {
106
+ if (serverName === "code_mode") continue;
107
+ try {
108
+ const connector = session.connector;
109
+ let tools;
110
+ try {
111
+ tools = connector.tools;
112
+ } catch (e) {
113
+ logger.warn(`Tools not available for server ${serverName}: ${e}`);
114
+ continue;
115
+ }
116
+ if (!tools || tools.length === 0) continue;
117
+ namespaces.push({ serverName, tools, session });
118
+ } catch (e) {
119
+ logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
120
+ }
121
+ }
122
+ return namespaces;
123
+ }
124
+ /**
125
+ * Create a search function for discovering available MCP tools.
126
+ * Used by code execution environments to find tools at runtime.
127
+ */
128
+ createSearchToolsFunction() {
129
+ return async (query = "", detailLevel = "full") => {
130
+ const allTools = [];
131
+ const queryLower = query.toLowerCase();
132
+ const activeSessions = this.client.getAllActiveSessions();
133
+ for (const [serverName, session] of Object.entries(activeSessions)) {
134
+ if (serverName === "code_mode") continue;
135
+ try {
136
+ const tools = session.connector.tools;
137
+ for (const tool of tools) {
138
+ if (query) {
139
+ const nameMatch = tool.name.toLowerCase().includes(queryLower);
140
+ const descMatch = tool.description?.toLowerCase().includes(queryLower);
141
+ if (!nameMatch && !descMatch) continue;
142
+ }
143
+ if (detailLevel === "names") {
144
+ allTools.push({ name: tool.name, server: serverName });
145
+ } else if (detailLevel === "descriptions") {
146
+ allTools.push({
147
+ name: tool.name,
148
+ server: serverName,
149
+ description: tool.description
150
+ });
151
+ } else {
152
+ allTools.push({
153
+ name: tool.name,
154
+ server: serverName,
155
+ description: tool.description,
156
+ input_schema: tool.inputSchema
157
+ });
158
+ }
159
+ }
160
+ } catch (e) {
161
+ logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
162
+ }
163
+ }
164
+ return allTools;
165
+ };
166
+ }
167
+ };
168
+
169
+ // src/client/executors/e2b.ts
170
+ var E2BCodeExecutor = class extends BaseCodeExecutor {
171
+ static {
172
+ __name(this, "E2BCodeExecutor");
173
+ }
174
+ e2bApiKey;
175
+ codeExecSandbox = null;
176
+ SandboxClass = null;
177
+ timeoutMs;
178
+ constructor(client, options) {
179
+ super(client);
180
+ this.e2bApiKey = options.apiKey;
181
+ this.timeoutMs = options.timeoutMs ?? 3e5;
182
+ }
183
+ /**
184
+ * Lazy load E2B Sandbox class.
185
+ * This allows the library to work without E2B installed.
186
+ */
187
+ async ensureSandboxClass() {
188
+ if (this.SandboxClass) return;
189
+ try {
190
+ const e2b = await import("@e2b/code-interpreter");
191
+ this.SandboxClass = e2b.Sandbox;
192
+ } catch (error) {
193
+ throw new Error(
194
+ "@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
195
+ );
196
+ }
197
+ }
198
+ /**
199
+ * Get or create a dedicated sandbox for code execution.
200
+ */
201
+ async getOrCreateCodeExecSandbox() {
202
+ if (this.codeExecSandbox) return this.codeExecSandbox;
203
+ await this.ensureSandboxClass();
204
+ logger.debug("Starting E2B sandbox for code execution...");
205
+ this.codeExecSandbox = await this.SandboxClass.create("base", {
206
+ apiKey: this.e2bApiKey,
207
+ timeoutMs: this.timeoutMs
208
+ });
209
+ return this.codeExecSandbox;
210
+ }
211
+ /**
212
+ * Generate the shim code that exposes tools to the sandbox environment.
213
+ * Creates a bridge that intercepts tool calls and sends them back to host.
214
+ */
215
+ generateShim(tools) {
216
+ let shim = `
217
+ // MCP Bridge Shim
218
+ global.__callMcpTool = async (server, tool, args) => {
219
+ const id = Math.random().toString(36).substring(7);
220
+ console.log(JSON.stringify({
221
+ type: '__MCP_TOOL_CALL__',
222
+ id,
223
+ server,
224
+ tool,
225
+ args
226
+ }));
227
+
228
+ const resultPath = \`/tmp/mcp_result_\${id}.json\`;
229
+ const fs = require('fs');
230
+
231
+ // Poll for result file
232
+ let attempts = 0;
233
+ while (attempts < 300) { // 30 seconds timeout
234
+ if (fs.existsSync(resultPath)) {
235
+ const content = fs.readFileSync(resultPath, 'utf8');
236
+ const result = JSON.parse(content);
237
+ fs.unlinkSync(resultPath); // Clean up
238
+
239
+ if (result.error) {
240
+ throw new Error(result.error);
241
+ }
242
+ return result.data;
243
+ }
244
+ await new Promise(resolve => setTimeout(resolve, 100));
245
+ attempts++;
246
+ }
247
+ throw new Error('Tool execution timed out');
248
+ };
249
+
250
+ // Global search_tools helper
251
+ global.search_tools = async (query, detailLevel = 'full') => {
252
+ const allTools = ${JSON.stringify(
253
+ Object.entries(tools).flatMap(
254
+ ([server, serverTools]) => serverTools.map((tool) => ({
255
+ name: tool.name,
256
+ description: tool.description,
257
+ server,
258
+ input_schema: tool.inputSchema
259
+ }))
260
+ )
261
+ )};
262
+
263
+ const filtered = allTools.filter(tool => {
264
+ if (!query) return true;
265
+ const q = query.toLowerCase();
266
+ return tool.name.toLowerCase().includes(q) ||
267
+ (tool.description && tool.description.toLowerCase().includes(q));
268
+ });
269
+
270
+ if (detailLevel === 'names') {
271
+ return filtered.map(t => ({ name: t.name, server: t.server }));
272
+ } else if (detailLevel === 'descriptions') {
273
+ return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
274
+ }
275
+ return filtered;
276
+ };
277
+ `;
278
+ for (const [serverName, serverTools] of Object.entries(tools)) {
279
+ if (!serverTools || serverTools.length === 0) continue;
280
+ const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
281
+ shim += `
282
+ global['${serverName}'] = {`;
283
+ for (const tool of serverTools) {
284
+ shim += `
285
+ '${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
286
+ }
287
+ shim += `
288
+ };
289
+
290
+ // Also expose as safe name if different
291
+ if ('${safeServerName}' !== '${serverName}') {
292
+ global['${safeServerName}'] = global['${serverName}'];
293
+ }
294
+ `;
295
+ }
296
+ return shim;
297
+ }
298
+ /**
299
+ * Build the tool catalog for the shim.
300
+ * Returns a map of server names to their available tools.
301
+ */
302
+ buildToolCatalog() {
303
+ const catalog = {};
304
+ const namespaces = this.getToolNamespaces();
305
+ for (const { serverName, tools } of namespaces) {
306
+ catalog[serverName] = tools;
307
+ }
308
+ return catalog;
309
+ }
310
+ /**
311
+ * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
312
+ * Tool calls are proxied back to the host via the bridge pattern.
313
+ *
314
+ * @param code - Code to execute
315
+ * @param timeout - Execution timeout in milliseconds (default: 30000)
316
+ */
317
+ async execute(code, timeout = 3e4) {
318
+ const startTime = Date.now();
319
+ let result = null;
320
+ let error = null;
321
+ let logs = [];
322
+ try {
323
+ await this.ensureServersConnected();
324
+ const sandbox = await this.getOrCreateCodeExecSandbox();
325
+ const toolCatalog = this.buildToolCatalog();
326
+ const shim = this.generateShim(toolCatalog);
327
+ const wrappedCode = `
328
+ ${shim}
329
+
330
+ (async () => {
331
+ try {
332
+ const func = async () => {
333
+ ${code}
334
+ };
335
+ const result = await func();
336
+ console.log('__MCP_RESULT_START__');
337
+ console.log(JSON.stringify(result));
338
+ console.log('__MCP_RESULT_END__');
339
+ } catch (e) {
340
+ console.error(e);
341
+ process.exit(1);
342
+ }
343
+ })();
344
+ `;
345
+ const filename = `exec_${Date.now()}.js`;
346
+ await sandbox.files.write(filename, wrappedCode);
347
+ const execution = await sandbox.commands.run(`node ${filename}`, {
348
+ timeoutMs: timeout,
349
+ onStdout: /* @__PURE__ */ __name(async (data) => {
350
+ try {
351
+ const lines = data.split("\n");
352
+ for (const line of lines) {
353
+ if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
354
+ const call = JSON.parse(line);
355
+ if (call.type === "__MCP_TOOL_CALL__") {
356
+ try {
357
+ logger.debug(
358
+ `[E2B Bridge] Calling tool ${call.server}.${call.tool}`
359
+ );
360
+ const activeSessions = this.client.getAllActiveSessions();
361
+ const session = activeSessions[call.server];
362
+ if (!session) {
363
+ throw new Error(`Server ${call.server} not found`);
364
+ }
365
+ const toolResult = await session.connector.callTool(
366
+ call.tool,
367
+ call.args
368
+ );
369
+ let extractedResult = toolResult;
370
+ if (toolResult.content && toolResult.content.length > 0) {
371
+ const item = toolResult.content[0];
372
+ if (item.type === "text") {
373
+ try {
374
+ extractedResult = JSON.parse(item.text);
375
+ } catch {
376
+ extractedResult = item.text;
377
+ }
378
+ } else {
379
+ extractedResult = item;
380
+ }
381
+ }
382
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
383
+ await sandbox.files.write(
384
+ resultPath,
385
+ JSON.stringify({ data: extractedResult })
386
+ );
387
+ } catch (err) {
388
+ logger.error(
389
+ `[E2B Bridge] Tool execution failed: ${err.message}`
390
+ );
391
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
392
+ await sandbox.files.write(
393
+ resultPath,
394
+ JSON.stringify({
395
+ error: err.message || String(err)
396
+ })
397
+ );
398
+ }
399
+ }
400
+ }
401
+ }
402
+ } catch (e) {
403
+ }
404
+ }, "onStdout")
405
+ });
406
+ logs = [execution.stdout, execution.stderr].filter(Boolean);
407
+ if (execution.exitCode !== 0) {
408
+ error = execution.stderr || "Execution failed";
409
+ } else {
410
+ const stdout = execution.stdout;
411
+ const startMarker = "__MCP_RESULT_START__";
412
+ const endMarker = "__MCP_RESULT_END__";
413
+ const startIndex = stdout.indexOf(startMarker);
414
+ const endIndex = stdout.indexOf(endMarker);
415
+ if (startIndex !== -1 && endIndex !== -1) {
416
+ const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
417
+ try {
418
+ result = JSON.parse(jsonStr);
419
+ } catch (e) {
420
+ result = jsonStr;
421
+ }
422
+ logs = logs.map((log) => {
423
+ let cleaned = log.replace(
424
+ new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
425
+ "[Result captured]"
426
+ );
427
+ cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
428
+ return cleaned;
429
+ });
430
+ }
431
+ }
432
+ } catch (e) {
433
+ error = e.message || String(e);
434
+ if (error && (error.includes("timeout") || error.includes("timed out"))) {
435
+ error = "Script execution timed out";
436
+ }
437
+ }
438
+ return {
439
+ result,
440
+ logs,
441
+ error,
442
+ execution_time: (Date.now() - startTime) / 1e3
443
+ };
444
+ }
445
+ /**
446
+ * Clean up the E2B sandbox.
447
+ * Should be called when the executor is no longer needed.
448
+ */
449
+ async cleanup() {
450
+ if (this.codeExecSandbox) {
451
+ try {
452
+ await this.codeExecSandbox.kill();
453
+ this.codeExecSandbox = null;
454
+ logger.debug("E2B code execution sandbox stopped");
455
+ } catch (error) {
456
+ logger.error("Failed to stop E2B code execution sandbox:", error);
457
+ }
458
+ }
459
+ }
460
+ };
461
+
462
+ // src/client/executors/vm.ts
463
+ import vm from "vm";
464
+ var VMCodeExecutor = class extends BaseCodeExecutor {
465
+ static {
466
+ __name(this, "VMCodeExecutor");
467
+ }
468
+ defaultTimeout;
469
+ memoryLimitMb;
470
+ constructor(client, options) {
471
+ super(client);
472
+ this.defaultTimeout = options?.timeoutMs ?? 3e4;
473
+ this.memoryLimitMb = options?.memoryLimitMb;
474
+ }
475
+ /**
476
+ * Execute JavaScript/TypeScript code with access to MCP tools.
477
+ *
478
+ * @param code - Code to execute
479
+ * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
480
+ */
481
+ async execute(code, timeout) {
482
+ const effectiveTimeout = timeout ?? this.defaultTimeout;
483
+ await this.ensureServersConnected();
484
+ const logs = [];
485
+ const startTime = Date.now();
486
+ let result = null;
487
+ let error = null;
488
+ try {
489
+ const context = await this._buildContext(logs);
490
+ const wrappedCode = `
491
+ (async () => {
492
+ try {
493
+ ${code}
494
+ } catch (e) {
495
+ throw e;
496
+ }
497
+ })()
498
+ `;
499
+ const script = new vm.Script(wrappedCode, {
500
+ filename: "agent_code.js"
501
+ });
502
+ const promise = script.runInNewContext(context, {
503
+ timeout: effectiveTimeout,
504
+ displayErrors: true
505
+ });
506
+ result = await promise;
507
+ } catch (e) {
508
+ error = e.message || String(e);
509
+ if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
510
+ error = "Script execution timed out";
511
+ }
512
+ if (e.stack) {
513
+ logger.debug(`Code execution error stack: ${e.stack}`);
514
+ }
515
+ }
516
+ const executionTime = (Date.now() - startTime) / 1e3;
517
+ return {
518
+ result,
519
+ logs,
520
+ error,
521
+ execution_time: executionTime
522
+ };
523
+ }
524
+ /**
525
+ * Build the VM execution context with MCP tools and standard globals.
526
+ *
527
+ * @param logs - Array to capture console output
528
+ */
529
+ async _buildContext(logs) {
530
+ const logHandler = /* @__PURE__ */ __name((...args) => {
531
+ logs.push(
532
+ args.map(
533
+ (arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
534
+ ).join(" ")
535
+ );
536
+ }, "logHandler");
537
+ const sandbox = {
538
+ console: {
539
+ log: logHandler,
540
+ error: /* @__PURE__ */ __name((...args) => {
541
+ logHandler("[ERROR]", ...args);
542
+ }, "error"),
543
+ warn: /* @__PURE__ */ __name((...args) => {
544
+ logHandler("[WARN]", ...args);
545
+ }, "warn"),
546
+ info: logHandler,
547
+ debug: logHandler
548
+ },
549
+ // Standard globals
550
+ Object,
551
+ Array,
552
+ String,
553
+ Number,
554
+ Boolean,
555
+ Date,
556
+ Math,
557
+ JSON,
558
+ RegExp,
559
+ Map,
560
+ Set,
561
+ Promise,
562
+ parseInt,
563
+ parseFloat,
564
+ isNaN,
565
+ isFinite,
566
+ encodeURI,
567
+ decodeURI,
568
+ encodeURIComponent,
569
+ decodeURIComponent,
570
+ setTimeout,
571
+ clearTimeout,
572
+ // Helper for tools
573
+ search_tools: this.createSearchToolsFunction(),
574
+ __tool_namespaces: []
575
+ };
576
+ const toolNamespaces = {};
577
+ const namespaceInfos = this.getToolNamespaces();
578
+ for (const { serverName, tools, session } of namespaceInfos) {
579
+ const serverNamespace = {};
580
+ for (const tool of tools) {
581
+ const toolName = tool.name;
582
+ serverNamespace[toolName] = async (args) => {
583
+ const result = await session.connector.callTool(toolName, args || {});
584
+ if (result.content && result.content.length > 0) {
585
+ const item = result.content[0];
586
+ if (item.type === "text") {
587
+ try {
588
+ return JSON.parse(item.text);
589
+ } catch {
590
+ return item.text;
591
+ }
592
+ }
593
+ return item;
594
+ }
595
+ return result;
596
+ };
597
+ }
598
+ sandbox[serverName] = serverNamespace;
599
+ toolNamespaces[serverName] = true;
600
+ }
601
+ sandbox.__tool_namespaces = Object.keys(toolNamespaces);
602
+ return vm.createContext(sandbox);
603
+ }
604
+ /**
605
+ * Clean up resources.
606
+ * VM executor doesn't need cleanup, but method kept for interface consistency.
607
+ */
608
+ async cleanup() {
609
+ }
610
+ };
611
+
53
612
  // src/config.ts
54
613
  import { readFileSync } from "fs";
55
614
 
@@ -222,7 +781,12 @@ var MCPClient = class _MCPClient extends BaseMCPClient {
222
781
  static {
223
782
  __name(this, "MCPClient");
224
783
  }
225
- constructor(config) {
784
+ codeMode = false;
785
+ _codeExecutor = null;
786
+ _customCodeExecutor = null;
787
+ _codeExecutorConfig = "vm";
788
+ _executorOptions;
789
+ constructor(config, options) {
226
790
  if (config) {
227
791
  if (typeof config === "string") {
228
792
  super(loadConfigFile(config));
@@ -232,12 +796,30 @@ var MCPClient = class _MCPClient extends BaseMCPClient {
232
796
  } else {
233
797
  super();
234
798
  }
799
+ let codeModeEnabled = false;
800
+ let executorConfig = "vm";
801
+ let executorOptions;
802
+ if (options?.codeMode) {
803
+ if (typeof options.codeMode === "boolean") {
804
+ codeModeEnabled = options.codeMode;
805
+ } else {
806
+ codeModeEnabled = options.codeMode.enabled;
807
+ executorConfig = options.codeMode.executor ?? "vm";
808
+ executorOptions = options.codeMode.executorOptions;
809
+ }
810
+ }
811
+ this.codeMode = codeModeEnabled;
812
+ this._codeExecutorConfig = executorConfig;
813
+ this._executorOptions = executorOptions;
814
+ if (this.codeMode) {
815
+ this._setupCodeModeConnector();
816
+ }
235
817
  }
236
- static fromDict(cfg) {
237
- return new _MCPClient(cfg);
818
+ static fromDict(cfg, options) {
819
+ return new _MCPClient(cfg, options);
238
820
  }
239
- static fromConfigFile(path2) {
240
- return new _MCPClient(loadConfigFile(path2));
821
+ static fromConfigFile(path2, options) {
822
+ return new _MCPClient(loadConfigFile(path2), options);
241
823
  }
242
824
  /**
243
825
  * Save configuration to a file (Node.js only)
@@ -256,6 +838,87 @@ var MCPClient = class _MCPClient extends BaseMCPClient {
256
838
  createConnectorFromConfig(serverConfig) {
257
839
  return createConnectorFromConfig(serverConfig);
258
840
  }
841
+ _setupCodeModeConnector() {
842
+ logger.debug("Code mode connector initialized as internal meta server");
843
+ const connector = new CodeModeConnector(this);
844
+ const session = new MCPSession(connector);
845
+ this.sessions["code_mode"] = session;
846
+ this.activeSessions.push("code_mode");
847
+ }
848
+ _ensureCodeExecutor() {
849
+ if (!this._codeExecutor) {
850
+ const config = this._codeExecutorConfig;
851
+ if (config instanceof BaseCodeExecutor) {
852
+ this._codeExecutor = config;
853
+ } else if (typeof config === "function") {
854
+ this._customCodeExecutor = config;
855
+ throw new Error(
856
+ "Custom executor function should be handled in executeCode"
857
+ );
858
+ } else if (config === "e2b") {
859
+ const opts = this._executorOptions;
860
+ if (!opts?.apiKey) {
861
+ logger.warn("E2B executor requires apiKey. Falling back to VM.");
862
+ this._codeExecutor = new VMCodeExecutor(
863
+ this,
864
+ this._executorOptions
865
+ );
866
+ } else {
867
+ this._codeExecutor = new E2BCodeExecutor(this, opts);
868
+ }
869
+ } else {
870
+ this._codeExecutor = new VMCodeExecutor(
871
+ this,
872
+ this._executorOptions
873
+ );
874
+ }
875
+ }
876
+ return this._codeExecutor;
877
+ }
878
+ /**
879
+ * Execute code in code mode
880
+ */
881
+ async executeCode(code, timeout) {
882
+ if (!this.codeMode) {
883
+ throw new Error("Code execution mode is not enabled");
884
+ }
885
+ if (this._customCodeExecutor) {
886
+ return this._customCodeExecutor(code, timeout);
887
+ }
888
+ return this._ensureCodeExecutor().execute(code, timeout);
889
+ }
890
+ /**
891
+ * Search available tools (used by code mode)
892
+ */
893
+ async searchTools(query = "", detailLevel = "full") {
894
+ if (!this.codeMode) {
895
+ throw new Error("Code execution mode is not enabled");
896
+ }
897
+ return this._ensureCodeExecutor().createSearchToolsFunction()(
898
+ query,
899
+ detailLevel
900
+ );
901
+ }
902
+ /**
903
+ * Override getServerNames to exclude internal code_mode server
904
+ */
905
+ getServerNames() {
906
+ const isCodeModeEnabled = this.codeMode;
907
+ return super.getServerNames().filter((name) => {
908
+ return !isCodeModeEnabled || name !== "code_mode";
909
+ });
910
+ }
911
+ /**
912
+ * Close the client and clean up resources including code executors.
913
+ * This ensures E2B sandboxes and other resources are properly released.
914
+ */
915
+ async close() {
916
+ if (this._codeExecutor) {
917
+ await this._codeExecutor.cleanup();
918
+ this._codeExecutor = null;
919
+ }
920
+ await this.closeAllSessions();
921
+ }
259
922
  };
260
923
 
261
924
  // src/oauth-helper.ts
@@ -679,6 +1342,7 @@ export {
679
1342
  MCPSession,
680
1343
  OAuthHelper,
681
1344
  ObservabilityManager,
1345
+ PROMPTS,
682
1346
  ReleaseMCPServerConnectionTool,
683
1347
  RemoteAgent,
684
1348
  ServerManager,