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
  }
@@ -1417,7 +1417,7 @@ __name(generateUUID, "generateUUID");
1417
1417
  init_logging();
1418
1418
 
1419
1419
  // src/version.ts
1420
- var VERSION = "1.11.0-canary.3";
1420
+ var VERSION = "1.11.0-canary.4";
1421
1421
  function getPackageVersion() {
1422
1422
  return VERSION;
1423
1423
  }
@@ -1738,26 +1738,26 @@ var Telemetry = class _Telemetry {
1738
1738
  * Get or create user ID from filesystem (Node.js/Bun)
1739
1739
  */
1740
1740
  _getUserIdFromFilesystem() {
1741
- const fs = require("fs");
1741
+ const fs2 = require("fs");
1742
1742
  const os = require("os");
1743
- const path = require("path");
1743
+ const path2 = require("path");
1744
1744
  if (!this._userIdPath) {
1745
- this._userIdPath = path.join(
1746
- this._getCacheHome(os, path),
1745
+ this._userIdPath = path2.join(
1746
+ this._getCacheHome(os, path2),
1747
1747
  "mcp_use_3",
1748
1748
  "telemetry_user_id"
1749
1749
  );
1750
1750
  }
1751
- const isFirstTime = !fs.existsSync(this._userIdPath);
1751
+ const isFirstTime = !fs2.existsSync(this._userIdPath);
1752
1752
  if (isFirstTime) {
1753
1753
  logger.debug(`Creating user ID path: ${this._userIdPath}`);
1754
- fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1754
+ fs2.mkdirSync(path2.dirname(this._userIdPath), { recursive: true });
1755
1755
  const newUserId = generateUUID();
1756
- fs.writeFileSync(this._userIdPath, newUserId);
1756
+ fs2.writeFileSync(this._userIdPath, newUserId);
1757
1757
  logger.debug(`User ID path created: ${this._userIdPath}`);
1758
1758
  return newUserId;
1759
1759
  }
1760
- return fs.readFileSync(this._userIdPath, "utf-8").trim();
1760
+ return fs2.readFileSync(this._userIdPath, "utf-8").trim();
1761
1761
  }
1762
1762
  /**
1763
1763
  * Get or create user ID from localStorage (Browser)
@@ -1776,9 +1776,9 @@ var Telemetry = class _Telemetry {
1776
1776
  return `session-${generateUUID()}`;
1777
1777
  }
1778
1778
  }
1779
- _getCacheHome(os, path) {
1779
+ _getCacheHome(os, path2) {
1780
1780
  const envVar = process.env.XDG_CACHE_HOME;
1781
- if (envVar && path.isAbsolute(envVar)) {
1781
+ if (envVar && path2.isAbsolute(envVar)) {
1782
1782
  return envVar;
1783
1783
  }
1784
1784
  const platform = process.platform;
@@ -1788,11 +1788,11 @@ var Telemetry = class _Telemetry {
1788
1788
  if (appdata) {
1789
1789
  return appdata;
1790
1790
  }
1791
- return path.join(homeDir, "AppData", "Local");
1791
+ return path2.join(homeDir, "AppData", "Local");
1792
1792
  } else if (platform === "darwin") {
1793
- return path.join(homeDir, "Library", "Caches");
1793
+ return path2.join(homeDir, "Library", "Caches");
1794
1794
  } else {
1795
- return path.join(homeDir, ".cache");
1795
+ return path2.join(homeDir, ".cache");
1796
1796
  }
1797
1797
  }
1798
1798
  async capture(event) {
@@ -1866,12 +1866,12 @@ var Telemetry = class _Telemetry {
1866
1866
  return;
1867
1867
  }
1868
1868
  try {
1869
- const fs = require("fs");
1870
- const path = require("path");
1869
+ const fs2 = require("fs");
1870
+ const path2 = require("path");
1871
1871
  const os = require("os");
1872
1872
  if (!this._versionDownloadPath) {
1873
- this._versionDownloadPath = path.join(
1874
- this._getCacheHome(os, path),
1873
+ this._versionDownloadPath = path2.join(
1874
+ this._getCacheHome(os, path2),
1875
1875
  "mcp_use",
1876
1876
  "download_version"
1877
1877
  );
@@ -1879,19 +1879,19 @@ var Telemetry = class _Telemetry {
1879
1879
  const currentVersion = getPackageVersion();
1880
1880
  let shouldTrack = false;
1881
1881
  let firstDownload = false;
1882
- if (!fs.existsSync(this._versionDownloadPath)) {
1882
+ if (!fs2.existsSync(this._versionDownloadPath)) {
1883
1883
  shouldTrack = true;
1884
1884
  firstDownload = true;
1885
- fs.mkdirSync(path.dirname(this._versionDownloadPath), {
1885
+ fs2.mkdirSync(path2.dirname(this._versionDownloadPath), {
1886
1886
  recursive: true
1887
1887
  });
1888
- fs.writeFileSync(this._versionDownloadPath, currentVersion);
1888
+ fs2.writeFileSync(this._versionDownloadPath, currentVersion);
1889
1889
  } else {
1890
- const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
1890
+ const savedVersion = fs2.readFileSync(this._versionDownloadPath, "utf-8").trim();
1891
1891
  if (currentVersion > savedVersion) {
1892
1892
  shouldTrack = true;
1893
1893
  firstDownload = false;
1894
- fs.writeFileSync(this._versionDownloadPath, currentVersion);
1894
+ fs2.writeFileSync(this._versionDownloadPath, currentVersion);
1895
1895
  }
1896
1896
  }
1897
1897
  if (shouldTrack) {
@@ -2084,6 +2084,480 @@ var Telemetry = class _Telemetry {
2084
2084
  }
2085
2085
  }
2086
2086
  };
2087
+ var Tel = Telemetry;
2088
+
2089
+ // src/connectors/base.ts
2090
+ var BaseConnector = class {
2091
+ static {
2092
+ __name(this, "BaseConnector");
2093
+ }
2094
+ client = null;
2095
+ connectionManager = null;
2096
+ toolsCache = null;
2097
+ capabilitiesCache = null;
2098
+ serverInfoCache = null;
2099
+ connected = false;
2100
+ opts;
2101
+ notificationHandlers = [];
2102
+ rootsCache = [];
2103
+ constructor(opts = {}) {
2104
+ this.opts = opts;
2105
+ if (opts.roots) {
2106
+ this.rootsCache = [...opts.roots];
2107
+ }
2108
+ }
2109
+ /**
2110
+ * Track connector initialization event
2111
+ * Should be called by subclasses after successful connection
2112
+ */
2113
+ trackConnectorInit(data) {
2114
+ const connectorType = this.constructor.name;
2115
+ Telemetry.getInstance().trackConnectorInit({
2116
+ connectorType,
2117
+ ...data
2118
+ }).catch((e) => logger.debug(`Failed to track connector init: ${e}`));
2119
+ }
2120
+ /**
2121
+ * Register a handler for server notifications
2122
+ *
2123
+ * @param handler - Function to call when a notification is received
2124
+ *
2125
+ * @example
2126
+ * ```typescript
2127
+ * connector.onNotification((notification) => {
2128
+ * console.log(`Received: ${notification.method}`, notification.params);
2129
+ * });
2130
+ * ```
2131
+ */
2132
+ onNotification(handler) {
2133
+ this.notificationHandlers.push(handler);
2134
+ if (this.client) {
2135
+ this.setupNotificationHandler();
2136
+ }
2137
+ }
2138
+ /**
2139
+ * Internal: wire notification handlers to the SDK client
2140
+ * Includes automatic handling for list_changed notifications per MCP spec
2141
+ */
2142
+ setupNotificationHandler() {
2143
+ if (!this.client) return;
2144
+ this.client.fallbackNotificationHandler = async (notification) => {
2145
+ switch (notification.method) {
2146
+ case "notifications/tools/list_changed":
2147
+ await this.refreshToolsCache();
2148
+ break;
2149
+ case "notifications/resources/list_changed":
2150
+ await this.onResourcesListChanged();
2151
+ break;
2152
+ case "notifications/prompts/list_changed":
2153
+ await this.onPromptsListChanged();
2154
+ break;
2155
+ default:
2156
+ break;
2157
+ }
2158
+ for (const handler of this.notificationHandlers) {
2159
+ try {
2160
+ await handler(notification);
2161
+ } catch (err) {
2162
+ logger.error("Error in notification handler:", err);
2163
+ }
2164
+ }
2165
+ };
2166
+ }
2167
+ /**
2168
+ * Auto-refresh tools cache when server sends tools/list_changed notification
2169
+ */
2170
+ async refreshToolsCache() {
2171
+ if (!this.client) return;
2172
+ try {
2173
+ logger.debug(
2174
+ "[Auto] Refreshing tools cache due to list_changed notification"
2175
+ );
2176
+ const result = await this.client.listTools();
2177
+ this.toolsCache = result.tools ?? [];
2178
+ logger.debug(
2179
+ `[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`
2180
+ );
2181
+ } catch (err) {
2182
+ logger.warn("[Auto] Failed to refresh tools cache:", err);
2183
+ }
2184
+ }
2185
+ /**
2186
+ * Called when server sends resources/list_changed notification
2187
+ * Resources aren't cached by default, but we log for user awareness
2188
+ */
2189
+ async onResourcesListChanged() {
2190
+ logger.debug(
2191
+ "[Auto] Resources list changed - clients should re-fetch if needed"
2192
+ );
2193
+ }
2194
+ /**
2195
+ * Called when server sends prompts/list_changed notification
2196
+ * Prompts aren't cached by default, but we log for user awareness
2197
+ */
2198
+ async onPromptsListChanged() {
2199
+ logger.debug(
2200
+ "[Auto] Prompts list changed - clients should re-fetch if needed"
2201
+ );
2202
+ }
2203
+ /**
2204
+ * Set roots and notify the server.
2205
+ * Roots represent directories or files that the client has access to.
2206
+ *
2207
+ * @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
2208
+ *
2209
+ * @example
2210
+ * ```typescript
2211
+ * await connector.setRoots([
2212
+ * { uri: "file:///home/user/project", name: "My Project" },
2213
+ * { uri: "file:///home/user/data" }
2214
+ * ]);
2215
+ * ```
2216
+ */
2217
+ async setRoots(roots) {
2218
+ this.rootsCache = [...roots];
2219
+ if (this.client) {
2220
+ logger.debug(
2221
+ `Sending roots/list_changed notification with ${roots.length} root(s)`
2222
+ );
2223
+ await this.client.sendRootsListChanged();
2224
+ }
2225
+ }
2226
+ /**
2227
+ * Get the current roots.
2228
+ */
2229
+ getRoots() {
2230
+ return [...this.rootsCache];
2231
+ }
2232
+ /**
2233
+ * Internal: set up roots/list request handler.
2234
+ * This is called after the client connects to register the handler for server requests.
2235
+ */
2236
+ setupRootsHandler() {
2237
+ if (!this.client) return;
2238
+ this.client.setRequestHandler(
2239
+ import_types.ListRootsRequestSchema,
2240
+ async (_request, _extra) => {
2241
+ logger.debug(
2242
+ `Server requested roots list, returning ${this.rootsCache.length} root(s)`
2243
+ );
2244
+ return { roots: this.rootsCache };
2245
+ }
2246
+ );
2247
+ }
2248
+ /**
2249
+ * Internal: set up sampling/createMessage request handler.
2250
+ * This is called after the client connects to register the handler for sampling requests.
2251
+ */
2252
+ setupSamplingHandler() {
2253
+ if (!this.client) {
2254
+ logger.debug("setupSamplingHandler: No client available");
2255
+ return;
2256
+ }
2257
+ if (!this.opts.samplingCallback) {
2258
+ logger.debug("setupSamplingHandler: No sampling callback provided");
2259
+ return;
2260
+ }
2261
+ logger.debug("setupSamplingHandler: Setting up sampling request handler");
2262
+ this.client.setRequestHandler(
2263
+ import_types.CreateMessageRequestSchema,
2264
+ async (request, _extra) => {
2265
+ logger.debug("Server requested sampling, forwarding to callback");
2266
+ return await this.opts.samplingCallback(request.params);
2267
+ }
2268
+ );
2269
+ logger.debug(
2270
+ "setupSamplingHandler: Sampling handler registered successfully"
2271
+ );
2272
+ }
2273
+ /**
2274
+ * Internal: set up elicitation/create request handler.
2275
+ * This is called after the client connects to register the handler for elicitation requests.
2276
+ */
2277
+ setupElicitationHandler() {
2278
+ if (!this.client) {
2279
+ logger.debug("setupElicitationHandler: No client available");
2280
+ return;
2281
+ }
2282
+ if (!this.opts.elicitationCallback) {
2283
+ logger.debug("setupElicitationHandler: No elicitation callback provided");
2284
+ return;
2285
+ }
2286
+ logger.debug(
2287
+ "setupElicitationHandler: Setting up elicitation request handler"
2288
+ );
2289
+ this.client.setRequestHandler(
2290
+ import_types.ElicitRequestSchema,
2291
+ async (request, _extra) => {
2292
+ logger.debug("Server requested elicitation, forwarding to callback");
2293
+ return await this.opts.elicitationCallback(request.params);
2294
+ }
2295
+ );
2296
+ logger.debug(
2297
+ "setupElicitationHandler: Elicitation handler registered successfully"
2298
+ );
2299
+ }
2300
+ /** Disconnect and release resources. */
2301
+ async disconnect() {
2302
+ if (!this.connected) {
2303
+ logger.debug("Not connected to MCP implementation");
2304
+ return;
2305
+ }
2306
+ logger.debug("Disconnecting from MCP implementation");
2307
+ await this.cleanupResources();
2308
+ this.connected = false;
2309
+ logger.debug("Disconnected from MCP implementation");
2310
+ }
2311
+ /** Check if the client is connected */
2312
+ get isClientConnected() {
2313
+ return this.client != null;
2314
+ }
2315
+ /**
2316
+ * Initialise the MCP session **after** `connect()` has succeeded.
2317
+ *
2318
+ * In the SDK, `Client.connect(transport)` automatically performs the
2319
+ * protocol‑level `initialize` handshake, so we only need to cache the list of
2320
+ * tools and expose some server info.
2321
+ */
2322
+ async initialize(defaultRequestOptions = this.opts.defaultRequestOptions ?? {}) {
2323
+ if (!this.client) {
2324
+ throw new Error("MCP client is not connected");
2325
+ }
2326
+ logger.debug("Caching server capabilities & tools");
2327
+ const capabilities = this.client.getServerCapabilities();
2328
+ this.capabilitiesCache = capabilities || null;
2329
+ const serverInfo = this.client.getServerVersion();
2330
+ this.serverInfoCache = serverInfo || null;
2331
+ const listToolsRes = await this.client.listTools(
2332
+ void 0,
2333
+ defaultRequestOptions
2334
+ );
2335
+ this.toolsCache = listToolsRes.tools ?? [];
2336
+ logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
2337
+ logger.debug("Server capabilities:", capabilities);
2338
+ logger.debug("Server info:", serverInfo);
2339
+ return capabilities;
2340
+ }
2341
+ /** Lazily expose the cached tools list. */
2342
+ get tools() {
2343
+ if (!this.toolsCache) {
2344
+ throw new Error("MCP client is not initialized; call initialize() first");
2345
+ }
2346
+ return this.toolsCache;
2347
+ }
2348
+ /** Expose cached server capabilities. */
2349
+ get serverCapabilities() {
2350
+ return this.capabilitiesCache || {};
2351
+ }
2352
+ /** Expose cached server info. */
2353
+ get serverInfo() {
2354
+ return this.serverInfoCache;
2355
+ }
2356
+ /** Call a tool on the server. */
2357
+ async callTool(name, args, options) {
2358
+ if (!this.client) {
2359
+ throw new Error("MCP client is not connected");
2360
+ }
2361
+ const enhancedOptions = options ? { ...options } : void 0;
2362
+ if (enhancedOptions?.resetTimeoutOnProgress && !enhancedOptions.onprogress) {
2363
+ enhancedOptions.onprogress = () => {
2364
+ };
2365
+ logger.debug(
2366
+ `[BaseConnector] Added onprogress callback for tool '${name}' to enable progressToken`
2367
+ );
2368
+ }
2369
+ logger.debug(`Calling tool '${name}' with args`, args);
2370
+ const res = await this.client.callTool(
2371
+ { name, arguments: args },
2372
+ void 0,
2373
+ enhancedOptions
2374
+ );
2375
+ logger.debug(`Tool '${name}' returned`, res);
2376
+ return res;
2377
+ }
2378
+ /**
2379
+ * List all available tools from the MCP server.
2380
+ * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
2381
+ *
2382
+ * @param options - Optional request options
2383
+ * @returns Array of available tools
2384
+ */
2385
+ async listTools(options) {
2386
+ if (!this.client) {
2387
+ throw new Error("MCP client is not connected");
2388
+ }
2389
+ const result = await this.client.listTools(void 0, options);
2390
+ return result.tools ?? [];
2391
+ }
2392
+ /**
2393
+ * List resources from the server with optional pagination
2394
+ *
2395
+ * @param cursor - Optional cursor for pagination
2396
+ * @param options - Request options
2397
+ * @returns Resource list with optional nextCursor for pagination
2398
+ */
2399
+ async listResources(cursor, options) {
2400
+ if (!this.client) {
2401
+ throw new Error("MCP client is not connected");
2402
+ }
2403
+ logger.debug("Listing resources", cursor ? `with cursor: ${cursor}` : "");
2404
+ return await this.client.listResources({ cursor }, options);
2405
+ }
2406
+ /**
2407
+ * List all resources from the server, automatically handling pagination
2408
+ *
2409
+ * @param options - Request options
2410
+ * @returns Complete list of all resources
2411
+ */
2412
+ async listAllResources(options) {
2413
+ if (!this.client) {
2414
+ throw new Error("MCP client is not connected");
2415
+ }
2416
+ if (!this.capabilitiesCache?.resources) {
2417
+ logger.debug("Server does not advertise resources capability, skipping");
2418
+ return { resources: [] };
2419
+ }
2420
+ try {
2421
+ logger.debug("Listing all resources (with auto-pagination)");
2422
+ const allResources = [];
2423
+ let cursor = void 0;
2424
+ do {
2425
+ const result = await this.client.listResources({ cursor }, options);
2426
+ allResources.push(...result.resources || []);
2427
+ cursor = result.nextCursor;
2428
+ } while (cursor);
2429
+ return { resources: allResources };
2430
+ } catch (err) {
2431
+ const error = err;
2432
+ if (error.code === -32601) {
2433
+ logger.debug("Server advertised resources but method not found");
2434
+ return { resources: [] };
2435
+ }
2436
+ throw err;
2437
+ }
2438
+ }
2439
+ /**
2440
+ * List resource templates from the server
2441
+ *
2442
+ * @param options - Request options
2443
+ * @returns List of available resource templates
2444
+ */
2445
+ async listResourceTemplates(options) {
2446
+ if (!this.client) {
2447
+ throw new Error("MCP client is not connected");
2448
+ }
2449
+ logger.debug("Listing resource templates");
2450
+ return await this.client.listResourceTemplates(void 0, options);
2451
+ }
2452
+ /** Read a resource by URI. */
2453
+ async readResource(uri, options) {
2454
+ if (!this.client) {
2455
+ throw new Error("MCP client is not connected");
2456
+ }
2457
+ logger.debug(`Reading resource ${uri}`);
2458
+ const res = await this.client.readResource({ uri }, options);
2459
+ return res;
2460
+ }
2461
+ /**
2462
+ * Subscribe to resource updates
2463
+ *
2464
+ * @param uri - URI of the resource to subscribe to
2465
+ * @param options - Request options
2466
+ */
2467
+ async subscribeToResource(uri, options) {
2468
+ if (!this.client) {
2469
+ throw new Error("MCP client is not connected");
2470
+ }
2471
+ logger.debug(`Subscribing to resource: ${uri}`);
2472
+ return await this.client.subscribeResource({ uri }, options);
2473
+ }
2474
+ /**
2475
+ * Unsubscribe from resource updates
2476
+ *
2477
+ * @param uri - URI of the resource to unsubscribe from
2478
+ * @param options - Request options
2479
+ */
2480
+ async unsubscribeFromResource(uri, options) {
2481
+ if (!this.client) {
2482
+ throw new Error("MCP client is not connected");
2483
+ }
2484
+ logger.debug(`Unsubscribing from resource: ${uri}`);
2485
+ return await this.client.unsubscribeResource({ uri }, options);
2486
+ }
2487
+ async listPrompts() {
2488
+ if (!this.client) {
2489
+ throw new Error("MCP client is not connected");
2490
+ }
2491
+ if (!this.capabilitiesCache?.prompts) {
2492
+ logger.debug("Server does not advertise prompts capability, skipping");
2493
+ return { prompts: [] };
2494
+ }
2495
+ try {
2496
+ logger.debug("Listing prompts");
2497
+ return await this.client.listPrompts();
2498
+ } catch (err) {
2499
+ const error = err;
2500
+ if (error.code === -32601) {
2501
+ logger.debug("Server advertised prompts but method not found");
2502
+ return { prompts: [] };
2503
+ }
2504
+ throw err;
2505
+ }
2506
+ }
2507
+ async getPrompt(name, args) {
2508
+ if (!this.client) {
2509
+ throw new Error("MCP client is not connected");
2510
+ }
2511
+ logger.debug(`Getting prompt ${name}`);
2512
+ return await this.client.getPrompt({ name, arguments: args });
2513
+ }
2514
+ /** Send a raw request through the client. */
2515
+ async request(method, params = null, options) {
2516
+ if (!this.client) {
2517
+ throw new Error("MCP client is not connected");
2518
+ }
2519
+ logger.debug(`Sending raw request '${method}' with params`, params);
2520
+ return await this.client.request(
2521
+ { method, params: params ?? {} },
2522
+ void 0,
2523
+ options
2524
+ );
2525
+ }
2526
+ /**
2527
+ * Helper to tear down the client & connection manager safely.
2528
+ */
2529
+ async cleanupResources() {
2530
+ const issues = [];
2531
+ if (this.client) {
2532
+ try {
2533
+ if (typeof this.client.close === "function") {
2534
+ await this.client.close();
2535
+ }
2536
+ } catch (e) {
2537
+ const msg = `Error closing client: ${e}`;
2538
+ logger.warn(msg);
2539
+ issues.push(msg);
2540
+ } finally {
2541
+ this.client = null;
2542
+ }
2543
+ }
2544
+ if (this.connectionManager) {
2545
+ try {
2546
+ await this.connectionManager.stop();
2547
+ } catch (e) {
2548
+ const msg = `Error stopping connection manager: ${e}`;
2549
+ logger.warn(msg);
2550
+ issues.push(msg);
2551
+ } finally {
2552
+ this.connectionManager = null;
2553
+ }
2554
+ }
2555
+ this.toolsCache = null;
2556
+ if (issues.length) {
2557
+ logger.warn(`Resource cleanup finished with ${issues.length} issue(s)`);
2558
+ }
2559
+ }
2560
+ };
2087
2561
 
2088
2562
  // src/client/connectors/codeMode.ts
2089
2563
  var CODE_MODE_AGENT_PROMPT = `
@@ -2173,6 +2647,110 @@ return {
2173
2647
 
2174
2648
  Remember: Always discover and understand available tools before attempting to use them in code execution.
2175
2649
  `;
2650
+ var CodeModeConnector = class extends BaseConnector {
2651
+ static {
2652
+ __name(this, "CodeModeConnector");
2653
+ }
2654
+ mcpClient;
2655
+ _tools;
2656
+ constructor(client) {
2657
+ super();
2658
+ this.mcpClient = client;
2659
+ this.connected = true;
2660
+ this._tools = this._createToolsList();
2661
+ }
2662
+ async connect() {
2663
+ this.connected = true;
2664
+ }
2665
+ async disconnect() {
2666
+ this.connected = false;
2667
+ }
2668
+ get publicIdentifier() {
2669
+ return { name: "code_mode", version: "1.0.0" };
2670
+ }
2671
+ _createToolsList() {
2672
+ return [
2673
+ {
2674
+ name: "execute_code",
2675
+ 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.",
2676
+ inputSchema: {
2677
+ type: "object",
2678
+ properties: {
2679
+ code: {
2680
+ type: "string",
2681
+ 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"
2682
+ },
2683
+ timeout: {
2684
+ type: "number",
2685
+ description: "Execution timeout in milliseconds",
2686
+ default: 3e4
2687
+ }
2688
+ },
2689
+ required: ["code"]
2690
+ }
2691
+ },
2692
+ {
2693
+ name: "search_tools",
2694
+ 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.",
2695
+ inputSchema: {
2696
+ type: "object",
2697
+ properties: {
2698
+ query: {
2699
+ type: "string",
2700
+ description: "Search query to filter tools by name or description",
2701
+ default: ""
2702
+ },
2703
+ detail_level: {
2704
+ type: "string",
2705
+ description: "Detail level: 'names', 'descriptions', or 'full'",
2706
+ enum: ["names", "descriptions", "full"],
2707
+ default: "full"
2708
+ }
2709
+ }
2710
+ }
2711
+ }
2712
+ ];
2713
+ }
2714
+ // Override tools getter to return static list immediately
2715
+ get tools() {
2716
+ return this._tools;
2717
+ }
2718
+ async initialize() {
2719
+ this.toolsCache = this._tools;
2720
+ return { capabilities: {}, version: "1.0.0" };
2721
+ }
2722
+ async callTool(name, args) {
2723
+ if (name === "execute_code") {
2724
+ const code = args.code;
2725
+ const timeout = args.timeout || 3e4;
2726
+ const result = await this.mcpClient.executeCode(code, timeout);
2727
+ return {
2728
+ content: [
2729
+ {
2730
+ type: "text",
2731
+ text: JSON.stringify(result)
2732
+ }
2733
+ ]
2734
+ };
2735
+ } else if (name === "search_tools") {
2736
+ const query = args.query || "";
2737
+ const detailLevel = args.detail_level;
2738
+ const result = await this.mcpClient.searchTools(
2739
+ query,
2740
+ detailLevel && detailLevel in ["names", "descriptions", "full"] ? detailLevel : "full"
2741
+ );
2742
+ return {
2743
+ content: [
2744
+ {
2745
+ type: "text",
2746
+ text: JSON.stringify(result)
2747
+ }
2748
+ ]
2749
+ };
2750
+ }
2751
+ throw new Error(`Unknown tool: ${name}`);
2752
+ }
2753
+ };
2176
2754
 
2177
2755
  // src/client/prompts.ts
2178
2756
  var PROMPTS = {
@@ -3179,63 +3757,1924 @@ var LangChainAdapter = class extends BaseAdapter {
3179
3757
  return JSON.stringify(content);
3180
3758
  }).join("\n");
3181
3759
  }
