@mcp-ts/sdk 1.3.5 → 1.3.6

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.
@@ -42,6 +42,12 @@ var __export = (target, all) => {
42
42
  };
43
43
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
44
44
 
45
+ // node_modules/tsup/assets/cjs_shims.js
46
+ var init_cjs_shims = __esm({
47
+ "node_modules/tsup/assets/cjs_shims.js"() {
48
+ }
49
+ });
50
+
45
51
  // src/server/storage/redis.ts
46
52
  var redis_exports = {};
47
53
  __export(redis_exports, {
@@ -117,6 +123,7 @@ async function closeRedis() {
117
123
  var redisInstance, redis;
118
124
  var init_redis = __esm({
119
125
  "src/server/storage/redis.ts"() {
126
+ init_cjs_shims();
120
127
  redisInstance = null;
121
128
  redis = new Proxy({}, {
122
129
  get(_target, prop) {
@@ -133,7 +140,23 @@ var init_redis = __esm({
133
140
  }
134
141
  });
135
142
 
143
+ // src/server/index.ts
144
+ init_cjs_shims();
145
+
146
+ // src/server/mcp/oauth-client.ts
147
+ init_cjs_shims();
148
+
149
+ // src/server/mcp/storage-oauth-provider.ts
150
+ init_cjs_shims();
151
+
152
+ // src/server/storage/index.ts
153
+ init_cjs_shims();
154
+
155
+ // src/server/storage/redis-backend.ts
156
+ init_cjs_shims();
157
+
136
158
  // src/shared/constants.ts
159
+ init_cjs_shims();
137
160
  var SESSION_TTL_SECONDS = 43200;
138
161
  var STATE_EXPIRATION_MS = 10 * 60 * 1e3;
139
162
  var TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1e3;
@@ -163,6 +186,14 @@ var RedisStorageBackend = class {
163
186
  __publicField(this, "IDENTITY_KEY_PREFIX", "mcp:identity:");
164
187
  __publicField(this, "IDENTITY_KEY_SUFFIX", ":sessions");
165
188
  }
189
+ async init() {
190
+ try {
191
+ await this.redis.ping();
192
+ console.log("[mcp-ts][Storage] Redis: \u2713 Connected to server.");
193
+ } catch (error) {
194
+ throw new Error(`[RedisStorage] Failed to connect to Redis: ${error.message}`);
195
+ }
196
+ }
166
197
  /**
167
198
  * Generates Redis key for a specific session
168
199
  * @private
@@ -373,6 +404,9 @@ var RedisStorageBackend = class {
373
404
  }
374
405
  }
375
406
  };
407
+
408
+ // src/server/storage/memory-backend.ts
409
+ init_cjs_shims();
376
410
  var firstChar2 = nanoid.customAlphabet(
377
411
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
378
412
  1
@@ -388,6 +422,9 @@ var MemoryStorageBackend = class {
388
422
  // Map<identity, Set<sessionId>>
389
423
  __publicField(this, "identitySessions", /* @__PURE__ */ new Map());
390
424
  }
425
+ async init() {
426
+ console.log("[mcp-ts][Storage] Memory: \u2713 internal memory store active.");
427
+ }
391
428
  getSessionKey(identity, sessionId) {
392
429
  return `${identity}:${sessionId}`;
393
430
  }
@@ -463,6 +500,9 @@ var MemoryStorageBackend = class {
463
500
  async disconnect() {
464
501
  }
465
502
  };
503
+
504
+ // src/server/storage/file-backend.ts
505
+ init_cjs_shims();
466
506
  var firstChar3 = nanoid.customAlphabet(
467
507
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
468
508
  1
@@ -507,6 +547,7 @@ var FileStorageBackend = class {
507
547
  }
508
548
  }
509
549
  this.initialized = true;
550
+ console.log(`[mcp-ts][Storage] File: \u2713 storage directory at ${path__namespace.dirname(this.filePath)} verified.`);
510
551
  }
511
552
  async ensureInitialized() {
512
553
  if (!this.initialized) await this.init();
@@ -583,6 +624,9 @@ var FileStorageBackend = class {
583
624
  async disconnect() {
584
625
  }
585
626
  };
627
+
628
+ // src/server/storage/sqlite-backend.ts
629
+ init_cjs_shims();
586
630
  var SqliteStorage = class {
587
631
  constructor(options = {}) {
588
632
  __publicField(this, "db", null);
@@ -611,6 +655,7 @@ var SqliteStorage = class {
611
655
  CREATE INDEX IF NOT EXISTS idx_${this.table}_identity ON ${this.table}(identity);
612
656
  `);
613
657
  this.initialized = true;
658
+ console.log(`[mcp-ts][Storage] SQLite: \u2713 database at ${this.dbPath} verified.`);
614
659
  } catch (error) {
615
660
  if (error.code === "MODULE_NOT_FOUND" || error.message?.includes("better-sqlite3")) {
616
661
  throw new Error(
@@ -726,6 +771,161 @@ var SqliteStorage = class {
726
771
  }
727
772
  };
728
773
 
774
+ // src/server/storage/supabase-backend.ts
775
+ init_cjs_shims();
776
+ var SupabaseStorageBackend = class {
777
+ constructor(supabase) {
778
+ this.supabase = supabase;
779
+ __publicField(this, "DEFAULT_TTL", SESSION_TTL_SECONDS);
780
+ }
781
+ async init() {
782
+ const { error } = await this.supabase.from("mcp_sessions").select("session_id").limit(0);
783
+ if (error) {
784
+ if (error.code === "42P01") {
785
+ throw new Error(
786
+ '[SupabaseStorage] Table "mcp_sessions" not found in your database. Please run "npx mcp-ts supabase-init" in your project to set up the required table and RLS policies.'
787
+ );
788
+ }
789
+ throw new Error(`[SupabaseStorage] Initialization check failed: ${error.message}`);
790
+ }
791
+ console.log('[mcp-ts][Storage] Supabase: \u2713 "mcp_sessions" table verified.');
792
+ }
793
+ generateSessionId() {
794
+ return crypto.randomUUID();
795
+ }
796
+ mapRowToSessionData(row) {
797
+ return {
798
+ sessionId: row.session_id,
799
+ serverId: row.server_id,
800
+ serverName: row.server_name,
801
+ serverUrl: row.server_url,
802
+ transportType: row.transport_type,
803
+ callbackUrl: row.callback_url,
804
+ createdAt: new Date(row.created_at).getTime(),
805
+ identity: row.identity,
806
+ headers: row.headers,
807
+ active: row.active,
808
+ clientInformation: row.client_information,
809
+ tokens: row.tokens,
810
+ codeVerifier: row.code_verifier,
811
+ clientId: row.client_id
812
+ };
813
+ }
814
+ async createSession(session, ttl) {
815
+ const { sessionId, identity } = session;
816
+ if (!sessionId || !identity) throw new Error("identity and sessionId required");
817
+ const effectiveTtl = ttl ?? this.DEFAULT_TTL;
818
+ const expiresAt = new Date(Date.now() + effectiveTtl * 1e3).toISOString();
819
+ const { error } = await this.supabase.from("mcp_sessions").insert({
820
+ session_id: sessionId,
821
+ user_id: identity,
822
+ // Maps user_id to identity to support RLS using auth.uid()
823
+ server_id: session.serverId,
824
+ server_name: session.serverName,
825
+ server_url: session.serverUrl,
826
+ transport_type: session.transportType,
827
+ callback_url: session.callbackUrl,
828
+ created_at: new Date(session.createdAt || Date.now()).toISOString(),
829
+ identity,
830
+ headers: session.headers,
831
+ active: session.active ?? false,
832
+ client_information: session.clientInformation,
833
+ tokens: session.tokens,
834
+ code_verifier: session.codeVerifier,
835
+ client_id: session.clientId,
836
+ expires_at: expiresAt
837
+ });
838
+ if (error) {
839
+ if (error.code === "23505") {
840
+ throw new Error(`Session ${sessionId} already exists`);
841
+ }
842
+ throw new Error(`Failed to create session in Supabase: ${error.message}`);
843
+ }
844
+ }
845
+ async updateSession(identity, sessionId, data, ttl) {
846
+ const effectiveTtl = ttl ?? this.DEFAULT_TTL;
847
+ const expiresAt = new Date(Date.now() + effectiveTtl * 1e3).toISOString();
848
+ const updateData = {
849
+ expires_at: expiresAt,
850
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
851
+ };
852
+ if ("serverId" in data) updateData.server_id = data.serverId;
853
+ if ("serverName" in data) updateData.server_name = data.serverName;
854
+ if ("serverUrl" in data) updateData.server_url = data.serverUrl;
855
+ if ("transportType" in data) updateData.transport_type = data.transportType;
856
+ if ("callbackUrl" in data) updateData.callback_url = data.callbackUrl;
857
+ if ("active" in data) updateData.active = data.active;
858
+ if ("headers" in data) updateData.headers = data.headers;
859
+ if ("clientInformation" in data) updateData.client_information = data.clientInformation;
860
+ if ("tokens" in data) updateData.tokens = data.tokens;
861
+ if ("codeVerifier" in data) updateData.code_verifier = data.codeVerifier;
862
+ if ("clientId" in data) updateData.client_id = data.clientId;
863
+ const { data: updatedRows, error } = await this.supabase.from("mcp_sessions").update(updateData).eq("identity", identity).eq("session_id", sessionId).select("id");
864
+ if (error) {
865
+ throw new Error(`Failed to update session: ${error.message}`);
866
+ }
867
+ if (!updatedRows || updatedRows.length === 0) {
868
+ throw new Error(`Session ${sessionId} not found for identity ${identity}`);
869
+ }
870
+ }
871
+ async getSession(identity, sessionId) {
872
+ const { data, error } = await this.supabase.from("mcp_sessions").select("*").eq("identity", identity).eq("session_id", sessionId).maybeSingle();
873
+ if (error) {
874
+ console.error("[SupabaseStorage] Failed to get session:", error);
875
+ return null;
876
+ }
877
+ if (!data) return null;
878
+ return this.mapRowToSessionData(data);
879
+ }
880
+ async getIdentitySessionsData(identity) {
881
+ const { data, error } = await this.supabase.from("mcp_sessions").select("*").eq("identity", identity);
882
+ if (error) {
883
+ console.error(`[SupabaseStorage] Failed to get session data for ${identity}:`, error);
884
+ return [];
885
+ }
886
+ return data.map((row) => this.mapRowToSessionData(row));
887
+ }
888
+ async removeSession(identity, sessionId) {
889
+ const { error } = await this.supabase.from("mcp_sessions").delete().eq("identity", identity).eq("session_id", sessionId);
890
+ if (error) {
891
+ console.error("[SupabaseStorage] Failed to remove session:", error);
892
+ }
893
+ }
894
+ async getIdentityMcpSessions(identity) {
895
+ const { data, error } = await this.supabase.from("mcp_sessions").select("session_id").eq("identity", identity);
896
+ if (error) {
897
+ console.error(`[SupabaseStorage] Failed to get sessions for ${identity}:`, error);
898
+ return [];
899
+ }
900
+ return data.map((row) => row.session_id);
901
+ }
902
+ async getAllSessionIds() {
903
+ const { data, error } = await this.supabase.from("mcp_sessions").select("session_id");
904
+ if (error) {
905
+ console.error("[SupabaseStorage] Failed to get all sessions:", error);
906
+ return [];
907
+ }
908
+ return data.map((row) => row.session_id);
909
+ }
910
+ async clearAll() {
911
+ const { error } = await this.supabase.from("mcp_sessions").delete().neq("session_id", "");
912
+ if (error) {
913
+ console.error("[SupabaseStorage] Failed to clear sessions:", error);
914
+ }
915
+ }
916
+ async cleanupExpiredSessions() {
917
+ const { error } = await this.supabase.from("mcp_sessions").delete().lt("expires_at", (/* @__PURE__ */ new Date()).toISOString());
918
+ if (error) {
919
+ console.error("[SupabaseStorage] Failed to cleanup expired sessions:", error);
920
+ }
921
+ }
922
+ async disconnect() {
923
+ }
924
+ };
925
+
926
+ // src/server/storage/types.ts
927
+ init_cjs_shims();
928
+
729
929
  // src/server/storage/index.ts
730
930
  var storageInstance = null;
731
931
  var storagePromise = null;
@@ -744,53 +944,85 @@ async function createStorage() {
744
944
  try {
745
945
  const { getRedis: getRedis2 } = await Promise.resolve().then(() => (init_redis(), redis_exports));
746
946
  const redis2 = await getRedis2();
747
- console.log("[Storage] Using Redis storage (Explicit)");
748
- return new RedisStorageBackend(redis2);
947
+ console.log('[mcp-ts][Storage] Explicit selection: "redis"');
948
+ return await initializeStorage(new RedisStorageBackend(redis2));
749
949
  } catch (error) {
750
- console.error("[Storage] Failed to initialize Redis:", error.message);
751
- console.log("[Storage] Falling back to In-Memory storage");
752
- return new MemoryStorageBackend();
950
+ console.error("[mcp-ts][Storage] Failed to initialize Redis:", error.message);
951
+ console.log("[mcp-ts][Storage] Falling back to In-Memory storage");
952
+ return await initializeStorage(new MemoryStorageBackend());
753
953
  }
754
954
  }
755
955
  if (type === "file") {
756
956
  const filePath = process.env.MCP_TS_STORAGE_FILE;
757
- if (!filePath) {
758
- console.warn('[Storage] MCP_TS_STORAGE_TYPE is "file" but MCP_TS_STORAGE_FILE is missing');
759
- }
760
- console.log(`[Storage] Using File storage (${filePath}) (Explicit)`);
957
+ console.log(`[mcp-ts][Storage] Explicit selection: "file" (${filePath || "default"})`);
761
958
  return await initializeStorage(new FileStorageBackend({ path: filePath }));
762
959
  }
763
960
  if (type === "sqlite") {
764
961
  const dbPath = process.env.MCP_TS_STORAGE_SQLITE_PATH;
765
- console.log(`[Storage] Using SQLite storage (${dbPath || "default"}) (Explicit)`);
962
+ console.log(`[mcp-ts][Storage] Explicit selection: "sqlite" (${dbPath || "default"})`);
766
963
  return await initializeStorage(new SqliteStorage({ path: dbPath }));
767
964
  }
965
+ if (type === "supabase") {
966
+ const url = process.env.SUPABASE_URL;
967
+ const key = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY;
968
+ if (!url || !key) {
969
+ console.warn('[mcp-ts][Storage] Explicit selection "supabase" requires SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.');
970
+ } else {
971
+ if (!process.env.SUPABASE_SERVICE_ROLE_KEY) {
972
+ 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.');
973
+ }
974
+ try {
975
+ const { createClient } = await import('@supabase/supabase-js');
976
+ const client = createClient(url, key);
977
+ console.log('[mcp-ts][Storage] Explicit selection: "supabase"');
978
+ return await initializeStorage(new SupabaseStorageBackend(client));
979
+ } catch (error) {
980
+ console.error("[mcp-ts][Storage] Failed to initialize Supabase:", error.message);
981
+ console.log("[mcp-ts][Storage] Falling back to In-Memory storage");
982
+ return await initializeStorage(new MemoryStorageBackend());
983
+ }
984
+ }
985
+ }
768
986
  if (type === "memory") {
769
- console.log("[Storage] Using In-Memory storage (Explicit)");
770
- return new MemoryStorageBackend();
987
+ console.log('[mcp-ts][Storage] Explicit selection: "memory"');
988
+ return await initializeStorage(new MemoryStorageBackend());
771
989
  }
772
990
  if (process.env.REDIS_URL) {
773
991
  try {
774
992
  const { getRedis: getRedis2 } = await Promise.resolve().then(() => (init_redis(), redis_exports));
775
993
  const redis2 = await getRedis2();
776
- console.log("[Storage] Auto-detected REDIS_URL. Using Redis storage.");
777
- return new RedisStorageBackend(redis2);
994
+ console.log('[mcp-ts][Storage] Auto-detection: "redis" (via REDIS_URL)');
995
+ return await initializeStorage(new RedisStorageBackend(redis2));
778
996
  } catch (error) {
779
- console.error("[Storage] Redis auto-detection failed:", error.message);
780
- console.log("[Storage] Falling back to In-Memory storage");
781
- return new MemoryStorageBackend();
997
+ console.error("[mcp-ts][Storage] Redis auto-detection failed:", error.message);
998
+ console.log("[mcp-ts][Storage] Falling back to next available backend");
782
999
  }
783
1000
  }
784
1001
  if (process.env.MCP_TS_STORAGE_FILE) {
785
- console.log(`[Storage] Auto-detected MCP_TS_STORAGE_FILE. Using File storage (${process.env.MCP_TS_STORAGE_FILE}).`);
1002
+ console.log(`[mcp-ts][Storage] Auto-detection: "file" (${process.env.MCP_TS_STORAGE_FILE})`);
786
1003
  return await initializeStorage(new FileStorageBackend({ path: process.env.MCP_TS_STORAGE_FILE }));
787
1004
  }
788
1005
  if (process.env.MCP_TS_STORAGE_SQLITE_PATH) {
789
- console.log(`[Storage] Auto-detected MCP_TS_STORAGE_SQLITE_PATH. Using SQLite storage (${process.env.MCP_TS_STORAGE_SQLITE_PATH}).`);
1006
+ console.log(`[mcp-ts][Storage] Auto-detection: "sqlite" (${process.env.MCP_TS_STORAGE_SQLITE_PATH})`);
790
1007
  return await initializeStorage(new SqliteStorage({ path: process.env.MCP_TS_STORAGE_SQLITE_PATH }));
791
1008
  }
792
- console.log("[Storage] No storage configured. Using In-Memory storage (Default).");
793
- return new MemoryStorageBackend();
1009
+ if (process.env.SUPABASE_URL && (process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY)) {
1010
+ try {
1011
+ const { createClient } = await import('@supabase/supabase-js');
1012
+ const url = process.env.SUPABASE_URL;
1013
+ const key = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_ANON_KEY;
1014
+ if (!process.env.SUPABASE_SERVICE_ROLE_KEY) {
1015
+ 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.');
1016
+ }
1017
+ const client = createClient(url, key);
1018
+ console.log('[mcp-ts][Storage] Auto-detection: "supabase" (via SUPABASE_URL)');
1019
+ return await initializeStorage(new SupabaseStorageBackend(client));
1020
+ } catch (error) {
1021
+ console.error("[mcp-ts][Storage] Supabase auto-detection failed:", error.message);
1022
+ }
1023
+ }
1024
+ console.log('[mcp-ts][Storage] Defaulting to: "memory"');
1025
+ return await initializeStorage(new MemoryStorageBackend());
794
1026
  }
795
1027
  async function getStorage() {
796
1028
  if (storageInstance) {
@@ -1001,6 +1233,7 @@ var StorageOAuthClientProvider = class {
1001
1233
  };
1002
1234
 
1003
1235
  // src/shared/utils.ts
1236
+ init_cjs_shims();
1004
1237
  function sanitizeServerLabel(name) {
1005
1238
  let sanitized = name.replace(/[^a-zA-Z0-9-_]/g, "_").replace(/_{2,}/g, "_").toLowerCase();
1006
1239
  if (!/^[a-zA-Z]/.test(sanitized)) {
@@ -1010,6 +1243,7 @@ function sanitizeServerLabel(name) {
1010
1243
  }
1011
1244
 
1012
1245
  // src/shared/events.ts
1246
+ init_cjs_shims();
1013
1247
  var Emitter = class {
1014
1248
  constructor() {
1015
1249
  __publicField(this, "listeners", /* @__PURE__ */ new Set());
@@ -1057,6 +1291,7 @@ var Emitter = class {
1057
1291
  };
1058
1292
 
1059
1293
  // src/shared/errors.ts
1294
+ init_cjs_shims();
1060
1295
  var McpError = class extends Error {
1061
1296
  constructor(code, message, cause) {
1062
1297
  super(message);
@@ -1971,6 +2206,7 @@ var MCPClient = class _MCPClient {
1971
2206
  };
1972
2207
 
1973
2208
  // src/server/mcp/multi-session-client.ts
2209
+ init_cjs_shims();
1974
2210
  var MultiSessionClient = class {
1975
2211
  constructor(identity, options = {}) {
1976
2212
  __publicField(this, "clients", []);
@@ -2060,7 +2296,11 @@ var MultiSessionClient = class {
2060
2296
  }
2061
2297
  };
2062
2298
 
2299
+ // src/server/handlers/sse-handler.ts
2300
+ init_cjs_shims();
2301
+
2063
2302
  // src/shared/event-routing.ts
2303
+ init_cjs_shims();
2064
2304
  function isRpcResponseEvent(event) {
2065
2305
  return "id" in event && ("result" in event || "error" in event);
2066
2306
  }
@@ -2499,6 +2739,7 @@ function writeSSEEvent(res, event, data) {
2499
2739
  }
2500
2740
 
2501
2741
  // src/server/handlers/nextjs-handler.ts
2742
+ init_cjs_shims();
2502
2743
  function createNextMcpHandler(options = {}) {
2503
2744
  const {
2504
2745
  getIdentity = (request) => new URL(request.url).searchParams.get("identity"),