@mcp-use/inspector 0.14.0-canary.8 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/client/assets/{browser-C2Fn0YFm.js → browser-EyInsrZa.js} +48 -48
  2. package/dist/client/assets/client-JeU2zpxn.js +92 -0
  3. package/dist/client/assets/{display-A5IEINAP-CARbqwYz.js → display-A5IEINAP-Btv2gL3n.js} +2 -2
  4. package/dist/client/assets/{embeddings-CS1tQ9WC.js → embeddings-Dya_KnH0.js} +1 -1
  5. package/dist/client/assets/{index-BHWuEnDp.js → index--IpKhg5F.js} +1 -1
  6. package/dist/client/assets/{index-w9z_NOXw.js → index-01y2e9ko.js} +1 -1
  7. package/dist/client/assets/{index-CZ1ZJ4DA.js → index-3gQQW6s7.js} +1 -1
  8. package/dist/client/assets/{index-CEc6a116.js → index-BZCfajuh.js} +1 -1
  9. package/dist/client/assets/{index-B66nJ4Ui.js → index-BiUxRAkS.js} +1 -1
  10. package/dist/client/assets/{index-CWxR53gB.js → index-CwGEcSpK.js} +1 -1
  11. package/dist/client/assets/{index-03ai9_N2.js → index-D7646HFQ.js} +1 -1
  12. package/dist/client/assets/index-DoHGzyNN.js +1753 -0
  13. package/dist/client/assets/index-G80eS8Oh.css +1 -0
  14. package/dist/client/assets/{index-BGExFjwX.js → index-dRu1bjMq.js} +1 -1
  15. package/dist/client/assets/{llms-BT3kT7gN.js → llms-CQ_t8ic9.js} +1 -1
  16. package/dist/client/index.html +3 -3
  17. package/dist/client/index.js +1096 -0
  18. package/dist/server/{chunk-NOEIHEAG.js → chunk-4OEEUHLZ.js} +1 -1
  19. package/dist/server/{chunk-F7YWZTWJ.js → chunk-E4Y73JSU.js} +1 -1
  20. package/dist/server/{chunk-JCLAFMDT.js → chunk-PUX4EJWH.js} +11 -0
  21. package/dist/server/cli.js +2 -2
  22. package/dist/server/index.js +3 -3
  23. package/dist/server/middleware.js +3 -3
  24. package/dist/server/server.d.ts +11 -0
  25. package/dist/server/server.d.ts.map +1 -1
  26. package/dist/server/server.js +6 -24
  27. package/dist/server/shared-routes.js +2 -2
  28. package/dist/server/shared-static.d.ts +5 -1
  29. package/dist/server/shared-static.d.ts.map +1 -1
  30. package/dist/server/shared-utils-browser.d.ts +9 -1
  31. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  32. package/dist/server/transport-wrapper.d.ts +1 -1
  33. package/dist/server/transport-wrapper.d.ts.map +1 -1
  34. package/dist/server/utils.d.ts +14 -0
  35. package/dist/server/utils.d.ts.map +1 -1
  36. package/dist/server/utils.js +5 -3
  37. package/package.json +9 -4
  38. package/dist/client/assets/client-Bt6xNGvA.js +0 -92
  39. package/dist/client/assets/index-BYhrMpLe.js +0 -1753
  40. package/dist/client/assets/index-D_5vBeGJ.css +0 -1
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  registerInspectorRoutes
3
- } from "./chunk-F7YWZTWJ.js";
3
+ } from "./chunk-E4Y73JSU.js";
4
4
  import {
5
5
  registerStaticRoutes
6
6
  } from "./chunk-BC23UV5D.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  formatErrorResponse
3
- } from "./chunk-JCLAFMDT.js";
3
+ } from "./chunk-PUX4EJWH.js";
4
4
  import {
5
5
  rpcLogBus
6
6
  } from "./chunk-CVECQ7BJ.js";
@@ -37,6 +37,16 @@ async function isPortAvailable(port) {
37
37
  server.on("error", () => resolve(false));
38
38
  });
39
39
  }
40
+ function parsePortFromArgs() {
41
+ const portArgIndex = process.argv.indexOf("--port");
42
+ if (portArgIndex !== -1 && portArgIndex + 1 < process.argv.length) {
43
+ const portValue = Number.parseInt(process.argv[portArgIndex + 1], 10);
44
+ if (!Number.isNaN(portValue) && portValue >= 1 && portValue <= 65535) {
45
+ return portValue;
46
+ }
47
+ }
48
+ return null;
49
+ }
40
50
  function formatErrorResponse(error, context) {
41
51
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
42
52
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
@@ -58,5 +68,6 @@ export {
58
68
  isValidUrl,
59
69
  findAvailablePort,
60
70
  isPortAvailable,
71
+ parsePortFromArgs,
61
72
  formatErrorResponse
62
73
  };
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  registerInspectorRoutes
4
- } from "./chunk-F7YWZTWJ.js";
4
+ } from "./chunk-E4Y73JSU.js";
5
5
  import {
6
6
  findAvailablePort,
7
7
  isValidUrl
8
- } from "./chunk-JCLAFMDT.js";
8
+ } from "./chunk-PUX4EJWH.js";
9
9
  import "./chunk-CVECQ7BJ.js";
10
10
  import {
11
11
  registerStaticRoutes
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  mountInspector
3
- } from "./chunk-NOEIHEAG.js";
4
- import "./chunk-F7YWZTWJ.js";
5
- import "./chunk-JCLAFMDT.js";
3
+ } from "./chunk-4OEEUHLZ.js";
4
+ import "./chunk-E4Y73JSU.js";
5
+ import "./chunk-PUX4EJWH.js";
6
6
  import "./chunk-CVECQ7BJ.js";
7
7
  import "./chunk-BC23UV5D.js";
8
8
  import "./chunk-67ROKQZG.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  mountInspector