3182
- return "Resource is empty or unavailable";
3183
- } catch (err) {
3184
- logger.error(`Error reading resource: ${err.message}`);
3185
- return `Error reading resource: ${String(err)}`;
3760
+ return "Resource is empty or unavailable";
3761
+ } catch (err) {
3762
+ logger.error(`Error reading resource: ${err.message}`);
3763
+ return `Error reading resource: ${String(err)}`;
3764
+ }
3765
+ }, "func")
3766
+ });
3767
+ return tool;
3768
+ }
3769
+ /**
3770
+ * Convert a single MCP prompt into a LangChainJS structured tool.
3771
+ * The resulting tool executes getPrompt on the connector with the prompt's name
3772
+ * and the user-provided arguments (if any).
3773
+ */
3774
+ convertPrompt(mcpPrompt, connector) {
3775
+ let argsSchema = import_zod2.z.object({}).optional();
3776
+ if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {
3777
+ const schemaFields = {};
3778
+ for (const arg of mcpPrompt.arguments) {
3779
+ const zodType = import_zod2.z.string();
3780
+ if (arg.required !== false) {
3781
+ schemaFields[arg.name] = zodType;
3782
+ } else {
3783
+ schemaFields[arg.name] = zodType.optional();
3784
+ }
3785
+ }
3786
+ argsSchema = Object.keys(schemaFields).length > 0 ? import_zod2.z.object(schemaFields) : import_zod2.z.object({}).optional();
3787
+ }
3788
+ const tool = new import_tools.DynamicStructuredTool({
3789
+ name: mcpPrompt.name,
3790
+ description: mcpPrompt.description || "",
3791
+ schema: argsSchema,
3792
+ func: /* @__PURE__ */ __name(async (input) => {
3793
+ logger.debug(
3794
+ `Prompt tool: "${mcpPrompt.name}" called with args: ${JSON.stringify(input)}`
3795
+ );
3796
+ try {
3797
+ const result = await connector.getPrompt(mcpPrompt.name, input);
3798
+ if (result.messages && result.messages.length > 0) {
3799
+ return result.messages.map((msg) => {
3800
+ if (typeof msg === "string") {
3801
+ return msg;
3802
+ }
3803
+ if (msg.content) {
3804
+ return typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
3805
+ }
3806
+ return JSON.stringify(msg);
3807
+ }).join("\n");
3808
+ }
3809
+ return "Prompt returned no messages";
3810
+ } catch (err) {
3811
+ logger.error(`Error getting prompt: ${err.message}`);
3812
+ return `Error getting prompt: ${String(err)}`;
3813
+ }
3814
+ }, "func")
3815
+ });
3816
+ return tool;
3817
+ }
3818
+ };
3819
+
3820
+ // src/client.ts
3821
+ var import_node_fs2 = __toESM(require("fs"), 1);
3822
+ var import_node_path = __toESM(require("path"), 1);
3823
+
3824
+ // src/client/base.ts
3825
+ init_logging();
3826
+
3827
+ // src/session.ts
3828
+ var MCPSession = class {
3829
+ static {
3830
+ __name(this, "MCPSession");
3831
+ }
3832
+ connector;
3833
+ autoConnect;
3834
+ constructor(connector, autoConnect = true) {
3835
+ this.connector = connector;
3836
+ this.autoConnect = autoConnect;
3837
+ }
3838
+ async connect() {
3839
+ await this.connector.connect();
3840
+ }
3841
+ async disconnect() {
3842
+ await this.connector.disconnect();
3843
+ }
3844
+ async initialize() {
3845
+ if (!this.isConnected && this.autoConnect) {
3846
+ await this.connect();
3847
+ }
3848
+ await this.connector.initialize();
3849
+ }
3850
+ get isConnected() {
3851
+ return this.connector && this.connector.isClientConnected;
3852
+ }
3853
+ /**
3854
+ * Register an event handler for session events
3855
+ *
3856
+ * @param event - The event type to listen for
3857
+ * @param handler - The handler function to call when the event occurs
3858
+ *
3859
+ * @example
3860
+ * ```typescript
3861
+ * session.on("notification", async (notification) => {
3862
+ * console.log(`Received: ${notification.method}`, notification.params);
3863
+ *
3864
+ * if (notification.method === "notifications/tools/list_changed") {
3865
+ * // Refresh tools list
3866
+ * }
3867
+ * });
3868
+ * ```
3869
+ */
3870
+ on(event, handler) {
3871
+ if (event === "notification") {
3872
+ this.connector.onNotification(handler);
3873
+ }
3874
+ }
3875
+ /**
3876
+ * Set roots and notify the server.
3877
+ * Roots represent directories or files that the client has access to.
3878
+ *
3879
+ * @param roots - Array of Root objects with `uri` (must start with "file://") and optional `name`
3880
+ *
3881
+ * @example
3882
+ * ```typescript
3883
+ * await session.setRoots([
3884
+ * { uri: "file:///home/user/project", name: "My Project" },
3885
+ * { uri: "file:///home/user/data" }
3886
+ * ]);
3887
+ * ```
3888
+ */
3889
+ async setRoots(roots) {
3890
+ return this.connector.setRoots(roots);
3891
+ }
3892
+ /**
3893
+ * Get the current roots.
3894
+ */
3895
+ getRoots() {
3896
+ return this.connector.getRoots();
3897
+ }
3898
+ /**
3899
+ * Get the cached list of tools from the server.
3900
+ *
3901
+ * @returns Array of available tools
3902
+ *
3903
+ * @example
3904
+ * ```typescript
3905
+ * const tools = session.tools;
3906
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
3907
+ * ```
3908
+ */
3909
+ get tools() {
3910
+ return this.connector.tools;
3911
+ }
3912
+ /**
3913
+ * List all available tools from the MCP server.
3914
+ * This method fetches fresh tools from the server, unlike the `tools` getter which returns cached tools.
3915
+ *
3916
+ * @param options - Optional request options
3917
+ * @returns Array of available tools
3918
+ *
3919
+ * @example
3920
+ * ```typescript
3921
+ * const tools = await session.listTools();
3922
+ * console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
3923
+ * ```
3924
+ */
3925
+ async listTools(options) {
3926
+ return this.connector.listTools(options);
3927
+ }
3928
+ /**
3929
+ * Get the server capabilities advertised during initialization.
3930
+ *
3931
+ * @returns Server capabilities object
3932
+ */
3933
+ get serverCapabilities() {
3934
+ return this.connector.serverCapabilities;
3935
+ }
3936
+ /**
3937
+ * Get the server information (name and version).
3938
+ *
3939
+ * @returns Server info object or null if not available
3940
+ */
3941
+ get serverInfo() {
3942
+ return this.connector.serverInfo;
3943
+ }
3944
+ /**
3945
+ * Call a tool on the server.
3946
+ *
3947
+ * @param name - Name of the tool to call
3948
+ * @param args - Arguments to pass to the tool
3949
+ * @param options - Optional request options (timeout, progress handlers, etc.)
3950
+ * @returns Result from the tool execution
3951
+ *
3952
+ * @example
3953
+ * ```typescript
3954
+ * const result = await session.callTool("add", { a: 5, b: 3 });
3955
+ * console.log(`Result: ${result.content[0].text}`);
3956
+ * ```
3957
+ */
3958
+ async callTool(name, args, options) {
3959
+ return this.connector.callTool(name, args, options);
3960
+ }
3961
+ /**
3962
+ * List resources from the server with optional pagination.
3963
+ *
3964
+ * @param cursor - Optional cursor for pagination
3965
+ * @param options - Request options
3966
+ * @returns Resource list with optional nextCursor for pagination
3967
+ *
3968
+ * @example
3969
+ * ```typescript
3970
+ * const result = await session.listResources();
3971
+ * console.log(`Found ${result.resources.length} resources`);
3972
+ * ```
3973
+ */
3974
+ async listResources(cursor, options) {
3975
+ return this.connector.listResources(cursor, options);
3976
+ }
3977
+ /**
3978
+ * List all resources from the server, automatically handling pagination.
3979
+ *
3980
+ * @param options - Request options
3981
+ * @returns Complete list of all resources
3982
+ *
3983
+ * @example
3984
+ * ```typescript
3985
+ * const result = await session.listAllResources();
3986
+ * console.log(`Total resources: ${result.resources.length}`);
3987
+ * ```
3988
+ */
3989
+ async listAllResources(options) {
3990
+ return this.connector.listAllResources(options);
3991
+ }
3992
+ /**
3993
+ * List resource templates from the server.
3994
+ *
3995
+ * @param options - Request options
3996
+ * @returns List of available resource templates
3997
+ *
3998
+ * @example
3999
+ * ```typescript
4000
+ * const result = await session.listResourceTemplates();
4001
+ * console.log(`Available templates: ${result.resourceTemplates.length}`);
4002
+ * ```
4003
+ */
4004
+ async listResourceTemplates(options) {
4005
+ return this.connector.listResourceTemplates(options);
4006
+ }
4007
+ /**
4008
+ * Read a resource by URI.
4009
+ *
4010
+ * @param uri - URI of the resource to read
4011
+ * @param options - Request options
4012
+ * @returns Resource content
4013
+ *
4014
+ * @example
4015
+ * ```typescript
4016
+ * const resource = await session.readResource("file:///path/to/file.txt");
4017
+ * console.log(resource.contents);
4018
+ * ```
4019
+ */
4020
+ async readResource(uri, options) {
4021
+ return this.connector.readResource(uri, options);
4022
+ }
4023
+ /**
4024
+ * Subscribe to resource updates.
4025
+ *
4026
+ * @param uri - URI of the resource to subscribe to
4027
+ * @param options - Request options
4028
+ *
4029
+ * @example
4030
+ * ```typescript
4031
+ * await session.subscribeToResource("file:///path/to/file.txt");
4032
+ * // Now you'll receive notifications when this resource changes
4033
+ * ```
4034
+ */
4035
+ async subscribeToResource(uri, options) {
4036
+ return this.connector.subscribeToResource(uri, options);
4037
+ }
4038
+ /**
4039
+ * Unsubscribe from resource updates.
4040
+ *
4041
+ * @param uri - URI of the resource to unsubscribe from
4042
+ * @param options - Request options
4043
+ *
4044
+ * @example
4045
+ * ```typescript
4046
+ * await session.unsubscribeFromResource("file:///path/to/file.txt");
4047
+ * ```
4048
+ */
4049
+ async unsubscribeFromResource(uri, options) {
4050
+ return this.connector.unsubscribeFromResource(uri, options);
4051
+ }
4052
+ /**
4053
+ * List available prompts from the server.
4054
+ *
4055
+ * @returns List of available prompts
4056
+ *
4057
+ * @example
4058
+ * ```typescript
4059
+ * const result = await session.listPrompts();
4060
+ * console.log(`Available prompts: ${result.prompts.length}`);
4061
+ * ```
4062
+ */
4063
+ async listPrompts() {
4064
+ return this.connector.listPrompts();
4065
+ }
4066
+ /**
4067
+ * Get a specific prompt with arguments.
4068
+ *
4069
+ * @param name - Name of the prompt to get
4070
+ * @param args - Arguments for the prompt
4071
+ * @returns Prompt result
4072
+ *
4073
+ * @example
4074
+ * ```typescript
4075
+ * const prompt = await session.getPrompt("greeting", { name: "Alice" });
4076
+ * console.log(prompt.messages);
4077
+ * ```
4078
+ */
4079
+ async getPrompt(name, args) {
4080
+ return this.connector.getPrompt(name, args);
4081
+ }
4082
+ /**
4083
+ * Send a raw request through the client.
4084
+ *
4085
+ * @param method - MCP method name
4086
+ * @param params - Request parameters
4087
+ * @param options - Request options
4088
+ * @returns Response from the server
4089
+ *
4090
+ * @example
4091
+ * ```typescript
4092
+ * const result = await session.request("custom/method", { key: "value" });
4093
+ * ```
4094
+ */
4095
+ async request(method, params = null, options) {
4096
+ return this.connector.request(method, params, options);
4097
+ }
4098
+ };
4099
+
4100
+ // src/client/base.ts
4101
+ var BaseMCPClient = class {
4102
+ static {
4103
+ __name(this, "BaseMCPClient");
4104
+ }
4105
+ config = {};
4106
+ sessions = {};
4107
+ activeSessions = [];
4108
+ constructor(config) {
4109
+ if (config) {
4110
+ this.config = config;
4111
+ }
4112
+ }
4113
+ static fromDict(_cfg) {
4114
+ throw new Error("fromDict must be implemented by concrete class");
4115
+ }
4116
+ addServer(name, serverConfig) {
4117
+ this.config.mcpServers = this.config.mcpServers || {};
4118
+ this.config.mcpServers[name] = serverConfig;
4119
+ Tel.getInstance().trackClientAddServer(name, serverConfig);
4120
+ }
4121
+ removeServer(name) {
4122
+ if (this.config.mcpServers?.[name]) {
4123
+ delete this.config.mcpServers[name];
4124
+ this.activeSessions = this.activeSessions.filter((n) => n !== name);
4125
+ Tel.getInstance().trackClientRemoveServer(name);
4126
+ }
4127
+ }
4128
+ getServerNames() {
4129
+ return Object.keys(this.config.mcpServers ?? {});
4130
+ }
4131
+ getServerConfig(name) {
4132
+ return this.config.mcpServers?.[name];
4133
+ }
4134
+ getConfig() {
4135
+ return this.config ?? {};
4136
+ }
4137
+ async createSession(serverName, autoInitialize = true) {
4138
+ const servers = this.config.mcpServers ?? {};
4139
+ if (Object.keys(servers).length === 0) {
4140
+ logger.warn("No MCP servers defined in config");
4141
+ }
4142
+ if (!servers[serverName]) {
4143
+ throw new Error(`Server '${serverName}' not found in config`);
4144
+ }
4145
+ const connector = this.createConnectorFromConfig(servers[serverName]);
4146
+ const session = new MCPSession(connector);
4147
+ if (autoInitialize) {
4148
+ await session.initialize();
4149
+ }
4150
+ this.sessions[serverName] = session;
4151
+ if (!this.activeSessions.includes(serverName)) {
4152
+ this.activeSessions.push(serverName);
4153
+ }
4154
+ return session;
4155
+ }
4156
+ async createAllSessions(autoInitialize = true) {
4157
+ const servers = this.config.mcpServers ?? {};
4158
+ if (Object.keys(servers).length === 0) {
4159
+ logger.warn("No MCP servers defined in config");
4160
+ }
4161
+ for (const name of Object.keys(servers)) {
4162
+ await this.createSession(name, autoInitialize);
4163
+ }
4164
+ return this.sessions;
4165
+ }
4166
+ getSession(serverName) {
4167
+ const session = this.sessions[serverName];
4168
+ if (!session) {
4169
+ return null;
4170
+ }
4171
+ return session;
4172
+ }
4173
+ getAllActiveSessions() {
4174
+ return Object.fromEntries(
4175
+ this.activeSessions.map((n) => [n, this.sessions[n]])
4176
+ );
4177
+ }
4178
+ async closeSession(serverName) {
4179
+ const session = this.sessions[serverName];
4180
+ if (!session) {
4181
+ logger.warn(
4182
+ `No session exists for server ${serverName}, nothing to close`
4183
+ );
4184
+ return;
4185
+ }
4186
+ try {
4187
+ logger.debug(`Closing session for server ${serverName}`);
4188
+ await session.disconnect();
4189
+ } catch (e) {
4190
+ logger.error(`Error closing session for server '${serverName}': ${e}`);
4191
+ } finally {
4192
+ delete this.sessions[serverName];
4193
+ this.activeSessions = this.activeSessions.filter((n) => n !== serverName);
4194
+ }
4195
+ }
4196
+ async closeAllSessions() {
4197
+ const serverNames = Object.keys(this.sessions);
4198
+ const errors = [];
4199
+ for (const serverName of serverNames) {
4200
+ try {
4201
+ logger.debug(`Closing session for server ${serverName}`);
4202
+ await this.closeSession(serverName);
4203
+ } catch (e) {
4204
+ const errorMsg = `Failed to close session for server '${serverName}': ${e}`;
4205
+ logger.error(errorMsg);
4206
+ errors.push(errorMsg);
4207
+ }
4208
+ }
4209
+ if (errors.length) {
4210
+ logger.error(
4211
+ `Encountered ${errors.length} errors while closing sessions`
4212
+ );
4213
+ } else {
4214
+ logger.debug("All sessions closed successfully");
4215
+ }
4216
+ }
4217
+ };
4218
+
4219
+ // src/client/executors/base.ts
4220
+ init_logging();
4221
+ var BaseCodeExecutor = class {
4222
+ static {
4223
+ __name(this, "BaseCodeExecutor");
4224
+ }
4225
+ client;
4226
+ _connecting = false;
4227
+ constructor(client) {
4228
+ this.client = client;
4229
+ }
4230
+ /**
4231
+ * Ensure all configured MCP servers are connected before execution.
4232
+ * Prevents race conditions with a connection lock.
4233
+ */
4234
+ async ensureServersConnected() {
4235
+ const configuredServers = this.client.getServerNames();
4236
+ const activeSessions = Object.keys(this.client.getAllActiveSessions());
4237
+ const missingServers = configuredServers.filter(
4238
+ (s) => !activeSessions.includes(s)
4239
+ );
4240
+ if (missingServers.length > 0 && !this._connecting) {
4241
+ this._connecting = true;
4242
+ try {
4243
+ logger.debug(
4244
+ `Connecting to configured servers for code execution: ${missingServers.join(", ")}`
4245
+ );
4246
+ await this.client.createAllSessions();
4247
+ } finally {
4248
+ this._connecting = false;
4249
+ }
4250
+ } else if (missingServers.length > 0 && this._connecting) {
4251
+ logger.debug("Waiting for ongoing server connection...");
4252
+ const startWait = Date.now();
4253
+ while (this._connecting && Date.now() - startWait < 5e3) {
4254
+ await new Promise((resolve) => setTimeout(resolve, 100));
4255
+ }
4256
+ }
4257
+ }
4258
+ /**
4259
+ * Get tool namespace information from all active MCP sessions.
4260
+ * Filters out the internal code_mode server.
4261
+ */
4262
+ getToolNamespaces() {
4263
+ const namespaces = [];
4264
+ const activeSessions = this.client.getAllActiveSessions();
4265
+ for (const [serverName, session] of Object.entries(activeSessions)) {
4266
+ if (serverName === "code_mode") continue;
4267
+ try {
4268
+ const connector = session.connector;
4269
+ let tools;
4270
+ try {
4271
+ tools = connector.tools;
4272
+ } catch (e) {
4273
+ logger.warn(`Tools not available for server ${serverName}: ${e}`);
4274
+ continue;
4275
+ }
4276
+ if (!tools || tools.length === 0) continue;
4277
+ namespaces.push({ serverName, tools, session });
4278
+ } catch (e) {
4279
+ logger.warn(`Failed to load tools for server ${serverName}: ${e}`);
4280
+ }
4281
+ }
4282
+ return namespaces;
4283
+ }
4284
+ /**
4285
+ * Create a search function for discovering available MCP tools.
4286
+ * Used by code execution environments to find tools at runtime.
4287
+ */
4288
+ createSearchToolsFunction() {
4289
+ return async (query = "", detailLevel = "full") => {
4290
+ const allTools = [];
4291
+ const allNamespaces = /* @__PURE__ */ new Set();
4292
+ const queryLower = query.toLowerCase();
4293
+ const activeSessions = this.client.getAllActiveSessions();
4294
+ for (const [serverName, session] of Object.entries(activeSessions)) {
4295
+ if (serverName === "code_mode") continue;
4296
+ try {
4297
+ const tools = session.connector.tools;
4298
+ if (tools && tools.length > 0) {
4299
+ allNamespaces.add(serverName);
4300
+ }
4301
+ for (const tool of tools) {
4302
+ if (detailLevel === "names") {
4303
+ allTools.push({ name: tool.name, server: serverName });
4304
+ } else if (detailLevel === "descriptions") {
4305
+ allTools.push({
4306
+ name: tool.name,
4307
+ server: serverName,
4308
+ description: tool.description
4309
+ });
4310
+ } else {
4311
+ allTools.push({
4312
+ name: tool.name,
4313
+ server: serverName,
4314
+ description: tool.description,
4315
+ input_schema: tool.inputSchema
4316
+ });
4317
+ }
4318
+ }
4319
+ } catch (e) {
4320
+ logger.warn(`Failed to search tools in server ${serverName}: ${e}`);
4321
+ }
4322
+ }
4323
+ let filteredTools = allTools;
4324
+ if (query) {
4325
+ filteredTools = allTools.filter((tool) => {
4326
+ const nameMatch = tool.name.toLowerCase().includes(queryLower);
4327
+ const descMatch = tool.description?.toLowerCase().includes(queryLower);
4328
+ const serverMatch = tool.server.toLowerCase().includes(queryLower);
4329
+ return nameMatch || descMatch || serverMatch;
4330
+ });
4331
+ }
4332
+ return {
4333
+ meta: {
4334
+ total_tools: allTools.length,
4335
+ namespaces: Array.from(allNamespaces).sort(),
4336
+ result_count: filteredTools.length
4337
+ },
4338
+ results: filteredTools
4339
+ };
4340
+ };
4341
+ }
4342
+ };
4343
+
4344
+ // src/client/executors/e2b.ts
4345
+ init_logging();
4346
+ var E2BCodeExecutor = class extends BaseCodeExecutor {
4347
+ static {
4348
+ __name(this, "E2BCodeExecutor");
4349
+ }
4350
+ e2bApiKey;
4351
+ codeExecSandbox = null;
4352
+ SandboxClass = null;
4353
+ timeoutMs;
4354
+ constructor(client, options) {
4355
+ super(client);
4356
+ this.e2bApiKey = options.apiKey;
4357
+ this.timeoutMs = options.timeoutMs ?? 3e5;
4358
+ }
4359
+ /**
4360
+ * Lazy load E2B Sandbox class.
4361
+ * This allows the library to work without E2B installed.
4362
+ */
4363
+ async ensureSandboxClass() {
4364
+ if (this.SandboxClass) return;
4365
+ try {
4366
+ const e2b = await import("@e2b/code-interpreter");
4367
+ this.SandboxClass = e2b.Sandbox;
4368
+ } catch (error) {
4369
+ throw new Error(
4370
+ "@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter"
4371
+ );
4372
+ }
4373
+ }
4374
+ /**
4375
+ * Get or create a dedicated sandbox for code execution.
4376
+ */
4377
+ async getOrCreateCodeExecSandbox() {
4378
+ if (this.codeExecSandbox) return this.codeExecSandbox;
4379
+ await this.ensureSandboxClass();
4380
+ logger.debug("Starting E2B sandbox for code execution...");
4381
+ this.codeExecSandbox = await this.SandboxClass.create("base", {
4382
+ apiKey: this.e2bApiKey,
4383
+ timeoutMs: this.timeoutMs
4384
+ });
4385
+ return this.codeExecSandbox;
4386
+ }
4387
+ /**
4388
+ * Generate the shim code that exposes tools to the sandbox environment.
4389
+ * Creates a bridge that intercepts tool calls and sends them back to host.
4390
+ */
4391
+ generateShim(tools) {
4392
+ let shim = `
4393
+ // MCP Bridge Shim
4394
+ global.__callMcpTool = async (server, tool, args) => {
4395
+ const id = Math.random().toString(36).substring(7);
4396
+ console.log(JSON.stringify({
4397
+ type: '__MCP_TOOL_CALL__',
4398
+ id,
4399
+ server,
4400
+ tool,
4401
+ args
4402
+ }));
4403
+
4404
+ const resultPath = \`/tmp/mcp_result_\${id}.json\`;
4405
+ const fs = require('fs');
4406
+
4407
+ // Poll for result file
4408
+ let attempts = 0;
4409
+ while (attempts < 300) { // 30 seconds timeout
4410
+ if (fs.existsSync(resultPath)) {
4411
+ const content = fs.readFileSync(resultPath, 'utf8');
4412
+ const result = JSON.parse(content);
4413
+ fs.unlinkSync(resultPath); // Clean up
4414
+
4415
+ if (result.error) {
4416
+ throw new Error(result.error);
4417
+ }
4418
+ return result.data;
4419
+ }
4420
+ await new Promise(resolve => setTimeout(resolve, 100));
4421
+ attempts++;
4422
+ }
4423
+ throw new Error('Tool execution timed out');
4424
+ };
4425
+
4426
+ // Global search_tools helper
4427
+ global.search_tools = async (query, detailLevel = 'full') => {
4428
+ const allTools = ${JSON.stringify(
4429
+ Object.entries(tools).flatMap(
4430
+ ([server, serverTools]) => serverTools.map((tool) => ({
4431
+ name: tool.name,
4432
+ description: tool.description,
4433
+ server,
4434
+ input_schema: tool.inputSchema
4435
+ }))
4436
+ )
4437
+ )};
4438
+
4439
+ const filtered = allTools.filter(tool => {
4440
+ if (!query) return true;
4441
+ const q = query.toLowerCase();
4442
+ return tool.name.toLowerCase().includes(q) ||
4443
+ (tool.description && tool.description.toLowerCase().includes(q));
4444
+ });
4445
+
4446
+ if (detailLevel === 'names') {
4447
+ return filtered.map(t => ({ name: t.name, server: t.server }));
4448
+ } else if (detailLevel === 'descriptions') {
4449
+ return filtered.map(t => ({ name: t.name, server: t.server, description: t.description }));
4450
+ }
4451
+ return filtered;
4452
+ };
4453
+ `;
4454
+ for (const [serverName, serverTools] of Object.entries(tools)) {
4455
+ if (!serverTools || serverTools.length === 0) continue;
4456
+ const safeServerName = serverName.replace(/[^a-zA-Z0-9_]/g, "_");
4457
+ shim += `
4458
+ global['${serverName}'] = {`;
4459
+ for (const tool of serverTools) {
4460
+ shim += `
4461
+ '${tool.name}': async (args) => await global.__callMcpTool('${serverName}', '${tool.name}', args),`;
4462
+ }
4463
+ shim += `
4464
+ };
4465
+
4466
+ // Also expose as safe name if different
4467
+ if ('${safeServerName}' !== '${serverName}') {
4468
+ global['${safeServerName}'] = global['${serverName}'];
4469
+ }
4470
+ `;
4471
+ }
4472
+ return shim;
4473
+ }
4474
+ /**
4475
+ * Build the tool catalog for the shim.
4476
+ * Returns a map of server names to their available tools.
4477
+ */
4478
+ buildToolCatalog() {
4479
+ const catalog = {};
4480
+ const namespaces = this.getToolNamespaces();
4481
+ for (const { serverName, tools } of namespaces) {
4482
+ catalog[serverName] = tools;
4483
+ }
4484
+ return catalog;
4485
+ }
4486
+ /**
4487
+ * Execute JavaScript/TypeScript code in an E2B sandbox with MCP tool access.
4488
+ * Tool calls are proxied back to the host via the bridge pattern.
4489
+ *
4490
+ * @param code - Code to execute
4491
+ * @param timeout - Execution timeout in milliseconds (default: 30000)
4492
+ */
4493
+ async execute(code, timeout = 3e4) {
4494
+ const startTime = Date.now();
4495
+ let result = null;
4496
+ let error = null;
4497
+ let logs = [];
4498
+ try {
4499
+ await this.ensureServersConnected();
4500
+ const sandbox = await this.getOrCreateCodeExecSandbox();
4501
+ const toolCatalog = this.buildToolCatalog();
4502
+ const shim = this.generateShim(toolCatalog);
4503
+ const wrappedCode = `
4504
+ ${shim}
4505
+
4506
+ (async () => {
4507
+ try {
4508
+ const func = async () => {
4509
+ ${code}
4510
+ };
4511
+ const result = await func();
4512
+ console.log('__MCP_RESULT_START__');
4513
+ console.log(JSON.stringify(result));
4514
+ console.log('__MCP_RESULT_END__');
4515
+ } catch (e) {
4516
+ console.error(e);
4517
+ process.exit(1);
4518
+ }
4519
+ })();
4520
+ `;
4521
+ const filename = `exec_${Date.now()}.js`;
4522
+ await sandbox.files.write(filename, wrappedCode);
4523
+ const execution = await sandbox.commands.run(`node ${filename}`, {
4524
+ timeoutMs: timeout,
4525
+ onStdout: /* @__PURE__ */ __name(async (data) => {
4526
+ try {
4527
+ const lines = data.split("\n");
4528
+ for (const line of lines) {
4529
+ if (line.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')) {
4530
+ const call = JSON.parse(line);
4531
+ if (call.type === "__MCP_TOOL_CALL__") {
4532
+ try {
4533
+ logger.debug(
4534
+ `[E2B Bridge] Calling tool ${call.server}.${call.tool}`
4535
+ );
4536
+ const activeSessions = this.client.getAllActiveSessions();
4537
+ const session = activeSessions[call.server];
4538
+ if (!session) {
4539
+ throw new Error(`Server ${call.server} not found`);
4540
+ }
4541
+ const toolResult = await session.connector.callTool(
4542
+ call.tool,
4543
+ call.args
4544
+ );
4545
+ let extractedResult = toolResult;
4546
+ if (toolResult.content && toolResult.content.length > 0) {
4547
+ const item = toolResult.content[0];
4548
+ if (item.type === "text") {
4549
+ try {
4550
+ extractedResult = JSON.parse(item.text);
4551
+ } catch {
4552
+ extractedResult = item.text;
4553
+ }
4554
+ } else {
4555
+ extractedResult = item;
4556
+ }
4557
+ }
4558
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
4559
+ await sandbox.files.write(
4560
+ resultPath,
4561
+ JSON.stringify({ data: extractedResult })
4562
+ );
4563
+ } catch (err) {
4564
+ logger.error(
4565
+ `[E2B Bridge] Tool execution failed: ${err.message}`
4566
+ );
4567
+ const resultPath = `/tmp/mcp_result_${call.id}.json`;
4568
+ await sandbox.files.write(
4569
+ resultPath,
4570
+ JSON.stringify({
4571
+ error: err.message || String(err)
4572
+ })
4573
+ );
4574
+ }
4575
+ }
4576
+ }
4577
+ }
4578
+ } catch (e) {
4579
+ }
4580
+ }, "onStdout")
4581
+ });
4582
+ logs = [execution.stdout, execution.stderr].filter(Boolean);
4583
+ if (execution.exitCode !== 0) {
4584
+ error = execution.stderr || "Execution failed";
4585
+ } else {
4586
+ const stdout = execution.stdout;
4587
+ const startMarker = "__MCP_RESULT_START__";
4588
+ const endMarker = "__MCP_RESULT_END__";
4589
+ const startIndex = stdout.indexOf(startMarker);
4590
+ const endIndex = stdout.indexOf(endMarker);
4591
+ if (startIndex !== -1 && endIndex !== -1) {
4592
+ const jsonStr = stdout.substring(startIndex + startMarker.length, endIndex).trim();
4593
+ try {
4594
+ result = JSON.parse(jsonStr);
4595
+ } catch (e) {
4596
+ result = jsonStr;
4597
+ }
4598
+ logs = logs.map((log) => {
4599
+ let cleaned = log.replace(
4600
+ new RegExp(startMarker + "[\\s\\S]*?" + endMarker),
4601
+ "[Result captured]"
4602
+ );
4603
+ cleaned = cleaned.split("\n").filter((l) => !l.includes("__MCP_TOOL_CALL__")).join("\n");
4604
+ return cleaned;
4605
+ });
4606
+ }
4607
+ }
4608
+ } catch (e) {
4609
+ error = e.message || String(e);
4610
+ if (error && (error.includes("timeout") || error.includes("timed out"))) {
4611
+ error = "Script execution timed out";
4612
+ }
4613
+ }
4614
+ return {
4615
+ result,
4616
+ logs,
4617
+ error,
4618
+ execution_time: (Date.now() - startTime) / 1e3
4619
+ };
4620
+ }
4621
+ /**
4622
+ * Clean up the E2B sandbox.
4623
+ * Should be called when the executor is no longer needed.
4624
+ */
4625
+ async cleanup() {
4626
+ if (this.codeExecSandbox) {
4627
+ try {
4628
+ await this.codeExecSandbox.kill();
4629
+ this.codeExecSandbox = null;
4630
+ logger.debug("E2B code execution sandbox stopped");
4631
+ } catch (error) {
4632
+ logger.error("Failed to stop E2B code execution sandbox:", error);
4633
+ }
4634
+ }
4635
+ }
4636
+ };
4637
+
4638
+ // src/client/executors/vm.ts
4639
+ init_logging();
4640
+ var vm = null;
4641
+ var vmCheckAttempted = false;
4642
+ function getVMModuleName() {
4643
+ return ["node", "vm"].join(":");
4644
+ }
4645
+ __name(getVMModuleName, "getVMModuleName");
4646
+ function tryLoadVM() {
4647
+ if (vmCheckAttempted) {
4648
+ return vm !== null;
4649
+ }
4650
+ vmCheckAttempted = true;
4651
+ try {
4652
+ const nodeRequire = typeof require !== "undefined" ? require : null;
4653
+ if (nodeRequire) {
4654
+ vm = nodeRequire(getVMModuleName());
4655
+ return true;
4656
+ }
4657
+ } catch (error) {
4658
+ logger.debug("node:vm module not available via require");
4659
+ }
4660
+ return false;
4661
+ }
4662
+ __name(tryLoadVM, "tryLoadVM");
4663
+ async function tryLoadVMAsync() {
4664
+ if (vm !== null) {
4665
+ return true;
4666
+ }
4667
+ if (!vmCheckAttempted) {
4668
+ if (tryLoadVM()) {
4669
+ return true;
4670
+ }
4671
+ }
4672
+ try {
4673
+ vm = await import(
4674
+ /* @vite-ignore */
4675
+ getVMModuleName()
4676
+ );
4677
+ return true;
4678
+ } catch (error) {
4679
+ logger.debug(
4680
+ "node:vm module not available in this environment (e.g., Deno)"
4681
+ );
4682
+ return false;
4683
+ }
4684
+ }
4685
+ __name(tryLoadVMAsync, "tryLoadVMAsync");
4686
+ var VMCodeExecutor = class extends BaseCodeExecutor {
4687
+ static {
4688
+ __name(this, "VMCodeExecutor");
4689
+ }
4690
+ defaultTimeout;
4691
+ memoryLimitMb;
4692
+ constructor(client, options) {
4693
+ super(client);
4694
+ this.defaultTimeout = options?.timeoutMs ?? 3e4;
4695
+ this.memoryLimitMb = options?.memoryLimitMb;
4696
+ tryLoadVM();
4697
+ }
4698
+ /**
4699
+ * Ensure VM module is loaded before execution
4700
+ */
4701
+ async ensureVMLoaded() {
4702
+ if (vm !== null) {
4703
+ return;
4704
+ }
4705
+ const loaded = await tryLoadVMAsync();
4706
+ if (!loaded) {
4707
+ throw new Error(
4708
+ "node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment."
4709
+ );
4710
+ }
4711
+ }
4712
+ /**
4713
+ * Execute JavaScript/TypeScript code with access to MCP tools.
4714
+ *
4715
+ * @param code - Code to execute
4716
+ * @param timeout - Execution timeout in milliseconds (default: configured timeout or 30000)
4717
+ */
4718
+ async execute(code, timeout) {
4719
+ const effectiveTimeout = timeout ?? this.defaultTimeout;
4720
+ await this.ensureVMLoaded();
4721
+ await this.ensureServersConnected();
4722
+ const logs = [];
4723
+ const startTime = Date.now();
4724
+ let result = null;
4725
+ let error = null;
4726
+ try {
4727
+ const context = await this._buildContext(logs);
4728
+ const wrappedCode = `
4729
+ (async () => {
4730
+ try {
4731
+ ${code}
4732
+ } catch (e) {
4733
+ throw e;
4734
+ }
4735
+ })()
4736
+ `;
4737
+ const script = new vm.Script(wrappedCode, {
4738
+ filename: "agent_code.js"
4739
+ });
4740
+ const promise = script.runInNewContext(context, {
4741
+ timeout: effectiveTimeout,
4742
+ displayErrors: true
4743
+ });
4744
+ result = await promise;
4745
+ } catch (e) {
4746
+ error = e.message || String(e);
4747
+ if (e.code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || e.message === "Script execution timed out." || typeof error === "string" && (error.includes("timed out") || error.includes("timeout"))) {
4748
+ error = "Script execution timed out";
4749
+ }
4750
+ if (e.stack) {
4751
+ logger.debug(`Code execution error stack: ${e.stack}`);
4752
+ }
4753
+ }
4754
+ const executionTime = (Date.now() - startTime) / 1e3;
4755
+ return {
4756
+ result,
4757
+ logs,
4758
+ error,
4759
+ execution_time: executionTime
4760
+ };
4761
+ }
4762
+ /**
4763
+ * Build the VM execution context with MCP tools and standard globals.
4764
+ *
4765
+ * @param logs - Array to capture console output
4766
+ */
4767
+ async _buildContext(logs) {
4768
+ const logHandler = /* @__PURE__ */ __name((...args) => {
4769
+ logs.push(
4770
+ args.map(
4771
+ (arg) => typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)
4772
+ ).join(" ")
4773
+ );
4774
+ }, "logHandler");
4775
+ const sandbox = {
4776
+ console: {
4777
+ log: logHandler,
4778
+ error: /* @__PURE__ */ __name((...args) => {
4779
+ logHandler("[ERROR]", ...args);
4780
+ }, "error"),
4781
+ warn: /* @__PURE__ */ __name((...args) => {
4782
+ logHandler("[WARN]", ...args);
4783
+ }, "warn"),
4784
+ info: logHandler,
4785
+ debug: logHandler
4786
+ },
4787
+ // Standard globals
4788
+ Object,
4789
+ Array,
4790
+ String,
4791
+ Number,
4792
+ Boolean,
4793
+ Date,
4794
+ Math,
4795
+ JSON,
4796
+ RegExp,
4797
+ Map,
4798
+ Set,
4799
+ Promise,
4800
+ parseInt,
4801
+ parseFloat,
4802
+ isNaN,
4803
+ isFinite,
4804
+ encodeURI,
4805
+ decodeURI,
4806
+ encodeURIComponent,
4807
+ decodeURIComponent,
4808
+ setTimeout,
4809
+ clearTimeout,
4810
+ // Helper for tools
4811
+ search_tools: this.createSearchToolsFunction(),
4812
+ __tool_namespaces: []
4813
+ };
4814
+ const toolNamespaces = {};
4815
+ const namespaceInfos = this.getToolNamespaces();
4816
+ for (const { serverName, tools, session } of namespaceInfos) {
4817
+ const serverNamespace = {};
4818
+ for (const tool of tools) {
4819
+ const toolName = tool.name;
4820
+ serverNamespace[toolName] = async (args) => {
4821
+ const result = await session.connector.callTool(toolName, args || {});
4822
+ if (result.content && result.content.length > 0) {
4823
+ const item = result.content[0];
4824
+ if (item.type === "text") {
4825
+ try {
4826
+ return JSON.parse(item.text);
4827
+ } catch {
4828
+ return item.text;
4829
+ }
4830
+ }
4831
+ return item;
4832
+ }
4833
+ return result;
4834
+ };
4835
+ }
4836
+ sandbox[serverName] = serverNamespace;
4837
+ toolNamespaces[serverName] = true;
4838
+ }
4839
+ sandbox.__tool_namespaces = Object.keys(toolNamespaces);
4840
+ return vm.createContext(sandbox);
4841
+ }
4842
+ /**
4843
+ * Clean up resources.
4844
+ * VM executor doesn't need cleanup, but method kept for interface consistency.
4845
+ */
4846
+ async cleanup() {
4847
+ }
4848
+ };
4849
+
4850
+ // src/config.ts
4851
+ var import_node_fs = require("fs");
4852
+
4853
+ // src/connectors/http.ts
4854
+ var import_client = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
4855
+ var import_streamableHttp = require("@mcp-use/modelcontextprotocol-sdk/client/streamableHttp.js");
4856
+ init_logging();
4857
+
4858
+ // src/task_managers/sse.ts
4859
+ var import_sse = require("@mcp-use/modelcontextprotocol-sdk/client/sse.js");
4860
+ init_logging();
4861
+
4862
+ // src/task_managers/base.ts
4863
+ init_logging();
4864
+ var ConnectionManager = class {
4865
+ static {
4866
+ __name(this, "ConnectionManager");
4867
+ }
4868
+ _readyPromise;
4869
+ _readyResolver;
4870
+ _donePromise;
4871
+ _doneResolver;
4872
+ _exception = null;
4873
+ _connection = null;
4874
+ _task = null;
4875
+ _abortController = null;
4876
+ constructor() {
4877
+ this.reset();
4878
+ }
4879
+ /**
4880
+ * Start the connection manager and establish a connection.
4881
+ *
4882
+ * @returns The established connection.
4883
+ * @throws If the connection cannot be established.
4884
+ */
4885
+ async start() {
4886
+ this.reset();
4887
+ logger.debug(`Starting ${this.constructor.name}`);
4888
+ this._task = this.connectionTask();
4889
+ await this._readyPromise;
4890
+ if (this._exception) {
4891
+ throw this._exception;
4892
+ }
4893
+ if (this._connection === null) {
4894
+ throw new Error("Connection was not established");
4895
+ }
4896
+ return this._connection;
4897
+ }
4898
+ /**
4899
+ * Stop the connection manager and close the connection.
4900
+ */
4901
+ async stop() {
4902
+ if (this._task && this._abortController) {
4903
+ logger.debug(`Cancelling ${this.constructor.name} task`);
4904
+ this._abortController.abort();
4905
+ try {
4906
+ await this._task;
4907
+ } catch (e) {
4908
+ if (e instanceof Error && e.name === "AbortError") {
4909
+ logger.debug(`${this.constructor.name} task aborted successfully`);
4910
+ } else {
4911
+ logger.warn(`Error stopping ${this.constructor.name} task: ${e}`);
4912
+ }
4913
+ }
4914
+ }
4915
+ await this._donePromise;
4916
+ logger.debug(`${this.constructor.name} task completed`);
4917
+ }
4918
+ /**
4919
+ * Reset all internal state.
4920
+ */
4921
+ reset() {
4922
+ this._readyPromise = new Promise((res) => this._readyResolver = res);
4923
+ this._donePromise = new Promise((res) => this._doneResolver = res);
4924
+ this._exception = null;
4925
+ this._connection = null;
4926
+ this._task = null;
4927
+ this._abortController = new AbortController();
4928
+ }
4929
+ /**
4930
+ * The background task responsible for establishing and maintaining the
4931
+ * connection until it is cancelled.
4932
+ */
4933
+ async connectionTask() {
4934
+ logger.debug(`Running ${this.constructor.name} task`);
4935
+ try {
4936
+ this._connection = await this.establishConnection();
4937
+ logger.debug(`${this.constructor.name} connected successfully`);
4938
+ this._readyResolver();
4939
+ await this.waitForAbort();
4940
+ } catch (err) {
4941
+ this._exception = err;
4942
+ logger.error(`Error in ${this.constructor.name} task: ${err}`);
4943
+ this._readyResolver();
4944
+ } finally {
4945
+ if (this._connection !== null) {
4946
+ try {
4947
+ await this.closeConnection(this._connection);
4948
+ } catch (closeErr) {
4949
+ logger.warn(
4950
+ `Error closing connection in ${this.constructor.name}: ${closeErr}`
4951
+ );
4952
+ }
4953
+ this._connection = null;
4954
+ }
4955
+ this._doneResolver();
4956
+ }
4957
+ }
4958
+ /**
4959
+ * Helper that returns a promise which resolves when the abort signal fires.
4960
+ */
4961
+ async waitForAbort() {
4962
+ return new Promise((_resolve, _reject) => {
4963
+ if (!this._abortController) {
4964
+ return;
4965
+ }
4966
+ const signal = this._abortController.signal;
4967
+ if (signal.aborted) {
4968
+ _resolve();
4969
+ return;
4970
+ }
4971
+ const onAbort = /* @__PURE__ */ __name(() => {
4972
+ signal.removeEventListener("abort", onAbort);
4973
+ _resolve();
4974
+ }, "onAbort");
4975
+ signal.addEventListener("abort", onAbort);
4976
+ });
4977
+ }
4978
+ };
4979
+
4980
+ // src/task_managers/sse.ts
4981
+ var SseConnectionManager = class extends ConnectionManager {
4982
+ static {
4983
+ __name(this, "SseConnectionManager");
4984
+ }
4985
+ url;
4986
+ opts;
4987
+ _transport = null;
4988
+ /**
4989
+ * Create an SSE connection manager.
4990
+ *
4991
+ * @param url The SSE endpoint URL.
4992
+ * @param opts Optional transport options (auth, headers, etc.).
4993
+ */
4994
+ constructor(url, opts) {
4995
+ super();
4996
+ this.url = typeof url === "string" ? new URL(url) : url;
4997
+ this.opts = opts;
4998
+ }
4999
+ /**
5000
+ * Spawn a new `SSEClientTransport` and start the connection.
5001
+ */
5002
+ async establishConnection() {
5003
+ this._transport = new import_sse.SSEClientTransport(this.url, this.opts);
5004
+ logger.debug(`${this.constructor.name} connected successfully`);
5005
+ return this._transport;
5006
+ }
5007
+ /**
5008
+ * Close the underlying transport and clean up resources.
5009
+ */
5010
+ async closeConnection(_connection) {
5011
+ if (this._transport) {
5012
+ try {
5013
+ await this._transport.close();
5014
+ } catch (e) {
5015
+ logger.warn(`Error closing SSE transport: ${e}`);
5016
+ } finally {
5017
+ this._transport = null;
5018
+ }
5019
+ }
5020
+ }
5021
+ };
5022
+
5023
+ // src/connectors/http.ts
5024
+ var HttpConnector = class extends BaseConnector {
5025
+ static {
5026
+ __name(this, "HttpConnector");
5027
+ }
5028
+ baseUrl;
5029
+ headers;
5030
+ timeout;
5031
+ sseReadTimeout;
5032
+ clientInfo;
5033
+ preferSse;
5034
+ transportType = null;
5035
+ streamableTransport = null;
5036
+ constructor(baseUrl, opts = {}) {
5037
+ super(opts);
5038
+ this.baseUrl = baseUrl.replace(/\/$/, "");
5039
+ this.headers = { ...opts.headers ?? {} };
5040
+ if (opts.authToken) {
5041
+ this.headers.Authorization = `Bearer ${opts.authToken}`;
5042
+ }
5043
+ this.timeout = opts.timeout ?? 3e4;
5044
+ this.sseReadTimeout = opts.sseReadTimeout ?? 3e5;
5045
+ this.clientInfo = opts.clientInfo ?? {
5046
+ name: "http-connector",
5047
+ version: "1.0.0"
5048
+ };
5049
+ this.preferSse = opts.preferSse ?? false;
5050
+ }
5051
+ /** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
5052
+ async connect() {
5053
+ if (this.connected) {
5054
+ logger.debug("Already connected to MCP implementation");
5055
+ return;
5056
+ }
5057
+ const baseUrl = this.baseUrl;
5058
+ if (this.preferSse) {
5059
+ logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${baseUrl}`);
5060
+ await this.connectWithSse(baseUrl);
5061
+ return;
5062
+ }
5063
+ logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);
5064
+ try {
5065
+ logger.info("\u{1F504} Attempting streamable HTTP transport...");
5066
+ await this.connectWithStreamableHttp(baseUrl);
5067
+ logger.info("\u2705 Successfully connected via streamable HTTP");
5068
+ } catch (err) {
5069
+ let fallbackReason = "Unknown error";
5070
+ let is401Error = false;
5071
+ if (err instanceof import_streamableHttp.StreamableHTTPError) {
5072
+ const streamableErr = err;
5073
+ is401Error = streamableErr.code === 401;
5074
+ if (streamableErr.code === 400 && streamableErr.message.includes("Missing session ID")) {
5075
+ fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
5076
+ logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
5077
+ } else if (streamableErr.code === 404 || streamableErr.code === 405) {
5078
+ fallbackReason = `Server returned ${streamableErr.code} - server likely doesn't support streamable HTTP`;
5079
+ logger.debug(fallbackReason);
5080
+ } else {
5081
+ fallbackReason = `Server returned ${streamableErr.code}: ${streamableErr.message}`;
5082
+ logger.debug(fallbackReason);
5083
+ }
5084
+ } else if (err instanceof Error) {
5085
+ const errorStr = err.toString();
5086
+ const errorMsg = err.message || "";
5087
+ is401Error = errorStr.includes("401") || errorMsg.includes("Unauthorized");
5088
+ if (errorStr.includes("Missing session ID") || errorStr.includes("Bad Request: Missing session ID") || errorMsg.includes("FastMCP session ID error")) {
5089
+ fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
5090
+ logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
5091
+ } else if (errorStr.includes("405 Method Not Allowed") || errorStr.includes("404 Not Found")) {
5092
+ fallbackReason = "Server doesn't support streamable HTTP (405/404)";
5093
+ logger.debug(fallbackReason);
5094
+ } else {
5095
+ fallbackReason = `Streamable HTTP failed: ${err.message}`;
5096
+ logger.debug(fallbackReason);
5097
+ }
5098
+ }
5099
+ if (is401Error) {
5100
+ logger.info("Authentication required - skipping SSE fallback");
5101
+ await this.cleanupResources();
5102
+ const authError = new Error("Authentication required");
5103
+ authError.code = 401;
5104
+ throw authError;
5105
+ }
5106
+ logger.info("\u{1F504} Falling back to SSE transport...");
5107
+ try {
5108
+ await this.connectWithSse(baseUrl);
5109
+ } catch (sseErr) {
5110
+ logger.error(`Failed to connect with both transports:`);
5111
+ logger.error(` Streamable HTTP: ${fallbackReason}`);
5112
+ logger.error(` SSE: ${sseErr}`);
5113
+ await this.cleanupResources();
5114
+ const sseIs401 = sseErr?.message?.includes("401") || sseErr?.message?.includes("Unauthorized");
5115
+ if (sseIs401) {
5116
+ const authError = new Error("Authentication required");
5117
+ authError.code = 401;
5118
+ throw authError;
5119
+ }
5120
+ throw new Error(
5121
+ "Could not connect to server with any available transport"
5122
+ );
5123
+ }
5124
+ }
5125
+ }
5126
+ async connectWithStreamableHttp(baseUrl) {
5127
+ try {
5128
+ const streamableTransport = new import_streamableHttp.StreamableHTTPClientTransport(
5129
+ new URL(baseUrl),
5130
+ {
5131
+ authProvider: this.opts.authProvider,
5132
+ // ← Pass OAuth provider to SDK
5133
+ requestInit: {
5134
+ headers: this.headers
5135
+ },
5136
+ // Pass through reconnection options
5137
+ reconnectionOptions: {
5138
+ maxReconnectionDelay: 3e4,
5139
+ initialReconnectionDelay: 1e3,
5140
+ reconnectionDelayGrowFactor: 1.5,
5141
+ maxRetries: 2
5142
+ }
5143
+ // Don't pass sessionId - let the SDK generate it automatically during connect()
5144
+ }
5145
+ );
5146
+ let transport = streamableTransport;
5147
+ if (this.opts.wrapTransport) {
5148
+ const serverId = this.baseUrl;
5149
+ transport = this.opts.wrapTransport(
5150
+ transport,
5151
+ serverId
5152
+ );
5153
+ }
5154
+ const clientOptions = {
5155
+ ...this.opts.clientOptions || {},
5156
+ capabilities: {
5157
+ ...this.opts.clientOptions?.capabilities || {},
5158
+ roots: { listChanged: true },
5159
+ // Always advertise roots capability
5160
+ // Add sampling capability if callback is provided
5161
+ ...this.opts.samplingCallback ? { sampling: {} } : {},
5162
+ // Add elicitation capability if callback is provided
5163
+ ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
5164
+ }
5165
+ };
5166
+ logger.debug(
5167
+ `Creating Client with capabilities:`,
5168
+ JSON.stringify(clientOptions.capabilities, null, 2)
5169
+ );
5170
+ this.client = new import_client.Client(this.clientInfo, clientOptions);
5171
+ this.setupRootsHandler();
5172
+ logger.debug("Roots handler registered before connect");
5173
+ try {
5174
+ await this.client.connect(transport, {
5175
+ timeout: Math.min(this.timeout, 3e3)
5176
+ });
5177
+ const sessionId = streamableTransport.sessionId;
5178
+ if (sessionId) {
5179
+ logger.debug(`Session ID obtained: ${sessionId}`);
5180
+ } else {
5181
+ logger.warn(
5182
+ "Session ID not available after connect - this may cause issues with SSE stream"
5183
+ );
5184
+ }
5185
+ } catch (connectErr) {
5186
+ if (connectErr instanceof Error) {
5187
+ const errMsg = connectErr.message || connectErr.toString();
5188
+ if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID") || errMsg.includes("Mcp-Session-Id header is required")) {
5189
+ const wrappedError = new Error(
5190
+ `Session ID error: ${errMsg}. The SDK should automatically extract session ID from initialize response.`
5191
+ );
5192
+ wrappedError.cause = connectErr;
5193
+ throw wrappedError;
5194
+ }
5195
+ }
5196
+ throw connectErr;
5197
+ }
5198
+ this.streamableTransport = streamableTransport;
5199
+ this.connectionManager = {
5200
+ stop: /* @__PURE__ */ __name(async () => {
5201
+ if (this.streamableTransport) {
5202
+ try {
5203
+ await this.streamableTransport.terminateSession();
5204
+ await this.streamableTransport.close();
5205
+ } catch (e) {
5206
+ logger.warn(`Error closing Streamable HTTP transport: ${e}`);
5207
+ } finally {
5208
+ this.streamableTransport = null;
5209
+ }
5210
+ }
5211
+ }, "stop")
5212
+ };
5213
+ this.connected = true;
5214
+ this.transportType = "streamable-http";
5215
+ this.setupNotificationHandler();
5216
+ this.setupSamplingHandler();
5217
+ this.setupElicitationHandler();
5218
+ logger.debug(
5219
+ `Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`
5220
+ );
5221
+ this.trackConnectorInit({
5222
+ serverUrl: this.baseUrl,
5223
+ publicIdentifier: `${this.baseUrl} (streamable-http)`
5224
+ });
5225
+ } catch (err) {
5226
+ await this.cleanupResources();
5227
+ throw err;
5228
+ }
5229
+ }
5230
+ async connectWithSse(baseUrl) {
5231
+ try {
5232
+ this.connectionManager = new SseConnectionManager(baseUrl, {
5233
+ authProvider: this.opts.authProvider,
5234
+ // ← Pass OAuth provider to SDK (same as streamable HTTP)
5235
+ requestInit: {
5236
+ headers: this.headers
5237
+ }
5238
+ });
5239
+ let transport = await this.connectionManager.start();
5240
+ if (this.opts.wrapTransport) {
5241
+ const serverId = this.baseUrl;
5242
+ transport = this.opts.wrapTransport(transport, serverId);
5243
+ }
5244
+ const clientOptions = {
5245
+ ...this.opts.clientOptions || {},
5246
+ capabilities: {
5247
+ ...this.opts.clientOptions?.capabilities || {},
5248
+ roots: { listChanged: true },
5249
+ // Always advertise roots capability
5250
+ // Add sampling capability if callback is provided
5251
+ ...this.opts.samplingCallback ? { sampling: {} } : {},
5252
+ // Add elicitation capability if callback is provided
5253
+ ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
5254
+ }
5255
+ };
5256
+ logger.debug(
5257
+ `Creating Client with capabilities (SSE):`,
5258
+ JSON.stringify(clientOptions.capabilities, null, 2)
5259
+ );
5260
+ this.client = new import_client.Client(this.clientInfo, clientOptions);
5261
+ this.setupRootsHandler();
5262
+ logger.debug("Roots handler registered before connect (SSE)");
5263
+ await this.client.connect(transport);
5264
+ this.connected = true;
5265
+ this.transportType = "sse";
5266
+ this.setupNotificationHandler();
5267
+ this.setupSamplingHandler();
5268
+ this.setupElicitationHandler();
5269
+ logger.debug(
5270
+ `Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`
5271
+ );
5272
+ this.trackConnectorInit({
5273
+ serverUrl: this.baseUrl,
5274
+ publicIdentifier: `${this.baseUrl} (sse)`
5275
+ });
5276
+ } catch (err) {
5277
+ await this.cleanupResources();
5278
+ throw err;
5279
+ }
5280
+ }
5281
+ get publicIdentifier() {
5282
+ return {
5283
+ type: "http",
5284
+ url: this.baseUrl,
5285
+ transport: this.transportType || "unknown"
5286
+ };
5287
+ }
5288
+ /**
5289
+ * Get the transport type being used (streamable-http or sse)
5290
+ */
5291
+ getTransportType() {
5292
+ return this.transportType;
5293
+ }
5294
+ };
5295
+
5296
+ // src/connectors/stdio.ts
5297
+ var import_node_process = __toESM(require("process"), 1);
5298
+ var import_client2 = require("@mcp-use/modelcontextprotocol-sdk/client/index.js");
5299
+ init_logging();
5300
+
5301
+ // src/task_managers/stdio.ts
5302
+ var import_stdio = require("@mcp-use/modelcontextprotocol-sdk/client/stdio.js");
5303
+ init_logging();
5304
+ var StdioConnectionManager = class extends ConnectionManager {
5305
+ static {
5306
+ __name(this, "StdioConnectionManager");
5307
+ }
5308
+ serverParams;
5309
+ errlog;
5310
+ _transport = null;
5311
+ /**
5312
+ * Create a new stdio connection manager.
5313
+ *
5314
+ * @param serverParams Parameters for the stdio server process.
5315
+ * @param errlog Stream to which the server's stderr should be piped.
5316
+ * Defaults to `process.stderr`.
5317
+ */
5318
+ constructor(serverParams, errlog = process.stderr) {
5319
+ super();
5320
+ this.serverParams = serverParams;
5321
+ this.errlog = errlog;
5322
+ }
5323
+ /**
5324
+ * Establish the stdio connection by spawning the server process and starting
5325
+ * the SDK's transport. Returns the live `StdioClientTransport` instance.
5326
+ */
5327
+ async establishConnection() {
5328
+ this._transport = new import_stdio.StdioClientTransport(this.serverParams);
5329
+ if (this._transport.stderr && typeof this._transport.stderr.pipe === "function") {
5330
+ this._transport.stderr.pipe(
5331
+ this.errlog
5332
+ );
5333
+ }
5334
+ logger.debug(`${this.constructor.name} connected successfully`);
5335
+ return this._transport;
5336
+ }
5337
+ /**
5338
+ * Close the stdio connection, making sure the transport cleans up the child
5339
+ * process and associated resources.
5340
+ */
5341
+ async closeConnection(_connection) {
5342
+ if (this._transport) {
5343
+ try {
5344
+ await this._transport.close();
5345
+ } catch (e) {
5346
+ logger.warn(`Error closing stdio transport: ${e}`);
5347
+ } finally {
5348
+ this._transport = null;
5349
+ }
5350
+ }
5351
+ }
5352
+ };
5353
+
5354
+ // src/connectors/stdio.ts
5355
+ var StdioConnector = class extends BaseConnector {
5356
+ static {
5357
+ __name(this, "StdioConnector");
5358
+ }
5359
+ command;
5360
+ args;
5361
+ env;
5362
+ errlog;
5363
+ clientInfo;
5364
+ constructor({
5365
+ command = "npx",
5366
+ args = [],
5367
+ env,
5368
+ errlog = import_node_process.default.stderr,
5369
+ ...rest
5370
+ } = {}) {
5371
+ super(rest);
5372
+ this.command = command;
5373
+ this.args = args;
5374
+ this.env = env;
5375
+ this.errlog = errlog;
5376
+ this.clientInfo = rest.clientInfo ?? {
5377
+ name: "stdio-connector",
5378
+ version: "1.0.0"
5379
+ };
5380
+ }
5381
+ /** Establish connection to the MCP implementation. */
5382
+ async connect() {
5383
+ if (this.connected) {
5384
+ logger.debug("Already connected to MCP implementation");
5385
+ return;
5386
+ }
5387
+ logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`);
5388
+ try {
5389
+ let mergedEnv;
5390
+ if (this.env) {
5391
+ mergedEnv = {};
5392
+ for (const [key, value] of Object.entries(import_node_process.default.env)) {
5393
+ if (value !== void 0) {
5394
+ mergedEnv[key] = value;
5395
+ }
3186
5396
  }
3187
- }, "func")
5397
+ Object.assign(mergedEnv, this.env);
5398
+ }
5399
+ const serverParams = {
5400
+ command: this.command,
5401
+ args: this.args,
5402
+ env: mergedEnv
5403
+ };
5404
+ this.connectionManager = new StdioConnectionManager(
5405
+ serverParams,
5406
+ this.errlog
5407
+ );
5408
+ const transport = await this.connectionManager.start();
5409
+ const clientOptions = {
5410
+ ...this.opts.clientOptions || {},
5411
+ capabilities: {
5412
+ ...this.opts.clientOptions?.capabilities || {},
5413
+ roots: { listChanged: true },
5414
+ // Always advertise roots capability
5415
+ // Add sampling capability if callback is provided
5416
+ ...this.opts.samplingCallback ? { sampling: {} } : {},
5417
+ // Add elicitation capability if callback is provided
5418
+ ...this.opts.elicitationCallback ? { elicitation: { form: {}, url: {} } } : {}
5419
+ }
5420
+ };
5421
+ this.client = new import_client2.Client(this.clientInfo, clientOptions);
5422
+ await this.client.connect(transport);
5423
+ this.connected = true;
5424
+ this.setupNotificationHandler();
5425
+ this.setupRootsHandler();
5426
+ this.setupSamplingHandler();
5427
+ this.setupElicitationHandler();
5428
+ logger.debug(
5429
+ `Successfully connected to MCP implementation: ${this.command}`
5430
+ );
5431
+ this.trackConnectorInit({
5432
+ serverCommand: this.command,
5433
+ serverArgs: this.args,
5434
+ publicIdentifier: `${this.command} ${this.args.join(" ")}`
5435
+ });
5436
+ } catch (err) {
5437
+ logger.error(`Failed to connect to MCP implementation: ${err}`);
5438
+ await this.cleanupResources();
5439
+ throw err;
5440
+ }
5441
+ }
5442
+ get publicIdentifier() {
5443
+ return {
5444
+ type: "stdio",
5445
+ "command&args": `${this.command} ${this.args.join(" ")}`
5446
+ };
5447
+ }
5448
+ };
5449
+
5450
+ // src/config.ts
5451
+ function loadConfigFile(filepath) {
5452
+ const raw = (0, import_node_fs.readFileSync)(filepath, "utf-8");
5453
+ return JSON.parse(raw);
5454
+ }
5455
+ __name(loadConfigFile, "loadConfigFile");
5456
+ function createConnectorFromConfig(serverConfig, connectorOptions) {
5457
+ if ("command" in serverConfig && "args" in serverConfig) {
5458
+ return new StdioConnector({
5459
+ command: serverConfig.command,
5460
+ args: serverConfig.args,
5461
+ env: serverConfig.env,
5462
+ ...connectorOptions
3188
5463
  });
3189
- return tool;
5464
+ }
5465
+ if ("url" in serverConfig) {
5466
+ const transport = serverConfig.transport || "http";
5467
+ return new HttpConnector(serverConfig.url, {
5468
+ headers: serverConfig.headers,
5469
+ authToken: serverConfig.auth_token || serverConfig.authToken,
5470
+ // Only force SSE if explicitly requested
5471
+ preferSse: serverConfig.preferSse || transport === "sse",
5472
+ ...connectorOptions
5473
+ });
5474
+ }
5475
+ throw new Error("Cannot determine connector type from config");
5476
+ }
5477
+ __name(createConnectorFromConfig, "createConnectorFromConfig");
5478
+
5479
+ // src/client.ts
5480
+ init_logging();
5481
+ var MCPClient = class _MCPClient extends BaseMCPClient {
5482
+ static {
5483
+ __name(this, "MCPClient");
3190
5484
  }
3191
5485
  /**
3192
- * Convert a single MCP prompt into a LangChainJS structured tool.
3193
- * The resulting tool executes getPrompt on the connector with the prompt's name
3194
- * and the user-provided arguments (if any).
5486
+ * Get the mcp-use package version.
5487
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
3195
5488
  */
3196
- convertPrompt(mcpPrompt, connector) {
3197
- let argsSchema = import_zod2.z.object({}).optional();
3198
- if (mcpPrompt.arguments && mcpPrompt.arguments.length > 0) {
3199
- const schemaFields = {};
3200
- for (const arg of mcpPrompt.arguments) {
3201
- const zodType = import_zod2.z.string();
3202
- if (arg.required !== false) {
3203
- schemaFields[arg.name] = zodType;
3204
- } else {
3205
- schemaFields[arg.name] = zodType.optional();
3206
- }
5489
+ static getPackageVersion() {
5490
+ return getPackageVersion();
5491
+ }
5492
+ codeMode = false;
5493
+ _codeExecutor = null;
5494
+ _customCodeExecutor = null;
5495
+ _codeExecutorConfig = "vm";
5496
+ _executorOptions;
5497
+ _samplingCallback;
5498
+ _elicitationCallback;
5499
+ constructor(config, options) {
5500
+ if (config) {
5501
+ if (typeof config === "string") {
5502
+ super(loadConfigFile(config));
5503
+ } else {
5504
+ super(config);
3207
5505
  }
3208
- argsSchema = Object.keys(schemaFields).length > 0 ? import_zod2.z.object(schemaFields) : import_zod2.z.object({}).optional();
5506
+ } else {
5507
+ super();
5508
+ }
5509
+ let codeModeEnabled = false;
5510
+ let executorConfig = "vm";
5511
+ let executorOptions;
5512
+ if (options?.codeMode) {
5513
+ if (typeof options.codeMode === "boolean") {
5514
+ codeModeEnabled = options.codeMode;
5515
+ } else {
5516
+ codeModeEnabled = options.codeMode.enabled;
5517
+ executorConfig = options.codeMode.executor ?? "vm";
5518
+ executorOptions = options.codeMode.executorOptions;
5519
+ }
5520
+ }
5521
+ this.codeMode = codeModeEnabled;
5522
+ this._codeExecutorConfig = executorConfig;
5523
+ this._executorOptions = executorOptions;
5524
+ this._samplingCallback = options?.samplingCallback;
5525
+ this._elicitationCallback = options?.elicitationCallback;
5526
+ if (this.codeMode) {
5527
+ this._setupCodeModeConnector();
5528
+ }
5529
+ this._trackClientInit();
5530
+ }
5531
+ _trackClientInit() {
5532
+ const servers = Object.keys(this.config.mcpServers ?? {});
5533
+ const hasSamplingCallback = !!this._samplingCallback;
5534
+ const hasElicitationCallback = !!this._elicitationCallback;
5535
+ Tel.getInstance().trackMCPClientInit({
5536
+ codeMode: this.codeMode,
5537
+ sandbox: false,
5538
+ // Sandbox not supported in TS yet
5539
+ allCallbacks: hasSamplingCallback && hasElicitationCallback,
5540
+ verify: false,
5541
+ // No verify option in TS client
5542
+ servers,
5543
+ numServers: servers.length,
5544
+ isBrowser: false
5545
+ // Node.js MCPClient
5546
+ }).catch((e) => logger.debug(`Failed to track MCPClient init: ${e}`));
5547
+ }
5548
+ static fromDict(cfg, options) {
5549
+ return new _MCPClient(cfg, options);
5550
+ }
5551
+ static fromConfigFile(path2, options) {
5552
+ return new _MCPClient(loadConfigFile(path2), options);
5553
+ }
5554
+ /**
5555
+ * Save configuration to a file (Node.js only)
5556
+ */
5557
+ saveConfig(filepath) {
5558
+ const dir = import_node_path.default.dirname(filepath);
5559
+ if (!import_node_fs2.default.existsSync(dir)) {
5560
+ import_node_fs2.default.mkdirSync(dir, { recursive: true });
3209
5561
  }
3210
- const tool = new import_tools.DynamicStructuredTool({
3211
- name: mcpPrompt.name,
3212
- description: mcpPrompt.description || "",
3213
- schema: argsSchema,
3214
- func: /* @__PURE__ */ __name(async (input) => {
3215
- logger.debug(
3216
- `Prompt tool: "${mcpPrompt.name}" called with args: ${JSON.stringify(input)}`
5562
+ import_node_fs2.default.writeFileSync(filepath, JSON.stringify(this.config, null, 2), "utf-8");
5563
+ }
5564
+ /**
5565
+ * Create a connector from server configuration (Node.js version)
5566
+ * Supports all connector types including StdioConnector
5567
+ */
5568
+ createConnectorFromConfig(serverConfig) {
5569
+ return createConnectorFromConfig(serverConfig, {
5570
+ samplingCallback: this._samplingCallback,
5571
+ elicitationCallback: this._elicitationCallback
5572
+ });
5573
+ }
5574
+ _setupCodeModeConnector() {
5575
+ logger.debug("Code mode connector initialized as internal meta server");
5576
+ const connector = new CodeModeConnector(this);
5577
+ const session = new MCPSession(connector);
5578
+ this.sessions["code_mode"] = session;
5579
+ this.activeSessions.push("code_mode");
5580
+ }
5581
+ _ensureCodeExecutor() {
5582
+ if (!this._codeExecutor) {
5583
+ const config = this._codeExecutorConfig;
5584
+ if (config instanceof BaseCodeExecutor) {
5585
+ this._codeExecutor = config;
5586
+ } else if (typeof config === "function") {
5587
+ this._customCodeExecutor = config;
5588
+ throw new Error(
5589
+ "Custom executor function should be handled in executeCode"
3217
5590
  );
5591
+ } else if (config === "e2b") {
5592
+ const opts = this._executorOptions;
5593
+ if (!opts?.apiKey) {
5594
+ logger.warn("E2B executor requires apiKey. Falling back to VM.");
5595
+ try {
5596
+ this._codeExecutor = new VMCodeExecutor(
5597
+ this,
5598
+ this._executorOptions
5599
+ );
5600
+ } catch (error) {
5601
+ throw new Error(
5602
+ "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."
5603
+ );
5604
+ }
5605
+ } else {
5606
+ this._codeExecutor = new E2BCodeExecutor(this, opts);
5607
+ }
5608
+ } else {
3218
5609
  try {
3219
- const result = await connector.getPrompt(mcpPrompt.name, input);
3220
- if (result.messages && result.messages.length > 0) {
3221
- return result.messages.map((msg) => {
3222
- if (typeof msg === "string") {
3223
- return msg;
3224
- }
3225
- if (msg.content) {
3226
- return typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
3227
- }
3228
- return JSON.stringify(msg);
3229
- }).join("\n");
5610
+ this._codeExecutor = new VMCodeExecutor(
5611
+ this,
5612
+ this._executorOptions
5613
+ );
5614
+ } catch (error) {
5615
+ const e2bOpts = this._executorOptions;
5616
+ const e2bApiKey = e2bOpts?.apiKey || process.env.E2B_API_KEY;
5617
+ if (e2bApiKey) {
5618
+ logger.info(
5619
+ "VM executor not available in this environment. Falling back to E2B."
5620
+ );
5621
+ this._codeExecutor = new E2BCodeExecutor(this, {
5622
+ ...e2bOpts,
5623
+ apiKey: e2bApiKey
5624
+ });
5625
+ } else {
5626
+ throw new Error(
5627
+ "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."
5628
+ );
3230
5629
  }
3231
- return "Prompt returned no messages";
3232
- } catch (err) {
3233
- logger.error(`Error getting prompt: ${err.message}`);
3234
- return `Error getting prompt: ${String(err)}`;
3235
5630
  }
3236
- }, "func")
5631
+ }
5632
+ }
5633
+ return this._codeExecutor;
5634
+ }
5635
+ /**
5636
+ * Execute code in code mode
5637
+ */
5638
+ async executeCode(code, timeout) {
5639
+ if (!this.codeMode) {
5640
+ throw new Error("Code execution mode is not enabled");
5641
+ }
5642
+ if (this._customCodeExecutor) {
5643
+ return this._customCodeExecutor(code, timeout);
5644
+ }
5645
+ return this._ensureCodeExecutor().execute(code, timeout);
5646
+ }
5647
+ /**
5648
+ * Search available tools (used by code mode)
5649
+ */
5650
+ async searchTools(query = "", detailLevel = "full") {
5651
+ if (!this.codeMode) {
5652
+ throw new Error("Code execution mode is not enabled");
5653
+ }
5654
+ return this._ensureCodeExecutor().createSearchToolsFunction()(
5655
+ query,
5656
+ detailLevel
5657
+ );
5658
+ }
5659
+ /**
5660
+ * Override getServerNames to exclude internal code_mode server
5661
+ */
5662
+ getServerNames() {
5663
+ const isCodeModeEnabled = this.codeMode;
5664
+ return super.getServerNames().filter((name) => {
5665
+ return !isCodeModeEnabled || name !== "code_mode";
3237
5666
  });
3238
- return tool;
5667
+ }
5668
+ /**
5669
+ * Close the client and clean up resources including code executors.
5670
+ * This ensures E2B sandboxes and other resources are properly released.
5671
+ */
5672
+ async close() {
5673
+ if (this._codeExecutor) {
5674
+ await this._codeExecutor.cleanup();
5675
+ this._codeExecutor = null;
5676
+ }
5677
+ await this.closeAllSessions();
3239
5678
  }
3240
5679
  };
3241
5680
 
@@ -3903,6 +6342,26 @@ var import_zod8 = require("zod");
3903
6342
  init_logging();
3904
6343
  var API_CHATS_ENDPOINT = "/api/v1/chats";
3905
6344
  var API_CHAT_EXECUTE_ENDPOINT = "/api/v1/chats/{chat_id}/execute";
6345
+ function normalizeRemoteRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6346
+ if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
6347
+ const options = queryOrOptions;
6348
+ return {
6349
+ query: options.prompt,
6350
+ maxSteps: options.maxSteps,
6351
+ manageConnector: options.manageConnector,
6352
+ externalHistory: options.externalHistory,
6353
+ outputSchema: options.schema
6354
+ };
6355
+ }
6356
+ return {
6357
+ query: queryOrOptions,
6358
+ maxSteps,
6359
+ manageConnector,
6360
+ externalHistory,
6361
+ outputSchema
6362
+ };
6363
+ }
6364
+ __name(normalizeRemoteRunOptions, "normalizeRemoteRunOptions");
3906
6365
  var RemoteAgent = class {
3907
6366
  static {
3908
6367
  __name(this, "RemoteAgent");
@@ -3999,8 +6458,20 @@ var RemoteAgent = class {
3999
6458
  throw new Error(`Failed to create chat session: ${String(e)}`);
4000
6459
  }
4001
6460
  }
4002
- async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
4003
- if (externalHistory !== void 0) {
6461
+ async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6462
+ const {
6463
+ query,
6464
+ maxSteps: steps,
6465
+ externalHistory: history,
6466
+ outputSchema: schema
6467
+ } = normalizeRemoteRunOptions(
6468
+ queryOrOptions,
6469
+ maxSteps,
6470
+ manageConnector,
6471
+ externalHistory,
6472
+ outputSchema
6473
+ );
6474
+ if (history !== void 0) {
4004
6475
  logger.warn("External history is not yet supported for remote execution");
4005
6476
  }
4006
6477
  try {
@@ -4011,10 +6482,10 @@ var RemoteAgent = class {
4011
6482
  const chatId = this.chatId;
4012
6483
  const executionPayload = {
4013
6484
  query,
4014
- max_steps: maxSteps ?? 10
6485
+ max_steps: steps ?? 10
4015
6486
  };
4016
- if (outputSchema) {
4017
- executionPayload.output_schema = this.pydanticToJsonSchema(outputSchema);
6487
+ if (schema) {
6488
+ executionPayload.output_schema = this.pydanticToJsonSchema(schema);
4018
6489
  logger.info(`\u{1F527} Using structured output with schema`);
4019
6490
  }
4020
6491
  const headers = {
@@ -4088,8 +6559,8 @@ Raw error: ${result}`
4088
6559
  );
4089
6560
  }
