@mcp-ts/sdk 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -264,6 +264,17 @@ declare class MCPClient {
264
264
  * @throws {Error} When client is not connected
265
265
  */
266
266
  readResource(uri: string): Promise<ReadResourceResult>;
267
+ /**
268
+ * Wraps an MCP request with automatic transport-session recovery.
269
+ *
270
+ * When the downstream MCP server rejects the request with a 404 indicating
271
+ * the transport session has expired, this method tears down the stale SDK
272
+ * client and transport, calls {@link reconnect} to negotiate a fresh session,
273
+ * and retries the request once.
274
+ *
275
+ * Non-transient errors (network failures, auth errors, etc.) propagate as-is.
276
+ */
277
+ private withRetry;
267
278
  /**
268
279
  * Reconnects to MCP server using existing OAuth provider from Redis
269
280
  * Used for session restoration in serverless environments
@@ -534,6 +545,12 @@ declare class MultiSessionClient implements ToolClientProvider {
534
545
  * or to route a tool call to the right client by `serverId`.
535
546
  */
536
547
  getClients(): MCPClient[];
548
+ /**
549
+ * Removes and disconnects a single session by ID.
550
+ *
551
+ * @returns `true` if the session was found and removed, `false` if not found.
552
+ */
553
+ removeSession(sessionId: string): Promise<boolean>;
537
554
  /**
538
555
  * Gracefully disconnects all active MCP clients and clears the internal list.
539
556
  *
@@ -264,6 +264,17 @@ declare class MCPClient {
264
264
  * @throws {Error} When client is not connected
265
265
  */
266
266
  readResource(uri: string): Promise<ReadResourceResult>;
267
+ /**
268
+ * Wraps an MCP request with automatic transport-session recovery.
269
+ *
270
+ * When the downstream MCP server rejects the request with a 404 indicating
271
+ * the transport session has expired, this method tears down the stale SDK
272
+ * client and transport, calls {@link reconnect} to negotiate a fresh session,
273
+ * and retries the request once.
274
+ *
275
+ * Non-transient errors (network failures, auth errors, etc.) propagate as-is.
276
+ */
277
+ private withRetry;
267
278
  /**
268
279
  * Reconnects to MCP server using existing OAuth provider from Redis
269
280
  * Used for session restoration in serverless environments
@@ -534,6 +545,12 @@ declare class MultiSessionClient implements ToolClientProvider {
534
545
  * or to route a tool call to the right client by `serverId`.
535
546
  */
536
547
  getClients(): MCPClient[];
548
+ /**
549
+ * Removes and disconnects a single session by ID.
550
+ *
551
+ * @returns `true` if the session was found and removed, `false` if not found.
552
+ */
553
+ removeSession(sessionId: string): Promise<boolean>;
537
554
  /**
538
555
  * Gracefully disconnects all active MCP clients and clears the internal list.
539
556
  *
@@ -1,5 +1,5 @@
1
- import { c as SessionMutationListener, e as SessionStore } from '../multi-session-client-CWs-AE78.mjs';
2
- export { M as MCPClient, a as MultiSessionClient, S as Session, b as SessionMutationEvent, d as SessionMutationType, f as StorageOAuthClientProvider } from '../multi-session-client-CWs-AE78.mjs';
1
+ import { c as SessionMutationListener, e as SessionStore } from '../multi-session-client-B6hsYO8V.mjs';
2
+ export { M as MCPClient, a as MultiSessionClient, S as Session, b as SessionMutationEvent, d as SessionMutationType, f as StorageOAuthClientProvider } from '../multi-session-client-B6hsYO8V.mjs';
3
3
  export { U as UnauthorizedError, s as sanitizeServerLabel } from '../utils-DELRKQPU.mjs';
4
4
  import { M as McpConnectionEvent, t as McpObservabilityEvent, x as McpRpcResponse, w as McpRpcRequest } from '../types-CjczQwNX.mjs';
5
5
  export { a as CallToolRequest, b as CallToolResponse, f as ConnectRequest, g as ConnectResponse, k as Disposable, E as Emitter, m as Event, q as ListToolsResponse, s as McpConnectionState, T as ToolClient, A as ToolClientProvider, B as ToolInfo } from '../types-CjczQwNX.mjs';
@@ -1,5 +1,5 @@
1
- import { c as SessionMutationListener, e as SessionStore } from '../multi-session-client-BluyCPo9.js';
2
- export { M as MCPClient, a as MultiSessionClient, S as Session, b as SessionMutationEvent, d as SessionMutationType, f as StorageOAuthClientProvider } from '../multi-session-client-BluyCPo9.js';
1
+ import { c as SessionMutationListener, e as SessionStore } from '../multi-session-client-DOBvtaQV.js';
2
+ export { M as MCPClient, a as MultiSessionClient, S as Session, b as SessionMutationEvent, d as SessionMutationType, f as StorageOAuthClientProvider } from '../multi-session-client-DOBvtaQV.js';
3
3
  export { U as UnauthorizedError, s as sanitizeServerLabel } from '../utils-DELRKQPU.js';
4
4
  import { M as McpConnectionEvent, t as McpObservabilityEvent, x as McpRpcResponse, w as McpRpcRequest } from '../types-CjczQwNX.js';
5
5
  export { a as CallToolRequest, b as CallToolResponse, f as ConnectRequest, g as ConnectResponse, k as Disposable, E as Emitter, m as Event, q as ListToolsResponse, s as McpConnectionState, T as ToolClient, A as ToolClientProvider, B as ToolInfo } from '../types-CjczQwNX.js';
@@ -1734,12 +1734,12 @@ async function createStorage() {
1734
1734
  }
1735
1735
  if (type === "supabase") {
1736
1736
  const url = process.env.SUPABASE_URL;
1737
- const key = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY;
1737
+ const key = process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_ANON_KEY;
1738
1738
  if (!url || !key) {
1739
- console.warn('[mcp-ts][Storage] Explicit selection "supabase" requires SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.');
1739
+ console.warn('[mcp-ts][Storage] Explicit selection "supabase" requires SUPABASE_URL and SUPABASE_SECRET_KEY.');
1740
1740
  } else {
1741
- if (!process.env.SUPABASE_SERVICE_ROLE_KEY) {
1742
- console.warn('[mcp-ts][Storage] \u26A0\uFE0F Warning: Using "SUPABASE_ANON_KEY" for server-side storage. You may encounter RLS policy violations. "SUPABASE_SERVICE_ROLE_KEY" is recommended.');
1741
+ if (!process.env.SUPABASE_SECRET_KEY) {
1742
+ console.warn('[mcp-ts][Storage] \u26A0\uFE0F Warning: Using "SUPABASE_ANON_KEY" for server-side storage. You may encounter RLS policy violations. "SUPABASE_SECRET_KEY" is recommended.');
1743
1743
  }
1744
1744
  try {
1745
1745
  const { createClient } = await import('@supabase/supabase-js');
@@ -1794,13 +1794,13 @@ async function createStorage() {
1794
1794
  console.log(`[mcp-ts][Storage] Auto-detection: "sqlite" (${process.env.MCP_TS_STORAGE_SQLITE_PATH})`);
1795
1795
  return await initializeStorage(new SqliteStorage({ path: process.env.MCP_TS_STORAGE_SQLITE_PATH }));
1796
1796
  }
1797
- if (process.env.SUPABASE_URL && (process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY)) {
1797
+ if (process.env.SUPABASE_URL && (process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_ANON_KEY)) {
1798
1798
  try {
1799
1799
  const { createClient } = await import('@supabase/supabase-js');
1800
1800
  const url = process.env.SUPABASE_URL;
1801
- const key = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY;
1802
- if (!process.env.SUPABASE_SERVICE_ROLE_KEY) {
1803
- console.warn('[mcp-ts][Storage] \u26A0\uFE0F Warning: Using "SUPABASE_ANON_KEY" for server-side storage. You may encounter RLS policy violations. "SUPABASE_SERVICE_ROLE_KEY" is recommended.');
1801
+ const key = process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_ANON_KEY;
1802
+ if (!process.env.SUPABASE_SECRET_KEY) {
1803
+ console.warn('[mcp-ts][Storage] \u26A0\uFE0F Warning: Using "SUPABASE_ANON_KEY" for server-side storage. You may encounter RLS policy violations. "SUPABASE_SECRET_KEY" is recommended.');
1804
1804
  }
1805
1805
  const client = createClient(url, key);
1806
1806
  console.log('[mcp-ts][Storage] Auto-detection: "supabase" (via SUPABASE_URL)');
@@ -2300,7 +2300,6 @@ var MCPClient = class {
2300
2300
  const response = await fetch(url, { ...init, signal });
2301
2301
  const hasSessionHeader = init?.headers && new Headers(init.headers).has("mcp-session-id");
2302
2302
  if (response.status === 404 && hasSessionHeader) {
2303
- this.client = null;
2304
2303
  throw new Error("MCP_SESSION_EXPIRED: Downstream session was not found on the server.");
2305
2304
  }
2306
2305
  return response;
@@ -2681,7 +2680,9 @@ var MCPClient = class {
2681
2680
  method: "tools/list",
2682
2681
  params: {}
2683
2682
  };
2684
- const result = await this.client.request(request, types_js.ListToolsResultSchema);
2683
+ const result = await this.withRetry(
2684
+ () => this.client.request(request, types_js.ListToolsResultSchema)
2685
+ );
2685
2686
  if (this.serverId) {
2686
2687
  this._onConnectionEvent.fire({
2687
2688
  type: "tools_discovered",
@@ -2721,7 +2722,9 @@ var MCPClient = class {
2721
2722
  }
2722
2723
  };
2723
2724
  try {
2724
- const result = await this.client.request(request, types_js.CallToolResultSchema);
2725
+ const result = await this.withRetry(
2726
+ () => this.client.request(request, types_js.CallToolResultSchema)
2727
+ );
2725
2728
  this._onObservabilityEvent.fire({
2726
2729
  type: "mcp:client:tool_call",
2727
2730
  level: "info",
@@ -2773,7 +2776,9 @@ var MCPClient = class {
2773
2776
  method: "prompts/list",
2774
2777
  params: {}
2775
2778
  };
2776
- const result = await this.client.request(request, types_js.ListPromptsResultSchema);
2779
+ const result = await this.withRetry(
2780
+ () => this.client.request(request, types_js.ListPromptsResultSchema)
2781
+ );
2777
2782
  this.emitStateChange("READY");
2778
2783
  this.emitProgress(`Discovered ${result.prompts.length} prompts`);
2779
2784
  return result;
@@ -2802,7 +2807,9 @@ var MCPClient = class {
2802
2807
  arguments: args
2803
2808
  }
2804
2809
  };
2805
- return await this.client.request(request, types_js.GetPromptResultSchema);
2810
+ return await this.withRetry(
2811
+ () => this.client.request(request, types_js.GetPromptResultSchema)
2812
+ );
2806
2813
  }
2807
2814
  /**
2808
2815
  * Lists all available resources from the connected MCP server
@@ -2819,7 +2826,9 @@ var MCPClient = class {
2819
2826
  method: "resources/list",
2820
2827
  params: {}
2821
2828
  };
2822
- const result = await this.client.request(request, types_js.ListResourcesResultSchema);
2829
+ const result = await this.withRetry(
2830
+ () => this.client.request(request, types_js.ListResourcesResultSchema)
2831
+ );
2823
2832
  this.emitStateChange("READY");
2824
2833
  this.emitProgress(`Discovered ${result.resources.length} resources`);
2825
2834
  return result;
@@ -2846,7 +2855,36 @@ var MCPClient = class {
2846
2855
  uri
2847
2856
  }
2848
2857
  };
2849
- return await this.client.request(request, types_js.ReadResourceResultSchema);
2858
+ return await this.withRetry(
2859
+ () => this.client.request(request, types_js.ReadResourceResultSchema)
2860
+ );
2861
+ }
2862
+ /**
2863
+ * Wraps an MCP request with automatic transport-session recovery.
2864
+ *
2865
+ * When the downstream MCP server rejects the request with a 404 indicating
2866
+ * the transport session has expired, this method tears down the stale SDK
2867
+ * client and transport, calls {@link reconnect} to negotiate a fresh session,
2868
+ * and retries the request once.
2869
+ *
2870
+ * Non-transient errors (network failures, auth errors, etc.) propagate as-is.
2871
+ */
2872
+ async withRetry(fn) {
2873
+ try {
2874
+ return await fn();
2875
+ } catch (error) {
2876
+ if (!(error instanceof Error && error.message.includes("MCP_SESSION_EXPIRED"))) throw error;
2877
+ if (this.client) {
2878
+ try {
2879
+ await this.client.close();
2880
+ } catch {
2881
+ }
2882
+ this.transport = null;
2883
+ this.client = null;
2884
+ }
2885
+ await this.reconnect();
2886
+ return await fn();
2887
+ }
2850
2888
  }
2851
2889
  /**
2852
2890
  * Reconnects to MCP server using existing OAuth provider from Redis
@@ -2859,6 +2897,12 @@ var MCPClient = class {
2859
2897
  if (!this.oauthProvider) {
2860
2898
  throw new Error("OAuth provider not initialized");
2861
2899
  }
2900
+ if (this.client) {
2901
+ try {
2902
+ await this.client.close();
2903
+ } catch {
2904
+ }
2905
+ }
2862
2906
  this.client = new index_js.Client(
2863
2907
  {
2864
2908
  name: MCP_CLIENT_NAME,
@@ -3055,6 +3099,18 @@ var MultiSessionClient = class {
3055
3099
  getClients() {
3056
3100
  return this.clients;
3057
3101
  }
3102
+ /**
3103
+ * Removes and disconnects a single session by ID.
3104
+ *
3105
+ * @returns `true` if the session was found and removed, `false` if not found.
3106
+ */
3107
+ async removeSession(sessionId) {
3108
+ const idx = this.clients.findIndex((c) => c.getSessionId() === sessionId);
3109
+ if (idx === -1) return false;
3110
+ const [client] = this.clients.splice(idx, 1);
3111
+ await client.disconnect();
3112
+ return true;
3113
+ }
3058
3114
  /**
3059
3115
  * Gracefully disconnects all active MCP clients and clears the internal list.
3060
3116
  *