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
@@ -35,9 +35,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
35
35
  async function getNodeModules() {
36
36
  if (typeof process !== "undefined" && process.platform) {
37
37
  try {
38
- const fs = await import("fs");
39
- const path = await import("path");
40
- return { fs: fs.default, path: path.default };
38
+ const fs2 = await import("fs");
39
+ const path2 = await import("path");
40
+ return { fs: fs2.default, path: path2.default };
41
41
  } catch {
42
42
  return { fs: null, path: null };
43
43
  }
@@ -1062,10 +1062,14 @@ __export(browser_exports, {
1062
1062
  Tel: () => Tel,
1063
1063
  Telemetry: () => Telemetry,
1064
1064
  VERSION: () => VERSION,
1065
+ createLLMFromString: () => createLLMFromString,
1065
1066
  createReadableStreamFromGenerator: () => createReadableStreamFromGenerator,
1066
1067
  getPackageVersion: () => getPackageVersion,
1068
+ getSupportedProviders: () => getSupportedProviders,
1069
+ isValidLLMString: () => isValidLLMString,
1067
1070
  logger: () => logger,
1068
1071
  onMcpAuthorization: () => onMcpAuthorization,
1072
+ parseLLMString: () => parseLLMString,
1069
1073
  setBrowserTelemetrySource: () => setTelemetrySource,
1070
1074
  setTelemetrySource: () => setTelemetrySource,
1071
1075
  streamEventsToAISDK: () => streamEventsToAISDK,
@@ -1606,7 +1610,7 @@ __name(generateUUID, "generateUUID");
1606
1610
  init_logging();
1607
1611
 
1608
1612
  // src/version.ts
1609
- var VERSION = "1.11.0-canary.3";
1613
+ var VERSION = "1.11.0-canary.4";
1610
1614
  function getPackageVersion() {
1611
1615
  return VERSION;
1612
1616
  }
@@ -1927,26 +1931,26 @@ var Telemetry = class _Telemetry {
1927
1931
  * Get or create user ID from filesystem (Node.js/Bun)
1928
1932
  */
1929
1933
  _getUserIdFromFilesystem() {
1930
- const fs = require("fs");
1934
+ const fs2 = require("fs");
1931
1935
  const os = require("os");
1932
- const path = require("path");
1936
+ const path2 = require("path");
1933
1937
  if (!this._userIdPath) {
1934
- this._userIdPath = path.join(
1935
- this._getCacheHome(os, path),
1938
+ this._userIdPath = path2.join(
1939
+ this._getCacheHome(os, path2),
1936
1940
  "mcp_use_3",
1937
1941
  "telemetry_user_id"
1938
1942
  );
1939
1943
  }
1940
- const isFirstTime = !fs.existsSync(this._userIdPath);
1944
+ const isFirstTime = !fs2.existsSync(this._userIdPath);
1941
1945
  if (isFirstTime) {
1942
1946
  logger.debug(`Creating user ID path: ${this._userIdPath}`);
1943
- fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1947
+ fs2.mkdirSync(path2.dirname(this._userIdPath), { recursive: true });
1944
1948
  const newUserId = generateUUID();
1945
- fs.writeFileSync(this._userIdPath, newUserId);
1949
+ fs2.writeFileSync(this._userIdPath, newUserId);
1946
1950
  logger.debug(`User ID path created: ${this._userIdPath}`);
1947
1951
  return newUserId;
1948
1952
  }
1949
- return fs.readFileSync(this._userIdPath, "utf-8").trim();
1953
+ return fs2.readFileSync(this._userIdPath, "utf-8").trim();
1950
1954
  }
1951
1955
  /**
1952
1956
  * Get or create user ID from localStorage (Browser)
@@ -1965,9 +1969,9 @@ var Telemetry = class _Telemetry {
1965
1969
  return `session-${generateUUID()}`;
1966
1970
  }
1967
1971
  }
1968
- _getCacheHome(os, path) {
1972
+ _getCacheHome(os, path2) {
1969
1973
  const envVar = process.env.XDG_CACHE_HOME;
1970
- if (envVar && path.isAbsolute(envVar)) {
1974
+ if (envVar && path2.isAbsolute(envVar)) {
1971
1975
  return envVar;
1972
1976
  }
1973
1977
  const platform = process.platform;
@@ -1977,11 +1981,11 @@ var Telemetry = class _Telemetry {
1977
1981
  if (appdata) {
1978
1982
  return appdata;
1979
1983
  }
1980
- return path.join(homeDir, "AppData", "Local");
1984
+ return path2.join(homeDir, "AppData", "Local");
1981
1985
  } else if (platform === "darwin") {
1982
- return path.join(homeDir, "Library", "Caches");
1986
+ return path2.join(homeDir, "Library", "Caches");
1983
1987
  } else {
1984
- return path.join(homeDir, ".cache");
1988
+ return path2.join(homeDir, ".cache");
1985
1989
  }
1986
1990
  }
1987
1991
  async capture(event) {
@@ -2055,12 +2059,12 @@ var Telemetry = class _Telemetry {
2055
2059
  return;
2056
2060
  }
2057
2061
  try {
2058
- const fs = require("fs");
2059
- const path = require("path");
2062
+ const fs2 = require("fs");
2063
+ const path2 = require("path");
2060
2064
  const os = require("os");
2061
2065
  if (!this._versionDownloadPath) {
2062
- this._versionDownloadPath = path.join(
2063
- this._getCacheHome(os, path),
2066
+ this._versionDownloadPath = path2.join(
2067
+ this._getCacheHome(os, path2),
2064
2068
  "mcp_use",
2065
2069
  "download_version"
2066
2070
  );
@@ -2068,19 +2072,19 @@ var Telemetry = class _Telemetry {
2068
2072
  const currentVersion = getPackageVersion();
2069
2073
  let shouldTrack = false;
2070
2074
  let firstDownload = false;
2071
- if (!fs.existsSync(this._versionDownloadPath)) {
2075
+ if (!fs2.existsSync(this._versionDownloadPath)) {
2072
2076
  shouldTrack = true;
2073
2077
  firstDownload = true;
2074
- fs.mkdirSync(path.dirname(this._versionDownloadPath), {
2078
+ fs2.mkdirSync(path2.dirname(this._versionDownloadPath), {
2075
2079
  recursive: true
2076
2080
  });
2077
- fs.writeFileSync(this._versionDownloadPath, currentVersion);
2081
+ fs2.writeFileSync(this._versionDownloadPath, currentVersion);
2078
2082
  } else {
2079
- const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
2083
+ const savedVersion = fs2.readFileSync(this._versionDownloadPath, "utf-8").trim();
2080
2084
  if (currentVersion > savedVersion) {
2081
2085
  shouldTrack = true;
2082
2086
  firstDownload = false;
2083
- fs.writeFileSync(this._versionDownloadPath, currentVersion);
2087
+ fs2.writeFileSync(this._versionDownloadPath, currentVersion);
2084
2088
  }
2085
2089
  }
2086
2090
  if (shouldTrack) {
@@ -4552,6 +4556,1135 @@ var LangChainAdapter = class extends BaseAdapter {
4552
4556
  }
4553
4557
  };
4554
4558
 
4559
+ // src/client.ts
4560
+ var import_node_fs2 = __toESM(require("fs"), 1);
4561
+ var import_node_path = __toESM(require("path"), 1);
4562
+
4563
+ // src/client/executors/base.ts
4564
+ init_logging();
4565
+ var BaseCodeExecutor = class {
4566
+ static {
4567
+ __name(this, "BaseCodeExecutor");
4568
+ }
4569
+ client;
4570
+ _connecting = false;
4571
+ constructor(client) {
4572
+ this.client = client;
4573
+ }
4574
+ /**
4575
+ * Ensure all configured MCP servers are connected before execution.
4576
+ * Prevents race conditions with a connection lock.
4577
+ */
4578
+ async ensureServersConnected() {
4579
+ const configuredServers = this.client.getServerNames();
4580
+ const activeSessions = Object.keys(this.client.getAllActiveSessions());
4581
+ const missingServers = configuredServers.filter(
4582
+ (s) => !activeSessions.includes(s)
4583
+ );
4584
+ if (missingServers.length > 0 && !this._connecting) {
4585
+ this._connecting = true;
4586
+ try {
4587
+ logger.debug(
4588
+ `Connecting to configured servers for code execution: ${missingServers.join(", ")}`
4589
+ );
4590
+ await this.client.createAllSessions();
4591
+ } finally {
4592
+ this._connecting = false;
4593
+ }
4594
+ } else if (missingServers.length > 0 && this._connecting) {
4595
+ logger.debug("Waiting for ongoing server connection...");
4596
+ const startWait = Date.now();
4597
+ while (this._connecting && Date.now() - startWait < 5e3) {
4598
+ await new Promise((resolve) => setTimeout(resolve, 100));
4599
+ }
4600
+ }
4601
+ }
4602
+ /**
4603
+ * Get tool namespace information from all active MCP sessions.
4604
+ * Filters out the internal code_mode server.
4605
+ */
4606
+ getToolNamespaces() {
4607
+ const namespaces = [];
4608
+ const activeSessions = this.client.getAllActiveSessions();
4609
+ for (const [serverName, session] of Object.entries(activeSessions)) {
4610
+ if (serverName === "code_mode") continue;
4611
+ try {
4612
+ const connector = session.connector;
4613
+ let tools;
4614
+ try {
4615
+ tools = connector.tools;
4616
+ } catch (e) {
4617
+ logger.warn(`Tools not available for server ${serverName}: ${e}`);
4618
+ continue;
4619
+ }
4620
+ if (!tools || tools.length === 0) continue;
4621
+ namespaces.push({ serverName, tools, session });
4622
+ } catch (e) {
4623
+ logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
4624
+ }
4625
+ }
4626
+ return namespaces;
4627
+ }
4628
+ /**
4629
+ * Create a search function for discovering available MCP tools.
4630
+ * Used by code execution environments to find tools at runtime.
4631
+ */
4632
+ createSearchToolsFunction() {
4633
+ return async (query = "", detailLevel = "full") => {
4634
+ const allTools = [];
4635
+ const allNamespaces = /* @__PURE__ */ new Set();
4636
+ const queryLower = query.toLowerCase();
4637
+ const activeSessions = this.client.getAllActiveSessions();
4638
+ for (const [serverName, session] of Object.entries(activeSessions)) {
4639
+ if (serverName === "code_mode") continue;
4640
+ try {
4641
+ const tools = session.connector.tools;
4642
+ if (tools && tools.length > 0) {
4643
+ allNamespaces.add(serverName);
4644
+ }
4645
+ for (const tool of tools) {
4646
+ if (detailLevel === "names") {
4647
+ allTools.push({ name: tool.name, server: serverName });
4648
+ } else if (detailLevel === "descriptions") {
4649
+ allTools.push({
4650
+ name: tool.name,
4651
+ server: serverName,
4652
+ description: tool.description
4653
+ });
4654
+ } else {
4655
+ allTools.push({
4656
+ name: tool.name,
4657
+ server: serverName,
4658
+ description: tool.description,
4659
+ input_schema: tool.inputSchema
4660
+ });
4661
+ }
4662
+ }
4663
+ } catch (e) {
4664
+ logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
4665
+ }
4666
+ }
4667
+ let filteredTools = allTools;
4668
+ if (query) {
4669
+ filteredTools = allTools.filter((tool) => {
4670
+ const nameMatch = tool.name.toLowerCase().includes(queryLower);
4671
+ const descMatch = tool.description?.toLowerCase().includes(queryLower);
4672
+ const serverMatch = tool.server.toLowerCase().includes(queryLower);
4673
+ return nameMatch || descMatch || serverMatch;
4674
+ });
4675
+ }
4676
+ return {
4677
+ meta: {
4678
+ total_tools: allTools.length,
4679
+ namespaces: Array.from(allNamespaces).sort(),
4680
+ result_count: filteredTools.length
4681
+ },
4682
+ results: filteredTools
4683
+ };
4684
+ };
4685
+ }
4686
+ };
4687
+
4688
+ // src/client/executors/e2b.ts
4689
+ init_logging();
4690
+ var E2BCodeExecutor = class extends BaseCodeExecutor {
4691
+ static {
4692
+ __name(this, "E2BCodeExecutor");
4693
+ }
4694
+ e2bApiKey;
4695
+ codeExecSandbox = null;
4696
+ SandboxClass = null;
4697
+ timeoutMs;
4698
+ constructor(client, options) {
4699
+ super(client);
4700
+ this.e2bApiKey = options.apiKey;
4701
+ this.timeoutMs = options.timeoutMs ?? 3e5;
4702
+ }
4703
+ /**
4704
+ * Lazy load E2B Sandbox class.
4705
+ * This allows the library to work without E2B installed.
4706
+ */
4707
+ async ensureSandboxClass() {
4708
+ if (this.SandboxClass) return;
4709
+ try {
4710
+ const e2b = await import("@e2b/code-interpreter");
4711
+ this.SandboxClass = e2b.Sandbox;
4712
+ } catch (error) {
4713
+ throw new Error(
4714
+ "@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
4715
+ );
4716
+ }
4717
+ }
4718
+ /**
4719
+ * Get or create a dedicated sandbox for code execution.
4720
+ */
4721
+ async getOrCreateCodeExecSandbox() {
4722
+ if (this.codeExecSandbox) return this.codeExecSandbox;
4723
+ await this.ensureSandboxClass();
4724
+ logger.debug("Starting E2B sandbox for code execution...");
4725
+ this.codeExecSandbox = await this.SandboxClass.create("base", {
4726
+ apiKey: this.e2bApiKey,
4727
+ timeoutMs: this.timeoutMs
4728
+ });
4729
+ return this.codeExecSandbox;
4730
+ }
4731
+ /**
4732
+ * Generate the shim code that exposes tools to the sandbox environment.
4733
+ * Creates a bridge that intercepts tool calls and sends them back to host.
4734
+ */
4735
+ generateShim(tools) {
4736
+ let shim = `
4737
+ // MCP Bridge Shim
4738
+ global.__callMcpTool = async (server, tool, args) => {
4739
+ const id = Math.random().toString(36).substring(7);
4740
+ console.log(JSON.stringify({
4741
+ type: '__MCP_TOOL_CALL__',
4742
+ id,
4743
+ server,
4744
+ tool,
4745
+ args
4746
+ }));
4747
+
4748
+ const resultPath = \`/tmp/mcp_result_\${id}.json\`;
4749
+ const fs = require('fs');
4750
+
4751
+ // Poll for result file
4752
+ let attempts = 0;
4753
+ while (attempts < 300) { // 30 seconds timeout
4754
+ if (fs.existsSync(resultPath)) {
4755
+ const content = fs.readFileSync(resultPath, 'utf8');
4756
+ const result = JSON.parse(content);
4757
+ fs.unlinkSync(resultPath); // Clean up
4758
+
4759
+ if (result.error) {
4760
+ throw new Error(result.error);
4761
+ }
4762
+ return result.data;
4763
+ }
4764
+ await new Promise(resolve => setTimeout(resolve, 100));
4765
+ attempts++;
4766
+ }
4767
+ throw new Error('Tool execution timed out');
4768
+ };
4769
+
4770
+ // Global search_tools helper
4771
+ global.search_tools = async (query, detailLevel = 'full') => {
4772
+ const allTools = ${JSON.stringify(
4773
+ Object.entries(tools).flatMap(
4774
+ ([server, serverTools]) => serverTools.map((tool) => ({
4775
+ name: tool.name,
4776
+ description: tool.description,
4777
+ server,
4778
+ input_schema: tool.inputSchema
4779
+ }))
4780
+ )
4781
+ )};
4782
+
4783
+ const filtered = allTools.filter(tool => {
4784
+ if (!query) return true;
4785
+ const q = query.toLowerCase();
4786
+ return tool.name.toLowerCase().includes(q) ||
4787
+ (tool.description && tool.description.toLowerCase().includes(q));
4788
+ });
4789
+
4790
+ if (detailLevel === 'names') {
4791
+ return filtered.map(t => ({ name: t.name, server: t.server }));
4792
+ } else if (detailLevel === 'descriptions') {
4793
+ return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
4794
+ }
4795
+ return filtered;
4796
+ };
4797
+ `;
4798
+ for (const [serverName, serverTools] of Object.entries(tools)) {
4799
+ if (!serverTools || serverTools.length === 0) continue;
4800
+ const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
4801
+ shim += `
4802
+ global['${serverName}'] = {`;
4803
+ for (const tool of serverTools) {
4804
+ shim += `
4805
+ '${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
4806
+ }
4807
+ shim += `
4808
+ };
4809
+
4810
+ // Also expose as safe name if different
4811
+ if ('${safeServerName}' !== '${serverName}') {
4812
+ global['${safeServerName}'] = global['${serverName}'];
4813
+ }
4814
+ `;
4815
+ }
4816
+ return shim;
4817
+ }
4818
+ /**
4819
+ * Build the tool catalog for the shim.
4820
+ * Returns a map of server names to their available tools.
4821
+ */
4822
+ buildToolCatalog() {
4823
+ const catalog = {};
4824
+ const namespaces = this.getToolNamespaces();
4825
+ for (const { serverName, tools } of namespaces) {
4826
+ catalog[serverName] = tools;
4827
+ }
4828
+ return catalog;
4829
+ }
4830
+ /**
4831
+ * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
4832
+ * Tool calls are proxied back to the host via the bridge pattern.
4833
+ *
4834
+ * @param code - Code to execute
4835
+ * @param timeout - Execution timeout in milliseconds (default: 30000)
4836
+ */
4837
+ async execute(code, timeout = 3e4) {
4838
+ const startTime = Date.now();
4839
+ let result = null;
4840
+ let error = null;
4841
+ let logs = [];
4842
+ try {
4843
+ await this.ensureServersConnected();
4844
+ const sandbox = await this.getOrCreateCodeExecSandbox();
4845
+ const toolCatalog = this.buildToolCatalog();
4846
+ const shim = this.generateShim(toolCatalog);
4847
+ const wrappedCode = `
4848
+ ${shim}
4849
+
4850
+ (async () => {
4851
+ try {
4852
+ const func = async () => {
4853
+ ${code}
4854
+ };
4855
+ const result = await func();
4856
+ console.log('__MCP_RESULT_START__');
4857
+ console.log(JSON.stringify(result));
4858
+ console.log('__MCP_RESULT_END__');
4859
+ } catch (e) {
4860
+ console.error(e);
4861
+ process.exit(1);
4862
+ }
4863
+ })();
4864
+ `;
4865
+ const filename = `exec_${Date.now()}.js`;
4866
+ await sandbox.files.write(filename, wrappedCode);
4867
+ const execution = await sandbox.commands.run(`node ${filename}`, {
4868
+ timeoutMs: timeout,
4869
+ onStdout: /* @__PURE__ */ __name(async (data) => {
4870
+ try {
4871
+ const lines = data.split("\n");
4872
+ for (const line of lines) {
4873
+ if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
4874
+ const call = JSON.parse(line);
4875
+ if (call.type === "__MCP_TOOL_CALL__") {
4876
+ try {
4877
+ logger.debug(
4878
+ `[E2B Bridge] Calling tool ${call.server}.${call.tool}`
4879
+ );
4880
+ const activeSessions = this.client.getAllActiveSessions();
4881
+ const session = activeSessions[call.server];
4882
+ if (!session) {
4883
+ throw new Error(`Server ${call.server} not found`);
4884
+ }
4885
+ const toolResult = await session.connector.callTool(
4886
+ call.tool,
4887
+ call.args
4888
+ );
4889
+ let extractedResult = toolResult;
4890
+ if (toolResult.content && toolResult.content.length > 0) {
4891
+ const item = toolResult.content[0];
4892
+ if (item.type === "text") {
4893
+ try {
4894
+ extractedResult = JSON.parse(item.text);
4895
+ } catch {
4896
+ extractedResult = item.text;
4897
+ }
4898
+ } else {
4899
+ extractedResult = item;
4900
+ }
4901
+ }
4902
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
4903
+ await sandbox.files.write(
4904
+ resultPath,
4905
+ JSON.stringify({ data: extractedResult })
4906
+ );
4907
+ } catch (err) {
4908
+ logger.error(
4909
+ `[E2B Bridge] Tool execution failed: ${err.message}`
4910
+ );
4911
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
4912
+ await sandbox.files.write(
4913
+ resultPath,
4914
+ JSON.stringify({
4915
+ error: err.message || String(err)
4916
+ })
4917
+ );
4918
+ }
4919
+ }
4920
+ }
4921
+ }
4922
+ } catch (e) {
4923
+ }
4924
+ }, "onStdout")
4925
+ });
4926
+ logs = [execution.stdout, execution.stderr].filter(Boolean);
4927
+ if (execution.exitCode !== 0) {
4928
+ error = execution.stderr || "Execution failed";
4929
+ } else {
4930
+ const stdout = execution.stdout;
4931
+ const startMarker = "__MCP_RESULT_START__";
4932
+ const endMarker = "__MCP_RESULT_END__";
4933
+ const startIndex = stdout.indexOf(startMarker);
4934
+ const endIndex = stdout.indexOf(endMarker);
4935
+ if (startIndex !== -1 && endIndex !== -1) {
4936
+ const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
4937
+ try {
4938
+ result = JSON.parse(jsonStr);
4939
+ } catch (e) {
4940
+ result = jsonStr;
4941
+ }
4942
+ logs = logs.map((log) => {
4943
+ let cleaned = log.replace(
4944
+ new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
4945
+ "[Result captured]"
4946
+ );
4947
+ cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
4948
+ return cleaned;
4949
+ });
4950
+ }
4951
+ }
4952
+ } catch (e) {
4953
+ error = e.message || String(e);
4954
+ if (error && (error.includes("timeout") || error.includes("timed out"))) {
4955
+ error = "Script execution timed out";
4956
+ }
4957
+ }
4958
+ return {
4959
+ result,
4960
+ logs,
4961
+ error,
4962
+ execution_time: (Date.now() - startTime) / 1e3
4963
+ };
4964
+ }
4965
+ /**
4966
+ * Clean up the E2B sandbox.
4967
+ * Should be called when the executor is no longer needed.
4968
+ */
4969
+ async cleanup() {
4970
+ if (this.codeExecSandbox) {
4971
+ try {
4972
+ await this.codeExecSandbox.kill();
4973
+ this.codeExecSandbox = null;
4974
+ logger.debug("E2B code execution sandbox stopped");
4975
+ } catch (error) {
4976
+ logger.error("Failed to stop E2B code execution sandbox:", error);
4977
+ }
4978
+ }
4979
+ }
4980
+ };
4981
+
4982
+ // src/client/executors/vm.ts
4983
+ init_logging();
4984
+ var vm = null;
4985
+ var vmCheckAttempted = false;
4986
+ function getVMModuleName() {
4987
+ return ["node", "vm"].join(":");
4988
+ }
4989
+ __name(getVMModuleName, "getVMModuleName");
4990
+ function tryLoadVM() {
4991
+ if (vmCheckAttempted) {
4992
+ return vm !== null;
4993
+ }
4994
+ vmCheckAttempted = true;
4995
+ try {
4996
+ const nodeRequire = typeof require !== "undefined" ? require : null;
4997
+ if (nodeRequire) {
4998
+ vm = nodeRequire(getVMModuleName());
4999
+ return true;
5000
+ }
5001
+ } catch (error) {
5002
+ logger.debug("node:vm module not available via require");
5003
+ }
5004
+ return false;
5005
+ }
5006
+ __name(tryLoadVM, "tryLoadVM");
5007
+ async function tryLoadVMAsync() {
5008
+ if (vm !== null) {
5009
+ return true;
5010
+ }
5011
+ if (!vmCheckAttempted) {
5012
+ if (tryLoadVM()) {
5013
+ return true;
5014
+ }
5015
+ }
5016
+ try {
5017
+ vm = await import(
5018
+ /* @vite-ignore */
5019
+ getVMModuleName()
5020
+ );
5021
+ return true;
5022
+ } catch (error) {
5023
+ logger.debug(
5024
+ "node:vm module not available in this environment (e.g., Deno)"
5025
+ );
5026
+ return false;
5027
+ }
5028
+ }
5029
+ __name(tryLoadVMAsync, "tryLoadVMAsync");
5030
+ var VMCodeExecutor = class extends BaseCodeExecutor {
5031
+ static {
5032
+ __name(this, "VMCodeExecutor");
5033
+ }
5034
+ defaultTimeout;
5035
+ memoryLimitMb;
5036
+ constructor(client, options) {
5037
+ super(client);
5038
+ this.defaultTimeout = options?.timeoutMs ?? 3e4;
5039
+ this.memoryLimitMb = options?.memoryLimitMb;
5040
+ tryLoadVM();
5041
+ }
5042
+ /**
5043
+ * Ensure VM module is loaded before execution
5044
+ */
5045
+ async ensureVMLoaded() {
5046
+ if (vm !== null) {
5047
+ return;
5048
+ }
5049
+ const loaded = await tryLoadVMAsync();
5050
+ if (!loaded) {
5051
+ throw new Error(
5052
+ "node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment."
5053
+ );
5054
+ }
5055
+ }
5056
+ /**
5057
+ * Execute JavaScript/TypeScript code with access to MCP tools.
5058
+ *
5059
+ * @param code - Code to execute
5060
+ * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
5061
+ */
5062
+ async execute(code, timeout) {
5063
+ const effectiveTimeout = timeout ?? this.defaultTimeout;
5064
+ await this.ensureVMLoaded();
5065
+ await this.ensureServersConnected();
5066
+ const logs = [];
5067
+ const startTime = Date.now();
5068
+ let result = null;
5069
+ let error = null;
5070
+ try {
5071
+ const context = await this._buildContext(logs);
5072
+ const wrappedCode = `
5073
+ (async () => {
5074
+ try {
5075
+ ${code}
5076
+ } catch (e) {
5077
+ throw e;
5078
+ }
5079
+ })()
5080
+ `;
5081
+ const script = new vm.Script(wrappedCode, {
5082
+ filename: "agent_code.js"
5083
+ });
5084
+ const promise = script.runInNewContext(context, {
5085
+ timeout: effectiveTimeout,
5086
+ displayErrors: true
5087
+ });
5088
+ result = await promise;
5089
+ } catch (e) {
5090
+ error = e.message || String(e);
5091
+ if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
5092
+ error = "Script execution timed out";
5093
+ }
5094
+ if (e.stack) {
5095
+ logger.debug(`Code execution error stack: ${e.stack}`);
5096
+ }
5097
+ }
5098
+ const executionTime = (Date.now() - startTime) / 1e3;
5099
+ return {
5100
+ result,
5101
+ logs,
5102
+ error,
5103
+ execution_time: executionTime
5104
+ };
5105
+ }
5106
+ /**
5107
+ * Build the VM execution context with MCP tools and standard globals.
5108
+ *
5109
+ * @param logs - Array to capture console output
5110
+ */
5111
+ async _buildContext(logs) {
5112
+ const logHandler = /* @__PURE__ */ __name((...args) => {
5113
+ logs.push(
5114
+ args.map(
5115
+ (arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
5116
+ ).join(" ")
5117
+ );
5118
+ }, "logHandler");
5119
+ const sandbox = {
5120
+ console: {
5121
+ log: logHandler,
5122
+ error: /* @__PURE__ */ __name((...args) => {
5123
+ logHandler("[ERROR]", ...args);
5124
+ }, "error"),
5125
+ warn: /* @__PURE__ */ __name((...args) => {
5126
+ logHandler("[WARN]", ...args);
5127
+ }, "warn"),
5128
+ info: logHandler,
5129
+ debug: logHandler
5130
+ },
5131
+ // Standard globals
5132
+ Object,
5133
+ Array,
5134
+ String,
5135
+ Number,
5136
+ Boolean,
5137
+ Date,
5138
+ Math,
5139
+ JSON,
5140
+ RegExp,
5141
+ Map,
5142
+ Set,
5143
+ Promise,
5144
+ parseInt,
5145
+ parseFloat,
5146
+ isNaN,
5147
+ isFinite,
5148
+ encodeURI,
5149
+ decodeURI,
5150
+ encodeURIComponent,
5151
+ decodeURIComponent,
5152
+ setTimeout,
5153
+ clearTimeout,
5154
+ // Helper for tools
5155
+ search_tools: this.createSearchToolsFunction(),
5156
+ __tool_namespaces: []
5157
+ };
5158
+ const toolNamespaces = {};
5159
+ const namespaceInfos = this.getToolNamespaces();
5160
+ for (const { serverName, tools, session } of namespaceInfos) {
5161
+ const serverNamespace = {};
5162
+ for (const tool of tools) {
5163
+ const toolName = tool.name;
5164
+ serverNamespace[toolName] = async (args) => {
5165
+ const result = await session.connector.callTool(toolName, args || {});
5166
+ if (result.content && result.content.length > 0) {
5167
+ const item = result.content[0];
5168
+ if (item.type === "text") {
5169
+ try {
5170
+ return JSON.parse(item.text);
5171
+ } catch {
5172
+ return item.text;
5173
+ }
5174
+ }
5175
+ return item;
5176
+ }
5177
+ return result;
5178
+ };
5179
+ }
5180
+ sandbox[serverName] = serverNamespace;
5181
+ toolNamespaces[serverName] = true;
5182
+ }
5183
+ sandbox.__tool_namespaces = Object.keys(toolNamespaces);
5184
+ return vm.createContext(sandbox);
5185
+ }
5186
+ /**
5187
+ * Clean up resources.
5188
+ * VM executor doesn't need cleanup, but method kept for interface consistency.
5189
+ */
5190
+ async cleanup() {
5191
+ }
5192
+ };
5193
+
5194
+ // src/client/connectors/codeMode.ts
5195
+ var CodeModeConnector = class extends BaseConnector {
5196
+ static {
5197
+ __name(this, "CodeModeConnector");
5198
+ }
5199
+ mcpClient;
5200
+ _tools;
5201
+ constructor(client) {
5202
+ super();
5203
+ this.mcpClient = client;
5204
+ this.connected = true;
5205
+ this._tools = this._createToolsList();
5206
+ }
5207
+ async connect() {
5208
+ this.connected = true;
5209
+ }
5210
+ async disconnect() {
5211
+ this.connected = false;
5212
+ }
5213
+ get publicIdentifier() {
5214
+ return { name: "code_mode", version: "1.0.0" };
5215
+ }
5216
+ _createToolsList() {
5217
+ return [
5218
+ {
5219
+ name: "execute_code",
5220
+ 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.",
5221
+ inputSchema: {
5222
+ type: "object",
5223
+ properties: {
5224
+ code: {
5225
+ type: "string",
5226
+ 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"
5227
+ },
5228
+ timeout: {
5229
+ type: "number",
5230
+ description: "Execution timeout in milliseconds",
5231
+ default: 3e4
5232
+ }
5233
+ },
5234
+ required: ["code"]
5235
+ }
5236
+ },
5237
+ {
5238
+ name: "search_tools",
5239
+ 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.",
5240
+ inputSchema: {
5241
+ type: "object",
5242
+ properties: {
5243
+ query: {
5244
+ type: "string",
5245
+ description: "Search query to filter tools by name or description",
5246
+ default: ""
5247
+ },
5248
+ detail_level: {
5249
+ type: "string",
5250
+ description: "Detail level: 'names', 'descriptions', or 'full'",
5251
+ enum: ["names", "descriptions", "full"],
5252
+ default: "full"
5253
+ }
5254
+ }
5255
+ }
5256
+ }
5257
+ ];
5258
+ }
5259
+ // Override tools getter to return static list immediately
5260
+ get tools() {
5261
+ return this._tools;
5262
+ }
5263
+ async initialize() {
5264
+ this.toolsCache = this._tools;
5265
+ return { capabilities: {}, version: "1.0.0" };
5266
+ }
5267
+ async callTool(name, args) {
5268
+ if (name === "execute_code") {
5269
+ const code = args.code;
5270
+ const timeout = args.timeout || 3e4;
5271
+ const result = await this.mcpClient.executeCode(code, timeout);
5272
+ return {
5273
+ content: [
5274
+ {
5275
+ type: "text",
5276
+ text: JSON.stringify(result)
5277
+ }
5278
+ ]
5279
+ };
5280
+ } else if (name === "search_tools") {
5281
+ const query = args.query || "";
5282
+ const detailLevel = args.detail_level;
5283
+ const result = await this.mcpClient.searchTools(
5284
+ query,
5285
+ detailLevel && detailLevel in ["names", "descriptions", "full"] ? detailLevel : "full"
5286
+ );
5287
+ return {
5288
+ content: [
5289
+ {
5290
+ type: "text",
5291
+ text: JSON.stringify(result)
5292
+ }
5293
+ ]
5294
+ };
5295
+ }
5296
+ throw new Error(`Unknown tool: ${name}`);
5297
+ }
5298
+ };
5299
+
5300
+ // src/config.ts
5301
+ var import_node_fs = require("fs");
5302
+
5303
+ // src/connectors/stdio.ts
5304
+ var import_node_process = __toESM(require("process"), 1);
5305
+ var import_client2 = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
5306
+ init_logging();
5307
+
5308
+ // src/task_managers/stdio.ts
5309
+ var import_stdio = require("@mcp-use/modelcontextprotocol-sdk/client/stdio.js");
5310
+ init_logging();
5311
+ var StdioConnectionManager = class extends ConnectionManager {
5312
+ static {
5313
+ __name(this, "StdioConnectionManager");
5314
+ }
5315
+ serverParams;
5316
+ errlog;
5317
+ _transport = null;
5318
+ /**
5319
+ * Create a new stdio connection manager.
5320
+ *
5321
+ * @param serverParams Parameters for the stdio server process.
5322
+ * @param errlog Stream to which the server's stderr should be piped.
5323
+ * Defaults to `process.stderr`.
5324
+ */
5325
+ constructor(serverParams, errlog = process.stderr) {
5326
+ super();
5327
+ this.serverParams = serverParams;
5328
+ this.errlog = errlog;
5329
+ }
5330
+ /**
5331
+ * Establish the stdio connection by spawning the server process and starting
5332
+ * the SDK's transport. Returns the live `StdioClientTransport` instance.
5333
+ */
5334
+ async establishConnection() {
5335
+ this._transport = new import_stdio.StdioClientTransport(this.serverParams);
5336
+ if (this._transport.stderr && typeof this._transport.stderr.pipe === "function") {
5337
+ this._transport.stderr.pipe(
5338
+ this.errlog
5339
+ );
5340
+ }
5341
+ logger.debug(`${this.constructor.name} connected successfully`);
5342
+ return this._transport;
5343
+ }
5344
+ /**
5345
+ * Close the stdio connection, making sure the transport cleans up the child
5346
+ * process and associated resources.
5347
+ */
5348
+ async closeConnection(_connection) {
5349
+ if (this._transport) {
5350
+ try {
5351
+ await this._transport.close();
5352
+ } catch (e) {
5353
+ logger.warn(`Error closing stdio transport: ${e}`);
5354
+ } finally {
5355
+ this._transport = null;
5356
+ }
5357
+ }
5358
+ }
5359
+ };
5360
+
5361
+ // src/connectors/stdio.ts
5362
+ var StdioConnector = class extends BaseConnector {
5363
+ static {
5364
+ __name(this, "StdioConnector");
5365
+ }
5366
+ command;
5367
+ args;
5368
+ env;
5369
+ errlog;
5370
+ clientInfo;
5371
+ constructor({
5372
+ command = "npx",
5373
+ args = [],
5374
+ env,
5375
+ errlog = import_node_process.default.stderr,
5376
+ ...rest
5377
+ } = {}) {
5378
+ super(rest);
5379
+ this.command = command;
5380
+ this.args = args;
5381
+ this.env = env;
5382
+ this.errlog = errlog;
5383
+ this.clientInfo = rest.clientInfo ?? {
5384
+ name: "stdio-connector",
5385
+ version: "1.0.0"
5386
+ };
5387
+ }
5388
+ /** Establish connection to the MCP implementation. */
5389
+ async connect() {
5390
+ if (this.connected) {
5391
+ logger.debug("Already connected to MCP implementation");
5392
+ return;
5393
+ }
5394
+ logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
5395
+ try {
5396
+ let mergedEnv;
5397
+ if (this.env) {
5398
+ mergedEnv = {};
5399
+ for (const [key, value] of Object.entries(import_node_process.default.env)) {
5400
+ if (value !== void 0) {
5401
+ mergedEnv[key] = value;
5402
+ }
5403
+ }
5404
+ Object.assign(mergedEnv, this.env);
5405
+ }
5406
+ const serverParams = {
5407
+ command: this.command,
5408
+ args: this.args,
5409
+ env: mergedEnv
5410
+ };
5411
+ this.connectionManager = new StdioConnectionManager(
5412
+ serverParams,
5413
+ this.errlog
5414
+ );
5415
+ const transport = await this.connectionManager.start();
5416
+ const clientOptions = {
5417
+ ...this.opts.clientOptions || {},
5418
+ capabilities: {
5419
+ ...this.opts.clientOptions?.capabilities || {},
5420
+ roots: { listChanged: true },
5421
+ // Always advertise roots capability
5422
+ // Add sampling capability if callback is provided
5423
+ ...this.opts.samplingCallback ? { sampling: {} } : {},
5424
+ // Add elicitation capability if callback is provided
5425
+ ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
5426
+ }
5427
+ };
5428
+ this.client = new import_client2.Client(this.clientInfo, clientOptions);
5429
+ await this.client.connect(transport);
5430
+ this.connected = true;
5431
+ this.setupNotificationHandler();
5432
+ this.setupRootsHandler();
5433
+ this.setupSamplingHandler();
5434
+ this.setupElicitationHandler();
5435
+ logger.debug(
5436
+ `Successfully connected to MCP implementation: ${this.command}`
5437
+ );
5438
+ this.trackConnectorInit({
5439
+ serverCommand: this.command,
5440
+ serverArgs: this.args,
5441
+ publicIdentifier: `${this.command} ${this.args.join(" ")}`
5442
+ });
5443
+ } catch (err) {
5444
+ logger.error(`Failed to connect to MCP implementation: ${err}`);
5445
+ await this.cleanupResources();
5446
+ throw err;
5447
+ }
5448
+ }
5449
+ get publicIdentifier() {
5450
+ return {
5451
+ type: "stdio",
5452
+ "command&args": `${this.command} ${this.args.join(" ")}`
5453
+ };
5454
+ }
5455
+ };
5456
+
5457
+ // src/config.ts
5458
+ function loadConfigFile(filepath) {
5459
+ const raw = (0, import_node_fs.readFileSync)(filepath, "utf-8");
5460
+ return JSON.parse(raw);
5461
+ }
5462
+ __name(loadConfigFile, "loadConfigFile");
5463
+ function createConnectorFromConfig(serverConfig, connectorOptions) {
5464
+ if ("command" in serverConfig && "args" in serverConfig) {
5465
+ return new StdioConnector({
5466
+ command: serverConfig.command,
5467
+ args: serverConfig.args,
5468
+ env: serverConfig.env,
5469
+ ...connectorOptions
5470
+ });
5471
+ }
5472
+ if ("url" in serverConfig) {
5473
+ const transport = serverConfig.transport || "http";
5474
+ return new HttpConnector(serverConfig.url, {
5475
+ headers: serverConfig.headers,
5476
+ authToken: serverConfig.auth_token || serverConfig.authToken,
5477
+ // Only force SSE if explicitly requested
5478
+ preferSse: serverConfig.preferSse || transport === "sse",
5479
+ ...connectorOptions
5480
+ });
5481
+ }
5482
+ throw new Error("Cannot determine connector type from config");
5483
+ }
5484
+ __name(createConnectorFromConfig, "createConnectorFromConfig");
5485
+
5486
+ // src/client.ts
5487
+ init_logging();
5488
+ var MCPClient = class _MCPClient extends BaseMCPClient {
5489
+ static {
5490
+ __name(this, "MCPClient");
5491
+ }
5492
+ /**
5493
+ * Get the mcp-use package version.
5494
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
5495
+ */
5496
+ static getPackageVersion() {
5497
+ return getPackageVersion();
5498
+ }
5499
+ codeMode = false;
5500
+ _codeExecutor = null;
5501
+ _customCodeExecutor = null;
5502
+ _codeExecutorConfig = "vm";
5503
+ _executorOptions;
5504
+ _samplingCallback;
5505
+ _elicitationCallback;
5506
+ constructor(config, options) {
5507
+ if (config) {
5508
+ if (typeof config === "string") {
5509
+ super(loadConfigFile(config));
5510
+ } else {
5511
+ super(config);
5512
+ }
5513
+ } else {
5514
+ super();
5515
+ }
5516
+ let codeModeEnabled = false;
5517
+ let executorConfig = "vm";
5518
+ let executorOptions;
5519
+ if (options?.codeMode) {
5520
+ if (typeof options.codeMode === "boolean") {
5521
+ codeModeEnabled = options.codeMode;
5522
+ } else {
5523
+ codeModeEnabled = options.codeMode.enabled;
5524
+ executorConfig = options.codeMode.executor ?? "vm";
5525
+ executorOptions = options.codeMode.executorOptions;
5526
+ }
5527
+ }
5528
+ this.codeMode = codeModeEnabled;
5529
+ this._codeExecutorConfig = executorConfig;
5530
+ this._executorOptions = executorOptions;
5531
+ this._samplingCallback = options?.samplingCallback;
5532
+ this._elicitationCallback = options?.elicitationCallback;
5533
+ if (this.codeMode) {
5534
+ this._setupCodeModeConnector();
5535
+ }
5536
+ this._trackClientInit();
5537
+ }
5538
+ _trackClientInit() {
5539
+ const servers = Object.keys(this.config.mcpServers ?? {});
5540
+ const hasSamplingCallback = !!this._samplingCallback;
5541
+ const hasElicitationCallback = !!this._elicitationCallback;
5542
+ Tel.getInstance().trackMCPClientInit({
5543
+ codeMode: this.codeMode,
5544
+ sandbox: false,
5545
+ // Sandbox not supported in TS yet
5546
+ allCallbacks: hasSamplingCallback && hasElicitationCallback,
5547
+ verify: false,
5548
+ // No verify option in TS client
5549
+ servers,
5550
+ numServers: servers.length,
5551
+ isBrowser: false
5552
+ // Node.js MCPClient
5553
+ }).catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));
5554
+ }
5555
+ static fromDict(cfg, options) {
5556
+ return new _MCPClient(cfg, options);
5557
+ }
5558
+ static fromConfigFile(path2, options) {
5559
+ return new _MCPClient(loadConfigFile(path2), options);
5560
+ }
5561
+ /**
5562
+ * Save configuration to a file (Node.js only)
5563
+ */
5564
+ saveConfig(filepath) {
5565
+ const dir = import_node_path.default.dirname(filepath);
5566
+ if (!import_node_fs2.default.existsSync(dir)) {
5567
+ import_node_fs2.default.mkdirSync(dir, { recursive: true });
5568
+ }
5569
+ import_node_fs2.default.writeFileSync(filepath, JSON.stringify(this.config, null, 2), "utf-8");
5570
+ }
5571
+ /**
5572
+ * Create a connector from server configuration (Node.js version)
5573
+ * Supports all connector types including StdioConnector
5574
+ */
5575
+ createConnectorFromConfig(serverConfig) {
5576
+ return createConnectorFromConfig(serverConfig, {
5577
+ samplingCallback: this._samplingCallback,
5578
+ elicitationCallback: this._elicitationCallback
5579
+ });
5580
+ }
5581
+ _setupCodeModeConnector() {
5582
+ logger.debug("Code mode connector initialized as internal meta server");
5583
+ const connector = new CodeModeConnector(this);
5584
+ const session = new MCPSession(connector);
5585
+ this.sessions["code_mode"] = session;
5586
+ this.activeSessions.push("code_mode");
5587
+ }
5588
+ _ensureCodeExecutor() {
5589
+ if (!this._codeExecutor) {
5590
+ const config = this._codeExecutorConfig;
5591
+ if (config instanceof BaseCodeExecutor) {
5592
+ this._codeExecutor = config;
5593
+ } else if (typeof config === "function") {
5594
+ this._customCodeExecutor = config;
5595
+ throw new Error(
5596
+ "Custom executor function should be handled in executeCode"
5597
+ );
5598
+ } else if (config === "e2b") {
5599
+ const opts = this._executorOptions;
5600
+ if (!opts?.apiKey) {
5601
+ logger.warn("E2B executor requires apiKey. Falling back to VM.");
5602
+ try {
5603
+ this._codeExecutor = new VMCodeExecutor(
5604
+ this,
5605
+ this._executorOptions
5606
+ );
5607
+ } catch (error) {
5608
+ throw new Error(
5609
+ "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."
5610
+ );
5611
+ }
5612
+ } else {
5613
+ this._codeExecutor = new E2BCodeExecutor(this, opts);
5614
+ }
5615
+ } else {
5616
+ try {
5617
+ this._codeExecutor = new VMCodeExecutor(
5618
+ this,
5619
+ this._executorOptions
5620
+ );
5621
+ } catch (error) {
5622
+ const e2bOpts = this._executorOptions;
5623
+ const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;
5624
+ if (e2bApiKey) {
5625
+ logger.info(
5626
+ "VM executor not available in this environment. Falling back to E2B."
5627
+ );
5628
+ this._codeExecutor = new E2BCodeExecutor(this, {
5629
+ ...e2bOpts,
5630
+ apiKey: e2bApiKey
5631
+ });
5632
+ } else {
5633
+ throw new Error(
5634
+ "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."
5635
+ );
5636
+ }
5637
+ }
5638
+ }
5639
+ }
5640
+ return this._codeExecutor;
5641
+ }
5642
+ /**
5643
+ * Execute code in code mode
5644
+ */
5645
+ async executeCode(code, timeout) {
5646
+ if (!this.codeMode) {
5647
+ throw new Error("Code execution mode is not enabled");
5648
+ }
5649
+ if (this._customCodeExecutor) {
5650
+ return this._customCodeExecutor(code, timeout);
5651
+ }
5652
+ return this._ensureCodeExecutor().execute(code, timeout);
5653
+ }
5654
+ /**
5655
+ * Search available tools (used by code mode)
5656
+ */
5657
+ async searchTools(query = "", detailLevel = "full") {
5658
+ if (!this.codeMode) {
5659
+ throw new Error("Code execution mode is not enabled");
5660
+ }
5661
+ return this._ensureCodeExecutor().createSearchToolsFunction()(
5662
+ query,
5663
+ detailLevel
5664
+ );
5665
+ }
5666
+ /**
5667
+ * Override getServerNames to exclude internal code_mode server
5668
+ */
5669
+ getServerNames() {
5670
+ const isCodeModeEnabled = this.codeMode;
5671
+ return super.getServerNames().filter((name) => {
5672
+ return !isCodeModeEnabled || name !== "code_mode";
5673
+ });
5674
+ }
5675
+ /**
5676
+ * Close the client and clean up resources including code executors.
5677
+ * This ensures E2B sandboxes and other resources are properly released.
5678
+ */
5679
+ async close() {
5680
+ if (this._codeExecutor) {
5681
+ await this._codeExecutor.cleanup();
5682
+ this._codeExecutor = null;
5683
+ }
5684
+ await this.closeAllSessions();
5685
+ }
5686
+ };
5687
+
4555
5688
  // src/agents/mcp_agent.ts
4556
5689
  init_logging();
4557
5690
 
@@ -5216,6 +6349,26 @@ var import_zod8 = require("zod");
5216
6349
  init_logging();
5217
6350
  var API_CHATS_ENDPOINT = "/api/v1/chats";
5218
6351
  var API_CHAT_EXECUTE_ENDPOINT = "/api/v1/chats/{chat_id}/execute";
6352
+ function normalizeRemoteRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6353
+ if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
6354
+ const options = queryOrOptions;
6355
+ return {
6356
+ query: options.prompt,
6357
+ maxSteps: options.maxSteps,
6358
+ manageConnector: options.manageConnector,
6359
+ externalHistory: options.externalHistory,
6360
+ outputSchema: options.schema
6361
+ };
6362
+ }
6363
+ return {
6364
+ query: queryOrOptions,
6365
+ maxSteps,
6366
+ manageConnector,
6367
+ externalHistory,
6368
+ outputSchema
6369
+ };
6370
+ }
6371
+ __name(normalizeRemoteRunOptions, "normalizeRemoteRunOptions");
5219
6372
  var RemoteAgent = class {
5220
6373
  static {
5221
6374
  __name(this, "RemoteAgent");
@@ -5312,8 +6465,20 @@ var RemoteAgent = class {
5312
6465
  throw new Error(`Failed to create chat session: ${String(e)}`);
5313
6466
  }
5314
6467
  }
5315
- async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
5316
- if (externalHistory !== void 0) {
6468
+ async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6469
+ const {
6470
+ query,
6471
+ maxSteps: steps,
6472
+ externalHistory: history,
6473
+ outputSchema: schema
6474
+ } = normalizeRemoteRunOptions(
6475
+ queryOrOptions,
6476
+ maxSteps,
6477
+ manageConnector,
6478
+ externalHistory,
6479
+ outputSchema
6480
+ );
6481
+ if (history !== void 0) {
5317
6482
  logger.warn("External history is not yet supported for remote execution");
5318
6483
  }
5319
6484
  try {
@@ -5324,10 +6489,10 @@ var RemoteAgent = class {
5324
6489
  const chatId = this.chatId;
5325
6490
  const executionPayload = {
5326
6491
  query,
5327
- max_steps: maxSteps ?? 10
6492
+ max_steps: steps ?? 10
5328
6493
  };
5329
- if (outputSchema) {
5330
- executionPayload.output_schema = this.pydanticToJsonSchema(outputSchema);
6494
+ if (schema) {
6495
+ executionPayload.output_schema = this.pydanticToJsonSchema(schema);
5331
6496
  logger.info(`\u{1F527} Using structured output with schema`);
5332
6497
  }
5333
6498
  const headers = {
@@ -5401,8 +6566,8 @@ Raw error: ${result}`
5401
6566
  );
5402
6567
  }
5403
6568
  }
5404
- if (outputSchema) {
5405
- return this.parseStructuredResponse(result, outputSchema);
6569
+ if (schema) {
6570
+ return this.parseStructuredResponse(result, schema);
5406
6571
  }
5407
6572
  if (typeof result === "object" && result !== null && "result" in result) {
5408
6573
  return result.result;
@@ -5427,9 +6592,9 @@ Raw error: ${result}`
5427
6592
  }
5428
6593
  }
5429
6594
  // eslint-disable-next-line require-yield
5430
- async *stream(query, maxSteps, manageConnector, externalHistory, outputSchema) {
6595
+ async *stream(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
5431
6596
  const result = await this.run(
5432
- query,
6597
+ queryOrOptions,
5433
6598
  maxSteps,
5434
6599
  manageConnector,
5435
6600
  externalHistory,
@@ -5442,7 +6607,166 @@ Raw error: ${result}`
5442
6607
  }
5443
6608
  };
5444
6609
 
6610
+ // src/agents/utils/llm_provider.ts
6611
+ init_logging();
6612
+ var PROVIDER_CONFIG = {
6613
+ openai: {
6614
+ package: "@langchain/openai",
6615
+ className: "ChatOpenAI",
6616
+ envVars: ["OPENAI_API_KEY"],
6617
+ defaultModel: "gpt-4o"
6618
+ },
6619
+ anthropic: {
6620
+ package: "@langchain/anthropic",
6621
+ className: "ChatAnthropic",
6622
+ envVars: ["ANTHROPIC_API_KEY"],
6623
+ defaultModel: "claude-3-5-sonnet-20241022"
6624
+ },
6625
+ google: {
6626
+ package: "@langchain/google-genai",
6627
+ className: "ChatGoogleGenerativeAI",
6628
+ envVars: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
6629
+ defaultModel: "gemini-pro"
6630
+ },
6631
+ groq: {
6632
+ package: "@langchain/groq",
6633
+ className: "ChatGroq",
6634
+ envVars: ["GROQ_API_KEY"],
6635
+ defaultModel: "llama-3.1-70b-versatile"
6636
+ }
6637
+ };
6638
+ function parseLLMString(llmString) {
6639
+ const parts = llmString.split("/");
6640
+ if (parts.length !== 2) {
6641
+ throw new Error(
6642
+ `Invalid LLM string format. Expected 'provider/model', got '${llmString}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`
6643
+ );
6644
+ }
6645
+ const [provider, model] = parts;
6646
+ if (!provider || !model) {
6647
+ throw new Error(
6648
+ `Invalid LLM string format. Both provider and model must be non-empty. Got '${llmString}'`
6649
+ );
6650
+ }
6651
+ const normalizedProvider = provider.toLowerCase();
6652
+ if (!(normalizedProvider in PROVIDER_CONFIG)) {
6653
+ const supportedProviders = Object.keys(PROVIDER_CONFIG).join(", ");
6654
+ throw new Error(
6655
+ `Unsupported LLM provider '${provider}'. Supported providers: ${supportedProviders}`
6656
+ );
6657
+ }
6658
+ return { provider: normalizedProvider, model };
6659
+ }
6660
+ __name(parseLLMString, "parseLLMString");
6661
+ function getAPIKey(provider, config) {
6662
+ if (config?.apiKey) {
6663
+ return config.apiKey;
6664
+ }
6665
+ const providerConfig = PROVIDER_CONFIG[provider];
6666
+ for (const envVar of providerConfig.envVars) {
6667
+ const apiKey = process.env[envVar];
6668
+ if (apiKey) {
6669
+ logger.debug(
6670
+ `Using API key from environment variable ${envVar} for provider ${provider}`
6671
+ );
6672
+ return apiKey;
6673
+ }
6674
+ }
6675
+ const envVarsStr = providerConfig.envVars.join(" or ");
6676
+ throw new Error(
6677
+ `API key not found for provider '${provider}'. Set ${envVarsStr} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${provider}/model', llmConfig: { apiKey: 'your-key' } })`
6678
+ );
6679
+ }
6680
+ __name(getAPIKey, "getAPIKey");
6681
+ async function createLLMFromString(llmString, config) {
6682
+ logger.info(`Creating LLM from string: ${llmString}`);
6683
+ const { provider, model } = parseLLMString(llmString);
6684
+ const providerConfig = PROVIDER_CONFIG[provider];
6685
+ const apiKey = getAPIKey(provider, config);
6686
+ let providerModule;
6687
+ try {
6688
+ logger.debug(`Importing package ${providerConfig.package}...`);
6689
+ providerModule = await import(providerConfig.package);
6690
+ } catch (error) {
6691
+ if (error?.code === "MODULE_NOT_FOUND" || error?.message?.includes("Cannot find module") || error?.message?.includes("Cannot find package")) {
6692
+ throw new Error(
6693
+ `Package '${providerConfig.package}' is not installed. Install it with: npm install ${providerConfig.package} or yarn add ${providerConfig.package}`
6694
+ );
6695
+ }
6696
+ throw new Error(
6697
+ `Failed to import ${providerConfig.package}: ${error?.message || error}`
6698
+ );
6699
+ }
6700
+ const LLMClass = providerModule[providerConfig.className];
6701
+ if (!LLMClass) {
6702
+ throw new Error(
6703
+ `Could not find ${providerConfig.className} in package ${providerConfig.package}. This might be a version compatibility issue.`
6704
+ );
6705
+ }
6706
+ const llmConfig = {
6707
+ model,
6708
+ apiKey,
6709
+ ...config
6710
+ };
6711
+ if (config?.apiKey) {
6712
+ delete llmConfig.apiKey;
6713
+ llmConfig.apiKey = apiKey;
6714
+ }
6715
+ if (provider === "anthropic") {
6716
+ llmConfig.model = model;
6717
+ } else if (provider === "google") {
6718
+ llmConfig.model = model;
6719
+ } else if (provider === "openai") {
6720
+ llmConfig.model = model;
6721
+ } else if (provider === "groq") {
6722
+ llmConfig.model = model;
6723
+ }
6724
+ try {
6725
+ const llmInstance = new LLMClass(llmConfig);
6726
+ logger.info(`Successfully created ${provider} LLM with model ${model}`);
6727
+ return llmInstance;
6728
+ } catch (error) {
6729
+ throw new Error(
6730
+ `Failed to instantiate ${providerConfig.className} with model '${model}': ${error?.message || error}`
6731
+ );
6732
+ }
6733
+ }
6734
+ __name(createLLMFromString, "createLLMFromString");
6735
+ function isValidLLMString(llmString) {
6736
+ try {
6737
+ parseLLMString(llmString);
6738
+ return true;
6739
+ } catch {
6740
+ return false;
6741
+ }
6742
+ }
6743
+ __name(isValidLLMString, "isValidLLMString");
6744
+ function getSupportedProviders() {
6745
+ return Object.keys(PROVIDER_CONFIG);
6746
+ }
6747
+ __name(getSupportedProviders, "getSupportedProviders");
6748
+
5445
6749
  // src/agents/mcp_agent.ts
6750
+ function normalizeRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6751
+ if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
6752
+ const options = queryOrOptions;
6753
+ return {
6754
+ query: options.prompt,
6755
+ maxSteps: options.maxSteps,
6756
+ manageConnector: options.manageConnector,
6757
+ externalHistory: options.externalHistory,
6758
+ outputSchema: options.schema
6759
+ };
6760
+ }
6761
+ return {
6762
+ query: queryOrOptions,
6763
+ maxSteps,
6764
+ manageConnector,
6765
+ externalHistory,
6766
+ outputSchema
6767
+ };
6768
+ }
6769
+ __name(normalizeRunOptions, "normalizeRunOptions");
5446
6770
  var MCPAgent = class {
5447
6771
  static {
5448
6772
  __name(this, "MCPAgent");
@@ -5488,6 +6812,12 @@ var MCPAgent = class {
5488
6812
  // Remote agent support
5489
6813
  isRemote = false;
5490
6814
  remoteAgent = null;
6815
+ // Simplified mode support
6816
+ isSimplifiedMode = false;
6817
+ llmString;
6818
+ llmConfig;
6819
+ mcpServersConfig;
6820
+ clientOwnedByAgent = false;
5491
6821
  constructor(options) {
5492
6822
  if (options.agentId) {
5493
6823
  this.isRemote = true;
@@ -5521,9 +6851,36 @@ var MCPAgent = class {
5521
6851
  "llm is required for local execution. For remote execution, provide agentId instead."
5522
6852
  );
5523
6853
  }
5524
- this.llm = options.llm;
5525
- this.client = options.client;
5526
- this.connectors = options.connectors ?? [];
6854
+ const isSimplifiedMode = typeof options.llm === "string";
6855
+ if (isSimplifiedMode) {
6856
+ this.isSimplifiedMode = true;
6857
+ this.llmString = options.llm;
6858
+ this.llmConfig = options.llmConfig;
6859
+ this.mcpServersConfig = options.mcpServers;
6860
+ if (!this.mcpServersConfig || Object.keys(this.mcpServersConfig).length === 0) {
6861
+ throw new Error(
6862
+ "Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }"
6863
+ );
6864
+ }
6865
+ this.llm = void 0;
6866
+ this.client = void 0;
6867
+ this.clientOwnedByAgent = true;
6868
+ this.connectors = [];
6869
+ logger.info(
6870
+ `\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`
6871
+ );
6872
+ } else {
6873
+ this.isSimplifiedMode = false;
6874
+ this.llm = options.llm;
6875
+ this.client = options.client;
6876
+ this.connectors = options.connectors ?? [];
6877
+ this.clientOwnedByAgent = false;
6878
+ if (!this.client && this.connectors.length === 0) {
6879
+ throw new Error(
6880
+ "Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config."
6881
+ );
6882
+ }
6883
+ }
5527
6884
  this.maxSteps = options.maxSteps ?? 5;
5528
6885
  this.autoInitialize = options.autoInitialize ?? false;
5529
6886
  this.memoryEnabled = options.memoryEnabled ?? true;
@@ -5536,28 +6893,30 @@ var MCPAgent = class {
5536
6893
  this.useServerManager = options.useServerManager ?? false;
5537
6894
  this.verbose = options.verbose ?? false;
5538
6895
  this.observe = options.observe ?? true;
5539
- if (!this.client && this.connectors.length === 0) {
5540
- throw new Error(
5541
- "Either 'client' or at least one 'connector' must be provided."
5542
- );
5543
- }
5544
- if (this.useServerManager) {
5545
- if (!this.client) {
5546
- throw new Error(
5547
- "'client' must be provided when 'useServerManager' is true."
5548
- );
6896
+ if (!this.isSimplifiedMode) {
6897
+ if (this.useServerManager) {
6898
+ if (!this.client) {
6899
+ throw new Error(
6900
+ "'client' must be provided when 'useServerManager' is true."
6901
+ );
6902
+ }
6903
+ this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
6904
+ this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
6905
+ } else {
6906
+ this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
6907
+ }
6908
+ this.telemetry = Telemetry.getInstance();
6909
+ if (this.llm) {
6910
+ const [provider, name] = extractModelInfo(this.llm);
6911
+ this.modelProvider = provider;
6912
+ this.modelName = name;
6913
+ } else {
6914
+ this.modelProvider = "unknown";
6915
+ this.modelName = "unknown";
5549
6916
  }
5550
- this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
5551
- this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
5552
6917
  } else {
5553
6918
  this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
5554
- }
5555
- this.telemetry = Telemetry.getInstance();
5556
- if (this.llm) {
5557
- const [provider, name] = extractModelInfo(this.llm);
5558
- this.modelProvider = provider;
5559
- this.modelName = name;
5560
- } else {
6919
+ this.telemetry = Telemetry.getInstance();
5561
6920
  this.modelProvider = "unknown";
5562
6921
  this.modelName = "unknown";
5563
6922
  }
@@ -5588,6 +6947,40 @@ var MCPAgent = class {
5588
6947
  return;
5589
6948
  }
5590
6949
  logger.info("\u{1F680} Initializing MCP agent and connecting to services...");
6950
+ if (this.isSimplifiedMode) {
6951
+ logger.info(
6952
+ "\u{1F3AF} Simplified mode: Creating client and LLM from configuration..."
6953
+ );
6954
+ if (this.mcpServersConfig) {
6955
+ logger.info(
6956
+ `Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`
6957
+ );
6958
+ this.client = new MCPClient({ mcpServers: this.mcpServersConfig });
6959
+ logger.info("\u2705 MCPClient created successfully");
6960
+ }
6961
+ if (this.llmString) {
6962
+ logger.info(`Creating LLM from string: ${this.llmString}...`);
6963
+ try {
6964
+ this.llm = await createLLMFromString(this.llmString, this.llmConfig);
6965
+ logger.info("\u2705 LLM created successfully");
6966
+ const [provider, name] = extractModelInfo(this.llm);
6967
+ this.modelProvider = provider;
6968
+ this.modelName = name;
6969
+ } catch (error) {
6970
+ throw new Error(
6971
+ `Failed to create LLM from string '${this.llmString}': ${error?.message || error}`
6972
+ );
6973
+ }
6974
+ }
6975
+ if (this.useServerManager) {
6976
+ if (!this.client) {
6977
+ throw new Error(
6978
+ "'client' must be available when 'useServerManager' is true."
6979
+ );
6980
+ }
6981
+ this.serverManager = new ServerManager(this.client, this.adapter);
6982
+ }
6983
+ }
5591
6984
  this.callbacks = await this.observabilityManager.getCallbacks();
5592
6985
  const handlerNames = await this.observabilityManager.getHandlerNames();
5593
6986
  if (handlerNames.length > 0) {
@@ -6130,33 +7523,47 @@ var MCPAgent = class {
6130
7523
  }
6131
7524
  }
6132
7525
  }
6133
- async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
6134
- if (this.isRemote && this.remoteAgent) {
6135
- return this.remoteAgent.run(
6136
- query,
6137
- maxSteps,
6138
- manageConnector,
6139
- externalHistory,
6140
- outputSchema
6141
- );
6142
- }
6143
- const generator = this.stream(
7526
+ async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
7527
+ const {
6144
7528
  query,
7529
+ maxSteps: steps,
7530
+ manageConnector: manage,
7531
+ externalHistory: history,
7532
+ outputSchema: schema
7533
+ } = normalizeRunOptions(
7534
+ queryOrOptions,
6145
7535
  maxSteps,
6146
7536
  manageConnector,
6147
7537
  externalHistory,
6148
7538
  outputSchema
6149
7539
  );
7540
+ if (this.isRemote && this.remoteAgent) {
7541
+ return this.remoteAgent.run(query, steps, manage, history, schema);
7542
+ }
7543
+ const generator = this.stream(query, steps, manage, history, schema);
6150
7544
  return this._consumeAndReturn(generator);
6151
7545
  }
6152
- async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7546
+ async *stream(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7547
+ const {
7548
+ query,
7549
+ maxSteps: steps,
7550
+ manageConnector: manage,
7551
+ externalHistory: history,
7552
+ outputSchema: schema
7553
+ } = normalizeRunOptions(
7554
+ queryOrOptions,
7555
+ maxSteps,
7556
+ manageConnector,
7557
+ externalHistory,
7558
+ outputSchema
7559
+ );
6153
7560
  if (this.isRemote && this.remoteAgent) {
6154
7561
  const result = await this.remoteAgent.run(
6155
7562
  query,
6156
- maxSteps,
6157
- manageConnector,
6158
- externalHistory,
6159
- outputSchema
7563
+ steps,
7564
+ manage,
7565
+ history,
7566
+ schema
6160
7567
  );
6161
7568
  return result;
6162
7569
  }
@@ -6166,7 +7573,7 @@ var MCPAgent = class {
6166
7573
  let finalOutput = null;
6167
7574
  let stepsTaken = 0;
6168
7575
  try {
6169
- if (manageConnector && !this._initialized) {
7576
+ if (manage && !this._initialized) {
6170
7577
  await this.initialize();
6171
7578
  initializedHere = true;
6172
7579
  } else if (!this._initialized && this.autoInitialize) {
@@ -6190,7 +7597,7 @@ var MCPAgent = class {
6190
7597
  this._agentExecutor = this.createAgent();
6191
7598
  }
6192
7599
  }
6193
- const historyToUse = externalHistory ?? this.conversationHistory;
7600
+ const historyToUse = history ?? this.conversationHistory;
6194
7601
  const langchainHistory = [];
6195
7602
  for (const msg of historyToUse) {
6196
7603
  if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
@@ -6331,13 +7738,13 @@ var MCPAgent = class {
6331
7738
  this.addToHistory(msg);
6332
7739
  }
6333
7740
  }
6334
- if (outputSchema && finalOutput) {
7741
+ if (schema && finalOutput) {
6335
7742
  try {
6336
7743
  logger.info("\u{1F527} Attempting structured output...");
6337
7744
  const structuredResult = await this._attemptStructuredOutput(
6338
7745
  finalOutput,
6339
7746
  this.llm,
6340
- outputSchema
7747
+ schema
6341
7748
  );
6342
7749
  if (this.memoryEnabled) {
6343
7750
  this.addToHistory(
@@ -6363,7 +7770,7 @@ var MCPAgent = class {
6363
7770
  return finalOutput || "No output generated";
6364
7771
  } catch (e) {
6365
7772
  logger.error(`\u274C Error running query: ${e}`);
6366
- if (initializedHere && manageConnector) {
7773
+ if (initializedHere && manage) {
6367
7774
  logger.info("\u{1F9F9} Cleaning up resources after error");
6368
7775
  await this.close();
6369
7776
  }
@@ -6393,9 +7800,9 @@ var MCPAgent = class {
6393
7800
  maxStepsConfigured: this.maxSteps,
6394
7801
  memoryEnabled: this.memoryEnabled,
6395
7802
  useServerManager: this.useServerManager,
6396
- maxStepsUsed: maxSteps ?? null,
6397
- manageConnector,
6398
- externalHistoryUsed: externalHistory !== void 0,
7803
+ maxStepsUsed: steps ?? null,
7804
+ manageConnector: manage ?? true,
7805
+ externalHistoryUsed: history !== void 0,
6399
7806
  stepsTaken,
6400
7807
  toolsUsedCount: this.toolsUsedNames.length,
6401
7808
  toolsUsedNames: this.toolsUsedNames,
@@ -6404,7 +7811,7 @@ var MCPAgent = class {
6404
7811
  errorType: success ? null : "execution_error",
6405
7812
  conversationHistoryLength
6406
7813
  });
6407
- if (manageConnector && !this.client && initializedHere) {
7814
+ if (manage && !this.client && initializedHere) {
6408
7815
  logger.info("\u{1F9F9} Closing agent after stream completion");
6409
7816
  await this.close();
6410
7817
  }
@@ -6432,15 +7839,28 @@ var MCPAgent = class {
6432
7839
  this._agentExecutor = null;
6433
7840
  this._tools = [];
6434
7841
  if (this.client) {
6435
- logger.info("\u{1F504} Closing client and cleaning up resources");
6436
- await this.client.close();
6437
- this.sessions = {};
7842
+ if (this.clientOwnedByAgent) {
7843
+ logger.info(
7844
+ "\u{1F504} Closing internally-created client (simplified mode) and cleaning up resources"
7845
+ );
7846
+ await this.client.close();
7847
+ this.sessions = {};
7848
+ this.client = void 0;
7849
+ } else {
7850
+ logger.info("\u{1F504} Closing client and cleaning up resources");
7851
+ await this.client.close();
7852
+ this.sessions = {};
7853
+ }
6438
7854
  } else {
6439
7855
  for (const connector of this.connectors) {
6440
7856
  logger.info("\u{1F504} Disconnecting connector");
6441
7857
  await connector.disconnect();
6442
7858
  }
6443
7859
  }
7860
+ if (this.isSimplifiedMode && this.llm) {
7861
+ logger.debug("\u{1F504} Clearing LLM reference (simplified mode)");
7862
+ this.llm = void 0;
7863
+ }
6444
7864
  if ("connectorToolMap" in this.adapter) {
6445
7865
  this.adapter = new LangChainAdapter();
6446
7866
  }
@@ -6449,16 +7869,12 @@ var MCPAgent = class {
6449
7869
  logger.info("\u{1F44B} Agent closed successfully");
6450
7870
  }
6451
7871
  }
6452
- /**
6453
- * Yields with pretty-printed output for code mode.
6454
- * This method formats and displays tool executions in a user-friendly way with syntax highlighting.
6455
- */
6456
- async *prettyStreamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7872
+ async *prettyStreamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
6457
7873
  const { prettyStreamEvents: prettyStream } = await Promise.resolve().then(() => (init_display(), display_exports));
6458
7874
  const finalResponse = "";
6459
7875
  for await (const _ of prettyStream(
6460
7876
  this.streamEvents(
6461
- query,
7877
+ queryOrOptions,
6462
7878
  maxSteps,
6463
7879
  manageConnector,
6464
7880
  externalHistory,
@@ -6469,22 +7885,32 @@ var MCPAgent = class {
6469
7885
  }
6470
7886
  return finalResponse;
6471
7887
  }
6472
- /**
6473
- * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
6474
- * This provides token-level streaming and fine-grained event updates.
6475
- */
6476
- async *streamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7888
+ async *streamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7889
+ const normalized = normalizeRunOptions(
7890
+ queryOrOptions,
7891
+ maxSteps,
7892
+ manageConnector,
7893
+ externalHistory,
7894
+ outputSchema
7895
+ );
7896
+ let { query } = normalized;
7897
+ const {
7898
+ maxSteps: steps,
7899
+ manageConnector: manage,
7900
+ externalHistory: history,
7901
+ outputSchema: schema
7902
+ } = normalized;
6477
7903
  let initializedHere = false;
6478
7904
  const startTime = Date.now();
6479
7905
  let success = false;
6480
7906
  let eventCount = 0;
6481
7907
  let totalResponseLength = 0;
6482
7908
  let finalResponse = "";
6483
- if (outputSchema) {
6484
- query = this._enhanceQueryWithSchema(query, outputSchema);
7909
+ if (schema) {
7910
+ query = this._enhanceQueryWithSchema(query, schema);
6485
7911
  }
6486
7912
  try {
6487
- if (manageConnector && !this._initialized) {
7913
+ if (manage && !this._initialized) {
6488
7914
  await this.initialize();
6489
7915
  initializedHere = true;
6490
7916
  } else if (!this._initialized && this.autoInitialize) {
@@ -6495,14 +7921,14 @@ var MCPAgent = class {
6495
7921
  if (!agentExecutor) {
6496
7922
  throw new Error("MCP agent failed to initialize");
6497
7923
  }
6498
- this.maxSteps = maxSteps ?? this.maxSteps;
7924
+ this.maxSteps = steps ?? this.maxSteps;
6499
7925
  const display_query = typeof query === "string" && query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, " ")}...` : typeof query === "string" ? query.replace(/\n/g, " ") : String(query);
6500
7926
  logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
6501
7927
  if (this.memoryEnabled) {
6502
7928
  logger.info(`\u{1F504} Adding user message to history: ${display_query}`);
6503
7929
  this.addToHistory(new import_langchain2.HumanMessage({ content: query }));
6504
7930
  }
6505
- const historyToUse = externalHistory ?? this.conversationHistory;
7931
+ const historyToUse = history ?? this.conversationHistory;
6506
7932
  const langchainHistory = [];
6507
7933
  for (const msg of historyToUse) {
6508
7934
  if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
@@ -6569,17 +7995,13 @@ var MCPAgent = class {
6569
7995
  }
6570
7996
  }
6571
7997
  }
6572
- if (outputSchema && finalResponse) {
7998
+ if (schema && finalResponse) {
6573
7999
  logger.info("\u{1F527} Attempting structured output conversion...");
6574
8000
  try {
6575
8001
  let conversionCompleted = false;
6576
8002
  let conversionResult = null;
6577
8003
  let conversionError = null;
6578
- this._attemptStructuredOutput(
6579
- finalResponse,
6580
- this.llm,
6581
- outputSchema
6582
- ).then((result) => {
8004
+ this._attemptStructuredOutput(finalResponse, this.llm, schema).then((result) => {
6583
8005
  conversionCompleted = true;
6584
8006
  conversionResult = result;
6585
8007
  return result;
@@ -6634,7 +8056,7 @@ var MCPAgent = class {
6634
8056
  success = true;
6635
8057
  } catch (e) {
6636
8058
  logger.error(`\u274C Error during streamEvents: ${e}`);
6637
- if (initializedHere && manageConnector) {
8059
+ if (initializedHere && manage) {
6638
8060
  logger.info(
6639
8061
  "\u{1F9F9} Cleaning up resources after initialization error in streamEvents"
6640
8062
  );
@@ -6665,15 +8087,15 @@ var MCPAgent = class {
6665
8087
  maxStepsConfigured: this.maxSteps,
6666
8088
  memoryEnabled: this.memoryEnabled,
6667
8089
  useServerManager: this.useServerManager,
6668
- maxStepsUsed: maxSteps ?? null,
6669
- manageConnector,
6670
- externalHistoryUsed: externalHistory !== void 0,
8090
+ maxStepsUsed: steps ?? null,
8091
+ manageConnector: manage ?? true,
8092
+ externalHistoryUsed: history !== void 0,
6671
8093
  response: `[STREAMED RESPONSE - ${totalResponseLength} chars]`,
6672
8094
  executionTimeMs,
6673
8095
  errorType: success ? null : "streaming_error",
6674
8096
  conversationHistoryLength
6675
8097
  });
6676
- if (manageConnector && !this.client && initializedHere) {
8098
+ if (manage && !this.client && initializedHere) {
6677
8099
  logger.info("\u{1F9F9} Closing agent after streamEvents completion");
6678
8100
  await this.close();
6679
8101
  }