4090
6561
  }
4091
- if (outputSchema) {
4092
- return this.parseStructuredResponse(result, outputSchema);
6562
+ if (schema) {
6563
+ return this.parseStructuredResponse(result, schema);
4093
6564
  }
4094
6565
  if (typeof result === "object" && result !== null && "result" in result) {
4095
6566
  return result.result;
@@ -4114,9 +6585,9 @@ Raw error: ${result}`
4114
6585
  }
4115
6586
  }
4116
6587
  // eslint-disable-next-line require-yield
4117
- async *stream(query, maxSteps, manageConnector, externalHistory, outputSchema) {
6588
+ async *stream(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
4118
6589
  const result = await this.run(
4119
- query,
6590
+ queryOrOptions,
4120
6591
  maxSteps,
4121
6592
  manageConnector,
4122
6593
  externalHistory,
@@ -4129,7 +6600,153 @@ Raw error: ${result}`
4129
6600
  }
4130
6601
  };
4131
6602
 
6603
+ // src/agents/utils/llm_provider.ts
6604
+ init_logging();
6605
+ var PROVIDER_CONFIG = {
6606
+ openai: {
6607
+ package: "@langchain/openai",
6608
+ className: "ChatOpenAI",
6609
+ envVars: ["OPENAI_API_KEY"],
6610
+ defaultModel: "gpt-4o"
6611
+ },
6612
+ anthropic: {
6613
+ package: "@langchain/anthropic",
6614
+ className: "ChatAnthropic",
6615
+ envVars: ["ANTHROPIC_API_KEY"],
6616
+ defaultModel: "claude-3-5-sonnet-20241022"
6617
+ },
6618
+ google: {
6619
+ package: "@langchain/google-genai",
6620
+ className: "ChatGoogleGenerativeAI",
6621
+ envVars: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
6622
+ defaultModel: "gemini-pro"
6623
+ },
6624
+ groq: {
6625
+ package: "@langchain/groq",
6626
+ className: "ChatGroq",
6627
+ envVars: ["GROQ_API_KEY"],
6628
+ defaultModel: "llama-3.1-70b-versatile"
6629
+ }
6630
+ };
6631
+ function parseLLMString(llmString) {
6632
+ const parts = llmString.split("/");
6633
+ if (parts.length !== 2) {
6634
+ throw new Error(
6635
+ `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'`
6636
+ );
6637
+ }
6638
+ const [provider, model] = parts;
6639
+ if (!provider || !model) {
6640
+ throw new Error(
6641
+ `Invalid LLM string format. Both provider and model must be non-empty. Got '${llmString}'`
6642
+ );
6643
+ }
6644
+ const normalizedProvider = provider.toLowerCase();
6645
+ if (!(normalizedProvider in PROVIDER_CONFIG)) {
6646
+ const supportedProviders = Object.keys(PROVIDER_CONFIG).join(", ");
6647
+ throw new Error(
6648
+ `Unsupported LLM provider '${provider}'. Supported providers: ${supportedProviders}`
6649
+ );
6650
+ }
6651
+ return { provider: normalizedProvider, model };
6652
+ }
6653
+ __name(parseLLMString, "parseLLMString");
6654
+ function getAPIKey(provider, config) {
6655
+ if (config?.apiKey) {
6656
+ return config.apiKey;
6657
+ }
6658
+ const providerConfig = PROVIDER_CONFIG[provider];
6659
+ for (const envVar of providerConfig.envVars) {
6660
+ const apiKey = process.env[envVar];
6661
+ if (apiKey) {
6662
+ logger.debug(
6663
+ `Using API key from environment variable ${envVar} for provider ${provider}`
6664
+ );
6665
+ return apiKey;
6666
+ }
6667
+ }
6668
+ const envVarsStr = providerConfig.envVars.join(" or ");
6669
+ throw new Error(
6670
+ `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' } })`
6671
+ );
6672
+ }
6673
+ __name(getAPIKey, "getAPIKey");
6674
+ async function createLLMFromString(llmString, config) {
6675
+ logger.info(`Creating LLM from string: ${llmString}`);
6676
+ const { provider, model } = parseLLMString(llmString);
6677
+ const providerConfig = PROVIDER_CONFIG[provider];
6678
+ const apiKey = getAPIKey(provider, config);
6679
+ let providerModule;
6680
+ try {
6681
+ logger.debug(`Importing package ${providerConfig.package}...`);
6682
+ providerModule = await import(providerConfig.package);
6683
+ } catch (error) {
6684
+ if (error?.code === "MODULE_NOT_FOUND" || error?.message?.includes("Cannot find module") || error?.message?.includes("Cannot find package")) {
6685
+ throw new Error(
6686
+ `Package '${providerConfig.package}' is not installed. Install it with: npm install ${providerConfig.package} or yarn add ${providerConfig.package}`
6687
+ );
6688
+ }
6689
+ throw new Error(
6690
+ `Failed to import ${providerConfig.package}: ${error?.message || error}`
6691
+ );
6692
+ }
6693
+ const LLMClass = providerModule[providerConfig.className];
6694
+ if (!LLMClass) {
6695
+ throw new Error(
6696
+ `Could not find ${providerConfig.className} in package ${providerConfig.package}. This might be a version compatibility issue.`
6697
+ );
6698
+ }
6699
+ const llmConfig = {
6700
+ model,
6701
+ apiKey,
6702
+ ...config
6703
+ };
6704
+ if (config?.apiKey) {
6705
+ delete llmConfig.apiKey;
6706
+ llmConfig.apiKey = apiKey;
6707
+ }
6708
+ if (provider === "anthropic") {
6709
+ llmConfig.model = model;
6710
+ } else if (provider === "google") {
6711
+ llmConfig.model = model;
6712
+ } else if (provider === "openai") {
6713
+ llmConfig.model = model;
6714
+ } else if (provider === "groq") {
6715
+ llmConfig.model = model;
6716
+ }
6717
+ try {
6718
+ const llmInstance = new LLMClass(llmConfig);
6719
+ logger.info(`Successfully created ${provider} LLM with model ${model}`);
6720
+ return llmInstance;
6721
+ } catch (error) {
6722
+ throw new Error(
6723
+ `Failed to instantiate ${providerConfig.className} with model '${model}': ${error?.message || error}`
6724
+ );
6725
+ }
6726
+ }
6727
+ __name(createLLMFromString, "createLLMFromString");
6728
+
4132
6729
  // src/agents/mcp_agent.ts
