mcp-use 1.2.1-canary.0 → 1.2.2-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  logger
3
- } from "./chunk-ZUEQQ6YK.js";
3
+ } from "./chunk-VPPILX7B.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-SHUYVCID.js";
@@ -510,9 +510,9 @@ var ObservabilityManager = class {
510
510
  return;
511
511
  }
512
512
  try {
513
- const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await import("./langfuse-6AJGHMAV.js");
513
+ const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await import("./langfuse-MO3AMDBE.js");
514
514
  if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
515
- const { initializeLangfuse } = await import("./langfuse-6AJGHMAV.js");
515
+ const { initializeLangfuse } = await import("./langfuse-MO3AMDBE.js");
516
516
  await initializeLangfuse(this.agentId, this.metadata, this.metadataProvider, this.tagsProvider);
517
517
  logger.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`);
518
518
  } else {
@@ -2403,841 +2403,6 @@ ${formatPrompt}`);
2403
2403
  }
2404
2404
  };
2405
2405
 
2406
- // src/session.ts
2407
- var MCPSession = class {
2408
- static {
2409
- __name(this, "MCPSession");
2410
- }
2411
- connector;
2412
- autoConnect;
2413
- constructor(connector, autoConnect = true) {
2414
- this.connector = connector;
2415
- this.autoConnect = autoConnect;
2416
- }
2417
- async connect() {
2418
- await this.connector.connect();
2419
- }
2420
- async disconnect() {
2421
- await this.connector.disconnect();
2422
- }
2423
- async initialize() {
2424
- if (!this.isConnected && this.autoConnect) {
2425
- await this.connect();
2426
- }
2427
- await this.connector.initialize();
2428
- }
2429
- get isConnected() {
2430
- return this.connector && this.connector.isClientConnected;
2431
- }
2432
- };
2433
-
2434
- // src/connectors/base.ts
2435
- var BaseConnector = class {
2436
- static {
2437
- __name(this, "BaseConnector");
2438
- }
2439
- client = null;
2440
- connectionManager = null;
2441
- toolsCache = null;
2442
- connected = false;
2443
- opts;
2444
- constructor(opts = {}) {
2445
- this.opts = opts;
2446
- }
2447
- /** Disconnect and release resources. */
2448
- async disconnect() {
2449
- if (!this.connected) {
2450
- logger.debug("Not connected to MCP implementation");
2451
- return;
2452
- }
2453
- logger.debug("Disconnecting from MCP implementation");
2454
- await this.cleanupResources();
2455
- this.connected = false;
2456
- logger.debug("Disconnected from MCP implementation");
2457
- }
2458
- /** Check if the client is connected */
2459
- get isClientConnected() {
2460
- return this.client != null;
2461
- }
2462
- /**
2463
- * Initialise the MCP session **after** `connect()` has succeeded.
2464
- *
2465
- * In the SDK, `Client.connect(transport)` automatically performs the
2466
- * protocol‑level `initialize` handshake, so we only need to cache the list of
2467
- * tools and expose some server info.
2468
- */
2469
- async initialize(defaultRequestOptions = this.opts.defaultRequestOptions ?? {}) {
2470
- if (!this.client) {
2471
- throw new Error("MCP client is not connected");
2472
- }
2473
- logger.debug("Caching server capabilities & tools");
2474
- const capabilities = this.client.getServerCapabilities();
2475
- const listToolsRes = await this.client.listTools(void 0, defaultRequestOptions);
2476
- this.toolsCache = listToolsRes.tools ?? [];
2477
- logger.debug(`Fetched ${this.toolsCache.length} tools from server`);
2478
- return capabilities;
2479
- }
2480
- /** Lazily expose the cached tools list. */
2481
- get tools() {
2482
- if (!this.toolsCache) {
2483
- throw new Error("MCP client is not initialized; call initialize() first");
2484
- }
2485
- return this.toolsCache;
2486
- }
2487
- /** Call a tool on the server. */
2488
- async callTool(name, args, options) {
2489
- if (!this.client) {
2490
- throw new Error("MCP client is not connected");
2491
- }
2492
- logger.debug(`Calling tool '${name}' with args`, args);
2493
- const res = await this.client.callTool({ name, arguments: args }, void 0, options);
2494
- logger.debug(`Tool '${name}' returned`, res);
2495
- return res;
2496
- }
2497
- /**
2498
- * List resources from the server with optional pagination
2499
- *
2500
- * @param cursor - Optional cursor for pagination
2501
- * @param options - Request options
2502
- * @returns Resource list with optional nextCursor for pagination
2503
- */
2504
- async listResources(cursor, options) {
2505
- if (!this.client) {
2506
- throw new Error("MCP client is not connected");
2507
- }
2508
- logger.debug("Listing resources", cursor ? `with cursor: ${cursor}` : "");
2509
- return await this.client.listResources({ cursor }, options);
2510
- }
2511
- /**
2512
- * List all resources from the server, automatically handling pagination
2513
- *
2514
- * @param options - Request options
2515
- * @returns Complete list of all resources
2516
- */
2517
- async listAllResources(options) {
2518
- if (!this.client) {
2519
- throw new Error("MCP client is not connected");
2520
- }
2521
- logger.debug("Listing all resources (with auto-pagination)");
2522
- const allResources = [];
2523
- let cursor = void 0;
2524
- do {
2525
- const result = await this.client.listResources({ cursor }, options);
2526
- allResources.push(...result.resources || []);
2527
- cursor = result.nextCursor;
2528
- } while (cursor);
2529
- return { resources: allResources };
2530
- }
2531
- /**
2532
- * List resource templates from the server
2533
- *
2534
- * @param options - Request options
2535
- * @returns List of available resource templates
2536
- */
2537
- async listResourceTemplates(options) {
2538
- if (!this.client) {
2539
- throw new Error("MCP client is not connected");
2540
- }
2541
- logger.debug("Listing resource templates");
2542
- return await this.client.listResourceTemplates(void 0, options);
2543
- }
2544
- /** Read a resource by URI. */
2545
- async readResource(uri, options) {
2546
- if (!this.client) {
2547
- throw new Error("MCP client is not connected");
2548
- }
2549
- logger.debug(`Reading resource ${uri}`);
2550
- const res = await this.client.readResource({ uri }, options);
2551
- return { content: res.content, mimeType: res.mimeType };
2552
- }
2553
- /**
2554
- * Subscribe to resource updates
2555
- *
2556
- * @param uri - URI of the resource to subscribe to
2557
- * @param options - Request options
2558
- */
2559
- async subscribeToResource(uri, options) {
2560
- if (!this.client) {
2561
- throw new Error("MCP client is not connected");
2562
- }
2563
- logger.debug(`Subscribing to resource: ${uri}`);
2564
- return await this.client.subscribeResource({ uri }, options);
2565
- }
2566
- /**
2567
- * Unsubscribe from resource updates
2568
- *
2569
- * @param uri - URI of the resource to unsubscribe from
2570
- * @param options - Request options
2571
- */
2572
- async unsubscribeFromResource(uri, options) {
2573
- if (!this.client) {
2574
- throw new Error("MCP client is not connected");
2575
- }
2576
- logger.debug(`Unsubscribing from resource: ${uri}`);
2577
- return await this.client.unsubscribeResource({ uri }, options);
2578
- }
2579
- async listPrompts() {
2580
- if (!this.client) {
2581
- throw new Error("MCP client is not connected");
2582
- }
2583
- logger.debug("Listing prompt");
2584
- return await this.client.listPrompts();
2585
- }
2586
- async getPrompt(name, args) {
2587
- if (!this.client) {
2588
- throw new Error("MCP client is not connected");
2589
- }
2590
- logger.debug(`Getting prompt ${name}`);
2591
- return await this.client.getPrompt({ name, arguments: args });
2592
- }
2593
- /** Send a raw request through the client. */
2594
- async request(method, params = null, options) {
2595
- if (!this.client) {
2596
- throw new Error("MCP client is not connected");
2597
- }
2598
- logger.debug(`Sending raw request '${method}' with params`, params);
2599
- return await this.client.request({ method, params: params ?? {} }, void 0, options);
2600
- }
2601
- /**
2602
- * Helper to tear down the client & connection manager safely.
2603
- */
2604
- async cleanupResources() {
2605
- const issues = [];
2606
- if (this.client) {
2607
- try {
2608
- if (typeof this.client.close === "function") {
2609
- await this.client.close();
2610
- }
2611
- } catch (e) {
2612
- const msg = `Error closing client: ${e}`;
2613
- logger.warn(msg);
2614
- issues.push(msg);
2615
- } finally {
2616
- this.client = null;
2617
- }
2618
- }
2619
- if (this.connectionManager) {
2620
- try {
2621
- await this.connectionManager.stop();
2622
- } catch (e) {
2623
- const msg = `Error stopping connection manager: ${e}`;
2624
- logger.warn(msg);
2625
- issues.push(msg);
2626
- } finally {
2627
- this.connectionManager = null;
2628
- }
2629
- }
2630
- this.toolsCache = null;
2631
- if (issues.length) {
2632
- logger.warn(`Resource cleanup finished with ${issues.length} issue(s)`);
2633
- }
2634
- }
2635
- };
2636
-
2637
- // src/connectors/http.ts
2638
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2639
- import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
2640
-
2641
- // src/task_managers/sse.ts
2642
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
2643
-
2644
- // src/task_managers/base.ts
2645
- var ConnectionManager = class {
2646
- static {
2647
- __name(this, "ConnectionManager");
2648
- }
2649
- _readyPromise;
2650
- _readyResolver;
2651
- _donePromise;
2652
- _doneResolver;
2653
- _exception = null;
2654
- _connection = null;
2655
- _task = null;
2656
- _abortController = null;
2657
- constructor() {
2658
- this.reset();
2659
- }
2660
- /**
2661
- * Start the connection manager and establish a connection.
2662
- *
2663
- * @returns The established connection.
2664
- * @throws If the connection cannot be established.
2665
- */
2666
- async start() {
2667
- this.reset();
2668
- logger.debug(`Starting ${this.constructor.name}`);
2669
- this._task = this.connectionTask();
2670
- await this._readyPromise;
2671
- if (this._exception) {
2672
- throw this._exception;
2673
- }
2674
- if (this._connection === null) {
2675
- throw new Error("Connection was not established");
2676
- }
2677
- return this._connection;
2678
- }
2679
- /**
2680
- * Stop the connection manager and close the connection.
2681
- */
2682
- async stop() {
2683
- if (this._task && this._abortController) {
2684
- logger.debug(`Cancelling ${this.constructor.name} task`);
2685
- this._abortController.abort();
2686
- try {
2687
- await this._task;
2688
- } catch (e) {
2689
- if (e instanceof Error && e.name === "AbortError") {
2690
- logger.debug(`${this.constructor.name} task aborted successfully`);
2691
- } else {
2692
- logger.warn(`Error stopping ${this.constructor.name} task: ${e}`);
2693
- }
2694
- }
2695
- }
2696
- await this._donePromise;
2697
- logger.debug(`${this.constructor.name} task completed`);
2698
- }
2699
- /**
2700
- * Reset all internal state.
2701
- */
2702
- reset() {
2703
- this._readyPromise = new Promise((res) => this._readyResolver = res);
2704
- this._donePromise = new Promise((res) => this._doneResolver = res);
2705
- this._exception = null;
2706
- this._connection = null;
2707
- this._task = null;
2708
- this._abortController = new AbortController();
2709
- }
2710
- /**
2711
- * The background task responsible for establishing and maintaining the
2712
- * connection until it is cancelled.
2713
- */
2714
- async connectionTask() {
2715
- logger.debug(`Running ${this.constructor.name} task`);
2716
- try {
2717
- this._connection = await this.establishConnection();
2718
- logger.debug(`${this.constructor.name} connected successfully`);
2719
- this._readyResolver();
2720
- await this.waitForAbort();
2721
- } catch (err) {
2722
- this._exception = err;
2723
- logger.error(`Error in ${this.constructor.name} task: ${err}`);
2724
- this._readyResolver();
2725
- } finally {
2726
- if (this._connection !== null) {
2727
- try {
2728
- await this.closeConnection(this._connection);
2729
- } catch (closeErr) {
2730
- logger.warn(`Error closing connection in ${this.constructor.name}: ${closeErr}`);
2731
- }
2732
- this._connection = null;
2733
- }
2734
- this._doneResolver();
2735
- }
2736
- }
2737
- /**
2738
- * Helper that returns a promise which resolves when the abort signal fires.
2739
- */
2740
- async waitForAbort() {
2741
- return new Promise((_resolve, _reject) => {
2742
- if (!this._abortController) {
2743
- return;
2744
- }
2745
- const signal = this._abortController.signal;
2746
- if (signal.aborted) {
2747
- _resolve();
2748
- return;
2749
- }
2750
- const onAbort = /* @__PURE__ */ __name(() => {
2751
- signal.removeEventListener("abort", onAbort);
2752
- _resolve();
2753
- }, "onAbort");
2754
- signal.addEventListener("abort", onAbort);
2755
- });
2756
- }
2757
- };
2758
-
2759
- // src/task_managers/sse.ts
2760
- var SseConnectionManager = class extends ConnectionManager {
2761
- static {
2762
- __name(this, "SseConnectionManager");
2763
- }
2764
- url;
2765
- opts;
2766
- _transport = null;
2767
- /**
2768
- * Create an SSE connection manager.
2769
- *
2770
- * @param url The SSE endpoint URL.
2771
- * @param opts Optional transport options (auth, headers, etc.).
2772
- */
2773
- constructor(url, opts) {
2774
- super();
2775
- this.url = typeof url === "string" ? new URL(url) : url;
2776
- this.opts = opts;
2777
- }
2778
- /**
2779
- * Spawn a new `SSEClientTransport` and start the connection.
2780
- */
2781
- async establishConnection() {
2782
- this._transport = new SSEClientTransport(this.url, this.opts);
2783
- logger.debug(`${this.constructor.name} connected successfully`);
2784
- return this._transport;
2785
- }
2786
- /**
2787
- * Close the underlying transport and clean up resources.
2788
- */
2789
- async closeConnection(_connection) {
2790
- if (this._transport) {
2791
- try {
2792
- await this._transport.close();
2793
- } catch (e) {
2794
- logger.warn(`Error closing SSE transport: ${e}`);
2795
- } finally {
2796
- this._transport = null;
2797
- }
2798
- }
2799
- }
2800
- };
2801
-
2802
- // src/task_managers/streamable_http.ts
2803
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
2804
- var StreamableHttpConnectionManager = class extends ConnectionManager {
2805
- static {
2806
- __name(this, "StreamableHttpConnectionManager");
2807
- }
2808
- url;
2809
- opts;
2810
- _transport = null;
2811
- /**
2812
- * Create a Streamable HTTP connection manager.
2813
- *
2814
- * @param url The HTTP endpoint URL.
2815
- * @param opts Optional transport options (auth, headers, etc.).
2816
- */
2817
- constructor(url, opts) {
2818
- super();
2819
- this.url = typeof url === "string" ? new URL(url) : url;
2820
- this.opts = opts;
2821
- }
2822
- /**
2823
- * Spawn a new `StreamableHTTPClientTransport` and return it.
2824
- * The Client.connect() method will handle starting the transport.
2825
- */
2826
- async establishConnection() {
2827
- this._transport = new StreamableHTTPClientTransport(this.url, this.opts);
2828
- logger.debug(`${this.constructor.name} created successfully`);
2829
- return this._transport;
2830
- }
2831
- /**
2832
- * Close the underlying transport and clean up resources.
2833
- */
2834
- async closeConnection(_connection) {
2835
- if (this._transport) {
2836
- try {
2837
- await this._transport.close();
2838
- } catch (e) {
2839
- logger.warn(`Error closing Streamable HTTP transport: ${e}`);
2840
- } finally {
2841
- this._transport = null;
2842
- }
2843
- }
2844
- }
2845
- /**
2846
- * Get the session ID from the transport if available.
2847
- */
2848
- get sessionId() {
2849
- return this._transport?.sessionId;
2850
- }
2851
- };
2852
-
2853
- // src/connectors/http.ts
2854
- var HttpConnector = class extends BaseConnector {
2855
- static {
2856
- __name(this, "HttpConnector");
2857
- }
2858
- baseUrl;
2859
- headers;
2860
- timeout;
2861
- sseReadTimeout;
2862
- clientInfo;
2863
- preferSse;
2864
- transportType = null;
2865
- constructor(baseUrl, opts = {}) {
2866
- super(opts);
2867
- this.baseUrl = baseUrl.replace(/\/$/, "");
2868
- this.headers = { ...opts.headers ?? {} };
2869
- if (opts.authToken) {
2870
- this.headers.Authorization = `Bearer ${opts.authToken}`;
2871
- }
2872
- this.timeout = opts.timeout ?? 3e4;
2873
- this.sseReadTimeout = opts.sseReadTimeout ?? 3e5;
2874
- this.clientInfo = opts.clientInfo ?? { name: "http-connector", version: "1.0.0" };
2875
- this.preferSse = opts.preferSse ?? false;
2876
- }
2877
- /** Establish connection to the MCP implementation via HTTP (streamable or SSE). */
2878
- async connect() {
2879
- if (this.connected) {
2880
- logger.debug("Already connected to MCP implementation");
2881
- return;
2882
- }
2883
- const baseUrl = this.baseUrl;
2884
- if (this.preferSse) {
2885
- logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${baseUrl}`);
2886
- await this.connectWithSse(baseUrl);
2887
- return;
2888
- }
2889
- logger.debug(`Connecting to MCP implementation via HTTP: ${baseUrl}`);
2890
- try {
2891
- logger.info("\u{1F504} Attempting streamable HTTP transport...");
2892
- await this.connectWithStreamableHttp(baseUrl);
2893
- logger.info("\u2705 Successfully connected via streamable HTTP");
2894
- } catch (err) {
2895
- let fallbackReason = "Unknown error";
2896
- if (err instanceof StreamableHTTPError) {
2897
- if (err.code === 400 && err.message.includes("Missing session ID")) {
2898
- fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
2899
- logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
2900
- } else if (err.code === 404 || err.code === 405) {
2901
- fallbackReason = `Server returned ${err.code} - server likely doesn't support streamable HTTP`;
2902
- logger.debug(fallbackReason);
2903
- } else {
2904
- fallbackReason = `Server returned ${err.code}: ${err.message}`;
2905
- logger.debug(fallbackReason);
2906
- }
2907
- } else if (err instanceof Error) {
2908
- const errorStr = err.toString();
2909
- const errorMsg = err.message || "";
2910
- if (errorStr.includes("Missing session ID") || errorStr.includes("Bad Request: Missing session ID") || errorMsg.includes("FastMCP session ID error")) {
2911
- fallbackReason = "Server requires session ID (FastMCP compatibility) - using SSE transport";
2912
- logger.warn(`\u26A0\uFE0F ${fallbackReason}`);
2913
- } else if (errorStr.includes("405 Method Not Allowed") || errorStr.includes("404 Not Found")) {
2914
- fallbackReason = "Server doesn't support streamable HTTP (405/404)";
2915
- logger.debug(fallbackReason);
2916
- } else {
2917
- fallbackReason = `Streamable HTTP failed: ${err.message}`;
2918
- logger.debug(fallbackReason);
2919
- }
2920
- }
2921
- logger.info("\u{1F504} Falling back to SSE transport...");
2922
- try {
2923
- await this.connectWithSse(baseUrl);
2924
- } catch (sseErr) {
2925
- logger.error(`Failed to connect with both transports:`);
2926
- logger.error(` Streamable HTTP: ${fallbackReason}`);
2927
- logger.error(` SSE: ${sseErr}`);
2928
- await this.cleanupResources();
2929
- throw new Error("Could not connect to server with any available transport");
2930
- }
2931
- }
2932
- }
2933
- async connectWithStreamableHttp(baseUrl) {
2934
- try {
2935
- this.connectionManager = new StreamableHttpConnectionManager(
2936
- baseUrl,
2937
- {
2938
- requestInit: {
2939
- headers: this.headers
2940
- },
2941
- // Pass through timeout and other options
2942
- reconnectionOptions: {
2943
- maxReconnectionDelay: 3e4,
2944
- initialReconnectionDelay: 1e3,
2945
- reconnectionDelayGrowFactor: 1.5,
2946
- maxRetries: 2
2947
- }
2948
- }
2949
- );
2950
- const transport = await this.connectionManager.start();
2951
- this.client = new Client(this.clientInfo, this.opts.clientOptions);
2952
- try {
2953
- await this.client.connect(transport);
2954
- } catch (connectErr) {
2955
- if (connectErr instanceof Error) {
2956
- const errMsg = connectErr.message || connectErr.toString();
2957
- if (errMsg.includes("Missing session ID") || errMsg.includes("Bad Request: Missing session ID")) {
2958
- const wrappedError = new Error(`FastMCP session ID error: ${errMsg}`);
2959
- wrappedError.cause = connectErr;
2960
- throw wrappedError;
2961
- }
2962
- }
2963
- throw connectErr;
2964
- }
2965
- this.connected = true;
2966
- this.transportType = "streamable-http";
2967
- logger.debug(`Successfully connected to MCP implementation via streamable HTTP: ${baseUrl}`);
2968
- } catch (err) {
2969
- await this.cleanupResources();
2970
- throw err;
2971
- }
2972
- }
2973
- async connectWithSse(baseUrl) {
2974
- try {
2975
- this.connectionManager = new SseConnectionManager(
2976
- baseUrl,
2977
- {
2978
- requestInit: {
2979
- headers: this.headers
2980
- }
2981
- }
2982
- );
2983
- const transport = await this.connectionManager.start();
2984
- this.client = new Client(this.clientInfo, this.opts.clientOptions);
2985
- await this.client.connect(transport);
2986
- this.connected = true;
2987
- this.transportType = "sse";
2988
- logger.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${baseUrl}`);
2989
- } catch (err) {
2990
- await this.cleanupResources();
2991
- throw err;
2992
- }
2993
- }
2994
- get publicIdentifier() {
2995
- return {
2996
- type: "http",
2997
- url: this.baseUrl,
2998
- transport: this.transportType || "unknown"
2999
- };
3000
- }
3001
- /**
3002
- * Get the transport type being used (streamable-http or sse)
3003
- */
3004
- getTransportType() {
3005
- return this.transportType;
3006
- }
3007
- };
3008
-
3009
- // src/connectors/websocket.ts
3010
- import { v4 as uuidv42 } from "uuid";
3011
-
3012
- // src/task_managers/websocket.ts
3013
- import WS from "ws";
3014
- var WebSocketConnectionManager = class extends ConnectionManager {
3015
- static {
3016
- __name(this, "WebSocketConnectionManager");
3017
- }
3018
- url;
3019
- headers;
3020
- _ws = null;
3021
- /**
3022
- * @param url The WebSocket URL to connect to.
3023
- * @param headers Optional headers to include in the connection handshake.
3024
- */
3025
- constructor(url, headers = {}) {
3026
- super();
3027
- this.url = url;
3028
- this.headers = headers;
3029
- }
3030
- /** Establish a WebSocket connection and wait until it is open. */
3031
- async establishConnection() {
3032
- logger.debug(`Connecting to WebSocket: ${this.url}`);
3033
- return new Promise((resolve, reject) => {
3034
- const ws = new WS(this.url, { headers: this.headers });
3035
- this._ws = ws;
3036
- const onOpen = /* @__PURE__ */ __name(() => {
3037
- cleanup();
3038
- logger.debug("WebSocket connected successfully");
3039
- resolve(ws);
3040
- }, "onOpen");
3041
- const onError = /* @__PURE__ */ __name((err) => {
3042
- cleanup();
3043
- logger.error(`Failed to connect to WebSocket: ${err}`);
3044
- reject(err);
3045
- }, "onError");
3046
- const cleanup = /* @__PURE__ */ __name(() => {
3047
- ws.off("open", onOpen);
3048
- ws.off("error", onError);
3049
- }, "cleanup");
3050
- ws.on("open", onOpen);
3051
- ws.on("error", onError);
3052
- });
3053
- }
3054
- /** Cleanly close the WebSocket connection. */
3055
- async closeConnection(connection) {
3056
- logger.debug("Closing WebSocket connection");
3057
- return new Promise((resolve) => {
3058
- const onClose = /* @__PURE__ */ __name(() => {
3059
- connection.off("close", onClose);
3060
- this._ws = null;
3061
- resolve();
3062
- }, "onClose");
3063
- if (connection.readyState === WS.CLOSED) {
3064
- onClose();
3065
- return;
3066
- }
3067
- connection.on("close", onClose);
3068
- try {
3069
- connection.close();
3070
- } catch (e) {
3071
- logger.warn(`Error closing WebSocket connection: ${e}`);
3072
- onClose();
3073
- }
3074
- });
3075
- }
3076
- };
3077
-
3078
- // src/connectors/websocket.ts
3079
- var WebSocketConnector = class extends BaseConnector {
3080
- static {
3081
- __name(this, "WebSocketConnector");
3082
- }
3083
- url;
3084
- headers;
3085
- connectionManager = null;
3086
- ws = null;
3087
- receiverTask = null;
3088
- pending = /* @__PURE__ */ new Map();
3089
- toolsCache = null;
3090
- constructor(url, opts = {}) {
3091
- super();
3092
- this.url = url;
3093
- this.headers = { ...opts.headers ?? {} };
3094
- if (opts.authToken)
3095
- this.headers.Authorization = `Bearer ${opts.authToken}`;
3096
- }
3097
- async connect() {
3098
- if (this.connected) {
3099
- logger.debug("Already connected to MCP implementation");
3100
- return;
3101
- }
3102
- logger.debug(`Connecting via WebSocket: ${this.url}`);
3103
- try {
3104
- this.connectionManager = new WebSocketConnectionManager(this.url, this.headers);
3105
- this.ws = await this.connectionManager.start();
3106
- this.receiverTask = this.receiveLoop();
3107
- this.connected = true;
3108
- logger.debug("WebSocket connected successfully");
3109
- } catch (e) {
3110
- logger.error(`Failed to connect: ${e}`);
3111
- await this.cleanupResources();
3112
- throw e;
3113
- }
3114
- }
3115
- async disconnect() {
3116
- if (!this.connected) {
3117
- logger.debug("Not connected to MCP implementation");
3118
- return;
3119
- }
3120
- logger.debug("Disconnecting \u2026");
3121
- await this.cleanupResources();
3122
- this.connected = false;
3123
- }
3124
- sendRequest(method, params = null) {
3125
- if (!this.ws)
3126
- throw new Error("WebSocket is not connected");
3127
- const id = uuidv42();
3128
- const payload = JSON.stringify({ id, method, params: params ?? {} });
3129
- return new Promise((resolve, reject) => {
3130
- this.pending.set(id, { resolve, reject });
3131
- this.ws.send(payload, (err) => {
3132
- if (err) {
3133
- this.pending.delete(id);
3134
- reject(err);
3135
- }
3136
- });
3137
- });
3138
- }
3139
- async receiveLoop() {
3140
- if (!this.ws)
3141
- return;
3142
- const socket = this.ws;
3143
- const onMessage = /* @__PURE__ */ __name((msg) => {
3144
- let data;
3145
- try {
3146
- data = JSON.parse(msg.data ?? msg);
3147
- } catch (e) {
3148
- logger.warn("Received non\u2011JSON frame", e);
3149
- return;
3150
- }
3151
- const id = data.id;
3152
- if (id && this.pending.has(id)) {
3153
- const { resolve, reject } = this.pending.get(id);
3154
- this.pending.delete(id);
3155
- if ("result" in data)
3156
- resolve(data.result);
3157
- else if ("error" in data)
3158
- reject(data.error);
3159
- } else {
3160
- logger.debug("Received unsolicited message", data);
3161
- }
3162
- }, "onMessage");
3163
- if (socket.addEventListener) {
3164
- socket.addEventListener("message", onMessage);
3165
- } else {
3166
- socket.on("message", onMessage);
3167
- }
3168
- return new Promise((resolve) => {
3169
- const onClose = /* @__PURE__ */ __name(() => {
3170
- if (socket.removeEventListener) {
3171
- socket.removeEventListener("message", onMessage);
3172
- } else {
3173
- socket.off("message", onMessage);
3174
- }
3175
- this.rejectAll(new Error("WebSocket closed"));
3176
- resolve();
3177
- }, "onClose");
3178
- if (socket.addEventListener) {
3179
- socket.addEventListener("close", onClose);
3180
- } else {
3181
- socket.on("close", onClose);
3182
- }
3183
- });
3184
- }
3185
- rejectAll(err) {
3186
- for (const { reject } of this.pending.values()) reject(err);
3187
- this.pending.clear();
3188
- }
3189
- async initialize() {
3190
- logger.debug("Initializing MCP session over WebSocket");
3191
- const result = await this.sendRequest("initialize");
3192
- const toolsList = await this.listTools();
3193
- this.toolsCache = toolsList.map((t) => t);
3194
- logger.debug(`Initialized with ${this.toolsCache.length} tools`);
3195
- return result;
3196
- }
3197
- async listTools() {
3198
- const res = await this.sendRequest("tools/list");
3199
- return res.tools ?? [];
3200
- }
3201
- async callTool(name, args) {
3202
- return await this.sendRequest("tools/call", { name, arguments: args });
3203
- }
3204
- async listResources() {
3205
- const resources = await this.sendRequest("resources/list");
3206
- return { resources: Array.isArray(resources) ? resources : [] };
3207
- }
3208
- async readResource(uri) {
3209
- const res = await this.sendRequest("resources/read", { uri });
3210
- return { content: res.content, mimeType: res.mimeType };
3211
- }
3212
- async request(method, params = null) {
3213
- return await this.sendRequest(method, params);
3214
- }
3215
- get tools() {
3216
- if (!this.toolsCache)
3217
- throw new Error("MCP client is not initialized");
3218
- return this.toolsCache;
3219
- }
3220
- async cleanupResources() {
3221
- if (this.receiverTask)
3222
- await this.receiverTask.catch(() => {
3223
- });
3224
- this.receiverTask = null;
3225
- this.rejectAll(new Error("WebSocket disconnected"));
3226
- if (this.connectionManager) {
3227
- await this.connectionManager.stop();
3228
- this.connectionManager = null;
3229
- this.ws = null;
3230
- }
3231
- this.toolsCache = null;
3232
- }
3233
- get publicIdentifier() {
3234
- return {
3235
- type: "websocket",
3236
- url: this.url
3237
- };
3238
- }
3239
- };
3240
-
3241
2406
  // src/agents/utils/ai_sdk.ts
3242
2407
  async function* streamEventsToAISDK(streamEvents) {
3243
2408
  for await (const event of streamEvents) {
@@ -3293,119 +2458,6 @@ async function* streamEventsToAISDKWithTools(streamEvents) {
3293
2458
  }
3294
2459
  __name(streamEventsToAISDKWithTools, "streamEventsToAISDKWithTools");
3295
2460
 
3296
- // src/client/base.ts
3297
- var BaseMCPClient = class {
3298
- static {
3299
- __name(this, "BaseMCPClient");
3300
- }
3301
- config = {};
3302
- sessions = {};
3303
- activeSessions = [];
3304
- constructor(config) {
3305
- if (config) {
3306
- this.config = config;
3307
- }
3308
- }
3309
- static fromDict(_cfg) {
3310
- throw new Error("fromDict must be implemented by concrete class");
3311
- }
3312
- addServer(name, serverConfig) {
3313
- this.config.mcpServers = this.config.mcpServers || {};
3314
- this.config.mcpServers[name] = serverConfig;
3315
- }
3316
- removeServer(name) {
3317
- if (this.config.mcpServers?.[name]) {
3318
- delete this.config.mcpServers[name];
3319
- this.activeSessions = this.activeSessions.filter((n) => n !== name);
3320
- }
3321
- }
3322
- getServerNames() {
3323
- return Object.keys(this.config.mcpServers ?? {});
3324
- }
3325
- getServerConfig(name) {
3326
- return this.config.mcpServers?.[name];
3327
- }
3328
- getConfig() {
3329
- return this.config ?? {};
3330
- }
3331
- async createSession(serverName, autoInitialize = true) {
3332
- const servers = this.config.mcpServers ?? {};
3333
- if (Object.keys(servers).length === 0) {
3334
- logger.warn("No MCP servers defined in config");
3335
- }
3336
- if (!servers[serverName]) {
3337
- throw new Error(`Server '${serverName}' not found in config`);
3338
- }
3339
- const connector = this.createConnectorFromConfig(servers[serverName]);
3340
- const session = new MCPSession(connector);
3341
- if (autoInitialize) {
3342
- await session.initialize();
3343
- }
3344
- this.sessions[serverName] = session;
3345
- if (!this.activeSessions.includes(serverName)) {
3346
- this.activeSessions.push(serverName);
3347
- }
3348
- return session;
3349
- }
3350
- async createAllSessions(autoInitialize = true) {
3351
- const servers = this.config.mcpServers ?? {};
3352
- if (Object.keys(servers).length === 0) {
3353
- logger.warn("No MCP servers defined in config");
3354
- }
3355
- for (const name of Object.keys(servers)) {
3356
- await this.createSession(name, autoInitialize);
3357
- }
3358
- return this.sessions;
3359
- }
3360
- getSession(serverName) {
3361
- const session = this.sessions[serverName];
3362
- if (!session) {
3363
- return null;
3364
- }
3365
- return session;
3366
- }
3367
- getAllActiveSessions() {
3368
- return Object.fromEntries(
3369
- this.activeSessions.map((n) => [n, this.sessions[n]])
3370
- );
3371
- }
3372
- async closeSession(serverName) {
3373
- const session = this.sessions[serverName];
3374
- if (!session) {
3375
- logger.warn(`No session exists for server ${serverName}, nothing to close`);
3376
- return;
3377
- }
3378
- try {
3379
- logger.debug(`Closing session for server ${serverName}`);
3380
- await session.disconnect();
3381
- } catch (e) {
3382
- logger.error(`Error closing session for server '${serverName}': ${e}`);
3383
- } finally {
3384
- delete this.sessions[serverName];
3385
- this.activeSessions = this.activeSessions.filter((n) => n !== serverName);
3386
- }
3387
- }
3388
- async closeAllSessions() {
3389
- const serverNames = Object.keys(this.sessions);
3390
- const errors = [];
3391
- for (const serverName of serverNames) {
3392
- try {
3393
- logger.debug(`Closing session for server ${serverName}`);
3394
- await this.closeSession(serverName);
3395
- } catch (e) {
3396
- const errorMsg = `Failed to close session for server '${serverName}': ${e}`;
3397
- logger.error(errorMsg);
3398
- errors.push(errorMsg);
3399
- }
3400
- }
3401
- if (errors.length) {
3402
- logger.error(`Encountered ${errors.length} errors while closing sessions`);
3403
- } else {
3404
- logger.debug("All sessions closed successfully");
3405
- }
3406
- }
3407
- };
3408
-
3409
2461
  export {
3410
2462
  BaseAdapter,
3411
2463
  LangChainAdapter,
@@ -3420,12 +2472,6 @@ export {
3420
2472
  setTelemetrySource,
3421
2473
  RemoteAgent,
3422
2474
  MCPAgent,
3423
- MCPSession,
3424
- BaseMCPClient,
3425
- ConnectionManager,
3426
- BaseConnector,
3427
- HttpConnector,
3428
- WebSocketConnector,
3429
2475
  streamEventsToAISDK,
3430
2476
  createReadableStreamFromGenerator,
3431
2477
  streamEventsToAISDKWithTools