3
- } from "./chunk-NOEIHEAG.js";
4
- import "./chunk-F7YWZTWJ.js";
5
- import "./chunk-JCLAFMDT.js";
3
+ } from "./chunk-4OEEUHLZ.js";
4
+ import "./chunk-E4Y73JSU.js";
5
+ import "./chunk-PUX4EJWH.js";
6
6
  import "./chunk-CVECQ7BJ.js";
7
7
  import "./chunk-BC23UV5D.js";
8
8
  import "./chunk-67ROKQZG.js";
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Start the MCP Inspector HTTP server and return its listening port and fetch handler.
3
+ *
4
+ * Starts the Hono app on an available port (prefers a CLI-specified port, otherwise 3001;
5
+ * in standalone/production mode it will fall back to 3002 if 3001 is unavailable),
6
+ * logs server status, and attempts to open the browser when not running in production.
7
+ * On unrecoverable startup failures (for example, requested ports unavailable), the process
8
+ * will exit with code 1.
9
+ *
10
+ * @returns An object containing the resolved `port` number and the application's `fetch` handler.
11
+ */
1
12
  declare function startServer(): Promise<{
2
13
  port: number;
3
14
  fetch: (request: Request, Env?: unknown, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAyCA,iBAAe,WAAW;;;GAwFzB;;;;AAOD,wBAA+B"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;GAUG;AACH,iBAAe,WAAW;;;GAkFzB;;;;AAOD,wBAA+B"}
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  registerInspectorRoutes
3
- } from "./chunk-F7YWZTWJ.js";
3
+ } from "./chunk-E4Y73JSU.js";
4
4
  import {
5
- isPortAvailable
6
- } from "./chunk-JCLAFMDT.js";
5
+ isPortAvailable,
6
+ parsePortFromArgs
7
+ } from "./chunk-PUX4EJWH.js";
7
8
  import "./chunk-CVECQ7BJ.js";