6730
+ function normalizeRunOptions(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
6731
+ if (typeof queryOrOptions === "object" && queryOrOptions !== null) {
6732
+ const options = queryOrOptions;
6733
+ return {
6734
+ query: options.prompt,
6735
+ maxSteps: options.maxSteps,
6736
+ manageConnector: options.manageConnector,
6737
+ externalHistory: options.externalHistory,
6738
+ outputSchema: options.schema
6739
+ };
6740
+ }
6741
+ return {
6742
+ query: queryOrOptions,
6743
+ maxSteps,
6744
+ manageConnector,
6745
+ externalHistory,
6746
+ outputSchema
6747
+ };
6748
+ }
6749
+ __name(normalizeRunOptions, "normalizeRunOptions");
4133
6750
  var MCPAgent = class {
4134
6751
  static {
4135
6752
  __name(this, "MCPAgent");
@@ -4175,6 +6792,12 @@ var MCPAgent = class {
4175
6792
  // Remote agent support
4176
6793
  isRemote = false;
4177
6794
  remoteAgent = null;
6795
+ // Simplified mode support
6796
+ isSimplifiedMode = false;
6797
+ llmString;
6798
+ llmConfig;
6799
+ mcpServersConfig;
6800
+ clientOwnedByAgent = false;
4178
6801
  constructor(options) {
4179
6802
  if (options.agentId) {
4180
6803
  this.isRemote = true;
@@ -4208,9 +6831,36 @@ var MCPAgent = class {
4208
6831
  "llm is required for local execution. For remote execution, provide agentId instead."
4209
6832
  );
4210
6833
  }
4211
- this.llm = options.llm;
4212
- this.client = options.client;
4213
- this.connectors = options.connectors ?? [];
6834
+ const isSimplifiedMode = typeof options.llm === "string";
6835
+ if (isSimplifiedMode) {
6836
+ this.isSimplifiedMode = true;
6837
+ this.llmString = options.llm;
6838
+ this.llmConfig = options.llmConfig;
6839
+ this.mcpServersConfig = options.mcpServers;
6840
+ if (!this.mcpServersConfig || Object.keys(this.mcpServersConfig).length === 0) {
6841
+ throw new Error(
6842
+ "Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }"
6843
+ );
6844
+ }
6845
+ this.llm = void 0;
6846
+ this.client = void 0;
6847
+ this.clientOwnedByAgent = true;
6848
+ this.connectors = [];
6849
+ logger.info(
6850
+ `\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`
6851
+ );
6852
+ } else {
6853
+ this.isSimplifiedMode = false;
6854
+ this.llm = options.llm;
6855
+ this.client = options.client;
6856
+ this.connectors = options.connectors ?? [];
6857
+ this.clientOwnedByAgent = false;
6858
+ if (!this.client && this.connectors.length === 0) {
6859
+ throw new Error(
6860
+ "Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config."
6861
+ );
6862
+ }
6863
+ }
4214
6864
  this.maxSteps = options.maxSteps ?? 5;
4215
6865
  this.autoInitialize = options.autoInitialize ?? false;
4216
6866
  this.memoryEnabled = options.memoryEnabled ?? true;
@@ -4223,28 +6873,30 @@ var MCPAgent = class {
4223
6873
  this.useServerManager = options.useServerManager ?? false;
4224
6874
  this.verbose = options.verbose ?? false;
4225
6875
  this.observe = options.observe ?? true;
4226
- if (!this.client && this.connectors.length === 0) {
4227
- throw new Error(
4228
- "Either 'client' or at least one 'connector' must be provided."
4229
- );
4230
- }
4231
- if (this.useServerManager) {
4232
- if (!this.client) {
4233
- throw new Error(
4234
- "'client' must be provided when 'useServerManager' is true."
4235
- );
6876
+ if (!this.isSimplifiedMode) {
6877
+ if (this.useServerManager) {
6878
+ if (!this.client) {
6879
+ throw new Error(
6880
+ "'client' must be provided when 'useServerManager' is true."
6881
+ );
6882
+ }
6883
+ this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
6884
+ this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
6885
+ } else {
6886
+ this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
6887
+ }
6888
+ this.telemetry = Telemetry.getInstance();
6889
+ if (this.llm) {
6890
+ const [provider, name] = extractModelInfo(this.llm);
6891
+ this.modelProvider = provider;
6892
+ this.modelName = name;
6893
+ } else {
6894
+ this.modelProvider = "unknown";
6895
+ this.modelName = "unknown";
4236
6896
  }
4237
- this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
4238
- this.serverManager = options.serverManagerFactory?.(this.client) ?? new ServerManager(this.client, this.adapter);
4239
6897
  } else {
4240
6898
  this.adapter = options.adapter ?? new LangChainAdapter(this.disallowedTools);
4241
- }
4242
- this.telemetry = Telemetry.getInstance();
4243
- if (this.llm) {
4244
- const [provider, name] = extractModelInfo(this.llm);
4245
- this.modelProvider = provider;
4246
- this.modelName = name;
4247
- } else {
6899
+ this.telemetry = Telemetry.getInstance();
4248
6900
  this.modelProvider = "unknown";
4249
6901
  this.modelName = "unknown";
4250
6902
  }
@@ -4275,6 +6927,40 @@ var MCPAgent = class {
4275
6927
  return;
4276
6928
  }
4277
6929
  logger.info("\u{1F680} Initializing MCP agent and connecting to services...");
6930
+ if (this.isSimplifiedMode) {
6931
+ logger.info(
6932
+ "\u{1F3AF} Simplified mode: Creating client and LLM from configuration..."
6933
+ );
6934
+ if (this.mcpServersConfig) {
6935
+ logger.info(
6936
+ `Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`
6937
+ );
6938
+ this.client = new MCPClient({ mcpServers: this.mcpServersConfig });
6939
+ logger.info("\u2705 MCPClient created successfully");
6940
+ }
6941
+ if (this.llmString) {
6942
+ logger.info(`Creating LLM from string: ${this.llmString}...`);
6943
+ try {
6944
+ this.llm = await createLLMFromString(this.llmString, this.llmConfig);
6945
+ logger.info("\u2705 LLM created successfully");
6946
+ const [provider, name] = extractModelInfo(this.llm);
6947
+ this.modelProvider = provider;
6948
+ this.modelName = name;
6949
+ } catch (error) {
6950
+ throw new Error(
6951
+ `Failed to create LLM from string '${this.llmString}': ${error?.message || error}`
6952
+ );
6953
+ }
6954
+ }
6955
+ if (this.useServerManager) {
6956
+ if (!this.client) {
6957
+ throw new Error(
6958
+ "'client' must be available when 'useServerManager' is true."
6959
+ );
6960
+ }
6961
+ this.serverManager = new ServerManager(this.client, this.adapter);
6962
+ }
6963
+ }
4278
6964
  this.callbacks = await this.observabilityManager.getCallbacks();
4279
6965
  const handlerNames = await this.observabilityManager.getHandlerNames();
4280
6966
  if (handlerNames.length > 0) {
@@ -4817,33 +7503,47 @@ var MCPAgent = class {
4817
7503
  }
4818
7504
  }
4819
7505
  }
4820
- async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
4821
- if (this.isRemote && this.remoteAgent) {
4822
- return this.remoteAgent.run(
4823
- query,
4824
- maxSteps,
4825
- manageConnector,
4826
- externalHistory,
4827
- outputSchema
4828
- );
4829
- }
4830
- const generator = this.stream(
7506
+ async run(queryOrOptions, maxSteps, manageConnector, externalHistory, outputSchema) {
7507
+ const {
4831
7508
  query,
7509
+ maxSteps: steps,
7510
+ manageConnector: manage,
7511
+ externalHistory: history,
7512
+ outputSchema: schema
7513
+ } = normalizeRunOptions(
7514
+ queryOrOptions,
4832
7515
  maxSteps,
4833
7516
  manageConnector,
4834
7517
  externalHistory,
4835
7518
  outputSchema
4836
7519
  );
7520
+ if (this.isRemote && this.remoteAgent) {
7521
+ return this.remoteAgent.run(query, steps, manage, history, schema);
7522
+ }
7523
+ const generator = this.stream(query, steps, manage, history, schema);
4837
7524
  return this._consumeAndReturn(generator);
4838
7525
  }
4839
- async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7526
+ async *stream(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7527
+ const {
7528
+ query,
7529
+ maxSteps: steps,
7530
+ manageConnector: manage,
7531
+ externalHistory: history,
7532
+ outputSchema: schema
7533
+ } = normalizeRunOptions(
7534
+ queryOrOptions,
7535
+ maxSteps,
7536
+ manageConnector,
7537
+ externalHistory,
7538
+ outputSchema
7539
+ );
4840
7540
  if (this.isRemote && this.remoteAgent) {
4841
7541
  const result = await this.remoteAgent.run(
4842
7542
  query,
4843
- maxSteps,
4844
- manageConnector,
4845
- externalHistory,
4846
- outputSchema
7543
+ steps,
7544
+ manage,
7545
+ history,
7546
+ schema
4847
7547
  );
4848
7548
  return result;
4849
7549
  }
@@ -4853,7 +7553,7 @@ var MCPAgent = class {
4853
7553
  let finalOutput = null;
4854
7554
  let stepsTaken = 0;
4855
7555
  try {
4856
- if (manageConnector && !this._initialized) {
7556
+ if (manage && !this._initialized) {
4857
7557
  await this.initialize();
4858
7558
  initializedHere = true;
4859
7559
  } else if (!this._initialized && this.autoInitialize) {
@@ -4877,7 +7577,7 @@ var MCPAgent = class {
4877
7577
  this._agentExecutor = this.createAgent();
4878
7578
  }
4879
7579
  }
4880
- const historyToUse = externalHistory ?? this.conversationHistory;
7580
+ const historyToUse = history ?? this.conversationHistory;
4881
7581
  const langchainHistory = [];
4882
7582
  for (const msg of historyToUse) {
4883
7583
  if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
@@ -5018,13 +7718,13 @@ var MCPAgent = class {
5018
7718
  this.addToHistory(msg);
5019
7719
  }
5020
7720
  }
5021
- if (outputSchema && finalOutput) {
7721
+ if (schema && finalOutput) {
5022
7722
  try {
5023
7723
  logger.info("\u{1F527} Attempting structured output...");
5024
7724
  const structuredResult = await this._attemptStructuredOutput(
5025
7725
  finalOutput,
5026
7726
  this.llm,
5027
- outputSchema
7727
+ schema
5028
7728
  );
5029
7729
  if (this.memoryEnabled) {
5030
7730
  this.addToHistory(
@@ -5050,7 +7750,7 @@ var MCPAgent = class {
5050
7750
  return finalOutput || "No output generated";
5051
7751
  } catch (e) {
5052
7752
  logger.error(`\u274C Error running query: ${e}`);
5053
- if (initializedHere && manageConnector) {
7753
+ if (initializedHere && manage) {
5054
7754
  logger.info("\u{1F9F9} Cleaning up resources after error");
5055
7755
  await this.close();
5056
7756
  }
@@ -5080,9 +7780,9 @@ var MCPAgent = class {
5080
7780
  maxStepsConfigured: this.maxSteps,
5081
7781
  memoryEnabled: this.memoryEnabled,
5082
7782
  useServerManager: this.useServerManager,
5083
- maxStepsUsed: maxSteps ?? null,
5084
- manageConnector,
5085
- externalHistoryUsed: externalHistory !== void 0,
7783
+ maxStepsUsed: steps ?? null,
7784
+ manageConnector: manage ?? true,
7785
+ externalHistoryUsed: history !== void 0,
5086
7786
  stepsTaken,
5087
7787
  toolsUsedCount: this.toolsUsedNames.length,
5088
7788
  toolsUsedNames: this.toolsUsedNames,
@@ -5091,7 +7791,7 @@ var MCPAgent = class {
5091
7791
  errorType: success ? null : "execution_error",
5092
7792
  conversationHistoryLength
5093
7793
  });
5094
- if (manageConnector && !this.client && initializedHere) {
7794
+ if (manage && !this.client && initializedHere) {
5095
7795
  logger.info("\u{1F9F9} Closing agent after stream completion");
5096
7796
  await this.close();
5097
7797
  }
@@ -5119,15 +7819,28 @@ var MCPAgent = class {
5119
7819
  this._agentExecutor = null;
5120
7820
  this._tools = [];
5121
7821
  if (this.client) {
5122
- logger.info("\u{1F504} Closing client and cleaning up resources");
5123
- await this.client.close();
5124
- this.sessions = {};
7822
+ if (this.clientOwnedByAgent) {
7823
+ logger.info(
7824
+ "\u{1F504} Closing internally-created client (simplified mode) and cleaning up resources"
7825
+ );
7826
+ await this.client.close();
7827
+ this.sessions = {};
7828
+ this.client = void 0;
7829
+ } else {
7830
+ logger.info("\u{1F504} Closing client and cleaning up resources");
7831
+ await this.client.close();
7832
+ this.sessions = {};
7833
+ }
5125
7834
  } else {
5126
7835
  for (const connector of this.connectors) {
5127
7836
  logger.info("\u{1F504} Disconnecting connector");
5128
7837
  await connector.disconnect();
5129
7838
  }
5130
7839
  }
7840
+ if (this.isSimplifiedMode && this.llm) {
7841
+ logger.debug("\u{1F504} Clearing LLM reference (simplified mode)");
7842
+ this.llm = void 0;
7843
+ }
5131
7844
  if ("connectorToolMap" in this.adapter) {
5132
7845
  this.adapter = new LangChainAdapter();
5133
7846
  }
@@ -5136,16 +7849,12 @@ var MCPAgent = class {
5136
7849
  logger.info("\u{1F44B} Agent closed successfully");
5137
7850
  }
5138
7851
  }
5139
- /**
5140
- * Yields with pretty-printed output for code mode.
5141
- * This method formats and displays tool executions in a user-friendly way with syntax highlighting.
5142
- */
5143
- async *prettyStreamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7852
+ async *prettyStreamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
5144
7853
  const { prettyStreamEvents: prettyStream } = await Promise.resolve().then(() => (init_display(), display_exports));
5145
7854
  const finalResponse = "";
5146
7855
  for await (const _ of prettyStream(
5147
7856
  this.streamEvents(
5148
- query,
7857
+ queryOrOptions,
5149
7858
  maxSteps,
5150
7859
  manageConnector,
5151
7860
  externalHistory,
@@ -5156,22 +7865,32 @@ var MCPAgent = class {
5156
7865
  }
5157
7866
  return finalResponse;
5158
7867
  }
5159
- /**
5160
- * Yields LangChain StreamEvent objects from the underlying streamEvents() method.
5161
- * This provides token-level streaming and fine-grained event updates.
5162
- */
5163
- async *streamEvents(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7868
+ async *streamEvents(queryOrOptions, maxSteps, manageConnector = true, externalHistory, outputSchema) {
7869
+ const normalized = normalizeRunOptions(
7870
+ queryOrOptions,
7871
+ maxSteps,
7872
+ manageConnector,
7873
+ externalHistory,
7874
+ outputSchema
7875
+ );
7876
+ let { query } = normalized;
7877
+ const {
7878
+ maxSteps: steps,
7879
+ manageConnector: manage,
7880
+ externalHistory: history,
7881
+ outputSchema: schema
7882
+ } = normalized;
5164
7883
  let initializedHere = false;
5165
7884
  const startTime = Date.now();
5166
7885
  let success = false;
5167
7886
  let eventCount = 0;
5168
7887
  let totalResponseLength = 0;
5169
7888
  let finalResponse = "";
5170
- if (outputSchema) {
5171
- query = this._enhanceQueryWithSchema(query, outputSchema);
7889
+ if (schema) {
7890
+ query = this._enhanceQueryWithSchema(query, schema);
5172
7891
  }
5173
7892
  try {
5174
- if (manageConnector && !this._initialized) {
7893
+ if (manage && !this._initialized) {
5175
7894
  await this.initialize();
5176
7895
  initializedHere = true;
5177
7896
  } else if (!this._initialized && this.autoInitialize) {
@@ -5182,14 +7901,14 @@ var MCPAgent = class {
5182
7901
  if (!agentExecutor) {
5183
7902
  throw new Error("MCP agent failed to initialize");
5184
7903
  }
5185
- this.maxSteps = maxSteps ?? this.maxSteps;
7904
+ this.maxSteps = steps ?? this.maxSteps;
5186
7905
  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);
5187
7906
  logger.info(`\u{1F4AC} Received query for streamEvents: '${display_query}'`);
5188
7907
  if (this.memoryEnabled) {
5189
7908
  logger.info(`\u{1F504} Adding user message to history: ${display_query}`);
5190
7909
  this.addToHistory(new import_langchain2.HumanMessage({ content: query }));
5191
7910
  }
5192
- const historyToUse = externalHistory ?? this.conversationHistory;
7911
+ const historyToUse = history ?? this.conversationHistory;
5193
7912
  const langchainHistory = [];
5194
7913
  for (const msg of historyToUse) {
5195
7914
  if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
@@ -5256,17 +7975,13 @@ var MCPAgent = class {
5256
7975
  }
5257
7976
  }
5258
7977
  }
5259
- if (outputSchema && finalResponse) {
7978
+ if (schema && finalResponse) {
5260
7979
  logger.info("\u{1F527} Attempting structured output conversion...");
5261
7980
  try {
5262
7981
  let conversionCompleted = false;
5263
7982
  let conversionResult = null;
5264
7983
  let conversionError = null;
5265
- this._attemptStructuredOutput(
5266
- finalResponse,
5267
- this.llm,
5268
- outputSchema
5269
- ).then((result) => {
7984
+ this._attemptStructuredOutput(finalResponse, this.llm, schema).then((result) => {
5270
7985
  conversionCompleted = true;
5271
7986
  conversionResult = result;
5272
7987
  return result;
@@ -5321,7 +8036,7 @@ var MCPAgent = class {
5321
8036
  success = true;
5322
8037
  } catch (e) {
5323
8038
  logger.error(`\u274C Error during streamEvents: ${e}`);
5324
- if (initializedHere && manageConnector) {
8039
+ if (initializedHere && manage) {
5325
8040
  logger.info(
5326
8041
  "\u{1F9F9} Cleaning up resources after initialization error in streamEvents"
5327
8042
  );
@@ -5352,15 +8067,15 @@ var MCPAgent = class {
5352
8067
  maxStepsConfigured: this.maxSteps,
5353
8068
  memoryEnabled: this.memoryEnabled,
5354
8069
  useServerManager: this.useServerManager,
5355
- maxStepsUsed: maxSteps ?? null,
5356
- manageConnector,
5357
- externalHistoryUsed: externalHistory !== void 0,
8070
+ maxStepsUsed: steps ?? null,
8071
+ manageConnector: manage ?? true,
8072
+ externalHistoryUsed: history !== void 0,
5358
8073
  response: `[STREAMED RESPONSE - ${totalResponseLength} chars]`,
5359
8074
  executionTimeMs,
5360
8075
  errorType: success ? null : "streaming_error",
5361
8076
  conversationHistoryLength
5362
8077
  });
5363
- if (manageConnector && !this.client && initializedHere) {
8078
+ if (manage && !this.client && initializedHere) {
5364
8079
  logger.info("\u{1F9F9} Closing agent after streamEvents completion");
5365
8080
  await this.close();
5366
8081
  }