8
9
  import {
9
10
  registerStaticRoutesWithDevProxy
@@ -16,25 +17,7 @@ import "./chunk-PKBMQBKP.js";
16
17
  import { serve } from "@hono/node-server";
17
18
  import { Hono } from "hono";
18
19
  import { cors } from "hono/cors";
19
- import { exec } from "child_process";
20
- import { promisify } from "util";
21
- var execAsync = promisify(exec);
22
- function parsePortFromArgs() {
23
- const args = process.argv.slice(2);
24
- for (let i = 0; i < args.length; i++) {
25
- if (args[i] === "--port" && i + 1 < args.length) {
26
- const parsedPort = Number.parseInt(args[i + 1], 10);
27
- if (Number.isNaN(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
28
- console.error(
29
- `Error: Port must be a number between 1 and 65535, got: ${args[i + 1]}`
30
- );
31
- process.exit(1);
32
- }
33
- return parsedPort;
34
- }
35
- }
36
- return null;
37
- }
20
+ import open from "open";
38
21
  var app = new Hono();
39
22
  app.use("*", cors());
40
23
  registerInspectorRoutes(app);
@@ -88,9 +71,8 @@ async function startServer() {
88
71
  }
89
72
  if (process.env.NODE_ENV !== "production") {
90
73
  try {
91
- const command = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
92
74
  const url = isDev ? "http://localhost:3000" : `http://localhost:${port}`;
93
- await execAsync(`${command} ${url}`);
75
+ await open(url);
94
76
  console.warn(`\u{1F310} Browser opened automatically`);
95
77
  } catch {
96
78
  const url = isDev ? "http://localhost:3000" : `http://localhost:${port}`;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  registerInspectorRoutes
3
- } from "./chunk-F7YWZTWJ.js";
4
- import "./chunk-JCLAFMDT.js";
3
+ } from "./chunk-E4Y73JSU.js";
4
+ import "./chunk-PUX4EJWH.js";
5
5
  import "./chunk-CVECQ7BJ.js";
6
6
  import "./chunk-Z5QIR3IS.js";
7
7
  import "./chunk-PKBMQBKP.js";
@@ -1,6 +1,10 @@
1
1
  import type { Hono } from "hono";
2
2
  /**
3
- * Register static file serving routes for the inspector client
3
+ * Register routes that serve the built inspector client, handle SPA entry routing, and provide a fallback when client files are missing.
4
+ *
5
+ * This registers asset serving under the inspector path, redirects the root path to `/inspector` while preserving query parameters, serves the SPA entry (`index.html`) for inspector routes, and installs a final catch-all that serves the SPA or a build-missing fallback page. If `clientDistPath` is not provided, the built client path is resolved automatically.
6
+ *
7
+ * @param clientDistPath - Optional path to the built inspector client directory; when omitted, the implementation resolves the default distribution path
4
8
  */
5
9
  export declare function registerStaticRoutes(app: Hono, clientDistPath?: string): void;
6
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"shared-static.d.ts","sourceRoot":"","sources":["../../src/server/shared-static.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AASjC;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,QAwGtE;AAED;;GAEG;AACH,wBAAgB,gCAAgC,CAC9C,GAAG,EAAE,IAAI,EACT,cAAc,CAAC,EAAE,MAAM,QA+DxB"}
1
+ {"version":3,"file":"shared-static.d.ts","sourceRoot":"","sources":["../../src/server/shared-static.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AASjC;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,QAwGtE;AAED;;GAEG;AACH,wBAAgB,gCAAgC,CAC9C,GAAG,EAAE,IAAI,EACT,cAAc,CAAC,EAAE,MAAM,QA+DxB"}
@@ -43,7 +43,15 @@ export declare function handleChatRequestStream(requestBody: {
43
43
  messages: ChatMessage[];
44
44
  }): AsyncGenerator<string, void, void>;
45
45
  /**
46
- * Handle chat API request with MCP agent (non-streaming, kept for backwards compatibility)
46
+ * Execute a non-streaming chat turn using an MCP agent and the specified LLM configuration.
47
+ *
48
+ * @param requestBody - Request parameters
49
+ * @param requestBody.mcpServerUrl - Base URL of the MCP server to connect to
50
+ * @param requestBody.llmConfig - LLM provider configuration (provider, model, apiKey, etc.)
51
+ * @param requestBody.authConfig - Optional authentication configuration for the MCP server
52
+ * @param requestBody.messages - Array of chat messages; only the last message with role "user" is used as the query
53
+ * @returns An object containing `content` with the agent's response text and `toolCalls` with recorded tool invocations (empty for this non-streaming implementation)
54
+ * @throws If required fields are missing, if the LLM provider is unsupported, or if no user message is found
47
55
  */
48
56
  export declare function handleChatRequest(requestBody: {
49
57
  mcpServerUrl: string;
@@ -1 +1 @@
1
- {"version":3,"file":"shared-utils-browser.d.ts","sourceRoot":"","sources":["../../src/server/shared-utils-browser.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,UAAU,SAAS;IACjB,QAAQ,EAAE,QAAQ,GAAG,WAAW,GAAG,QAAQ,CAAC;IAC5C,KAAK,EAAE,MAAM,CAAC;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G;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,GAAG;IACpE,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CA6DA;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAEpE;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,MAAM,CAiCR;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,UAAU,GAAG;IACjE,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CA4WA;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,SAAS,CAAC,EAAE;IACV,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B,EACD,gBAAgB,CAAC,EAAE,MAAM,GACxB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CA+FxB"}
@@ -1,4 +1,4 @@
1
- import type { Transport } from "@mcp-use/modelcontextprotocol-sdk/shared/transport.js";
1
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
2
2
  /**
3
3
  * Wrap a transport to log all RPC messages to the RPC log bus
4
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"transport-wrapper.d.ts","sourceRoot":"","sources":["../../src/server/transport-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uDAAuD,CAAC;AAQvF;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,MAAM,GACf,SAAS,CA0EX"}
1
+ {"version":3,"file":"transport-wrapper.d.ts","sourceRoot":"","sources":["../../src/server/transport-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAQ/E;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,MAAM,GACf,SAAS,CA0EX"}
@@ -1,6 +1,20 @@
1
1
  export declare function isValidUrl(urlString: string): boolean;
2
2
  export declare function findAvailablePort(startPort?: number, maxAttempts?: number): Promise<number>;
3
+ /**
4
+ * Determines whether the given TCP port is available for binding on the local machine.
5
+ *
6
+ * @param port - The port number to check (1–65535)
7
+ * @returns `true` if the port can be bound (is available), `false` otherwise
8
+ */
3
9
  export declare function isPortAvailable(port: number): Promise<boolean>;
10
+ /**
11
+ * Parses a TCP port number from command-line arguments using the `--port` flag.
12
+ *
13
+ * If `--port` is present and followed by an integer between 1 and 65535, returns that port.
14
+ *
15
+ * @returns The parsed port number if valid, `null` if the flag is missing or the value is invalid.
16
+ */
17
+ export declare function parsePortFromArgs(): number | null;
4
18
  /**
5
19
  * Helper function to format error responses with context and timestamp
6
20
  */
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/server/utils.ts"],"names":[],"mappings":"AACA,wBAAgB,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAYrD;AAGD,wBAAsB,iBAAiB,CACrC,SAAS,SAAO,EAChB,WAAW,SAAM,GAChB,OAAO,CAAC,MAAM,CAAC,CAqBjB;AAGD,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAUpE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM;;;;;EAoBlE"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/server/utils.ts"],"names":[],"mappings":"AACA,wBAAgB,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAYrD;AAGD,wBAAsB,iBAAiB,CACrC,SAAS,SAAO,EAChB,WAAW,SAAM,GAChB,OAAO,CAAC,MAAM,CAAC,CAqBjB;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAUpE;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,GAAG,IAAI,CASjD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM;;;;;EAoBlE"}
@@ -2,12 +2,14 @@ import {
2
2
  findAvailablePort,
3
3
  formatErrorResponse,
4
4
  isPortAvailable,
5
- isValidUrl
6
- } from "./chunk-JCLAFMDT.js";
5
+ isValidUrl,
6
+ parsePortFromArgs
7
+ } from "./chunk-PUX4EJWH.js";
7
8
  import "./chunk-PKBMQBKP.js";
8
9
  export {
9
10
  findAvailablePort,
10
11
  formatErrorResponse,
11
12
  isPortAvailable,
12
- isValidUrl
13
+ isValidUrl,
14
+ parsePortFromArgs
13
15
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/inspector",
3
3
  "type": "module",
4
- "version": "0.14.0-canary.8",
4
+ "version": "0.14.0",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -24,6 +24,10 @@
24
24
  ".": {
25
25
  "types": "./dist/server/index.d.ts",
26
26
  "import": "./dist/server/index.js"
27
+ },
28
+ "./client": {
29
+ "types": "./dist/client/index.d.ts",
30
+ "import": "./dist/client/index.js"
27
31
  }
28
32
  },
29
33
  "main": "./dist/server/index.js",
@@ -56,7 +60,7 @@
56
60
  "@langchain/google-genai": "^2.1.0",
57
61
  "@langchain/openai": "^1.2.0",
58
62
  "@mcp-ui/client": "^5.17.1",
59
- "@mcp-use/modelcontextprotocol-sdk": "1.24.3-mcp-use.4",
63
+ "@modelcontextprotocol/sdk": "^1.25.1",
60
64
  "@radix-ui/react-alert-dialog": "^1.1.15",
61
65
  "@radix-ui/react-checkbox": "^1.3.3",
62
66
  "@radix-ui/react-dialog": "^1.1.15",
@@ -86,7 +90,7 @@
86
90
  "sonner": "^2.0.7",
87
91
  "tailwind-merge": "^3.4.0",
88
92
  "vite-express": "^0.21.1",
89
- "mcp-use": "1.12.0-canary.8"
93
+ "mcp-use": "1.12.0"
90
94
  },
91
95
  "publishConfig": {
92
96
  "access": "public"
@@ -119,8 +123,9 @@
119
123
  "dev:client": "rm -rf node_modules/.vite && vite --port 3000",
120
124
  "dev:server": "VITE_DEV=true tsx watch src/server/server.ts",
121
125
  "dev:standalone": "tsx watch src/server/server.ts",
122
- "build": "npm run build:client && npm run build:server && npm run build:cli",
126
+ "build": "npm run build:client && npm run build:client-exports && npm run build:server && npm run build:cli",
123
127
  "build:client": "vite build",
128
+ "build:client-exports": "tsup src/client/index.ts --format esm --out-dir dist/client --tsconfig tsconfig.client.json --external react --external react-dom --external lucide-react --no-splitting && tsc -p tsconfig.client.json --emitDeclarationOnly --declaration",
124
129
  "build:server": "tsup src/server/*.ts --format esm --out-dir dist/server && tsc -p tsconfig.server.json --emitDeclarationOnly --declaration",
125
130
  "build:cli": "tsup src/server/cli.ts --format esm --out-dir dist/",
126
131
  "start": "node dist/server/server.js",
@@ -1,92 +0,0 @@
1
- import{B as me,_ as g,g as Y,c as Ue,J as He,d as Ke,e as We,T as ze,l as m,M as Ge,H as Ye,a as Xe,C as Ze,f as re,h as Qe}from"./index-BYhrMpLe.js";var O,et=(O=class extends me{mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:"code_mode",version:"1.0.0"}}_createToolsList(){return[{name:"execute_code",description:"Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"},timeout:{type:"number",description:"Execution timeout in milliseconds",default:3e4}},required:["code"]}},{name:"search_tools",description:"Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query to filter tools by name or description",default:""},detail_level:{type:"string",description:"Detail level: 'names', 'descriptions', or 'full'",enum:["names","descriptions","full"],default:"full"}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:"1.0.0"}}async callTool(e,t){if(e==="execute_code"){const n=t.code,r=t.timeout||3e4,o=await this.mcpClient.executeCode(n,r);return{content:[{type:"text",text:JSON.stringify(o)}]}}else if(e==="search_tools"){const n=t.query||"",r=t.detail_level,o=await this.mcpClient.searchTools(n,r&&r in["names","descriptions","full"]?r:"full");return{content:[{type:"text",text:JSON.stringify(o)}]}}throw new Error(`Unknown tool: ${e}`)}},g(O,"CodeModeConnector"),O);function X(){throw new Error("fs.readFileSync is not available in browser environment")}function _e(){throw new Error("fs.writeFileSync is not available in browser environment")}function ve(){return!1}function we(){throw new Error("fs.readFile is not available in browser environment")}function ge(){throw new Error("fs.writeFile is not available in browser environment")}function ye(){throw new Error("fs.mkdir is not available in browser environment")}function be(){throw new Error("fs.readdir is not available in browser environment")}function xe(){throw new Error("fs.stat is not available in browser environment")}function Ee(){throw new Error("fs.unlink is not available in browser environment")}function Ce(){throw new Error("fs.rmdir is not available in browser environment")}const j={readFileSync:X,writeFileSync:_e,existsSync:ve,readFile:we,writeFile:ge,mkdir:ye,readdir:be,stat:xe,unlink:Ee,rmdir:Ce},tt=Object.freeze(Object.defineProperty({__proto__:null,default:j,existsSync:ve,mkdir:ye,readFile:we,readFileSync:X,readdir:be,rmdir:Ce,stat:xe,unlink:Ee,writeFile:ge,writeFileSync:_e},Symbol.toStringTag,{value:"Module"}));function Z(...i){return i.filter(Boolean).join("/").replace(/\/+/g,"/").replace(/\/$/,"")}function Se(...i){return Z(...i)}function Q(i){const e=i.split("/");return e.pop(),e.join("/")||"/"}function q(i,e){const t=i.split("/");let n=t[t.length-1]||"";return e&&n.endsWith(e)&&(n=n.slice(0,-e.length)),n}function ee(i){const e=q(i),t=e.lastIndexOf(".");return t>0?e.slice(t):""}function Me(i){return i.replace(/\/+/g,"/")}function Te(i){return i.startsWith("/")}function Pe(i){const e=i.startsWith("/")?"/":"",t=Q(i),n=q(i),r=ee(i),o=r?n.slice(0,-r.length):n;return{root:e,dir:t,base:n,ext:r,name:o}}const Oe="/",Ne=":",ke={join:Z,resolve:Se,dirname:Q,basename:q,extname:ee,normalize:Me,isAbsolute:Te,parse:Pe,sep:Oe,delimiter:Ne},nt=Object.freeze(Object.defineProperty({__proto__:null,basename:q,default:ke,delimiter:Ne,dirname:Q,extname:ee,isAbsolute:Te,join:Z,normalize:Me,parse:Pe,resolve:Se,sep:Oe},Symbol.toStringTag,{value:"Module"})),rt={},ot="browser",st="v18.0.0",it={node:"18.0.0"},at=()=>"/",ct=(i,...e)=>queueMicrotask(()=>i(...e)),lt=!0,I={env:rt,platform:ot,version:st,versions:it,cwd:at,nextTick:ct,browser:lt};var T={exports:{}};function $e(){throw new Error("child_process.spawn is not available in browser environment")}function Ae(){throw new Error("child_process.exec is not available in browser environment")}function Re(){throw new Error("child_process.execFile is not available in browser environment")}function Le(){throw new Error("child_process.fork is not available in browser environment")}function je(){throw new Error("child_process.execSync is not available in browser environment")}function Ie(){throw new Error("child_process.spawnSync is not available in browser environment")}function qe(){throw new Error("child_process.execFileSync is not available in browser environment")}const ut={spawn:$e,exec:Ae,execFile:Re,fork:Le,execSync:je,spawnSync:Ie,execFileSync:qe},dt=Object.freeze(Object.defineProperty({__proto__:null,default:ut,exec:Ae,execFile:Re,execFileSync:qe,execSync:je,fork:Le,spawn:$e,spawnSync:Ie},Symbol.toStringTag,{value:"Module"})),ht=Y(dt),Fe=Y(nt),Be=Y(tt);var J,oe;function ft(){if(oe)return J;oe=1;var i={};J=r,r.sync=o;var e=Be;function t(s,c){var l=c.pathExt!==void 0?c.pathExt:i.PATHEXT;if(!l||(l=l.split(";"),l.indexOf("")!==-1))return!0;for(var a=0;a<l.length;a++){var u=l[a].toLowerCase();if(u&&s.substr(-u.length).toLowerCase()===u)return!0}return!1}function n(s,c,l){return!s.isSymbolicLink()&&!s.isFile()?!1:t(c,l)}function r(s,c,l){e.stat(s,function(a,u){l(a,a?!1:n(u,s,c))})}function o(s,c){return n(e.statSync(s),s,c)}return J}var V,se;function pt(){if(se)return V;se=1,V=e,e.sync=t;var i=Be;function e(o,s,c){i.stat(o,function(l,a){c(l,l?!1:n(a,s))})}function t(o,s){return n(i.statSync(o),s)}function n(o,s){return o.isFile()&&r(o,s)}function r(o,s){var c=o.mode,l=o.uid,a=o.gid,u=s.uid!==void 0?s.uid:process.getuid&&process.getuid(),d=s.gid!==void 0?s.gid:process.getgid&&process.getgid(),h=parseInt("100",8),f=parseInt("010",8),p=parseInt("001",8),y=h|f,_=c&p||c&f&&a===d||c&h&&l===u||c&y&&u===0;return _}return V}var D,ie;function mt(){if(ie)return D;ie=1;var i;globalThis.TESTING_WINDOWS?i=ft():i=pt(),D=e,e.sync=t;function e(n,r,o){if(typeof r=="function"&&(o=r,r={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(s,c){e(n,r||{},function(l,a){l?c(l):s(a)})})}i(n,r||{},function(s,c){s&&(s.code==="EACCES"||r&&r.ignoreErrors)&&(s=null,c=!1),o(s,c)})}function t(n,r){try{return i.sync(n,r||{})}catch(o){if(r&&r.ignoreErrors||o.code==="EACCES")return!1;throw o}}return D}var U,ae;function _t(){if(ae)return U;ae=1;var i={};const e=i.OSTYPE==="cygwin"||i.OSTYPE==="msys",t=Fe,n=e?";":":",r=mt(),o=a=>Object.assign(new Error(`not found: ${a}`),{code:"ENOENT"}),s=(a,u)=>{const d=u.colon||n,h=a.match(/\//)||e&&a.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||i.PATH||"").split(d)],f=e?u.pathExt||i.PATHEXT||".EXE;.CMD;.BAT;.COM":"",p=e?f.split(d):[""];return e&&a.indexOf(".")!==-1&&p[0]!==""&&p.unshift(""),{pathEnv:h,pathExt:p,pathExtExe:f}},c=(a,u,d)=>{typeof u=="function"&&(d=u,u={}),u||(u={});const{pathEnv:h,pathExt:f,pathExtExe:p}=s(a,u),y=[],_=v=>new Promise((b,w)=>{if(v===h.length)return u.all&&y.length?b(y):w(o(a));const x=h[v],C=/^".*"$/.test(x)?x.slice(1,-1):x,P=t.join(C,a),B=!C&&/^\.[\\\/]/.test(a)?a.slice(0,2)+P:P;b(E(B,v,0))}),E=(v,b,w)=>new Promise((x,C)=>{if(w===f.length)return x(_(b+1));const P=f[w];r(v+P,{pathExt:p},(B,De)=>{if(!B&&De)if(u.all)y.push(v+P);else return x(v+P);return x(E(v,b,w+1))})});return d?_(0).then(v=>d(null,v),d):_(0)},l=(a,u)=>{u=u||{};const{pathEnv:d,pathExt:h,pathExtExe:f}=s(a,u),p=[];for(let y=0;y<d.length;y++){const _=d[y],E=/^".*"$/.test(_)?_.slice(1,-1):_,v=t.join(E,a),b=!E&&/^\.[\\\/]/.test(a)?a.slice(0,2)+v:v;for(let w=0;w<h.length;w++){const x=b+h[w];try{if(r.sync(x,{pathExt:f}))if(u.all)p.push(x);else return x}catch{}}}if(u.all&&p.length)return p;if(u.nothrow)return null;throw o(a)};return U=c,c.sync=l,U}var L={exports:{}},ce;function vt(){if(ce)return L.exports;ce=1;var i={};const e=(t={})=>{const n=t.env||i;return(t.platform||"browser")!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};return L.exports=e,L.exports.default=e,L.exports}var H,le;function wt(){if(le)return H;le=1;var i={};const e=Fe,t=_t(),n=vt();function r(s,c){const l=s.options.env||i,a=process.cwd(),u=s.options.cwd!=null,d=u&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let h;try{h=t.sync(s.command,{path:l[n({env:l})],pathExt:c?e.delimiter:void 0})}catch{}finally{d&&process.chdir(a)}return h&&(h=e.resolve(u?s.options.cwd:"",h)),h}function o(s){return r(s)||r(s,!0)}return H=o,H}var K,ue;function gt(){if(ue)return K;ue=1,wt();function i(t){return t}function e(t,n,r){n&&!Array.isArray(n)&&(r=n,n=null),n=n?n.slice(0):[],r=Object.assign({},r);const o={command:t,args:n,options:r,file:void 0,original:{command:t,args:n}};return r.shell?o:o}return K=e,K}var W,de;function yt(){if(de)return W;de=1;function i(r,o){return Object.assign(new Error(`${o} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${r.command}`,path:r.command,spawnargs:r.args})}function e(r,o){}function t(r,o){return null}function n(r,o){return null}return W={hookChildProcess:e,verifyENOENT:t,verifyENOENTSync:n,notFoundError:i},W}var he;function bt(){if(he)return T.exports;he=1;const i=ht,e=gt(),t=yt();function n(o,s,c){const l=e(o,s,c),a=i.spawn(l.command,l.args,l.options);return t.hookChildProcess(a,l),a}function r(o,s,c){const l=e(o,s,c),a=i.spawnSync(l.command,l.args,l.options);return a.error=a.error||t.verifyENOENTSync(a.status,l),a}return T.exports=n,T.exports.spawn=n,T.exports.sync=r,T.exports._parse=e,T.exports._enoent=t,T.exports}var xt=bt();const Et=Ue(xt);class Ct{constructor(){console.warn("PassThrough stream is not available in browser environment")}}class St{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
2
- `);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Mt(t)}clear(){this._buffer=void 0}}function Mt(i){return He.parse(JSON.parse(i))}function Tt(i){return JSON.stringify(i)+`
3
- `}const Pt=["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Ot(){const i={};for(const e of Pt){const t=I.env[e];t!==void 0&&(t.startsWith("()")||(i[e]=t))}return i}class Nt{constructor(e){this._readBuffer=new St,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Ct)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var n,r,o,s,c;this._process=Et(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Ot(),...this._serverParams.env},stdio:["pipe","pipe",(r=this._serverParams.stderr)!==null&&r!==void 0?r:"inherit"],shell:!1,windowsHide:I.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",l=>{var a;t(l),(a=this.onerror)===null||a===void 0||a.call(this,l)}),this._process.on("spawn",()=>{e()}),this._process.on("close",l=>{var a;this._process=void 0,(a=this.onclose)===null||a===void 0||a.call(this)}),(o=this._process.stdin)===null||o===void 0||o.on("error",l=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,l)}),(s=this._process.stdout)===null||s===void 0||s.on("data",l=>{this._readBuffer.append(l),this.processReadBuffer()}),(c=this._process.stdout)===null||c===void 0||c.on("error",l=>{var a;(a=this.onerror)===null||a===void 0||a.call(this,l)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{const n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){var e;if(this._process){const t=this._process;this._process=void 0;const n=new Promise(r=>{t.once("close",()=>{r()})});try{(e=t.stdin)===null||e===void 0||e.end()}catch{}if(await Promise.race([n,new Promise(r=>setTimeout(r,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([n,new Promise(r=>setTimeout(r,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");const r=Tt(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}var kt={},N,te=(N=class{client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){const e=this.client.getServerNames(),t=Object.keys(this.client.getAllActiveSessions()),n=e.filter(r=>!t.includes(r));if(n.length>0&&!this._connecting){this._connecting=!0;try{m.debug(`Connecting to configured servers for code execution: ${n.join(", ")}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(n.length>0&&this._connecting){m.debug("Waiting for ongoing server connection...");const r=Date.now();for(;this._connecting&&Date.now()-r<5e3;)await new Promise(o=>setTimeout(o,100))}}getToolNamespaces(){const e=[],t=this.client.getAllActiveSessions();for(const[n,r]of Object.entries(t))if(n!=="code_mode")try{const o=r.connector;let s;try{s=o.tools}catch(c){m.warn(`Tools not available for server ${n}: ${c}`);continue}if(!s||s.length===0)continue;e.push({serverName:n,tools:s,session:r})}catch(o){m.warn(`Failed to load tools for server ${n}: ${o}`)}return e}createSearchToolsFunction(){return async(e="",t="full")=>{const n=[],r=new Set,o=e.toLowerCase(),s=this.client.getAllActiveSessions();for(const[l,a]of Object.entries(s))if(l!=="code_mode")try{const u=a.connector.tools;u&&u.length>0&&r.add(l);for(const d of u)t==="names"?n.push({name:d.name,server:l}):t==="descriptions"?n.push({name:d.name,server:l,description:d.description}):n.push({name:d.name,server:l,description:d.description,input_schema:d.inputSchema})}catch(u){m.warn(`Failed to search tools in server ${l}: ${u}`)}let c=n;return e&&(c=n.filter(l=>{const a=l.name.toLowerCase().includes(o),u=l.description?.toLowerCase().includes(o),d=l.server.toLowerCase().includes(o);return a||u||d})),{meta:{total_tools:n.length,namespaces:Array.from(r).sort(),result_count:c.length},results:c}}}},g(N,"BaseCodeExecutor"),N),k,fe=(k=class extends te{e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,t){super(e),this.e2bApiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{const e=await Xe(()=>import("@e2b/code-interpreter"),[]);this.SandboxClass=e.Sandbox}catch{throw new Error("@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter")}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),m.debug("Starting E2B sandbox for code execution..."),this.codeExecSandbox=await this.SandboxClass.create("base",{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let t=`
4
- // MCP Bridge Shim
5
- global.__callMcpTool = async (server, tool, args) => {
6
- const id = Math.random().toString(36).substring(7);
7
- console.log(JSON.stringify({
8
- type: '__MCP_TOOL_CALL__',
9
- id,
10
- server,
11
- tool,
12
- args
13
- }));
14
-
15
- const resultPath = \`/tmp/mcp_result_\${id}.json\`;
16
- const fs = require('fs');
17
-
18
- // Poll for result file
19
- let attempts = 0;
20
- while (attempts < 300) { // 30 seconds timeout
21
- if (fs.existsSync(resultPath)) {
22
- const content = fs.readFileSync(resultPath, 'utf8');
23
- const result = JSON.parse(content);
24
- fs.unlinkSync(resultPath); // Clean up
25
-
26
- if (result.error) {
27
- throw new Error(result.error);
28
- }
29
- return result.data;
30
- }
31
- await new Promise(resolve => setTimeout(resolve, 100));
32
- attempts++;
33
- }
34
- throw new Error('Tool execution timed out');
35
- };
36
-
37
- // Global search_tools helper
38
- global.search_tools = async (query, detailLevel = 'full') => {
39
- const allTools = ${JSON.stringify(Object.entries(e).flatMap(([n,r])=>r.map(o=>({name:o.name,description:o.description,server:n,input_schema:o.inputSchema}))))};
40
-
41
- const filtered = allTools.filter(tool => {
42
- if (!query) return true;
43
- const q = query.toLowerCase();
44
- return tool.name.toLowerCase().includes(q) ||
45
- (tool.description && tool.description.toLowerCase().includes(q));
46
- });
47
-
48
- if (detailLevel === 'names') {
49
- return filtered.map(t => ({ name: t.name, server: t.server }));
50
- } else if (detailLevel === 'descriptions') {
51
- return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
52
- }
53
- return filtered;
54
- };
55
- `;for(const[n,r]of Object.entries(e)){if(!r||r.length===0)continue;const o=n.replace(/[^a-zA-Z0-9_]/g,"_");t+=`
56
- global['${n}'] = {`;for(const s of r)t+=`
57
- '${s.name}': async (args) => await global.__callMcpTool('${n}', '${s.name}', args),`;t+=`
58
- };
59
-
60
- // Also expose as safe name if different
61
- if ('${o}' !== '${n}') {
62
- global['${o}'] = global['${n}'];
63
- }
64
- `}return t}buildToolCatalog(){const e={},t=this.getToolNamespaces();for(const{serverName:n,tools:r}of t)e[n]=r;return e}async execute(e,t=3e4){const n=Date.now();let r=null,o=null,s=[];try{await this.ensureServersConnected();const c=await this.getOrCreateCodeExecSandbox(),l=this.buildToolCatalog(),u=`
65
- ${this.generateShim(l)}
66
-
67
- (async () => {
68
- try {
69
- const func = async () => {
70
- ${e}
71
- };
72
- const result = await func();
73
- console.log('__MCP_RESULT_START__');
74
- console.log(JSON.stringify(result));
75
- console.log('__MCP_RESULT_END__');
76
- } catch (e) {
77
- console.error(e);
78
- process.exit(1);
79
- }
80
- })();
81
- `,d=`exec_${Date.now()}.js`;await c.files.write(d,u);const h=await c.commands.run(`node ${d}`,{timeoutMs:t,onStdout:g(async f=>{try{const p=f.split(`
82
- `);for(const y of p)if(y.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')){const _=JSON.parse(y);if(_.type==="__MCP_TOOL_CALL__")try{m.debug(`[E2B Bridge] Calling tool ${_.server}.${_.tool}`);const v=this.client.getAllActiveSessions()[_.server];if(!v)throw new Error(`Server ${_.server} not found`);const b=await v.connector.callTool(_.tool,_.args);let w=b;if(b.content&&b.content.length>0){const C=b.content[0];if(C.type==="text")try{w=JSON.parse(C.text)}catch{w=C.text}else w=C}const x=`/tmp/mcp_result_${_.id}.json`;await c.files.write(x,JSON.stringify({data:w}))}catch(E){m.error(`[E2B Bridge] Tool execution failed: ${E.message}`);const v=`/tmp/mcp_result_${_.id}.json`;await c.files.write(v,JSON.stringify({error:E.message||String(E)}))}}}catch{}},"onStdout")});if(s=[h.stdout,h.stderr].filter(Boolean),h.exitCode!==0)o=h.stderr||"Execution failed";else{const f=h.stdout,p="__MCP_RESULT_START__",y="__MCP_RESULT_END__",_=f.indexOf(p),E=f.indexOf(y);if(_!==-1&&E!==-1){const v=f.substring(_+p.length,E).trim();try{r=JSON.parse(v)}catch{r=v}s=s.map(b=>{let w=b.replace(new RegExp(p+"[\\s\\S]*?"+y),"[Result captured]");return w=w.split(`
83
- `).filter(x=>!x.includes("__MCP_TOOL_CALL__")).join(`
84
- `),w})}}}catch(c){o=c.message||String(c),o&&(o.includes("timeout")||o.includes("timed out"))&&(o="Script execution timed out")}return{result:r,logs:s,error:o,execution_time:(Date.now()-n)/1e3}}async cleanup(){if(this.codeExecSandbox)try{await this.codeExecSandbox.kill(),this.codeExecSandbox=null,m.debug("E2B code execution sandbox stopped")}catch(e){m.error("Failed to stop E2B code execution sandbox:",e)}}},g(k,"E2BCodeExecutor"),k),S=null,z=!1;function ne(){return["node","vm"].join(":")}g(ne,"getVMModuleName");function F(){if(z)return S!==null;z=!0;try{const i=typeof re<"u"?re:null;if(i)return S=i(ne()),!0}catch{m.debug("node:vm module not available via require")}return!1}g(F,"tryLoadVM");async function Je(){if(S!==null||!z&&F())return!0;try{return S=await import(ne()),!0}catch{return m.debug("node:vm module not available in this environment (e.g., Deno)"),!1}}g(Je,"tryLoadVMAsync");function $t(){return F(),S!==null}g($t,"isVMAvailable");var $,pe=($=class extends te{defaultTimeout;memoryLimitMb;constructor(e,t){super(e),this.defaultTimeout=t?.timeoutMs??3e4,this.memoryLimitMb=t?.memoryLimitMb,F()}async ensureVMLoaded(){if(S!==null)return;if(!await Je())throw new Error("node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment.")}async execute(e,t){const n=t??this.defaultTimeout;await this.ensureVMLoaded(),await this.ensureServersConnected();const r=[],o=Date.now();let s=null,c=null;try{const a=await this._buildContext(r),u=`
85
- (async () => {
86
- try {
87
- ${e}
88
- } catch (e) {
89
- throw e;
90
- }
91
- })()
92
- `;s=await new S.Script(u,{filename:"agent_code.js"}).runInNewContext(a,{timeout:n,displayErrors:!0})}catch(a){c=a.message||String(a),(a.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"||a.message==="Script execution timed out."||typeof c=="string"&&(c.includes("timed out")||c.includes("timeout")))&&(c="Script execution timed out"),a.stack&&m.debug(`Code execution error stack: ${a.stack}`)}const l=(Date.now()-o)/1e3;return{result:s,logs:r,error:c,execution_time:l}}async _buildContext(e){const t=g((...s)=>{e.push(s.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "))},"logHandler"),n={console:{log:t,error:g((...s)=>{t("[ERROR]",...s)},"error"),warn:g((...s)=>{t("[WARN]",...s)},"warn"),info:t,debug:t},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},r={},o=this.getToolNamespaces();for(const{serverName:s,tools:c,session:l}of o){const a={};for(const u of c){const d=u.name;a[d]=async h=>{const f=await l.connector.callTool(d,h||{});if(f.content&&f.content.length>0){const p=f.content[0];if(p.type==="text")try{return JSON.parse(p.text)}catch{return p.text}return p}return f}}n[s]=a,r[s]=!0}return n.__tool_namespaces=Object.keys(r),S.createContext(n)}async cleanup(){}},g($,"VMCodeExecutor"),$),A,At=(A=class extends Qe{serverParams;errlog;_transport=null;constructor(e,t=process.stderr){super(),this.serverParams=e,this.errlog=t}async establishConnection(){return this._transport=new Nt(this.serverParams),this._transport.stderr&&typeof this._transport.stderr.pipe=="function"&&this._transport.stderr.pipe(this.errlog),m.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(e){if(this._transport)try{await this._transport.close()}catch(t){m.warn(`Error closing stdio transport: ${t}`)}finally{this._transport=null}}},g(A,"StdioConnectionManager"),A),R,Rt=(R=class extends me{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:t=[],env:n,errlog:r=I.stderr,...o}={}){super(o),this.command=e,this.args=t,this.env=n,this.errlog=r,this.clientInfo=o.clientInfo??{name:"stdio-connector",version:"1.0.0"}}async connect(){if(this.connected){m.debug("Already connected to MCP implementation");return}m.debug(`Connecting to MCP implementation via stdio: ${this.command}`);try{let e;if(this.env){e={};for(const[o,s]of Object.entries(I.env))s!==void 0&&(e[o]=s);Object.assign(e,this.env)}const t={command:this.command,args:this.args,env:e};this.connectionManager=new At(t,this.errlog);const n=await this.connectionManager.start(),r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};this.client=new Ze(this.clientInfo,r),await this.client.connect(n),this.connected=!0,this.setupNotificationHandler(),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),m.debug(`Successfully connected to MCP implementation: ${this.command}`),this.trackConnectorInit({serverCommand:this.command,serverArgs:this.args,publicIdentifier:`${this.command} ${this.args.join(" ")}`})}catch(e){throw m.error(`Failed to connect to MCP implementation: ${e}`),await this.cleanupResources(),e}}get publicIdentifier(){return{type:"stdio","command&args":`${this.command} ${this.args.join(" ")}`}}},g(R,"StdioConnector"),R);function G(i){const e=X();return JSON.parse(e)}g(G,"loadConfigFile");function Ve(i,e){if("command"in i&&"args"in i)return new Rt({command:i.command,args:i.args,env:i.env,...e});if("url"in i){const t=i.transport||"http";return new Ye(i.url,{headers:i.headers,authToken:i.auth_token||i.authToken,preferSse:i.preferSse||t==="sse",disableSseFallback:i.disableSseFallback,...e})}throw new Error("Cannot determine connector type from config")}g(Ve,"createConnectorFromConfig");var M,jt=(M=class extends Ke{static getPackageVersion(){return We()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,t){e?typeof e=="string"?super(G()):super(e):super();let n=!1,r="vm",o;t?.codeMode&&(typeof t.codeMode=="boolean"?n=t.codeMode:(n=t.codeMode.enabled,r=t.codeMode.executor??"vm",o=t.codeMode.executorOptions)),this.codeMode=n,this._codeExecutorConfig=r,this._executorOptions=o,this._samplingCallback=t?.samplingCallback,this._elicitationCallback=t?.elicitationCallback,this.codeMode&&this._setupCodeModeConnector(),this._trackClientInit()}_trackClientInit(){const e=Object.keys(this.config.mcpServers??{}),t=!!this._samplingCallback,n=!!this._elicitationCallback;ze.getInstance().trackMCPClientInit({codeMode:this.codeMode,sandbox:!1,allCallbacks:t&&n,verify:!1,servers:e,numServers:e.length,isBrowser:!1}).catch(r=>m.debug(`Failed to track MCPClient init: ${r}`))}static fromDict(e,t){return new M(e,t)}static fromConfigFile(e,t){return new M(G(),t)}saveConfig(e){const t=ke.dirname(e);j.existsSync(t)||j.mkdirSync(t,{recursive:!0}),j.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return Ve(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new et(this),t=new Ge(e);this.sessions.code_mode=t,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof te)this._codeExecutor=e;else{if(typeof e=="function")throw this._customCodeExecutor=e,new Error("Custom executor function should be handled in executeCode");if(e==="e2b"){const t=this._executorOptions;if(t?.apiKey)this._codeExecutor=new fe(this,t);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new pe(this,this._executorOptions)}catch{throw new Error("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.")}}}else try{this._codeExecutor=new pe(this,this._executorOptions)}catch{const n=this._executorOptions,r=n?.apiKey||kt.E2B_API_KEY;if(r)m.info("VM executor not available in this environment. Falling back to E2B."),this._codeExecutor=new fe(this,{...n,apiKey:r});else throw new Error("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.")}}}return this._codeExecutor}async executeCode(e,t){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._customCodeExecutor?this._customCodeExecutor(e,t):this._ensureCodeExecutor().execute(e,t)}async searchTools(e="",t="full"){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._ensureCodeExecutor().createSearchToolsFunction()(e,t)}getServerNames(){const e=this.codeMode;return super.getServerNames().filter(t=>!e||t!=="code_mode")}async close(){this._codeExecutor&&(await this._codeExecutor.cleanup(),this._codeExecutor=null),await this.closeAllSessions()}},g(M,"MCPClient"),M);export{te as BaseCodeExecutor,fe as E2BCodeExecutor,jt as MCPClient,Ge as MCPSession,pe as VMCodeExecutor,$t as isVMAvailable};