@mcp-ts/sdk 2.5.2 → 2.6.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.
Files changed (73) hide show
  1. package/README.md +3 -574
  2. package/dist/adapters/agui-adapter.d.mts +4 -4
  3. package/dist/adapters/agui-adapter.d.ts +4 -4
  4. package/dist/adapters/agui-middleware.d.mts +4 -4
  5. package/dist/adapters/agui-middleware.d.ts +4 -4
  6. package/dist/adapters/ai-adapter.d.mts +4 -4
  7. package/dist/adapters/ai-adapter.d.ts +4 -4
  8. package/dist/adapters/langchain-adapter.d.mts +4 -4
  9. package/dist/adapters/langchain-adapter.d.ts +4 -4
  10. package/dist/adapters/mastra-adapter.d.mts +3 -3
  11. package/dist/adapters/mastra-adapter.d.ts +3 -3
  12. package/dist/client/index.d.mts +2 -2
  13. package/dist/client/index.d.ts +2 -2
  14. package/dist/client/index.js +3 -0
  15. package/dist/client/index.js.map +1 -1
  16. package/dist/client/index.mjs +3 -0
  17. package/dist/client/index.mjs.map +1 -1
  18. package/dist/client/react.d.mts +10 -18
  19. package/dist/client/react.d.ts +10 -18
  20. package/dist/client/react.js +17 -0
  21. package/dist/client/react.js.map +1 -1
  22. package/dist/client/react.mjs +17 -0
  23. package/dist/client/react.mjs.map +1 -1
  24. package/dist/client/vue.d.mts +4 -4
  25. package/dist/client/vue.d.ts +4 -4
  26. package/dist/client/vue.js +3 -0
  27. package/dist/client/vue.js.map +1 -1
  28. package/dist/client/vue.mjs +3 -0
  29. package/dist/client/vue.mjs.map +1 -1
  30. package/dist/{index-B3GPsPsi.d.mts → index-BrDkbut5.d.ts} +2 -1
  31. package/dist/{index-gNdSQTSz.d.ts → index-DHQvlx4K.d.mts} +2 -1
  32. package/dist/index.d.mts +5 -5
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +1056 -863
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +1048 -858
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/{multi-session-client-CB4oDrQX.d.ts → multi-session-client-CQzymvHl.d.ts} +183 -227
  39. package/dist/{multi-session-client-xj3iQIv6.d.mts → multi-session-client-C_Ja2TuV.d.mts} +183 -227
  40. package/dist/server/index.d.mts +338 -88
  41. package/dist/server/index.d.ts +338 -88
  42. package/dist/server/index.js +1054 -864
  43. package/dist/server/index.js.map +1 -1
  44. package/dist/server/index.mjs +1046 -859
  45. package/dist/server/index.mjs.map +1 -1
  46. package/dist/shared/index.d.mts +4 -4
  47. package/dist/shared/index.d.ts +4 -4
  48. package/dist/shared/index.js.map +1 -1
  49. package/dist/shared/index.mjs.map +1 -1
  50. package/dist/{tool-router-CsKVXbQB.d.mts → tool-router-C1n7OXbl.d.mts} +1 -1
  51. package/dist/{tool-router-C-Mw1_BQ.d.ts → tool-router-CBIawFnt.d.ts} +1 -1
  52. package/dist/{types-6SmXege4.d.mts → types-DX71u9gR.d.mts} +11 -3
  53. package/dist/{types-6SmXege4.d.ts → types-DX71u9gR.d.ts} +11 -3
  54. package/migrations/neon/20260513010000_install_mcp_sessions.sql +4 -34
  55. package/migrations/supabase/20260330195700_install_mcp_sessions.sql +5 -62
  56. package/package.json +2 -1
  57. package/src/client/core/sse-client.ts +5 -0
  58. package/src/client/react/use-mcp.ts +27 -28
  59. package/src/server/handlers/sse-handler.ts +671 -629
  60. package/src/server/index.ts +2 -1
  61. package/src/server/mcp/multi-session-client.ts +34 -10
  62. package/src/server/mcp/oauth-client.ts +197 -205
  63. package/src/server/mcp/storage-oauth-provider.ts +149 -29
  64. package/src/server/mcp/tool-policy-gateway.ts +11 -1
  65. package/src/server/storage/file-backend.ts +25 -21
  66. package/src/server/storage/index.ts +71 -0
  67. package/src/server/storage/memory-backend.ts +24 -12
  68. package/src/server/storage/neon-backend.ts +70 -72
  69. package/src/server/storage/redis-backend.ts +26 -36
  70. package/src/server/storage/sqlite-backend.ts +25 -39
  71. package/src/server/storage/supabase-backend.ts +45 -54
  72. package/src/server/storage/types.ts +22 -2
  73. package/src/shared/types.ts +13 -1
package/dist/index.mjs CHANGED
@@ -4,6 +4,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
4
4
  import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
5
5
  import { UnauthorizedError as UnauthorizedError$1 } from '@modelcontextprotocol/sdk/client/auth.js';
6
6
  import { ListToolsResultSchema, CallToolResultSchema, ListPromptsResultSchema, GetPromptResultSchema, ListResourcesResultSchema, ReadResourceResultSchema } from '@modelcontextprotocol/sdk/types.js';
7
+ import { AsyncLocalStorage } from 'async_hooks';
7
8
  import * as fs2 from 'fs';
8
9
  import { promises } from 'fs';
9
10
  import * as path from 'path';
@@ -277,7 +278,6 @@ var RedisStorageBackend = class {
277
278
  constructor(redis2) {
278
279
  this.redis = redis2;
279
280
  __publicField(this, "KEY_PREFIX", "mcp:session:");
280
- __publicField(this, "CREDENTIALS_KEY_PREFIX", "mcp:credentials:");
281
281
  __publicField(this, "USER_ID_KEY_PREFIX", "mcp:userId:");
282
282
  __publicField(this, "USER_ID_KEY_SUFFIX", ":sessions");
283
283
  }
@@ -296,9 +296,6 @@ var RedisStorageBackend = class {
296
296
  getSessionKey(userId, sessionId) {
297
297
  return `${this.KEY_PREFIX}${userId}:${sessionId}`;
298
298
  }
299
- getCredentialsKey(userId, sessionId) {
300
- return `${this.CREDENTIALS_KEY_PREFIX}${userId}:${sessionId}`;
301
- }
302
299
  /**
303
300
  * Generates Redis key for tracking all sessions for a user
304
301
  * @private
@@ -388,48 +385,54 @@ var RedisStorageBackend = class {
388
385
  }
389
386
  async patchCredentials(userId, sessionId, data) {
390
387
  const sessionKey = this.getSessionKey(userId, sessionId);
391
- const credentialsKey = this.getCredentialsKey(userId, sessionId);
392
- const sessionExists = await this.redis.exists(sessionKey);
393
- if (!sessionExists) {
388
+ const currentStr = await this.redis.get(sessionKey);
389
+ if (!currentStr) {
394
390
  throw new Error(`Session ${sessionId} not found for userId ${userId}`);
395
391
  }
396
- const session = await this.get(userId, sessionId);
397
- const currentTtl = await this.redis.ttl(sessionKey);
398
- const effectiveTtl = currentTtl > 0 && session ? currentTtl : resolveSessionRedisTtlSeconds(session ?? { status: "pending" });
399
- const currentStr = await this.redis.get(credentialsKey);
400
- const current = currentStr ? JSON.parse(currentStr) : { sessionId, userId };
401
- const credentials = { ...current, ...data, sessionId, userId };
402
- if (effectiveTtl > 0) {
403
- await this.redis.set(credentialsKey, JSON.stringify(credentials), "EX", effectiveTtl);
404
- } else {
405
- await this.redis.set(credentialsKey, JSON.stringify(credentials));
406
- }
392
+ const current = JSON.parse(currentStr);
393
+ const updated = { ...current, ...data, sessionId, userId };
394
+ const effectiveTtl = resolveSessionRedisTtlSeconds(updated);
395
+ await this.redis.set(sessionKey, JSON.stringify(updated), "EX", effectiveTtl);
407
396
  }
408
- async get(userId, sessionId) {
397
+ async get(userId, sessionId, options) {
409
398
  try {
410
399
  const sessionKey = this.getSessionKey(userId, sessionId);
411
400
  const sessionDataStr = await this.redis.get(sessionKey);
412
- if (!sessionDataStr) {
413
- return null;
401
+ if (!sessionDataStr) return null;
402
+ const session = normalizeStoredSession(JSON.parse(sessionDataStr));
403
+ if (!options?.includeCredentials) {
404
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState, ...sessionOnly } = session;
405
+ return sessionOnly;
414
406
  }
415
- const session = JSON.parse(sessionDataStr);
416
- return normalizeStoredSession(session);
407
+ return session;
417
408
  } catch (error) {
418
409
  console.error("[RedisStorageBackend] Failed to get session:", error);
419
410
  return null;
420
411
  }
421
412
  }
422
413
  async getCredentials(userId, sessionId) {
423
- const session = await this.get(userId, sessionId);
414
+ const session = await this.get(userId, sessionId, { includeCredentials: true });
424
415
  if (!session) return null;
425
- const credentialsStr = await this.redis.get(this.getCredentialsKey(userId, sessionId));
426
- return credentialsStr ? JSON.parse(credentialsStr) : { sessionId, userId };
416
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState } = session;
417
+ return {
418
+ sessionId,
419
+ userId,
420
+ clientInformation,
421
+ tokens,
422
+ codeVerifier,
423
+ codeVerifierChallenge,
424
+ codeVerifierNonce,
425
+ clientId,
426
+ oauthState
427
+ };
427
428
  }
428
429
  async clearCredentials(userId, sessionId) {
429
430
  await this.patchCredentials(userId, sessionId, {
430
431
  clientInformation: null,
431
432
  tokens: null,
432
433
  codeVerifier: null,
434
+ codeVerifierChallenge: null,
435
+ codeVerifierNonce: null,
433
436
  clientId: null,
434
437
  oauthState: null
435
438
  });
@@ -462,10 +465,9 @@ var RedisStorageBackend = class {
462
465
  async delete(userId, sessionId) {
463
466
  try {
464
467
  const sessionKey = this.getSessionKey(userId, sessionId);
465
- const credentialsKey = this.getCredentialsKey(userId, sessionId);
466
468
  const userIdKey = this.getUserIdKey(userId);
467
469
  await this.redis.srem(userIdKey, sessionId);
468
- await this.redis.del(sessionKey, credentialsKey);
470
+ await this.redis.del(sessionKey);
469
471
  } catch (error) {
470
472
  console.error("[RedisStorageBackend] Failed to remove session:", error);
471
473
  }
@@ -496,9 +498,8 @@ var RedisStorageBackend = class {
496
498
  async clearAll() {
497
499
  try {
498
500
  const keys = await this.scanKeys(`${this.KEY_PREFIX}*`);
499
- const credentialKeys = await this.scanKeys(`${this.CREDENTIALS_KEY_PREFIX}*`);
500
501
  const userIdKeys = await this.scanKeys(`${this.USER_ID_KEY_PREFIX}*${this.USER_ID_KEY_SUFFIX}`);
501
- const allKeys = [...keys, ...credentialKeys, ...userIdKeys];
502
+ const allKeys = [...keys, ...userIdKeys];
502
503
  if (allKeys.length > 0) {
503
504
  await this.redis.del(...allKeys);
504
505
  }
@@ -522,7 +523,6 @@ var RedisStorageBackend = class {
522
523
  const staleSessionIds = sessionIds.filter((_, index) => existenceChecks[index] === 0);
523
524
  if (staleSessionIds.length > 0) {
524
525
  await this.redis.srem(userIdKey, ...staleSessionIds);
525
- await this.redis.del(...staleSessionIds.map((sessionId) => this.getCredentialsKey(userId, sessionId)));
526
526
  }
527
527
  const remainingCount = await this.redis.scard(userIdKey);
528
528
  if (remainingCount === 0) {
@@ -547,7 +547,6 @@ var MemoryStorageBackend = class {
547
547
  constructor() {
548
548
  // Map<userId:sessionId, Session>
549
549
  __publicField(this, "sessions", /* @__PURE__ */ new Map());
550
- __publicField(this, "credentials", /* @__PURE__ */ new Map());
551
550
  // Map<userId, Set<sessionId>>
552
551
  __publicField(this, "userIdSessions", /* @__PURE__ */ new Map());
553
552
  }
@@ -585,26 +584,46 @@ var MemoryStorageBackend = class {
585
584
  }
586
585
  async patchCredentials(userId, sessionId, data) {
587
586
  const sessionKey = this.getSessionKey(userId, sessionId);
588
- if (!this.sessions.has(sessionKey)) {
587
+ const current = this.sessions.get(sessionKey);
588
+ if (!current) {
589
589
  throw new Error(`Session ${sessionId} not found`);
590
590
  }
591
- const current = this.credentials.get(sessionKey) ?? { sessionId, userId };
592
- this.credentials.set(sessionKey, { ...current, ...data, sessionId, userId });
591
+ this.sessions.set(sessionKey, { ...current, ...data, sessionId, userId });
593
592
  }
594
- async get(userId, sessionId) {
593
+ async get(userId, sessionId, options) {
595
594
  const sessionKey = this.getSessionKey(userId, sessionId);
596
- return this.sessions.get(sessionKey) || null;
595
+ const session = this.sessions.get(sessionKey) || null;
596
+ if (!session) return session;
597
+ if (!options?.includeCredentials) {
598
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState, ...sessionOnly } = session;
599
+ return sessionOnly;
600
+ }
601
+ return session;
597
602
  }
598
603
  async getCredentials(userId, sessionId) {
599
604
  const sessionKey = this.getSessionKey(userId, sessionId);
600
- if (!this.sessions.has(sessionKey)) return null;
601
- return this.credentials.get(sessionKey) ?? { sessionId, userId };
605
+ const session = this.sessions.get(sessionKey);
606
+ if (!session) return null;
607
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState } = session;
608
+ return {
609
+ sessionId,
610
+ userId,
611
+ clientInformation,
612
+ tokens,
613
+ codeVerifier,
614
+ codeVerifierChallenge,
615
+ codeVerifierNonce,
616
+ clientId,
617
+ oauthState
618
+ };
602
619
  }
603
620
  async clearCredentials(userId, sessionId) {
604
621
  await this.patchCredentials(userId, sessionId, {
605
622
  clientInformation: null,
606
623
  tokens: null,
607
624
  codeVerifier: null,
625
+ codeVerifierChallenge: null,
626
+ codeVerifierNonce: null,
608
627
  clientId: null,
609
628
  oauthState: null
610
629
  });
@@ -628,7 +647,6 @@ var MemoryStorageBackend = class {
628
647
  async delete(userId, sessionId) {
629
648
  const sessionKey = this.getSessionKey(userId, sessionId);
630
649
  this.sessions.delete(sessionKey);
631
- this.credentials.delete(sessionKey);
632
650
  const set = this.userIdSessions.get(userId);
633
651
  if (set) {
634
652
  set.delete(sessionId);
@@ -642,14 +660,12 @@ var MemoryStorageBackend = class {
642
660
  }
643
661
  async clearAll() {
644
662
  this.sessions.clear();
645
- this.credentials.clear();
646
663
  this.userIdSessions.clear();
647
664
  }
648
665
  async cleanupExpired() {
649
666
  for (const [key, session] of this.sessions.entries()) {
650
667
  if (!isSessionExpired(session)) continue;
651
668
  this.sessions.delete(key);
652
- this.credentials.delete(key);
653
669
  const set = this.userIdSessions.get(session.userId);
654
670
  if (set) {
655
671
  set.delete(session.sessionId);
@@ -669,7 +685,6 @@ var FileStorageBackend = class {
669
685
  constructor(options = {}) {
670
686
  __publicField(this, "filePath");
671
687
  __publicField(this, "memoryCache", null);
672
- __publicField(this, "credentialsCache", null);
673
688
  __publicField(this, "initialized", false);
674
689
  this.filePath = options.path || "./sessions.json";
675
690
  }
@@ -684,22 +699,15 @@ var FileStorageBackend = class {
684
699
  const data = await promises.readFile(this.filePath, "utf-8");
685
700
  const json = JSON.parse(data);
686
701
  this.memoryCache = /* @__PURE__ */ new Map();
687
- this.credentialsCache = /* @__PURE__ */ new Map();
688
702
  if (Array.isArray(json.sessions)) {
689
703
  json.sessions.forEach((s) => {
690
704
  const session = normalizeStoredSession(s);
691
705
  this.memoryCache.set(this.getSessionKey(session.userId || "unknown", session.sessionId), session);
692
706
  });
693
707
  }
694
- if (Array.isArray(json.credentials)) {
695
- json.credentials.forEach((c) => {
696
- this.credentialsCache.set(this.getSessionKey(c.userId, c.sessionId), c);
697
- });
698
- }
699
708
  } catch (error) {
700
709
  if (error.code === "ENOENT") {
701
710
  this.memoryCache = /* @__PURE__ */ new Map();
702
- this.credentialsCache = /* @__PURE__ */ new Map();
703
711
  await this.flush();
704
712
  } else {
705
713
  console.error("[FileStorage] Failed to load sessions:", error);
@@ -713,10 +721,9 @@ var FileStorageBackend = class {
713
721
  if (!this.initialized) await this.init();
714
722
  }
715
723
  async flush() {
716
- if (!this.memoryCache || !this.credentialsCache) return;
724
+ if (!this.memoryCache) return;
717
725
  await promises.writeFile(this.filePath, JSON.stringify({
718
- sessions: Array.from(this.memoryCache.values()),
719
- credentials: Array.from(this.credentialsCache.values())
726
+ sessions: Array.from(this.memoryCache.values())
720
727
  }, null, 2), "utf-8");
721
728
  }
722
729
  getSessionKey(userId, sessionId) {
@@ -751,29 +758,49 @@ var FileStorageBackend = class {
751
758
  async patchCredentials(userId, sessionId, data) {
752
759
  await this.ensureInitialized();
753
760
  const sessionKey = this.getSessionKey(userId, sessionId);
754
- if (!this.memoryCache.has(sessionKey)) {
761
+ const current = this.memoryCache.get(sessionKey);
762
+ if (!current) {
755
763
  throw new Error(`Session ${sessionId} not found`);
756
764
  }
757
- const current = this.credentialsCache.get(sessionKey) ?? { sessionId, userId };
758
- this.credentialsCache.set(sessionKey, { ...current, ...data, sessionId, userId });
765
+ this.memoryCache.set(sessionKey, { ...current, ...data, sessionId, userId });
759
766
  await this.flush();
760
767
  }
761
- async get(userId, sessionId) {
768
+ async get(userId, sessionId, options) {
762
769
  await this.ensureInitialized();
763
770
  const sessionKey = this.getSessionKey(userId, sessionId);
764
- return this.memoryCache.get(sessionKey) || null;
771
+ const session = this.memoryCache.get(sessionKey) || null;
772
+ if (!session) return null;
773
+ if (!options?.includeCredentials) {
774
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState, ...sessionOnly } = session;
775
+ return sessionOnly;
776
+ }
777
+ return session;
765
778
  }
766
779
  async getCredentials(userId, sessionId) {
767
780
  await this.ensureInitialized();
768
781
  const sessionKey = this.getSessionKey(userId, sessionId);
769
- if (!this.memoryCache.has(sessionKey)) return null;
770
- return this.credentialsCache.get(sessionKey) ?? { sessionId, userId };
782
+ const session = this.memoryCache.get(sessionKey);
783
+ if (!session) return null;
784
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState } = session;
785
+ return {
786
+ sessionId,
787
+ userId,
788
+ clientInformation,
789
+ tokens,
790
+ codeVerifier,
791
+ codeVerifierChallenge,
792
+ codeVerifierNonce,
793
+ clientId,
794
+ oauthState
795
+ };
771
796
  }
772
797
  async clearCredentials(userId, sessionId) {
773
798
  await this.patchCredentials(userId, sessionId, {
774
799
  clientInformation: null,
775
800
  tokens: null,
776
801
  codeVerifier: null,
802
+ codeVerifierChallenge: null,
803
+ codeVerifierNonce: null,
777
804
  clientId: null,
778
805
  oauthState: null
779
806
  });
@@ -790,7 +817,6 @@ var FileStorageBackend = class {
790
817
  await this.ensureInitialized();
791
818
  const sessionKey = this.getSessionKey(userId, sessionId);
792
819
  const deleted = this.memoryCache.delete(sessionKey);
793
- this.credentialsCache.delete(sessionKey);
794
820
  if (deleted) {
795
821
  await this.flush();
796
822
  }
@@ -802,7 +828,6 @@ var FileStorageBackend = class {
802
828
  async clearAll() {
803
829
  await this.ensureInitialized();
804
830
  this.memoryCache.clear();
805
- this.credentialsCache.clear();
806
831
  await this.flush();
807
832
  }
808
833
  async cleanupExpired() {
@@ -811,7 +836,6 @@ var FileStorageBackend = class {
811
836
  for (const [key, session] of this.memoryCache.entries()) {
812
837
  if (!isSessionExpired(session)) continue;
813
838
  this.memoryCache.delete(key);
814
- this.credentialsCache.delete(key);
815
839
  changed = true;
816
840
  }
817
841
  if (changed) {
@@ -825,12 +849,10 @@ var SqliteStorage = class {
825
849
  constructor(options = {}) {
826
850
  __publicField(this, "db", null);
827
851
  __publicField(this, "table");
828
- __publicField(this, "credentialsTable");
829
852
  __publicField(this, "initialized", false);
830
853
  __publicField(this, "dbPath");
831
854
  this.dbPath = options.path || "./sessions.db";
832
855
  this.table = options.table || "mcp_sessions";
833
- this.credentialsTable = `${this.table}_credentials`;
834
856
  }
835
857
  async init() {
836
858
  if (this.initialized) return;
@@ -850,13 +872,6 @@ var SqliteStorage = class {
850
872
  expiresAt INTEGER
851
873
  );
852
874
  CREATE INDEX IF NOT EXISTS idx_${this.table}_userId ON ${this.table}(userId);
853
- CREATE TABLE IF NOT EXISTS ${this.credentialsTable} (
854
- sessionId TEXT NOT NULL,
855
- userId TEXT NOT NULL,
856
- data TEXT NOT NULL,
857
- PRIMARY KEY (userId, sessionId),
858
- FOREIGN KEY (sessionId) REFERENCES ${this.table}(sessionId) ON DELETE CASCADE
859
- );
860
875
  `);
861
876
  this.initialized = true;
862
877
  console.log(`[mcp-ts][Storage] SQLite: \u2713 database at ${this.dbPath} verified.`);
@@ -913,41 +928,54 @@ var SqliteStorage = class {
913
928
  }
914
929
  async patchCredentials(userId, sessionId, data) {
915
930
  this.ensureInitialized();
916
- if (!await this.get(userId, sessionId)) {
931
+ const currentSession = await this.get(userId, sessionId, { includeCredentials: true });
932
+ if (!currentSession) {
917
933
  throw new Error(`Session ${sessionId} not found for userId ${userId}`);
918
934
  }
919
- const current = await this.getCredentials(userId, sessionId) ?? { sessionId, userId };
920
- const credentials = { ...current, ...data, sessionId, userId };
935
+ const updated = { ...currentSession, ...data, sessionId, userId };
921
936
  const stmt = this.db.prepare(
922
- `INSERT INTO ${this.credentialsTable} (sessionId, userId, data)
923
- VALUES (?, ?, ?)
924
- ON CONFLICT(userId, sessionId) DO UPDATE SET data = excluded.data`
937
+ `UPDATE ${this.table} SET data = ? WHERE sessionId = ? AND userId = ?`
925
938
  );
926
- stmt.run(sessionId, userId, JSON.stringify(credentials));
939
+ stmt.run(JSON.stringify(updated), sessionId, userId);
927
940
  }
928
- async get(userId, sessionId) {
941
+ async get(userId, sessionId, options) {
929
942
  this.ensureInitialized();
930
943
  const stmt = this.db.prepare(
931
944
  `SELECT data FROM ${this.table} WHERE sessionId = ? AND userId = ?`
932
945
  );
933
946
  const row = stmt.get(sessionId, userId);
934
947
  if (!row) return null;
935
- return normalizeStoredSession(JSON.parse(row.data));
948
+ const session = normalizeStoredSession(JSON.parse(row.data));
949
+ if (!options?.includeCredentials) {
950
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState, ...sessionOnly } = session;
951
+ return sessionOnly;
952
+ }
953
+ return session;
936
954
  }
937
955
  async getCredentials(userId, sessionId) {
938
956
  this.ensureInitialized();
939
- if (!await this.get(userId, sessionId)) return null;
940
- const stmt = this.db.prepare(
941
- `SELECT data FROM ${this.credentialsTable} WHERE sessionId = ? AND userId = ?`
942
- );
943
- const row = stmt.get(sessionId, userId);
944
- return row ? JSON.parse(row.data) : { sessionId, userId };
957
+ const session = await this.get(userId, sessionId, { includeCredentials: true });
958
+ if (!session) return null;
959
+ const { clientInformation, tokens, codeVerifier, codeVerifierChallenge, codeVerifierNonce, clientId, oauthState } = session;
960
+ return {
961
+ sessionId,
962
+ userId,
963
+ clientInformation,
964
+ tokens,
965
+ codeVerifier,
966
+ codeVerifierChallenge,
967
+ codeVerifierNonce,
968
+ clientId,
969
+ oauthState
970
+ };
945
971
  }
946
972
  async clearCredentials(userId, sessionId) {
947
973
  await this.patchCredentials(userId, sessionId, {
948
974
  clientInformation: null,
949
975
  tokens: null,
950
976
  codeVerifier: null,
977
+ codeVerifierChallenge: null,
978
+ codeVerifierNonce: null,
951
979
  clientId: null,
952
980
  oauthState: null
953
981
  });
@@ -973,9 +1001,6 @@ var SqliteStorage = class {
973
1001
  const stmt = this.db.prepare(
974
1002
  `DELETE FROM ${this.table} WHERE sessionId = ? AND userId = ?`
975
1003
  );
976
- this.db.prepare(
977
- `DELETE FROM ${this.credentialsTable} WHERE sessionId = ? AND userId = ?`
978
- ).run(sessionId, userId);
979
1004
  stmt.run(sessionId, userId);
980
1005
  }
981
1006
  async listAllIds() {
@@ -986,7 +1011,6 @@ var SqliteStorage = class {
986
1011
  }
987
1012
  async clearAll() {
988
1013
  this.ensureInitialized();
989
- this.db.prepare(`DELETE FROM ${this.credentialsTable}`).run();
990
1014
  const stmt = this.db.prepare(`DELETE FROM ${this.table}`);
991
1015
  stmt.run();
992
1016
  }
@@ -1000,14 +1024,6 @@ var SqliteStorage = class {
1000
1024
  deleteStmt.run(row.sessionId, row.userId);
1001
1025
  }
1002
1026
  }
1003
- this.db.prepare(
1004
- `DELETE FROM ${this.credentialsTable}
1005
- WHERE NOT EXISTS (
1006
- SELECT 1 FROM ${this.table}
1007
- WHERE ${this.table}.sessionId = ${this.credentialsTable}.sessionId
1008
- AND ${this.table}.userId = ${this.credentialsTable}.userId
1009
- )`
1010
- ).run();
1011
1027
  }
1012
1028
  async disconnect() {
1013
1029
  if (this.db) {
@@ -1089,7 +1105,6 @@ var SupabaseStorageBackend = class {
1089
1105
  }
1090
1106
  async init() {
1091
1107
  await this.assertTable("mcp_sessions", "session_id");
1092
- await this.assertTable("mcp_credentials", "session_id");
1093
1108
  console.log("[mcp-ts][Storage] Supabase: storage tables verified.");
1094
1109
  }
1095
1110
  async assertTable(table, column) {
@@ -1120,18 +1135,13 @@ var SupabaseStorageBackend = class {
1120
1135
  headers: decryptObject(row.headers),
1121
1136
  authUrl: row.auth_url,
1122
1137
  status: row.status ?? "pending",
1123
- toolPolicy: normalizeToolPolicy(row.tool_policy)
1124
- };
1125
- }
1126
- mapRowToCredentials(row, userId, sessionId) {
1127
- return {
1128
- sessionId,
1129
- userId,
1130
- clientInformation: decryptObject(row?.client_information),
1131
- tokens: decryptObject(row?.tokens),
1132
- codeVerifier: decryptObject(row?.code_verifier),
1133
- clientId: row?.client_id,
1134
- oauthState: row?.oauth_state
1138
+ toolPolicy: normalizeToolPolicy(row.tool_policy),
1139
+ clientInformation: decryptObject(row.client_information),
1140
+ tokens: decryptObject(row.tokens),
1141
+ codeVerifier: decryptObject(row.code_verifier),
1142
+ clientId: row.client_id,
1143
+ oauthState: row.oauth_state,
1144
+ enabled: row.enabled ?? true
1135
1145
  };
1136
1146
  }
1137
1147
  hasCredentialData(data) {
@@ -1189,6 +1199,7 @@ var SupabaseStorageBackend = class {
1189
1199
  if ("headers" in data) updateData.headers = encryptObject(data.headers);
1190
1200
  if ("authUrl" in data) updateData.auth_url = data.authUrl ?? null;
1191
1201
  if ("toolPolicy" in data) updateData.tool_policy = normalizeToolPolicy(data.toolPolicy);
1202
+ if ("enabled" in data) updateData.enabled = data.enabled;
1192
1203
  const shouldUpdateSession = Object.keys(updateData).some((key) => key !== "updated_at");
1193
1204
  let updatedRows = null;
1194
1205
  if (shouldUpdateSession) {
@@ -1210,23 +1221,22 @@ var SupabaseStorageBackend = class {
1210
1221
  }
1211
1222
  async patchCredentials(userId, sessionId, data) {
1212
1223
  if (!this.hasCredentialData(data)) return;
1213
- const row = {
1214
- user_id: userId,
1215
- session_id: sessionId,
1224
+ const updateData = {
1216
1225
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
1217
1226
  };
1218
- if ("clientInformation" in data) row.client_information = data.clientInformation == null ? null : encryptObject(data.clientInformation);
1219
- if ("tokens" in data) row.tokens = data.tokens == null ? null : encryptObject(data.tokens);
1220
- if ("codeVerifier" in data) row.code_verifier = data.codeVerifier == null ? null : encryptObject(data.codeVerifier);
1221
- if ("clientId" in data) row.client_id = data.clientId ?? null;
1222
- if ("oauthState" in data) row.oauth_state = data.oauthState ?? null;
1223
- const { error } = await this.supabase.from("mcp_credentials").upsert(row, { onConflict: "user_id,session_id" });
1227
+ if ("clientInformation" in data) updateData.client_information = data.clientInformation == null ? null : encryptObject(data.clientInformation);
1228
+ if ("tokens" in data) updateData.tokens = data.tokens == null ? null : encryptObject(data.tokens);
1229
+ if ("codeVerifier" in data) updateData.code_verifier = data.codeVerifier == null ? null : encryptObject(data.codeVerifier);
1230
+ if ("clientId" in data) updateData.client_id = data.clientId ?? null;
1231
+ if ("oauthState" in data) updateData.oauth_state = data.oauthState ?? null;
1232
+ const { error } = await this.supabase.from("mcp_sessions").update(updateData).eq("user_id", userId).eq("session_id", sessionId);
1224
1233
  if (error) {
1225
1234
  throw new Error(`Failed to update credentials: ${error.message}`);
1226
1235
  }
1227
1236
  }
1228
- async get(userId, sessionId) {
1229
- const { data, error } = await this.supabase.from("mcp_sessions").select("*").eq("user_id", userId).eq("session_id", sessionId).maybeSingle();
1237
+ async get(userId, sessionId, options) {
1238
+ const selection = options?.includeCredentials ? "*" : "session_id, user_id, server_id, server_name, server_url, transport_type, callback_url, created_at, updated_at, expires_at, headers, auth_url, status, tool_policy, enabled";
1239
+ const { data, error } = await this.supabase.from("mcp_sessions").select(selection).eq("user_id", userId).eq("session_id", sessionId).maybeSingle();
1230
1240
  if (error) {
1231
1241
  console.error("[SupabaseStorage] Failed to get session:", error);
1232
1242
  return null;
@@ -1235,19 +1245,21 @@ var SupabaseStorageBackend = class {
1235
1245
  return this.mapRowToSessionData(data);
1236
1246
  }
1237
1247
  async getCredentials(userId, sessionId) {
1238
- const { data, error } = await this.supabase.from("mcp_credentials").select("*").eq("user_id", userId).eq("session_id", sessionId).maybeSingle();
1248
+ const { data, error } = await this.supabase.from("mcp_sessions").select("client_information, tokens, code_verifier, client_id, oauth_state").eq("user_id", userId).eq("session_id", sessionId).maybeSingle();
1239
1249
  if (error) {
1240
1250
  console.error("[SupabaseStorage] Failed to get credentials:", error);
1241
1251
  return null;
1242
1252
  }
1243
- if (data) {
1244
- return this.mapRowToCredentials(data, userId, sessionId);
1245
- }
1246
- const { data: sessionRows, error: sessionError } = await this.supabase.from("mcp_sessions").select("id").eq("user_id", userId).eq("session_id", sessionId);
1247
- if (sessionError || !sessionRows || sessionRows.length === 0) {
1248
- return null;
1249
- }
1250
- return { sessionId, userId };
1253
+ if (!data) return null;
1254
+ return {
1255
+ sessionId,
1256
+ userId,
1257
+ clientInformation: decryptObject(data.client_information),
1258
+ tokens: decryptObject(data.tokens),
1259
+ codeVerifier: decryptObject(data.code_verifier),
1260
+ clientId: data.client_id,
1261
+ oauthState: data.oauth_state
1262
+ };
1251
1263
  }
1252
1264
  async list(userId) {
1253
1265
  const { data, error } = await this.supabase.from("mcp_sessions").select("*").eq("user_id", userId);
@@ -1258,7 +1270,14 @@ var SupabaseStorageBackend = class {
1258
1270
  return data.map((row) => this.mapRowToSessionData(row));
1259
1271
  }
1260
1272
  async clearCredentials(userId, sessionId) {
1261
- const { error } = await this.supabase.from("mcp_credentials").delete().eq("user_id", userId).eq("session_id", sessionId);
1273
+ const { error } = await this.supabase.from("mcp_sessions").update({
1274
+ client_information: null,
1275
+ tokens: null,
1276
+ code_verifier: null,
1277
+ client_id: null,
1278
+ oauth_state: null,
1279
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
1280
+ }).eq("user_id", userId).eq("session_id", sessionId);
1262
1281
  if (error) {
1263
1282
  throw new Error(`Failed to clear credentials: ${error.message}`);
1264
1283
  }
@@ -1286,10 +1305,6 @@ var SupabaseStorageBackend = class {
1286
1305
  return data.map((row) => row.session_id);
1287
1306
  }
1288
1307
  async clearAll() {
1289
- const { error: credentialsError } = await this.supabase.from("mcp_credentials").delete().neq("session_id", "");
1290
- if (credentialsError) {
1291
- console.error("[SupabaseStorage] Failed to clear credentials:", credentialsError);
1292
- }
1293
1308
  const { error } = await this.supabase.from("mcp_sessions").delete().neq("session_id", "");
1294
1309
  if (error) {
1295
1310
  console.error("[SupabaseStorage] Failed to clear sessions:", error);
@@ -1315,16 +1330,12 @@ var NeonStorageBackend = class {
1315
1330
  constructor(sql, options = {}) {
1316
1331
  this.sql = sql;
1317
1332
  __publicField(this, "tableName");
1318
- __publicField(this, "credentialsTableName");
1319
1333
  const schema = options.schema || "public";
1320
1334
  const table = options.table || "mcp_sessions";
1321
- const credentialsTable = options.credentialsTable || "mcp_credentials";
1322
1335
  this.tableName = `${this.quoteIdentifier(schema)}.${this.quoteIdentifier(table)}`;
1323
- this.credentialsTableName = `${this.quoteIdentifier(schema)}.${this.quoteIdentifier(credentialsTable)}`;
1324
1336
  }
1325
1337
  async init() {
1326
1338
  await this.assertTable(this.tableName, "mcp_sessions");
1327
- await this.assertTable(this.credentialsTableName, "mcp_credentials");
1328
1339
  console.log("[mcp-ts][Storage] Neon: storage tables verified.");
1329
1340
  }
1330
1341
  async assertTable(qualifiedName, displayName) {
@@ -1362,18 +1373,13 @@ var NeonStorageBackend = class {
1362
1373
  headers: decryptObject(row.headers),
1363
1374
  authUrl: row.auth_url ?? void 0,
1364
1375
  status: row.status ?? "pending",
1365
- toolPolicy: normalizeToolPolicy(row.tool_policy)
1366
- };
1367
- }
1368
- mapRowToCredentials(row, userId, sessionId) {
1369
- return {
1370
- sessionId,
1371
- userId,
1376
+ toolPolicy: normalizeToolPolicy(row.tool_policy),
1372
1377
  clientInformation: decryptObject(row.client_information),
1373
1378
  tokens: decryptObject(row.tokens),
1374
1379
  codeVerifier: decryptObject(row.code_verifier),
1375
1380
  clientId: row.client_id ?? void 0,
1376
- oauthState: row.oauth_state
1381
+ oauthState: row.oauth_state,
1382
+ enabled: row.enabled ?? true
1377
1383
  };
1378
1384
  }
1379
1385
  hasCredentialData(data) {
@@ -1443,7 +1449,7 @@ var NeonStorageBackend = class {
1443
1449
  const updatedSession = { ...currentSession, ...data };
1444
1450
  const status = updatedSession.status ?? "pending";
1445
1451
  const expiresAt = resolveSessionExpiresAt(status);
1446
- const shouldUpdateSession = "serverId" in data || "serverName" in data || "serverUrl" in data || "transportType" in data || "callbackUrl" in data || "status" in data || "headers" in data || "authUrl" in data || "toolPolicy" in data;
1452
+ const shouldUpdateSession = "serverId" in data || "serverName" in data || "serverUrl" in data || "transportType" in data || "callbackUrl" in data || "status" in data || "headers" in data || "authUrl" in data || "toolPolicy" in data || "enabled" in data;
1447
1453
  if (shouldUpdateSession) {
1448
1454
  const setClauses = [];
1449
1455
  const values = [];
@@ -1466,6 +1472,9 @@ var NeonStorageBackend = class {
1466
1472
  const toolPolicy = normalizeToolPolicy(updatedSession.toolPolicy, policyUpdatedAt) ?? { mode: "all", toolIds: [], updatedAt: policyUpdatedAt };
1467
1473
  addSet("tool_policy", toolPolicy);
1468
1474
  }
1475
+ if ("enabled" in data) {
1476
+ addSet("enabled", updatedSession.enabled);
1477
+ }
1469
1478
  setClauses.push("updated_at = now()");
1470
1479
  const updatedRows = await this.sql.query(
1471
1480
  `UPDATE ${this.tableName}
@@ -1481,45 +1490,45 @@ var NeonStorageBackend = class {
1481
1490
  }
1482
1491
  async patchCredentials(userId, sessionId, data) {
1483
1492
  if (!this.hasCredentialData(data)) return;
1484
- await this.sql.query(
1485
- `INSERT INTO ${this.credentialsTableName} (
1486
- user_id,
1487
- session_id,
1488
- client_information,
1489
- tokens,
1490
- code_verifier,
1491
- client_id,
1492
- oauth_state,
1493
- updated_at
1494
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, now())
1495
- ON CONFLICT (user_id, session_id)
1496
- DO UPDATE SET
1497
- client_information = CASE WHEN $8 THEN EXCLUDED.client_information ELSE ${this.credentialsTableName}.client_information END,
1498
- tokens = CASE WHEN $9 THEN EXCLUDED.tokens ELSE ${this.credentialsTableName}.tokens END,
1499
- code_verifier = CASE WHEN $10 THEN EXCLUDED.code_verifier ELSE ${this.credentialsTableName}.code_verifier END,
1500
- client_id = CASE WHEN $11 THEN EXCLUDED.client_id ELSE ${this.credentialsTableName}.client_id END,
1501
- oauth_state = CASE WHEN $12 THEN EXCLUDED.oauth_state ELSE ${this.credentialsTableName}.oauth_state END,
1502
- updated_at = now()`,
1503
- [
1504
- userId,
1505
- sessionId,
1506
- "clientInformation" in data ? data.clientInformation == null ? null : encryptObject(data.clientInformation) : null,
1507
- "tokens" in data ? data.tokens == null ? null : encryptObject(data.tokens) : null,
1508
- "codeVerifier" in data ? data.codeVerifier == null ? null : encryptObject(data.codeVerifier) : null,
1509
- "clientId" in data ? data.clientId ?? null : null,
1510
- "oauthState" in data ? data.oauthState ?? null : null,
1511
- "clientInformation" in data,
1512
- "tokens" in data,
1513
- "codeVerifier" in data,
1514
- "clientId" in data,
1515
- "oauthState" in data
1516
- ]
1493
+ const setClauses = [];
1494
+ const values = [];
1495
+ let paramIndex = 1;
1496
+ const addSet = (column, value) => {
1497
+ setClauses.push(`${column} = $${paramIndex++}`);
1498
+ values.push(value);
1499
+ };
1500
+ if ("clientInformation" in data) {
1501
+ addSet("client_information", data.clientInformation == null ? null : encryptObject(data.clientInformation));
1502
+ }
1503
+ if ("tokens" in data) {
1504
+ addSet("tokens", data.tokens == null ? null : encryptObject(data.tokens));
1505
+ }
1506
+ if ("codeVerifier" in data) {
1507
+ addSet("code_verifier", data.codeVerifier == null ? null : encryptObject(data.codeVerifier));
1508
+ }
1509
+ if ("clientId" in data) {
1510
+ addSet("client_id", data.clientId ?? null);
1511
+ }
1512
+ if ("oauthState" in data) {
1513
+ addSet("oauth_state", data.oauthState ?? null);
1514
+ }
1515
+ setClauses.push("updated_at = now()");
1516
+ const updatedRows = await this.sql.query(
1517
+ `UPDATE ${this.tableName}
1518
+ SET ${setClauses.join(", ")}
1519
+ WHERE user_id = $${paramIndex++} AND session_id = $${paramIndex++}
1520
+ RETURNING id`,
1521
+ [...values, userId, sessionId]
1517
1522
  );
1523
+ if (updatedRows.length === 0) {
1524
+ throw new Error(`Session ${sessionId} not found for userId ${userId}`);
1525
+ }
1518
1526
  }
1519
- async get(userId, sessionId) {
1527
+ async get(userId, sessionId, options) {
1520
1528
  try {
1529
+ const selection = options?.includeCredentials ? "*" : "session_id, user_id, server_id, server_name, server_url, transport_type, callback_url, created_at, updated_at, expires_at, headers, auth_url, status, tool_policy, enabled";
1521
1530
  const rows = await this.sql.query(
1522
- `SELECT * FROM ${this.tableName} WHERE user_id = $1 AND session_id = $2`,
1531
+ `SELECT ${selection} FROM ${this.tableName} WHERE user_id = $1 AND session_id = $2`,
1523
1532
  [userId, sessionId]
1524
1533
  );
1525
1534
  if (!rows[0]) return null;
@@ -1531,18 +1540,22 @@ var NeonStorageBackend = class {
1531
1540
  }
1532
1541
  async getCredentials(userId, sessionId) {
1533
1542
  try {
1534
- const credentialRows = await this.sql.query(
1535
- `SELECT * FROM ${this.credentialsTableName} WHERE user_id = $1 AND session_id = $2`,
1536
- [userId, sessionId]
1537
- );
1538
- if (credentialRows[0]) {
1539
- return this.mapRowToCredentials(credentialRows[0], userId, sessionId);
1540
- }
1541
- const sessionRows = await this.sql.query(
1542
- `SELECT id FROM ${this.tableName} WHERE user_id = $1 AND session_id = $2`,
1543
+ const rows = await this.sql.query(
1544
+ `SELECT client_information, tokens, code_verifier, client_id, oauth_state
1545
+ FROM ${this.tableName} WHERE user_id = $1 AND session_id = $2`,
1543
1546
  [userId, sessionId]
1544
1547
  );
1545
- return sessionRows[0] ? { sessionId, userId } : null;
1548
+ if (!rows[0]) return null;
1549
+ const row = rows[0];
1550
+ return {
1551
+ sessionId,
1552
+ userId,
1553
+ clientInformation: decryptObject(row.client_information),
1554
+ tokens: decryptObject(row.tokens),
1555
+ codeVerifier: decryptObject(row.code_verifier),
1556
+ clientId: row.client_id ?? void 0,
1557
+ oauthState: row.oauth_state
1558
+ };
1546
1559
  } catch (error) {
1547
1560
  console.error("[NeonStorage] Failed to get credentials:", error);
1548
1561
  return null;
@@ -1563,7 +1576,9 @@ var NeonStorageBackend = class {
1563
1576
  async clearCredentials(userId, sessionId) {
1564
1577
  try {
1565
1578
  await this.sql.query(
1566
- `DELETE FROM ${this.credentialsTableName} WHERE user_id = $1 AND session_id = $2`,
1579
+ `UPDATE ${this.tableName}
1580
+ SET client_information = null, tokens = null, code_verifier = null, client_id = null, oauth_state = null, updated_at = now()
1581
+ WHERE user_id = $1 AND session_id = $2`,
1567
1582
  [userId, sessionId]
1568
1583
  );
1569
1584
  } catch (error) {
@@ -1605,7 +1620,6 @@ var NeonStorageBackend = class {
1605
1620
  }
1606
1621
  async clearAll() {
1607
1622
  try {
1608
- await this.sql.query(`DELETE FROM ${this.credentialsTableName}`);
1609
1623
  await this.sql.query(`DELETE FROM ${this.tableName}`);
1610
1624
  } catch (error) {
1611
1625
  console.error("[NeonStorage] Failed to clear sessions:", error);
@@ -1847,6 +1861,60 @@ function onSessionMutation(listener) {
1847
1861
  sessionMutationListeners.delete(listener);
1848
1862
  };
1849
1863
  }
1864
+ function withDbObservability(store, emit) {
1865
+ const readMethods = /* @__PURE__ */ new Set([
1866
+ "get",
1867
+ "getCredentials",
1868
+ "list",
1869
+ "listIds",
1870
+ "listAllIds"
1871
+ ]);
1872
+ return new Proxy(store, {
1873
+ get(target, prop, receiver) {
1874
+ const original = Reflect.get(target, prop, receiver);
1875
+ if (typeof original !== "function") return original;
1876
+ return (...args) => {
1877
+ const method = prop;
1878
+ const isRead = readMethods.has(prop);
1879
+ const start = performance.now();
1880
+ const emitEvent = (error) => {
1881
+ emit({
1882
+ type: isRead ? "db:read" : "db:write",
1883
+ level: error ? "error" : "debug",
1884
+ message: `${method}(${args.map(
1885
+ (a) => typeof a === "string" ? a.slice(0, 24) : typeof a
1886
+ ).join(", ")})`,
1887
+ sessionId: typeof args[1] === "string" ? args[1] : void 0,
1888
+ payload: {
1889
+ method,
1890
+ argTypes: args.map((a) => typeof a),
1891
+ durationMs: performance.now() - start,
1892
+ ...error ? { error } : {}
1893
+ },
1894
+ timestamp: Date.now()
1895
+ });
1896
+ };
1897
+ try {
1898
+ const result = original.apply(target, args);
1899
+ if (result instanceof Promise) {
1900
+ return result.then((r) => {
1901
+ emitEvent();
1902
+ return r;
1903
+ }).catch((e) => {
1904
+ emitEvent(String(e));
1905
+ throw e;
1906
+ });
1907
+ }
1908
+ emitEvent();
1909
+ return result;
1910
+ } catch (e) {
1911
+ emitEvent(String(e));
1912
+ throw e;
1913
+ }
1914
+ };
1915
+ }
1916
+ });
1917
+ }
1850
1918
  var sessions = new Proxy({}, {
1851
1919
  get(_target, prop) {
1852
1920
  return async (...args) => {
@@ -1866,6 +1934,24 @@ var sessions = new Proxy({}, {
1866
1934
  });
1867
1935
 
1868
1936
  // src/server/mcp/storage-oauth-provider.ts
1937
+ var codeVerifierContext = new AsyncLocalStorage();
1938
+ function runWithCodeVerifierState(verifier, method, fn) {
1939
+ return codeVerifierContext.run({ verifier, method }, fn);
1940
+ }
1941
+ function base64UrlEncode(bytes) {
1942
+ let binary = "";
1943
+ for (const byte of bytes) {
1944
+ binary += String.fromCharCode(byte);
1945
+ }
1946
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1947
+ }
1948
+ async function createCodeChallenge(verifier) {
1949
+ const digest = await crypto.subtle.digest(
1950
+ "SHA-256",
1951
+ new TextEncoder().encode(verifier)
1952
+ );
1953
+ return base64UrlEncode(new Uint8Array(digest));
1954
+ }
1869
1955
  var StorageOAuthClientProvider = class {
1870
1956
  /**
1871
1957
  * Creates a new session-backed OAuth provider
@@ -1881,8 +1967,12 @@ var StorageOAuthClientProvider = class {
1881
1967
  __publicField(this, "logoUri");
1882
1968
  __publicField(this, "policyUri");
1883
1969
  __publicField(this, "clientSecret");
1970
+ __publicField(this, "_store");
1884
1971
  __publicField(this, "_authUrl");
1885
1972
  __publicField(this, "_clientId");
1973
+ __publicField(this, "_cachedCodeVerifier");
1974
+ __publicField(this, "_hasCodeVerifier", false);
1975
+ __publicField(this, "_cachedTokens");
1886
1976
  __publicField(this, "onRedirectCallback");
1887
1977
  this.userId = options.userId;
1888
1978
  this.serverId = options.serverId;
@@ -1894,6 +1984,8 @@ var StorageOAuthClientProvider = class {
1894
1984
  this.policyUri = options.policyUri;
1895
1985
  this._clientId = options.clientId;
1896
1986
  this.clientSecret = options.clientSecret;
1987
+ this._cachedTokens = options.cachedTokens;
1988
+ this._store = options.sessionStore ?? sessions;
1897
1989
  this.onRedirectCallback = options.onRedirect;
1898
1990
  }
1899
1991
  get clientMetadata() {
@@ -1921,7 +2013,7 @@ var StorageOAuthClientProvider = class {
1921
2013
  * @private
1922
2014
  */
1923
2015
  async getCredentials() {
1924
- const data = await sessions.getCredentials(this.userId, this.sessionId);
2016
+ const data = await this._store.getCredentials(this.userId, this.sessionId);
1925
2017
  if (!data) {
1926
2018
  return { userId: this.userId, sessionId: this.sessionId };
1927
2019
  }
@@ -1934,26 +2026,33 @@ var StorageOAuthClientProvider = class {
1934
2026
  * @throws Error if session doesn't exist (session must be created by controller layer)
1935
2027
  */
1936
2028
  async patchCredentials(data) {
1937
- await sessions.patchCredentials(this.userId, this.sessionId, data);
2029
+ await this._store.patchCredentials(this.userId, this.sessionId, data);
1938
2030
  }
1939
2031
  /**
1940
- * Retrieves stored OAuth client information
2032
+ * Retrieves stored OAuth client information.
1941
2033
  */
1942
2034
  async clientInformation() {
1943
- const data = await this.getCredentials();
1944
- if (data.clientId && !this._clientId) {
1945
- this._clientId = data.clientId;
2035
+ if (this._clientId) {
2036
+ return {
2037
+ client_id: this._clientId,
2038
+ ...this.clientSecret ? { client_secret: this.clientSecret } : {}
2039
+ };
1946
2040
  }
1947
- if (data.clientInformation) {
1948
- return data.clientInformation;
2041
+ const data = await this.getCredentials();
2042
+ if (this._cachedTokens === void 0) {
2043
+ this._cachedTokens = data.tokens ?? null;
1949
2044
  }
1950
- if (!this._clientId) {
1951
- return void 0;
2045
+ if (data.clientId) {
2046
+ this._clientId = data.clientId;
2047
+ if (data.clientInformation) {
2048
+ return data.clientInformation;
2049
+ }
2050
+ return {
2051
+ client_id: data.clientId,
2052
+ ...this.clientSecret ? { client_secret: this.clientSecret } : {}
2053
+ };
1952
2054
  }
1953
- return {
1954
- client_id: this._clientId,
1955
- ...this.clientSecret ? { client_secret: this.clientSecret } : {}
1956
- };
2055
+ return void 0;
1957
2056
  }
1958
2057
  /**
1959
2058
  * Stores OAuth client information
@@ -1970,11 +2069,30 @@ var StorageOAuthClientProvider = class {
1970
2069
  */
1971
2070
  async saveTokens(tokens) {
1972
2071
  await this.patchCredentials({ tokens });
2072
+ this._cachedTokens = tokens;
2073
+ }
2074
+ /**
2075
+ * Persists static client credentials to DB immediately on creation.
2076
+ * Ensures getOrCreateClient() finds them on rehydration, even when the
2077
+ * server allows anonymous connect and never triggers DCR.
2078
+ */
2079
+ async initializeCredentials() {
2080
+ if (this._clientId) {
2081
+ await this.patchCredentials({
2082
+ clientId: this._clientId,
2083
+ clientInformation: {
2084
+ client_id: this._clientId,
2085
+ ...this.clientSecret ? { client_secret: this.clientSecret } : {}
2086
+ }
2087
+ });
2088
+ }
1973
2089
  }
1974
2090
  get authUrl() {
1975
2091
  return this._authUrl;
1976
2092
  }
1977
2093
  async state() {
2094
+ this._cachedCodeVerifier = void 0;
2095
+ this._hasCodeVerifier = false;
1978
2096
  const nonce = nanoid(32);
1979
2097
  await this.patchCredentials({
1980
2098
  oauthState: {
@@ -1995,7 +2113,7 @@ var StorageOAuthClientProvider = class {
1995
2113
  if (parsed.sessionId !== this.sessionId) {
1996
2114
  return { valid: false, error: "OAuth state mismatch" };
1997
2115
  }
1998
- const data = await sessions.getCredentials(this.userId, parsed.sessionId);
2116
+ const data = await this._store.getCredentials(this.userId, parsed.sessionId);
1999
2117
  if (!data) {
2000
2118
  return { valid: false, error: "Session not found" };
2001
2119
  }
@@ -2020,49 +2138,77 @@ var StorageOAuthClientProvider = class {
2020
2138
  }
2021
2139
  async redirectToAuthorization(authUrl) {
2022
2140
  this._authUrl = authUrl.toString();
2023
- await sessions.update(this.userId, this.sessionId, { authUrl: this._authUrl });
2141
+ const codeChallenge = authUrl.searchParams.get("code_challenge");
2142
+ const state = authUrl.searchParams.get("state");
2143
+ if (this._cachedCodeVerifier && codeChallenge && state) {
2144
+ const expectedChallenge = await createCodeChallenge(this._cachedCodeVerifier);
2145
+ if (expectedChallenge === codeChallenge) {
2146
+ const parsed = parseOAuthState(state);
2147
+ if (parsed) {
2148
+ await this.patchCredentials({
2149
+ codeVerifier: this._cachedCodeVerifier
2150
+ });
2151
+ }
2152
+ }
2153
+ }
2024
2154
  if (this.onRedirectCallback) {
2025
2155
  this.onRedirectCallback(authUrl.toString());
2026
2156
  }
2027
2157
  }
2028
2158
  async invalidateCredentials(scope) {
2029
2159
  if (scope === "all") {
2030
- await sessions.delete(this.userId, this.sessionId);
2160
+ this._cachedTokens = void 0;
2161
+ await this._store.delete(this.userId, this.sessionId);
2031
2162
  } else {
2032
2163
  const updates = {};
2033
2164
  if (scope === "client") {
2034
2165
  updates.clientInformation = null;
2035
2166
  updates.clientId = null;
2036
2167
  } else if (scope === "tokens") {
2168
+ this._cachedTokens = void 0;
2037
2169
  updates.tokens = null;
2038
2170
  } else if (scope === "verifier") {
2171
+ this._cachedCodeVerifier = void 0;
2172
+ this._hasCodeVerifier = false;
2039
2173
  updates.codeVerifier = null;
2040
2174
  }
2041
2175
  await this.patchCredentials(updates);
2042
2176
  }
2043
2177
  }
2044
2178
  async saveCodeVerifier(verifier) {
2045
- const data = await this.getCredentials();
2046
- if (data.codeVerifier) {
2179
+ if (this._hasCodeVerifier) {
2047
2180
  return;
2048
2181
  }
2049
- await this.patchCredentials({ codeVerifier: verifier });
2182
+ this._cachedCodeVerifier = verifier;
2183
+ this._hasCodeVerifier = true;
2050
2184
  }
2051
2185
  async codeVerifier() {
2052
- const data = await this.getCredentials();
2053
- if (data.clientId && !this._clientId) {
2054
- this._clientId = data.clientId;
2186
+ if (this._cachedCodeVerifier) {
2187
+ return this._cachedCodeVerifier;
2188
+ }
2189
+ const ctx = codeVerifierContext.getStore();
2190
+ if (ctx?.verifier) {
2191
+ return ctx.verifier;
2055
2192
  }
2056
- if (!data.codeVerifier) {
2057
- throw new Error("No code verifier found");
2193
+ const data = await this.getCredentials();
2194
+ if (data.codeVerifier) {
2195
+ return data.codeVerifier;
2058
2196
  }
2059
- return data.codeVerifier;
2197
+ throw new Error("No code verifier found");
2060
2198
  }
2061
2199
  async deleteCodeVerifier() {
2062
- await this.patchCredentials({ codeVerifier: null });
2200
+ this._cachedCodeVerifier = void 0;
2201
+ this._hasCodeVerifier = false;
2202
+ await this.patchCredentials({
2203
+ codeVerifier: null
2204
+ });
2063
2205
  }
2064
2206
  async tokens() {
2207
+ if (this._cachedTokens !== void 0) {
2208
+ return this._cachedTokens ?? void 0;
2209
+ }
2065
2210
  const data = await this.getCredentials();
2211
+ this._cachedTokens = data.tokens ?? null;
2066
2212
  if (data.clientId && !this._clientId) {
2067
2213
  this._clientId = data.clientId;
2068
2214
  }
@@ -2223,23 +2369,10 @@ var MCPClient = class {
2223
2369
  __publicField(this, "client");
2224
2370
  __publicField(this, "oauthProvider", null);
2225
2371
  __publicField(this, "transport", null);
2226
- __publicField(this, "userId");
2227
- __publicField(this, "serverId");
2228
- __publicField(this, "sessionId");
2229
- __publicField(this, "serverName");
2230
- __publicField(this, "transportType");
2231
- __publicField(this, "serverUrl");
2232
- __publicField(this, "callbackUrl");
2233
- __publicField(this, "onRedirect");
2234
- __publicField(this, "clientId");
2235
- __publicField(this, "clientSecret");
2236
- __publicField(this, "headers");
2237
- /** OAuth Client Metadata */
2238
- __publicField(this, "clientName");
2239
- __publicField(this, "clientUri");
2240
- __publicField(this, "logoUri");
2241
- __publicField(this, "policyUri");
2372
+ __publicField(this, "config");
2242
2373
  __publicField(this, "createdAt");
2374
+ __publicField(this, "_serverInfo");
2375
+ __publicField(this, "_store");
2243
2376
  /** Event emitters for connection lifecycle */
2244
2377
  __publicField(this, "_onConnectionEvent", new Emitter());
2245
2378
  __publicField(this, "onConnectionEvent", this._onConnectionEvent.event);
@@ -2255,21 +2388,8 @@ var MCPClient = class {
2255
2388
  * the memory when the client is no longer needed.
2256
2389
  */
2257
2390
  __publicField(this, "cachedTools", null);
2258
- this.serverUrl = options.serverUrl;
2259
- this.serverName = options.serverName;
2260
- this.callbackUrl = options.callbackUrl;
2261
- this.onRedirect = options.onRedirect;
2262
- this.userId = options.userId;
2263
- this.serverId = options.serverId;
2264
- this.sessionId = options.sessionId;
2265
- this.transportType = options.transportType;
2266
- this.clientId = options.clientId;
2267
- this.clientSecret = options.clientSecret;
2268
- this.headers = options.headers;
2269
- this.clientName = options.clientName;
2270
- this.clientUri = options.clientUri;
2271
- this.logoUri = options.logoUri;
2272
- this.policyUri = options.policyUri;
2391
+ this.config = { ...options };
2392
+ this._store = options.sessionStore ?? sessions;
2273
2393
  this.client = new Client(
2274
2394
  {
2275
2395
  name: MCP_CLIENT_NAME,
@@ -2286,6 +2406,21 @@ var MCPClient = class {
2286
2406
  }
2287
2407
  );
2288
2408
  }
2409
+ /** Shared session-shaped data for ensureSession and saveSession */
2410
+ get session() {
2411
+ return {
2412
+ sessionId: this.config.sessionId,
2413
+ userId: this.config.userId,
2414
+ serverId: this.config.serverId,
2415
+ serverName: this.config.serverName,
2416
+ serverUrl: this.config.serverUrl,
2417
+ callbackUrl: this.config.callbackUrl,
2418
+ transportType: this.config.transportType || "streamable-http",
2419
+ headers: this.config.headers,
2420
+ createdAt: this.createdAt ?? Date.now(),
2421
+ updatedAt: Date.now()
2422
+ };
2423
+ }
2289
2424
  /**
2290
2425
  * Emit a connection state change event
2291
2426
  * @private
@@ -2293,13 +2428,13 @@ var MCPClient = class {
2293
2428
  emitStateChange(newState) {
2294
2429
  const previousState = this.currentState;
2295
2430
  this.currentState = newState;
2296
- if (!this.serverId) return;
2431
+ if (!this.config.serverId) return;
2297
2432
  this._onConnectionEvent.fire({
2298
2433
  type: "state_changed",
2299
- sessionId: this.sessionId,
2300
- serverId: this.serverId,
2301
- serverName: this.serverName || this.serverId,
2302
- serverUrl: this.serverUrl || "",
2434
+ sessionId: this.config.sessionId,
2435
+ serverId: this.config.serverId,
2436
+ serverName: this.config.serverName || this.config.serverId,
2437
+ serverUrl: this.config.serverUrl || "",
2303
2438
  createdAt: this.createdAt,
2304
2439
  state: newState,
2305
2440
  previousState,
@@ -2310,8 +2445,8 @@ var MCPClient = class {
2310
2445
  level: "info",
2311
2446
  message: `Connection state: ${previousState} \u2192 ${newState}`,
2312
2447
  displayMessage: `State changed to ${newState}`,
2313
- sessionId: this.sessionId,
2314
- serverId: this.serverId,
2448
+ sessionId: this.config.sessionId,
2449
+ serverId: this.config.serverId,
2315
2450
  payload: { previousState, newState },
2316
2451
  timestamp: Date.now(),
2317
2452
  id: nanoid()
@@ -2322,11 +2457,11 @@ var MCPClient = class {
2322
2457
  * @private
2323
2458
  */
2324
2459
  emitError(error, errorType = "unknown") {
2325
- if (!this.serverId) return;
2460
+ if (!this.config.serverId) return;
2326
2461
  this._onConnectionEvent.fire({
2327
2462
  type: "error",
2328
- sessionId: this.sessionId,
2329
- serverId: this.serverId,
2463
+ sessionId: this.config.sessionId,
2464
+ serverId: this.config.serverId,
2330
2465
  error,
2331
2466
  errorType,
2332
2467
  timestamp: Date.now()
@@ -2336,8 +2471,8 @@ var MCPClient = class {
2336
2471
  level: "error",
2337
2472
  message: error,
2338
2473
  displayMessage: error,
2339
- sessionId: this.sessionId,
2340
- serverId: this.serverId,
2474
+ sessionId: this.config.sessionId,
2475
+ serverId: this.config.serverId,
2341
2476
  payload: { errorType, error },
2342
2477
  timestamp: Date.now(),
2343
2478
  id: nanoid()
@@ -2348,11 +2483,11 @@ var MCPClient = class {
2348
2483
  * @private
2349
2484
  */
2350
2485
  emitProgress(message) {
2351
- if (!this.serverId) return;
2486
+ if (!this.config.serverId) return;
2352
2487
  this._onConnectionEvent.fire({
2353
2488
  type: "progress",
2354
- sessionId: this.sessionId,
2355
- serverId: this.serverId,
2489
+ sessionId: this.config.sessionId,
2490
+ serverId: this.config.serverId,
2356
2491
  message,
2357
2492
  timestamp: Date.now()
2358
2493
  });
@@ -2370,14 +2505,14 @@ var MCPClient = class {
2370
2505
  * @private
2371
2506
  */
2372
2507
  getTransport(type) {
2373
- if (!this.serverUrl) {
2508
+ if (!this.config.serverUrl) {
2374
2509
  throw new Error("Server URL is required to create transport");
2375
2510
  }
2376
- const baseUrl = new URL(this.serverUrl);
2377
- const hasAuthorizationHeader = Object.keys(this.headers || {}).some((key) => key.toLowerCase() === "authorization");
2511
+ const baseUrl = new URL(this.config.serverUrl);
2512
+ const hasAuthorizationHeader = Object.keys(this.config.headers || {}).some((key) => key.toLowerCase() === "authorization");
2378
2513
  const transportOptions = {
2379
2514
  ...!hasAuthorizationHeader && { authProvider: this.oauthProvider },
2380
- ...this.headers && { requestInit: { headers: this.headers } },
2515
+ ...this.config.headers && { requestInit: { headers: this.config.headers } },
2381
2516
  /**
2382
2517
  * Custom fetch implementation to handle connection timeouts.
2383
2518
  * Observation: SDK 1.24.0+ connections may hang indefinitely in some environments.
@@ -2415,78 +2550,74 @@ var MCPClient = class {
2415
2550
  * @private
2416
2551
  */
2417
2552
  async ensureSession() {
2418
- if (this.oauthProvider) {
2419
- return;
2420
- }
2553
+ if (this.oauthProvider) return;
2421
2554
  this.emitStateChange("INITIALIZING");
2422
2555
  this.emitProgress("Loading session configuration...");
2423
- let existingSession = null;
2424
- if (!this.serverUrl || !this.callbackUrl || !this.serverId) {
2425
- existingSession = await sessions.get(this.userId, this.sessionId);
2426
- if (!existingSession) {
2427
- throw new Error(`Session not found: ${this.sessionId}`);
2556
+ if (!this.config.serverUrl || !this.config.callbackUrl || !this.config.serverId) {
2557
+ const existingSession2 = await this._store.get(this.config.userId, this.config.sessionId);
2558
+ if (!existingSession2) {
2559
+ throw new Error(`Session not found: ${this.config.sessionId}`);
2428
2560
  }
2429
- this.serverUrl = this.serverUrl || existingSession.serverUrl;
2430
- this.callbackUrl = this.callbackUrl || existingSession.callbackUrl;
2431
- this.serverName = this.serverName || existingSession.serverName;
2432
- this.serverId = this.serverId || existingSession.serverId || "unknown";
2433
- this.headers = this.headers || existingSession.headers;
2434
- this.createdAt = existingSession.createdAt;
2435
- }
2436
- if (!this.serverUrl || !this.callbackUrl || !this.serverId) {
2561
+ this.config.serverUrl = this.config.serverUrl || existingSession2.serverUrl;
2562
+ this.config.callbackUrl = this.config.callbackUrl || existingSession2.callbackUrl;
2563
+ this.config.serverName = this.config.serverName || existingSession2.serverName;
2564
+ this.config.serverId = this.config.serverId || existingSession2.serverId || "unknown";
2565
+ this.config.headers = this.config.headers || existingSession2.headers;
2566
+ this.createdAt = existingSession2.createdAt;
2567
+ }
2568
+ if (!this.config.serverUrl || !this.config.callbackUrl || !this.config.serverId) {
2437
2569
  throw new Error("Missing required connection metadata");
2438
2570
  }
2439
- if (!this.oauthProvider) {
2440
- if (!this.serverId) {
2441
- throw new Error("serverId required for OAuth provider initialization");
2442
- }
2443
- this.oauthProvider = new StorageOAuthClientProvider({
2444
- userId: this.userId,
2445
- serverId: this.serverId,
2446
- sessionId: this.sessionId,
2447
- redirectUrl: this.callbackUrl,
2448
- clientName: this.clientName,
2449
- clientUri: this.clientUri,
2450
- logoUri: this.logoUri,
2451
- policyUri: this.policyUri,
2452
- clientId: this.clientId,
2453
- clientSecret: this.clientSecret,
2454
- onRedirect: (redirectUrl) => {
2455
- if (this.onRedirect) {
2456
- this.onRedirect(redirectUrl);
2457
- }
2571
+ this.oauthProvider = new StorageOAuthClientProvider({
2572
+ userId: this.config.userId,
2573
+ serverId: this.config.serverId,
2574
+ sessionId: this.config.sessionId,
2575
+ redirectUrl: this.config.callbackUrl,
2576
+ clientName: this.config.clientName,
2577
+ clientUri: this.config.clientUri,
2578
+ logoUri: this.config.logoUri,
2579
+ policyUri: this.config.policyUri,
2580
+ clientId: this.config.clientId,
2581
+ clientSecret: this.config.clientSecret,
2582
+ cachedTokens: this.config.cachedCredentials?.tokens,
2583
+ sessionStore: this._store,
2584
+ onRedirect: (redirectUrl) => {
2585
+ if (this.config.serverId) {
2586
+ this._onConnectionEvent.fire({
2587
+ type: "auth_required",
2588
+ sessionId: this.config.sessionId,
2589
+ serverId: this.config.serverId,
2590
+ authUrl: redirectUrl,
2591
+ timestamp: Date.now()
2592
+ });
2458
2593
  }
2459
- });
2460
- }
2461
- if (existingSession === null) {
2462
- existingSession = await sessions.get(this.userId, this.sessionId);
2463
- }
2464
- if (!existingSession && this.serverId && this.serverUrl && this.callbackUrl) {
2594
+ if (this.config.onRedirect) {
2595
+ this.config.onRedirect(redirectUrl);
2596
+ }
2597
+ }
2598
+ });
2599
+ const existingSession = this.config.hasSession ? {} : await this._store.get(this.config.userId, this.config.sessionId);
2600
+ if (!existingSession) {
2465
2601
  this.createdAt = Date.now();
2466
2602
  const updatedAt = this.createdAt;
2467
2603
  this._onObservabilityEvent.fire({
2468
2604
  type: "mcp:client:session_created",
2469
2605
  level: "info",
2470
- message: `Creating pending session ${this.sessionId} for connection setup`,
2471
- sessionId: this.sessionId,
2472
- serverId: this.serverId,
2606
+ message: `Creating pending session ${this.config.sessionId} for connection setup`,
2607
+ sessionId: this.config.sessionId,
2608
+ serverId: this.config.serverId,
2473
2609
  timestamp: Date.now(),
2474
2610
  id: nanoid()
2475
2611
  });
2476
- await sessions.create({
2477
- sessionId: this.sessionId,
2478
- userId: this.userId,
2479
- serverId: this.serverId,
2480
- serverName: this.serverName,
2481
- serverUrl: this.serverUrl,
2482
- callbackUrl: this.callbackUrl,
2483
- transportType: this.transportType || "streamable-http",
2484
- headers: this.headers,
2485
- createdAt: this.createdAt,
2612
+ await this._store.create({
2613
+ ...this.session,
2486
2614
  updatedAt,
2487
2615
  status: "pending"
2488
2616
  });
2489
2617
  }
2618
+ if (!existingSession && this.oauthProvider instanceof StorageOAuthClientProvider) {
2619
+ await this.oauthProvider.initializeCredentials();
2620
+ }
2490
2621
  }
2491
2622
  /**
2492
2623
  * Saves current session state to the session store
@@ -2494,34 +2625,14 @@ var MCPClient = class {
2494
2625
  * @param status - Session lifecycle status used by storage cleanup
2495
2626
  * @private
2496
2627
  */
2497
- async saveSession(status = "active", existingSession) {
2498
- if (!this.sessionId || !this.serverId || !this.serverUrl || !this.callbackUrl) {
2628
+ async saveSession(status = "active") {
2629
+ if (!this.config.sessionId || !this.config.serverId || !this.config.serverUrl || !this.config.callbackUrl) {
2499
2630
  return;
2500
2631
  }
2501
- const sessionData = {
2502
- sessionId: this.sessionId,
2503
- userId: this.userId,
2504
- serverId: this.serverId,
2505
- serverName: this.serverName,
2506
- serverUrl: this.serverUrl,
2507
- callbackUrl: this.callbackUrl,
2508
- transportType: this.transportType || "streamable-http",
2509
- headers: this.headers,
2510
- createdAt: this.createdAt || Date.now(),
2511
- updatedAt: Date.now(),
2632
+ await this._store.update(this.config.userId, this.config.sessionId, {
2633
+ ...this.session,
2512
2634
  status
2513
- };
2514
- if (status === "active") {
2515
- sessionData.authUrl = null;
2516
- }
2517
- if (existingSession === void 0) {
2518
- existingSession = await sessions.get(this.userId, this.sessionId);
2519
- }
2520
- if (existingSession) {
2521
- await sessions.update(this.userId, this.sessionId, sessionData);
2522
- } else {
2523
- await sessions.create(sessionData);
2524
- }
2635
+ });
2525
2636
  }
2526
2637
  /**
2527
2638
  * Removes transient setup/auth sessions without masking the original error.
@@ -2529,7 +2640,7 @@ var MCPClient = class {
2529
2640
  */
2530
2641
  async deleteTransientSession() {
2531
2642
  try {
2532
- await sessions.delete(this.userId, this.sessionId);
2643
+ await this._store.delete(this.config.userId, this.config.sessionId);
2533
2644
  } catch {
2534
2645
  }
2535
2646
  }
@@ -2539,7 +2650,7 @@ var MCPClient = class {
2539
2650
  * @private
2540
2651
  */
2541
2652
  async tryConnect() {
2542
- const transportsToTry = this.transportType ? [this.transportType] : ["streamable-http", "sse"];
2653
+ const transportsToTry = this.config.transportType ? [this.config.transportType] : ["streamable-http", "sse"];
2543
2654
  let lastError;
2544
2655
  for (const currentType of transportsToTry) {
2545
2656
  const isLastAttempt = currentType === transportsToTry[transportsToTry.length - 1];
@@ -2547,6 +2658,7 @@ var MCPClient = class {
2547
2658
  const transport = this.getTransport(currentType);
2548
2659
  this.transport = transport;
2549
2660
  await this.client.connect(transport);
2661
+ this._serverInfo = this.client.getServerVersion();
2550
2662
  return { transportType: currentType };
2551
2663
  } catch (error) {
2552
2664
  lastError = error;
@@ -2562,8 +2674,8 @@ var MCPClient = class {
2562
2674
  this._onObservabilityEvent.fire({
2563
2675
  level: "warn",
2564
2676
  message: `Transport ${currentType} failed, falling back`,
2565
- sessionId: this.sessionId,
2566
- serverId: this.serverId,
2677
+ sessionId: this.config.sessionId,
2678
+ serverId: this.config.serverId,
2567
2679
  metadata: {
2568
2680
  failedTransport: currentType,
2569
2681
  error: errorMessage
@@ -2606,15 +2718,15 @@ var MCPClient = class {
2606
2718
  try {
2607
2719
  this.emitStateChange("CONNECTING");
2608
2720
  const { transportType } = await this.tryConnect();
2609
- this.transportType = transportType;
2721
+ this.config.transportType = transportType;
2610
2722
  this.emitStateChange("CONNECTED");
2611
2723
  this.emitProgress("Connected successfully");
2612
2724
  this._onObservabilityEvent.fire({
2613
2725
  type: "mcp:client:session_saved",
2614
2726
  level: "info",
2615
- message: `Saving active session ${this.sessionId} (connect success)`,
2616
- sessionId: this.sessionId,
2617
- serverId: this.serverId,
2727
+ message: `Saving active session ${this.config.sessionId} (connect success)`,
2728
+ sessionId: this.config.sessionId,
2729
+ serverId: this.config.serverId,
2618
2730
  timestamp: Date.now(),
2619
2731
  id: nanoid()
2620
2732
  });
@@ -2637,23 +2749,23 @@ var MCPClient = class {
2637
2749
  this._onObservabilityEvent.fire({
2638
2750
  type: "mcp:client:session_saved",
2639
2751
  level: "info",
2640
- message: `Saving pending OAuth session ${this.sessionId}`,
2641
- sessionId: this.sessionId,
2642
- serverId: this.serverId,
2752
+ message: `Saving pending OAuth session ${this.config.sessionId}`,
2753
+ sessionId: this.config.sessionId,
2754
+ serverId: this.config.serverId,
2643
2755
  timestamp: Date.now(),
2644
2756
  id: nanoid()
2645
2757
  });
2646
2758
  await this.saveSession("pending");
2647
- if (this.serverId) {
2759
+ if (this.config.serverId) {
2648
2760
  this._onConnectionEvent.fire({
2649
2761
  type: "auth_required",
2650
- sessionId: this.sessionId,
2651
- serverId: this.serverId,
2762
+ sessionId: this.config.sessionId,
2763
+ serverId: this.config.serverId,
2652
2764
  authUrl,
2653
2765
  timestamp: Date.now()
2654
2766
  });
2655
- if (authUrl && this.onRedirect) {
2656
- this.onRedirect(authUrl);
2767
+ if (authUrl && this.config.onRedirect) {
2768
+ this.config.onRedirect(authUrl);
2657
2769
  }
2658
2770
  }
2659
2771
  throw new UnauthorizedError("OAuth authorization required");
@@ -2662,9 +2774,9 @@ var MCPClient = class {
2662
2774
  this.emitError(errorMessage, "connection");
2663
2775
  this.emitStateChange("FAILED");
2664
2776
  try {
2665
- const existingSession = await sessions.get(this.userId, this.sessionId);
2777
+ const existingSession = await this._store.get(this.config.userId, this.config.sessionId);
2666
2778
  if (!existingSession || existingSession.status !== "active") {
2667
- await sessions.delete(this.userId, this.sessionId);
2779
+ await this._store.delete(this.config.userId, this.config.sessionId);
2668
2780
  }
2669
2781
  } catch {
2670
2782
  }
@@ -2689,16 +2801,16 @@ var MCPClient = class {
2689
2801
  throw new Error(error);
2690
2802
  }
2691
2803
  if (state) {
2692
- const stateCheck = await this.oauthProvider.checkState(state);
2693
- if (!stateCheck.valid) {
2694
- const error = stateCheck.error || "Invalid OAuth state";
2695
- this.emitError(error, "auth");
2804
+ try {
2805
+ await this.oauthProvider.consumeState(state);
2806
+ } catch (error) {
2807
+ const msg = error instanceof Error ? error.message : "Invalid OAuth state";
2808
+ this.emitError(msg, "auth");
2696
2809
  this.emitStateChange("FAILED");
2697
- throw new Error(error);
2810
+ throw error;
2698
2811
  }
2699
- await this.oauthProvider.consumeState(state);
2700
2812
  }
2701
- const transportsToTry = this.transportType ? [this.transportType] : ["streamable-http", "sse"];
2813
+ const transportsToTry = this.config.transportType ? [this.config.transportType] : ["streamable-http", "sse"];
2702
2814
  let lastError;
2703
2815
  let tokensExchanged = false;
2704
2816
  let authenticatedStateEmitted = false;
@@ -2725,14 +2837,15 @@ var MCPClient = class {
2725
2837
  }
2726
2838
  }
2727
2839
  await this.client.connect(this.transport);
2728
- this.transportType = currentType;
2840
+ this._serverInfo = this.client.getServerVersion();
2841
+ this.config.transportType = currentType;
2729
2842
  this.emitStateChange("CONNECTED");
2730
2843
  this._onObservabilityEvent.fire({
2731
2844
  type: "mcp:client:session_saved",
2732
2845
  level: "info",
2733
- message: `Saving active session ${this.sessionId} (OAuth complete)`,
2734
- sessionId: this.sessionId,
2735
- serverId: this.serverId,
2846
+ message: `Saving active session ${this.config.sessionId} (OAuth complete)`,
2847
+ sessionId: this.config.sessionId,
2848
+ serverId: this.config.serverId,
2736
2849
  timestamp: Date.now(),
2737
2850
  id: nanoid()
2738
2851
  });
@@ -2805,11 +2918,11 @@ var MCPClient = class {
2805
2918
  this.emitStateChange("DISCOVERING");
2806
2919
  try {
2807
2920
  const result = await this.fetchTools();
2808
- if (this.serverId) {
2921
+ if (this.config.serverId) {
2809
2922
  this._onConnectionEvent.fire({
2810
2923
  type: "tools_discovered",
2811
- sessionId: this.sessionId,
2812
- serverId: this.serverId,
2924
+ sessionId: this.config.sessionId,
2925
+ serverId: this.config.serverId,
2813
2926
  toolCount: result.tools.length,
2814
2927
  tools: result.tools,
2815
2928
  timestamp: Date.now()
@@ -2849,8 +2962,8 @@ var MCPClient = class {
2849
2962
  level: "info",
2850
2963
  message: `Tool ${toolName} called successfully`,
2851
2964
  displayMessage: `Called tool ${toolName}`,
2852
- sessionId: this.sessionId,
2853
- serverId: this.serverId,
2965
+ sessionId: this.config.sessionId,
2966
+ serverId: this.config.serverId,
2854
2967
  payload: {
2855
2968
  toolName,
2856
2969
  args: toolArgs
@@ -2866,8 +2979,8 @@ var MCPClient = class {
2866
2979
  level: "error",
2867
2980
  message: errorMessage,
2868
2981
  displayMessage: `Failed to call tool ${toolName}`,
2869
- sessionId: this.sessionId,
2870
- serverId: this.serverId,
2982
+ sessionId: this.config.sessionId,
2983
+ serverId: this.config.serverId,
2871
2984
  payload: {
2872
2985
  errorType: "tool_execution",
2873
2986
  error: errorMessage,
@@ -3015,8 +3128,8 @@ var MCPClient = class {
3015
3128
  type: "mcp:client:error",
3016
3129
  level: "warn",
3017
3130
  message: "Initialization failed during clearSession",
3018
- sessionId: this.sessionId,
3019
- serverId: this.serverId,
3131
+ sessionId: this.config.sessionId,
3132
+ serverId: this.config.serverId,
3020
3133
  payload: { error: String(error) },
3021
3134
  timestamp: Date.now(),
3022
3135
  id: nanoid()
@@ -3025,7 +3138,7 @@ var MCPClient = class {
3025
3138
  if (this.oauthProvider) {
3026
3139
  await this.oauthProvider.invalidateCredentials("all");
3027
3140
  }
3028
- await sessions.delete(this.userId, this.sessionId);
3141
+ await this._store.delete(this.config.userId, this.config.sessionId);
3029
3142
  await this.disconnect();
3030
3143
  }
3031
3144
  /**
@@ -3059,19 +3172,19 @@ var MCPClient = class {
3059
3172
  }
3060
3173
  this.oauthProvider = null;
3061
3174
  this.transport = null;
3062
- if (this.serverId) {
3175
+ if (this.config.serverId) {
3063
3176
  this._onConnectionEvent.fire({
3064
3177
  type: "disconnected",
3065
- sessionId: this.sessionId,
3066
- serverId: this.serverId,
3178
+ sessionId: this.config.sessionId,
3179
+ serverId: this.config.serverId,
3067
3180
  timestamp: Date.now()
3068
3181
  });
3069
3182
  this._onObservabilityEvent.fire({
3070
3183
  type: "mcp:client:disconnect",
3071
3184
  level: "info",
3072
- message: `Disconnected from ${this.serverId}`,
3073
- sessionId: this.sessionId,
3074
- serverId: this.serverId,
3185
+ message: `Disconnected from ${this.config.serverId}`,
3186
+ sessionId: this.config.sessionId,
3187
+ serverId: this.config.serverId,
3075
3188
  payload: {},
3076
3189
  timestamp: Date.now(),
3077
3190
  id: nanoid()
@@ -3096,42 +3209,52 @@ var MCPClient = class {
3096
3209
  * @returns Server URL or empty string if not set
3097
3210
  */
3098
3211
  getServerUrl() {
3099
- return this.serverUrl || "";
3212
+ return this.config.serverUrl || "";
3100
3213
  }
3101
3214
  /**
3102
3215
  * Gets the OAuth callback URL
3103
3216
  * @returns Callback URL or empty string if not set
3104
3217
  */
3105
3218
  getCallbackUrl() {
3106
- return this.callbackUrl || "";
3219
+ return this.config.callbackUrl || "";
3107
3220
  }
3108
3221
  /**
3109
3222
  * Gets the transport type being used
3110
3223
  * @returns Transport type (defaults to 'streamable-http')
3111
3224
  */
3112
3225
  getTransportType() {
3113
- return this.transportType || "streamable-http";
3226
+ return this.config.transportType || "streamable-http";
3227
+ }
3228
+ /**
3229
+ * Gets the full server metadata from the MCP initialize response.
3230
+ * Includes name, version, icons, title, description, and website URL.
3231
+ * Returns undefined if the client hasn't connected yet.
3232
+ */
3233
+ getServerInfo() {
3234
+ return this._serverInfo;
3114
3235
  }
3115
3236
  /**
3116
- * Gets the human-readable server name
3237
+ * Gets the human-readable server name.
3238
+ * Prefers the server's reported title/name from the initialize response,
3239
+ * falling back to the name provided at construction or session metadata.
3117
3240
  * @returns Server name or undefined
3118
3241
  */
3119
3242
  getServerName() {
3120
- return this.serverName;
3243
+ return this.config.serverName;
3121
3244
  }
3122
3245
  /**
3123
3246
  * Gets the server ID
3124
3247
  * @returns Server ID or undefined
3125
3248
  */
3126
3249
  getServerId() {
3127
- return this.serverId;
3250
+ return this.config.serverId;
3128
3251
  }
3129
3252
  /**
3130
3253
  * Gets the session ID
3131
3254
  * @returns Session ID
3132
3255
  */
3133
3256
  getSessionId() {
3134
- return this.sessionId;
3257
+ return this.config.sessionId;
3135
3258
  }
3136
3259
  };
3137
3260
 
@@ -3154,6 +3277,14 @@ var ToolPolicyGateway = class {
3154
3277
  getServerId() {
3155
3278
  return this.client.getServerId?.();
3156
3279
  }
3280
+ /**
3281
+ * Returns the full server metadata from the underlying client, if available.
3282
+ * Includes name, version, icons, title, description, and website URL.
3283
+ * Available only after the client has connected and completed initialization.
3284
+ */
3285
+ getServerInfo() {
3286
+ return this.client.getServerInfo?.();
3287
+ }
3157
3288
  /**
3158
3289
  * Returns the human-readable server name from the underlying client, if available.
3159
3290
  */
@@ -3282,6 +3413,7 @@ var MultiSessionClient = class {
3282
3413
  __publicField(this, "connectionPromises", /* @__PURE__ */ new Map());
3283
3414
  __publicField(this, "userId");
3284
3415
  __publicField(this, "options");
3416
+ __publicField(this, "_store");
3285
3417
  this.userId = userId;
3286
3418
  this.options = {
3287
3419
  timeout: DEFAULT_TIMEOUT_MS,
@@ -3289,6 +3421,7 @@ var MultiSessionClient = class {
3289
3421
  retryDelay: DEFAULT_RETRY_DELAY_MS,
3290
3422
  ...options
3291
3423
  };
3424
+ this._store = options.onObservabilityEvent ? withDbObservability(options.sessionStore ?? sessions, options.onObservabilityEvent) : options.sessionStore ?? sessions;
3292
3425
  }
3293
3426
  // -----------------------------------------------------------------------
3294
3427
  // Public API
@@ -3372,9 +3505,9 @@ var MultiSessionClient = class {
3372
3505
  * to querying the storage backend via `sessions.list(userId)`.
3373
3506
  */
3374
3507
  async fetchActiveSessions() {
3375
- const sessionList = this.options.sessionProvider ? await this.options.sessionProvider() : await sessions.list(this.userId);
3508
+ const sessionList = this.options.sessionProvider ? await this.options.sessionProvider() : await this._store.list(this.userId);
3376
3509
  return sessionList.filter(
3377
- (s) => s.serverId && s.serverUrl && s.callbackUrl && s.status === "active"
3510
+ (s) => s.serverId && s.serverUrl && s.callbackUrl && s.status === "active" && s.enabled !== false
3378
3511
  );
3379
3512
  }
3380
3513
  /**
@@ -3447,8 +3580,13 @@ var MultiSessionClient = class {
3447
3580
  callbackUrl: session.callbackUrl,
3448
3581
  serverName: session.serverName,
3449
3582
  transportType: session.transportType,
3450
- headers: session.headers
3583
+ headers: session.headers,
3584
+ hasSession: true,
3585
+ sessionStore: this._store
3451
3586
  });
3587
+ if (this.options.onObservabilityEvent) {
3588
+ client.onObservabilityEvent(this.options.onObservabilityEvent);
3589
+ }
3452
3590
  const timeoutMs = this.options.timeout;
3453
3591
  let timeoutTimer;
3454
3592
  const timeoutPromise = new Promise((_, reject) => {
@@ -3503,130 +3641,188 @@ function isConnectionEvent(event) {
3503
3641
  }
3504
3642
 
3505
3643
  // src/server/handlers/sse-handler.ts
3506
- var DEFAULT_HEARTBEAT_INTERVAL = 3e4;
3644
+ var DEFAULT_HEARTBEAT_MS = 3e4;
3507
3645
  function normalizeHeaders(headers) {
3508
3646
  if (!headers || typeof headers !== "object") return void 0;
3509
- const entries = Object.entries(headers).map(([key, value]) => [key.trim(), String(value).trim()]).filter(([key, value]) => key.length > 0 && value.length > 0);
3647
+ const entries = Object.entries(headers).map(([k, v]) => [k.trim(), String(v).trim()]).filter(([k, v]) => k.length > 0 && v.length > 0);
3510
3648
  return entries.length > 0 ? Object.fromEntries(entries) : void 0;
3511
3649
  }
3650
+ function validatingStateEvent(sessionId, session) {
3651
+ return {
3652
+ type: "state_changed",
3653
+ sessionId,
3654
+ serverId: session.serverId ?? "unknown",
3655
+ serverName: session.serverName ?? "Unknown",
3656
+ serverUrl: session.serverUrl,
3657
+ state: "VALIDATING",
3658
+ previousState: "DISCONNECTED",
3659
+ timestamp: Date.now()
3660
+ };
3661
+ }
3662
+ function connectionErrorEvent(sessionId, serverId, error, errorType) {
3663
+ return {
3664
+ type: "error",
3665
+ sessionId,
3666
+ serverId: serverId ?? "unknown",
3667
+ error: error instanceof Error ? error.message : "Connection failed",
3668
+ errorType,
3669
+ timestamp: Date.now()
3670
+ };
3671
+ }
3512
3672
  var SSEConnectionManager = class {
3673
+ // -----------------------------------------------------------------------
3674
+ // Constructor
3675
+ // -----------------------------------------------------------------------
3676
+ /**
3677
+ * @param options - Handler configuration (userId, auth, metadata, heartbeat, observability).
3678
+ * @param sendEvent - Callback that writes a typed event onto the SSE stream.
3679
+ */
3513
3680
  constructor(options, sendEvent) {
3514
3681
  this.options = options;
3515
3682
  this.sendEvent = sendEvent;
3683
+ // -----------------------------------------------------------------------
3684
+ // State
3685
+ // -----------------------------------------------------------------------
3516
3686
  __publicField(this, "userId");
3687
+ /** Active MCP transports keyed by sessionId. */
3517
3688
  __publicField(this, "clients", /* @__PURE__ */ new Map());
3689
+ /** Instrumented session store — always wraps `sessions` with DB observability. */
3690
+ __publicField(this, "observedStore");
3518
3691
  __publicField(this, "heartbeatTimer");
3519
- __publicField(this, "isActive", true);
3692
+ __publicField(this, "active", true);
3520
3693
  this.userId = options.userId;
3694
+ this.observedStore = withDbObservability(sessions, (event) => this.sendEvent(event));
3521
3695
  this.startHeartbeat();
3522
3696
  }
3697
+ // -----------------------------------------------------------------------
3698
+ // Public API
3699
+ // -----------------------------------------------------------------------
3523
3700
  /**
3524
- * Get resolved client metadata (dynamic > static > defaults)
3525
- */
3526
- async getResolvedClientMetadata(request) {
3527
- let metadata = {};
3528
- if (this.options.clientDefaults) {
3529
- metadata = { ...this.options.clientDefaults };
3530
- }
3531
- if (this.options.getClientMetadata) {
3532
- const dynamicMetadata = await this.options.getClientMetadata(request);
3533
- metadata = { ...metadata, ...dynamicMetadata };
3534
- }
3535
- return metadata;
3536
- }
3537
- /**
3538
- * Start heartbeat to keep connection alive
3539
- */
3540
- startHeartbeat() {
3541
- const interval = this.options.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL;
3542
- this.heartbeatTimer = setInterval(() => {
3543
- if (this.isActive) {
3544
- this.sendEvent({
3545
- level: "debug",
3546
- message: "heartbeat",
3547
- timestamp: Date.now()
3548
- });
3549
- }
3550
- }, interval);
3551
- }
3552
- /**
3553
- * Handle incoming RPC requests
3554
- * Returns the RPC response directly for immediate HTTP response (bypassing SSE latency)
3701
+ * Dispatches an incoming RPC request, emits timing observability,
3702
+ * and returns the response.
3703
+ *
3704
+ * Emits `rpc:start` before dispatch and `rpc:end` on completion
3705
+ * (success or error), each carrying the method name, sessionId, and
3706
+ * duration. All events flow through the unified `onObservability`
3707
+ * and the SSE stream.
3708
+ *
3709
+ * @param request - The deserialized RPC envelope.
3710
+ * @returns The RPC response (success or error).
3555
3711
  */
3556
3712
  async handleRequest(request) {
3713
+ const method = request.method;
3714
+ const sessionId = request.params?.sessionId;
3715
+ const t0 = performance.now();
3716
+ this.sendEvent({
3717
+ type: "rpc:start",
3718
+ level: "debug",
3719
+ message: method,
3720
+ sessionId,
3721
+ timestamp: Date.now()
3722
+ });
3557
3723
  try {
3558
- let result;
3559
- switch (request.method) {
3560
- case "listSessions":
3561
- result = await this.listSessions();
3562
- break;
3563
- case "connect":
3564
- result = await this.connect(request.params);
3565
- break;
3566
- case "reconnect":
3567
- result = await this.reconnect(request.params);
3568
- break;
3569
- case "disconnect":
3570
- result = await this.disconnect(request.params);
3571
- break;
3572
- case "listTools":
3573
- result = await this.listTools(request.params);
3574
- break;
3575
- case "setToolPolicy":
3576
- result = await this.setToolPolicy(request.params);
3577
- break;
3578
- case "getToolPolicy":
3579
- result = await this.getToolPolicy(request.params);
3580
- break;
3581
- case "callTool":
3582
- result = await this.callTool(request.params);
3583
- break;
3584
- case "getSession":
3585
- result = await this.getSession(request.params);
3586
- break;
3587
- case "finishAuth":
3588
- result = await this.finishAuth(request.params);
3589
- break;
3590
- case "listPrompts":
3591
- result = await this.listPrompts(request.params);
3592
- break;
3593
- case "getPrompt":
3594
- result = await this.getPrompt(request.params);
3595
- break;
3596
- case "listResources":
3597
- result = await this.listResources(request.params);
3598
- break;
3599
- case "readResource":
3600
- result = await this.readResource(request.params);
3601
- break;
3602
- default:
3603
- throw new Error(`Unknown method: ${request.method}`);
3604
- }
3605
- const response = {
3606
- id: request.id,
3607
- result
3608
- };
3724
+ const result = await this.dispatchImpl(request);
3725
+ this.sendEvent({
3726
+ type: "rpc:end",
3727
+ level: "debug",
3728
+ message: method,
3729
+ sessionId,
3730
+ payload: { durationMs: performance.now() - t0 },
3731
+ timestamp: Date.now()
3732
+ });
3733
+ const response = { id: request.id, result };
3609
3734
  this.sendEvent(response);
3610
3735
  return response;
3611
3736
  } catch (error) {
3612
- const errorResponse = {
3737
+ this.sendEvent({
3738
+ type: "rpc:end",
3739
+ level: "error",
3740
+ message: method,
3741
+ sessionId,
3742
+ payload: { durationMs: performance.now() - t0, error: String(error) },
3743
+ timestamp: Date.now()
3744
+ });
3745
+ const response = {
3613
3746
  id: request.id,
3614
3747
  error: {
3615
3748
  code: RpcErrorCodes.EXECUTION_ERROR,
3616
3749
  message: error instanceof Error ? error.message : "Unknown error"
3617
3750
  }
3618
3751
  };
3619
- this.sendEvent(errorResponse);
3620
- return errorResponse;
3752
+ this.sendEvent(response);
3753
+ return response;
3754
+ }
3755
+ }
3756
+ /**
3757
+ * Tears down all active MCP transports and stops the heartbeat timer.
3758
+ *
3759
+ * Disconnects are issued in parallel across all sessions. After calling
3760
+ * this method the manager instance should be discarded.
3761
+ */
3762
+ async dispose() {
3763
+ this.active = false;
3764
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
3765
+ await Promise.all(
3766
+ Array.from(this.clients.values()).map((c) => c.disconnect())
3767
+ );
3768
+ this.clients.clear();
3769
+ }
3770
+ // -----------------------------------------------------------------------
3771
+ // RPC Dispatch (raw — called by handleRequest which adds timing)
3772
+ // -----------------------------------------------------------------------
3773
+ /**
3774
+ * Routes an RPC method name to the appropriate private handler.
3775
+ *
3776
+ * @throws {Error} When the method name is unrecognized.
3777
+ */
3778
+ async dispatchImpl(request) {
3779
+ switch (request.method) {
3780
+ case "listSessions":
3781
+ return this.listSessions();
3782
+ case "connect":
3783
+ return this.connect(request.params);
3784
+ case "reconnect":
3785
+ return this.reconnect(request.params);
3786
+ case "disconnect":
3787
+ return this.disconnect(request.params);
3788
+ case "listTools":
3789
+ return this.listTools(request.params);
3790
+ case "setToolPolicy":
3791
+ return this.setToolPolicy(request.params);
3792
+ case "getToolPolicy":
3793
+ return this.getToolPolicy(request.params);
3794
+ case "updateSession":
3795
+ return this.updateSession(request.params);
3796
+ case "callTool":
3797
+ return this.callTool(request.params);
3798
+ case "getSession":
3799
+ return this.getSession(request.params);
3800
+ case "finishAuth":
3801
+ return this.finishAuth(request.params);
3802
+ case "listPrompts":
3803
+ return this.listPrompts(request.params);
3804
+ case "getPrompt":
3805
+ return this.getPrompt(request.params);
3806
+ case "listResources":
3807
+ return this.listResources(request.params);
3808
+ case "readResource":
3809
+ return this.readResource(request.params);
3810
+ default:
3811
+ throw new Error(`Unknown RPC method: ${request.method}`);
3621
3812
  }
3622
3813
  }
3814
+ // -----------------------------------------------------------------------
3815
+ // Session Query
3816
+ // -----------------------------------------------------------------------
3623
3817
  /**
3624
- * Get all sessions for the current userId
3818
+ * Lists all sessions owned by the current user.
3819
+ *
3820
+ * Returns a lightweight view — session metadata only, no credential fields.
3625
3821
  */
3626
3822
  async listSessions() {
3627
- const sessionList = await sessions.list(this.userId);
3823
+ const all = await sessions.list(this.userId);
3628
3824
  return {
3629
- sessions: sessionList.map((s) => ({
3825
+ sessions: all.map((s) => ({
3630
3826
  sessionId: s.sessionId,
3631
3827
  serverId: s.serverId,
3632
3828
  serverName: s.serverName,
@@ -3635,211 +3831,203 @@ var SSEConnectionManager = class {
3635
3831
  createdAt: s.createdAt,
3636
3832
  updatedAt: s.updatedAt ?? s.createdAt,
3637
3833
  status: s.status ?? "pending",
3638
- toolPolicy: s.toolPolicy
3834
+ toolPolicy: s.toolPolicy,
3835
+ enabled: s.enabled ?? true
3639
3836
  }))
3640
3837
  };
3641
3838
  }
3642
3839
  /**
3643
- * Connect to an MCP server
3840
+ * Restores and validates a previously persisted session.
3841
+ *
3842
+ * Loads the full session row (including credentials) from storage, creates
3843
+ * a new MCP transport, connects to the remote server, and emits the
3844
+ * discovered (policy-filtered) tool list via SSE.
3644
3845
  */
3645
- async connect(params) {
3646
- const { serverName, serverUrl, callbackUrl, transportType } = params;
3647
- const headers = normalizeHeaders(params.headers);
3648
- const serverId = params.serverId && params.serverId.length <= 12 ? params.serverId : generateServerId();
3649
- const existingSessions = await sessions.list(this.userId);
3650
- const duplicate = existingSessions.find(
3651
- (s) => s.serverId === serverId || s.serverUrl === serverUrl
3652
- );
3653
- if (duplicate) {
3654
- if (duplicate.status === "pending") {
3655
- await this.getSession({ sessionId: duplicate.sessionId });
3656
- return {
3657
- sessionId: duplicate.sessionId,
3658
- success: true
3659
- };
3660
- }
3661
- throw new Error(`Connection already exists for server: ${duplicate.serverUrl || duplicate.serverId} (${duplicate.serverName})`);
3662
- }
3663
- const sessionId = await sessions.generateSessionId();
3846
+ async getSession(params) {
3847
+ const session = await this.requireSession(params.sessionId);
3848
+ this.sendEvent(validatingStateEvent(params.sessionId, session));
3664
3849
  try {
3665
- const clientMetadata = await this.getResolvedClientMetadata();
3666
- const client = new MCPClient({
3667
- userId: this.userId,
3668
- sessionId,
3669
- serverId,
3670
- serverName,
3671
- serverUrl,
3672
- callbackUrl,
3673
- transportType,
3674
- headers,
3675
- ...clientMetadata
3676
- // Spread client metadata (clientName, clientUri, logoUri, policyUri)
3677
- });
3678
- this.clients.set(sessionId, client);
3679
- client.onConnectionEvent((event) => {
3680
- this.emitConnectionEvent(event);
3681
- });
3682
- client.onObservabilityEvent((event) => {
3683
- this.sendEvent(event);
3684
- });
3850
+ const client = this.restoreClient(session);
3851
+ this.attachClientEvents(client);
3685
3852
  await client.connect();
3686
- await this.listPolicyFilteredTools(sessionId);
3687
- return {
3688
- sessionId,
3689
- success: true
3690
- };
3853
+ this.clients.set(params.sessionId, client);
3854
+ const { result } = await this.listPolicyFilteredTools(params.sessionId);
3855
+ return { success: true, toolCount: result.tools.length };
3691
3856
  } catch (error) {
3692
- if (error instanceof UnauthorizedError) {
3693
- this.clients.delete(sessionId);
3694
- return {
3695
- sessionId,
3696
- success: true
3697
- };
3698
- }
3699
- this.emitConnectionEvent({
3700
- type: "error",
3701
- sessionId,
3702
- serverId,
3703
- error: error instanceof Error ? error.message : "Connection failed",
3704
- errorType: "connection",
3705
- timestamp: Date.now()
3706
- });
3707
- this.clients.delete(sessionId);
3857
+ this.sendEvent(connectionErrorEvent(params.sessionId, session.serverId, error, "validation"));
3708
3858
  throw error;
3709
3859
  }
3710
3860
  }
3861
+ // -----------------------------------------------------------------------
3862
+ // Connection Lifecycle
3863
+ // -----------------------------------------------------------------------
3711
3864
  /**
3712
- * Reconnect to an MCP server — tears down the active client transport/connection
3713
- * and creates a fresh connection while reusing the existing session credentials in a single RPC call.
3865
+ * Initiates a connection to a new MCP server.
3866
+ *
3867
+ * If a session for the same `serverId` or `serverUrl` already exists and
3868
+ * is still in a `pending` (OAuth) state, the existing session is resumed
3869
+ * instead of creating a duplicate.
3870
+ *
3871
+ * `UnauthorizedError` is treated as a pending-auth state and returned as
3872
+ * a successful result (the client will then redirect to the auth URL).
3714
3873
  */
3715
- async reconnect(params) {
3716
- const { serverId: rawServerId, serverName, serverUrl, callbackUrl, transportType } = params;
3874
+ async connect(params) {
3717
3875
  const headers = normalizeHeaders(params.headers);
3718
- const serverId = rawServerId && rawServerId.length <= 12 ? rawServerId : generateServerId();
3719
- const existingSessions = await sessions.list(this.userId);
3720
- const duplicate = existingSessions.find(
3721
- (s) => s.serverId === serverId || s.serverUrl === serverUrl
3722
- );
3723
- const sessionId = duplicate ? duplicate.sessionId : await sessions.generateSessionId();
3724
- if (duplicate) {
3725
- const existingClient = this.clients.get(duplicate.sessionId);
3726
- if (existingClient) {
3727
- await existingClient.disconnect();
3728
- this.clients.delete(duplicate.sessionId);
3876
+ const serverId = this.normalizeServerId(params.serverId);
3877
+ const existing = await this.findExistingSession(serverId, params.serverUrl);
3878
+ if (existing) {
3879
+ if (existing.status === "pending") {
3880
+ return this.getSession({ sessionId: existing.sessionId }).then(() => ({
3881
+ sessionId: existing.sessionId,
3882
+ success: true
3883
+ }));
3729
3884
  }
3885
+ throw new Error(
3886
+ `Connection already exists for server: ${existing.serverUrl ?? existing.serverId} (${existing.serverName})`
3887
+ );
3730
3888
  }
3731
- try {
3732
- const clientMetadata = await this.getResolvedClientMetadata();
3733
- const client = new MCPClient({
3734
- userId: this.userId,
3735
- sessionId,
3736
- serverId,
3737
- serverName,
3738
- serverUrl,
3739
- callbackUrl,
3740
- transportType,
3741
- headers,
3742
- ...clientMetadata
3743
- });
3744
- this.clients.set(sessionId, client);
3745
- client.onConnectionEvent((event) => {
3746
- this.emitConnectionEvent(event);
3747
- });
3748
- client.onObservabilityEvent((event) => {
3749
- this.sendEvent(event);
3750
- });
3751
- await client.connect();
3752
- await this.listPolicyFilteredTools(sessionId);
3753
- return { sessionId, success: true };
3754
- } catch (error) {
3755
- if (error instanceof UnauthorizedError) {
3756
- this.clients.delete(sessionId);
3757
- return { sessionId, success: true };
3889
+ const sessionId = await sessions.generateSessionId();
3890
+ const metadata = await this.getResolvedClientMetadata();
3891
+ const client = new MCPClient({
3892
+ userId: this.userId,
3893
+ sessionId,
3894
+ serverId,
3895
+ serverName: params.serverName,
3896
+ serverUrl: params.serverUrl,
3897
+ callbackUrl: params.callbackUrl,
3898
+ transportType: params.transportType,
3899
+ headers,
3900
+ sessionStore: this.observedStore,
3901
+ ...metadata
3902
+ });
3903
+ this.cacheClient(sessionId, client);
3904
+ return this.connectAndDiscover(client, sessionId, serverId);
3905
+ }
3906
+ /**
3907
+ * Reconnects to an MCP server by tearing down the active transport if one
3908
+ * exists and instantiating a fresh connection, reusing the existing session
3909
+ * (and its stored credentials / DCR client info) from the database.
3910
+ */
3911
+ async reconnect(params) {
3912
+ const headers = normalizeHeaders(params.headers);
3913
+ const serverId = this.normalizeServerId(params.serverId);
3914
+ const existing = await this.findExistingSession(serverId, params.serverUrl);
3915
+ const sessionId = existing ? existing.sessionId : await sessions.generateSessionId();
3916
+ if (existing) {
3917
+ const staleClient = this.clients.get(existing.sessionId);
3918
+ if (staleClient) {
3919
+ await staleClient.disconnect();
3920
+ this.clients.delete(existing.sessionId);
3758
3921
  }
3759
- this.emitConnectionEvent({
3760
- type: "error",
3761
- sessionId,
3762
- serverId,
3763
- error: error instanceof Error ? error.message : "Connection failed",
3764
- errorType: "connection",
3765
- timestamp: Date.now()
3766
- });
3767
- this.clients.delete(sessionId);
3768
- throw error;
3769
3922
  }
3923
+ const metadata = await this.getResolvedClientMetadata();
3924
+ const client = new MCPClient({
3925
+ userId: this.userId,
3926
+ sessionId,
3927
+ serverId,
3928
+ serverName: params.serverName,
3929
+ serverUrl: params.serverUrl,
3930
+ callbackUrl: params.callbackUrl,
3931
+ transportType: params.transportType,
3932
+ headers,
3933
+ sessionStore: this.observedStore,
3934
+ ...metadata
3935
+ });
3936
+ this.cacheClient(sessionId, client);
3937
+ return this.connectAndDiscover(client, sessionId, serverId);
3770
3938
  }
3771
3939
  /**
3772
- * Disconnect from an MCP server
3940
+ * Disconnects from an MCP server.
3941
+ *
3942
+ * If an active in-memory transport exists it delegates to `clearSession()`
3943
+ * (which sends the server an HTTP DELETE per the Streamable spec). If no
3944
+ * active transport is available (orphaned session from a failed OAuth flow),
3945
+ * the session row is removed directly from storage.
3773
3946
  */
3774
3947
  async disconnect(params) {
3775
- const { sessionId } = params;
3776
- const client = this.clients.get(sessionId);
3948
+ const client = this.clients.get(params.sessionId);
3777
3949
  if (client) {
3778
3950
  await client.clearSession();
3779
- this.clients.delete(sessionId);
3951
+ this.clients.delete(params.sessionId);
3780
3952
  } else {
3781
- await sessions.delete(this.userId, sessionId);
3953
+ await sessions.delete(this.userId, params.sessionId);
3782
3954
  }
3783
3955
  return { success: true };
3784
3956
  }
3957
+ // -----------------------------------------------------------------------
3958
+ // OAuth
3959
+ // -----------------------------------------------------------------------
3785
3960
  /**
3786
- * Get an existing client or create and connect a new one for the session.
3961
+ * Completes the OAuth 2.1 authorization code flow for a pending session.
3962
+ *
3963
+ * Loads the stored session (with credentials), creates a fresh `MCPClient`,
3964
+ * and calls `finishAuth` inside a {@link runWithCodeVerifierState} context
3965
+ * so the PKCE code verifier is available without a DB read.
3966
+ *
3967
+ * The session's stored `transportType` is intentionally **omitted** from the
3968
+ * client config — this lets `MCPClient` auto-negotiate (try Streamable HTTP
3969
+ * first, fall back to SSE), which is required for servers like Neon that
3970
+ * only support SSE transport.
3787
3971
  */
3788
- async getOrCreateClient(sessionId) {
3789
- const existing = this.clients.get(sessionId);
3790
- if (existing) {
3791
- return existing;
3792
- }
3793
- const session = await sessions.get(this.userId, sessionId);
3794
- if (!session) {
3795
- throw new Error("Session not found");
3972
+ async finishAuth(params) {
3973
+ const parsed = parseOAuthState(params.state);
3974
+ const sessionId = parsed?.sessionId ?? params.state;
3975
+ const session = await this.requireSession(sessionId);
3976
+ try {
3977
+ const clientId = session.clientId ?? void 0;
3978
+ const clientSecret = session.clientInformation?.client_secret ?? void 0;
3979
+ const client = new MCPClient({
3980
+ userId: this.userId,
3981
+ sessionId,
3982
+ serverId: session.serverId,
3983
+ serverName: session.serverName,
3984
+ serverUrl: session.serverUrl,
3985
+ callbackUrl: session.callbackUrl,
3986
+ headers: session.headers,
3987
+ clientId,
3988
+ clientSecret,
3989
+ hasSession: true,
3990
+ cachedCredentials: { tokens: session.tokens ?? void 0 },
3991
+ sessionStore: this.observedStore
3992
+ });
3993
+ this.attachClientEvents(client);
3994
+ await runWithCodeVerifierState(
3995
+ session.codeVerifier ?? "",
3996
+ "S256",
3997
+ () => client.finishAuth(params.code, params.state)
3998
+ );
3999
+ this.clients.set(sessionId, client);
4000
+ const { result } = await this.listPolicyFilteredTools(sessionId);
4001
+ return { success: true, toolCount: result.tools.length };
4002
+ } catch (error) {
4003
+ this.sendEvent(connectionErrorEvent(sessionId, session.serverId, error, "auth"));
4004
+ throw error;
3796
4005
  }
3797
- const client = new MCPClient({
3798
- userId: this.userId,
3799
- sessionId,
3800
- // These fields are optional in MCPClient, but when rehydrating a known
3801
- // stored session on the server we pass them explicitly to preserve the
3802
- // original transport/connection metadata instead of relying on lazy
3803
- // reloading during initialize().
3804
- serverId: session.serverId,
3805
- serverName: session.serverName,
3806
- serverUrl: session.serverUrl,
3807
- callbackUrl: session.callbackUrl,
3808
- transportType: session.transportType,
3809
- headers: session.headers
3810
- });
3811
- client.onConnectionEvent((event) => this.emitConnectionEvent(event));
3812
- client.onObservabilityEvent((event) => this.sendEvent(event));
3813
- await client.connect();
3814
- this.clients.set(sessionId, client);
3815
- return client;
3816
4006
  }
4007
+ // -----------------------------------------------------------------------
4008
+ // Tool Discovery & Policy
4009
+ // -----------------------------------------------------------------------
3817
4010
  /**
3818
- * Fetches all tools from the remote MCP server and emits a `tools_discovered` event.
4011
+ * Fetches the complete tool list from the remote MCP server and emits a
4012
+ * `tools_discovered` SSE event with two lists:
3819
4013
  *
3820
- * Two lists are always published together:
3821
- * - `tools` policy-filtered list that agents are allowed to call.
3822
- * - `allTools` — the complete, unfiltered list used by the management UI so
3823
- * that blocked tools still appear as checkboxes in the dialog.
4014
+ * - `tools` — policy-filtered (what agents are allowed to call)
4015
+ * - `allTools` complete, unfiltered (used by the management UI)
3824
4016
  *
3825
- * `fetchTools()` is called first (populates the in-memory cache), then
3826
- * `gateway.listTools()` re-uses that cache internally — so only one remote
3827
- * network round-trip is made regardless of how many callers follow.
4017
+ * Only a single network round-trip is made: `fetchTools()` populates the
4018
+ * in-memory cache, then `gateway.listTools()` reuses that cache.
3828
4019
  *
3829
- * @param sessionId - The session whose tools should be discovered.
3830
- * @returns The session record and the policy-filtered tool list.
3831
- * @throws {Error} When the session does not exist in the store.
4020
+ * @param sessionId - The session to discover tools for.
4021
+ * @returns The session record and the filtered tool result.
4022
+ * @throws {Error} If the session does not exist in storage.
3832
4023
  */
3833
4024
  async listPolicyFilteredTools(sessionId) {
3834
- const session = await sessions.get(this.userId, sessionId);
3835
- if (!session) {
3836
- throw new Error("Session not found");
3837
- }
4025
+ const session = await this.requireSession(sessionId);
3838
4026
  const client = await this.getOrCreateClient(sessionId);
3839
4027
  const allTools = await client.fetchTools().catch(() => ({ tools: [] }));
3840
4028
  const gateway = createToolPolicyGateway(this.userId, sessionId, client);
3841
4029
  const result = await gateway.listTools();
3842
- this.emitConnectionEvent({
4030
+ this.sendEvent({
3843
4031
  type: "tools_discovered",
3844
4032
  sessionId,
3845
4033
  serverId: session.serverId ?? "unknown",
@@ -3851,254 +4039,254 @@ var SSEConnectionManager = class {
3851
4039
  return { session, result };
3852
4040
  }
3853
4041
  /**
3854
- * Returns the policy-filtered tool list for a session (agent-facing).
3855
- * Internally re-uses `listPolicyFilteredTools` which also emits a
3856
- * `tools_discovered` SSE event to keep client state up to date.
4042
+ * Returns the policy-filtered tool list for a session.
4043
+ *
4044
+ * Delegates to {@link listPolicyFilteredTools}, which also emits a
4045
+ * `tools_discovered` SSE event to keep the client state current.
3857
4046
  */
3858
4047
  async listTools(params) {
3859
- const { sessionId } = params;
3860
- const { result } = await this.listPolicyFilteredTools(sessionId);
4048
+ const { result } = await this.listPolicyFilteredTools(params.sessionId);
3861
4049
  return { tools: result.tools };
3862
4050
  }
3863
4051
  /**
3864
- * Get all raw tools with effective access state for management UI.
4052
+ * Returns all raw tools annotated with their effective policy state
4053
+ * for display in the management UI.
3865
4054
  */
3866
4055
  async getToolPolicy(params) {
3867
- const { sessionId } = params;
3868
- const session = await sessions.get(this.userId, sessionId);
3869
- if (!session) {
3870
- throw new Error("Session not found");
3871
- }
3872
- const client = await this.getOrCreateClient(sessionId);
4056
+ const session = await this.requireSession(params.sessionId);
4057
+ const client = await this.getOrCreateClient(params.sessionId);
3873
4058
  const allTools = await client.fetchTools();
3874
- const toolPolicy = session.toolPolicy ?? {
4059
+ const policy = session.toolPolicy ?? {
3875
4060
  mode: "all",
3876
4061
  toolIds: [],
3877
4062
  updatedAt: session.updatedAt ?? session.createdAt
3878
4063
  };
3879
4064
  const serverId = session.serverId ?? "unknown";
3880
- const tools = allTools.tools.map((tool) => ({
3881
- ...tool,
3882
- toolId: createToolId(serverId, tool.name),
3883
- allowed: isToolAllowed(toolPolicy, tool.name, session.serverId)
4065
+ const tools = allTools.tools.map((t) => ({
4066
+ ...t,
4067
+ toolId: createToolId(serverId, t.name),
4068
+ allowed: isToolAllowed(policy, t.name, session.serverId)
3884
4069
  }));
3885
4070
  return {
3886
- toolPolicy,
4071
+ toolPolicy: policy,
3887
4072
  tools,
3888
4073
  toolCount: tools.length,
3889
- allowedToolCount: tools.filter((tool) => tool.allowed).length
4074
+ allowedToolCount: tools.filter((t) => t.allowed).length
3890
4075
  };
3891
4076
  }
3892
4077
  /**
3893
- * Persists a new tool access policy for a session and broadcasts the updated
3894
- * filtered tool list to all connected browser clients via a `tools_discovered` event.
3895
- *
3896
- * Both `tools` (policy-filtered) and `allTools` (complete list) are emitted
3897
- * so the management UI can immediately reflect the new checkbox states without
3898
- * an additional round-trip to the server.
4078
+ * Persists a new tool access policy and broadcasts the updated filtered
4079
+ * tool list via a `tools_discovered` SSE event.
3899
4080
  *
3900
- * @param params - Session ID and the new `{ mode, toolIds }` policy to apply.
3901
- * @throws {Error} When the session does not exist or the policy references unknown tool IDs.
4081
+ * @throws {Error} If the session does not exist or the policy references
4082
+ * tool IDs that don't match any known tool.
3902
4083
  */
3903
4084
  async setToolPolicy(params) {
3904
- const { sessionId } = params;
3905
- const session = await sessions.get(this.userId, sessionId);
3906
- if (!session) {
3907
- throw new Error("Session not found");
3908
- }
3909
- const client = await this.getOrCreateClient(sessionId);
4085
+ const session = await this.requireSession(params.sessionId);
4086
+ const client = await this.getOrCreateClient(params.sessionId);
3910
4087
  const allTools = await client.fetchTools();
3911
- const toolPolicy = normalizeToolPolicyForUpdate(params.toolPolicy);
3912
- validateToolPolicyAgainstTools(toolPolicy, allTools.tools, session.serverId);
3913
- await sessions.update(this.userId, sessionId, { toolPolicy });
3914
- const filteredTools = createToolPolicyGateway(this.userId, sessionId, client).filterTools({ ...session, toolPolicy }, allTools.tools);
3915
- this.emitConnectionEvent({
4088
+ const policy = normalizeToolPolicyForUpdate(params.toolPolicy);
4089
+ validateToolPolicyAgainstTools(policy, allTools.tools, session.serverId);
4090
+ await sessions.update(this.userId, params.sessionId, { toolPolicy: policy });
4091
+ const filtered = createToolPolicyGateway(
4092
+ this.userId,
4093
+ params.sessionId,
4094
+ client
4095
+ ).filterTools({ ...session, toolPolicy: policy }, allTools.tools);
4096
+ this.sendEvent({
3916
4097
  type: "tools_discovered",
3917
- sessionId,
4098
+ sessionId: params.sessionId,
3918
4099
  serverId: session.serverId ?? "unknown",
3919
- toolCount: filteredTools.length,
3920
- tools: filteredTools,
4100
+ toolCount: filtered.length,
4101
+ tools: filtered,
3921
4102
  allTools: allTools.tools,
3922
4103
  timestamp: Date.now()
3923
4104
  });
3924
- return {
3925
- success: true,
3926
- toolPolicy,
3927
- tools: filteredTools,
3928
- toolCount: filteredTools.length
3929
- };
3930
- }
3931
- /**
3932
- * Proxies a tool invocation to the remote MCP server.
3933
- * Resolves the client for the given session and delegates to the tool router.
3934
- */
3935
- async callTool(params) {
3936
- const { sessionId, toolName, toolArgs } = params;
3937
- const client = await this.getOrCreateClient(sessionId);
3938
- const result = await createToolPolicyGateway(this.userId, sessionId, client).callTool(toolName, toolArgs);
3939
- const meta = result._meta || {};
3940
- return {
3941
- ...result,
3942
- _meta: {
3943
- ...meta,
3944
- sessionId
3945
- }
3946
- };
4105
+ return { success: true, toolPolicy: policy, tools: filtered, toolCount: filtered.length };
3947
4106
  }
3948
4107
  /**
3949
- * Restore and validate an existing session
4108
+ * Enables or disables a session for agent tool discovery.
4109
+ *
4110
+ * Disabled sessions retain their OAuth tokens and connection metadata
4111
+ * but are hidden from `MultiSessionClient.connect()` and blocked from
4112
+ * RPC tool access. Re-enabling does not require re-authentication.
4113
+ *
4114
+ * @param params - `{ sessionId, enabled: boolean }`
4115
+ * @returns `{ success: true }`
4116
+ * @throws {Error} If the session does not exist.
3950
4117
  */
3951
- async getSession(params) {
3952
- const { sessionId } = params;
3953
- const session = await sessions.get(this.userId, sessionId);
3954
- if (!session) {
3955
- throw new Error("Session not found");
3956
- }
3957
- this.emitConnectionEvent({
3958
- type: "state_changed",
3959
- sessionId,
3960
- serverId: session.serverId ?? "unknown",
3961
- serverName: session.serverName ?? "Unknown",
3962
- serverUrl: session.serverUrl,
3963
- state: "VALIDATING",
3964
- previousState: "DISCONNECTED",
3965
- timestamp: Date.now()
3966
- });
3967
- try {
3968
- const clientMetadata = await this.getResolvedClientMetadata();
3969
- const client = new MCPClient({
3970
- userId: this.userId,
3971
- sessionId,
3972
- // These fields are optional in MCPClient, but when rehydrating a known
3973
- // stored session on the server we pass them explicitly to preserve the
3974
- // original transport/connection metadata instead of relying on lazy
3975
- // reloading during initialize().
3976
- serverId: session.serverId,
3977
- serverName: session.serverName,
3978
- serverUrl: session.serverUrl,
3979
- callbackUrl: session.callbackUrl,
3980
- transportType: session.transportType,
3981
- headers: session.headers,
3982
- ...clientMetadata
3983
- });
3984
- client.onConnectionEvent((event) => this.emitConnectionEvent(event));
3985
- client.onObservabilityEvent((event) => this.sendEvent(event));
3986
- await client.connect();
3987
- this.clients.set(sessionId, client);
3988
- const { result: tools } = await this.listPolicyFilteredTools(sessionId);
3989
- return { success: true, toolCount: tools.tools.length };
3990
- } catch (error) {
3991
- this.emitConnectionEvent({
3992
- type: "error",
3993
- sessionId,
3994
- serverId: session.serverId ?? "unknown",
3995
- error: error instanceof Error ? error.message : "Validation failed",
3996
- errorType: "validation",
3997
- timestamp: Date.now()
3998
- });
3999
- throw error;
4000
- }
4118
+ async updateSession(params) {
4119
+ await this.requireSession(params.sessionId);
4120
+ await sessions.update(this.userId, params.sessionId, { enabled: params.enabled });
4121
+ return { success: true };
4001
4122
  }
4123
+ // -----------------------------------------------------------------------
4124
+ // Tool Execution
4125
+ // -----------------------------------------------------------------------
4002
4126
  /**
4003
- * Complete OAuth authorization flow
4127
+ * Proxies a tool invocation to the remote MCP server.
4128
+ *
4129
+ * Resolves (or creates) the transport for the given session, runs the call
4130
+ * through the tool-policy gateway, and injects `sessionId` into the result
4131
+ * metadata so the client can route the response without scanning all sessions.
4004
4132
  */
4005
- async finishAuth(params) {
4006
- const { code } = params;
4007
- const oauthState = params.state;
4008
- const parsedState = parseOAuthState(oauthState);
4009
- const sessionId = parsedState?.sessionId || oauthState;
4010
- const session = await sessions.get(this.userId, sessionId);
4011
- if (!session) {
4012
- throw new Error("Session not found");
4013
- }
4014
- try {
4015
- const client = new MCPClient({
4016
- userId: this.userId,
4017
- sessionId,
4018
- // These fields are optional in MCPClient, but when rehydrating a known
4019
- // stored session on the server we pass them explicitly to preserve the
4020
- // original connection metadata instead of relying on lazy
4021
- // reloading during initialize().
4022
- serverId: session.serverId,
4023
- serverName: session.serverName,
4024
- serverUrl: session.serverUrl,
4025
- callbackUrl: session.callbackUrl,
4026
- // NOTE: transportType is intentionally omitted here.
4027
- // The session's stored transportType is a placeholder ('streamable-http')
4028
- // set before transport negotiation. Omitting it lets MCPClient auto-negotiate
4029
- // (try streamable_http → SSE fallback), which is critical for servers like
4030
- // Neon that only support SSE transport.
4031
- headers: session.headers
4032
- });
4033
- client.onConnectionEvent((event) => this.emitConnectionEvent(event));
4034
- await client.finishAuth(code, oauthState);
4035
- this.clients.set(sessionId, client);
4036
- const { result: tools } = await this.listPolicyFilteredTools(sessionId);
4037
- return { success: true, toolCount: tools.tools.length };
4038
- } catch (error) {
4039
- this.emitConnectionEvent({
4040
- type: "error",
4041
- sessionId,
4042
- serverId: session.serverId ?? "unknown",
4043
- error: error instanceof Error ? error.message : "OAuth completion failed",
4044
- errorType: "auth",
4045
- timestamp: Date.now()
4046
- });
4047
- throw error;
4048
- }
4133
+ async callTool(params) {
4134
+ const client = await this.getOrCreateClient(params.sessionId);
4135
+ const result = await createToolPolicyGateway(
4136
+ this.userId,
4137
+ params.sessionId,
4138
+ client
4139
+ ).callTool(params.toolName, params.toolArgs);
4140
+ return { ...result, _meta: { ...result._meta ?? {}, sessionId: params.sessionId } };
4049
4141
  }
4050
- /**
4051
- * List prompts from a session
4052
- */
4142
+ // -----------------------------------------------------------------------
4143
+ // Prompts
4144
+ // -----------------------------------------------------------------------
4145
+ /** Lists all prompts exposed by the remote MCP server. */
4053
4146
  async listPrompts(params) {
4054
- const { sessionId } = params;
4055
- const client = await this.getOrCreateClient(sessionId);
4147
+ const client = await this.getOrCreateClient(params.sessionId);
4056
4148
  const result = await client.listPrompts();
4057
4149
  return { prompts: result.prompts };
4058
4150
  }
4059
- /**
4060
- * Get a specific prompt
4061
- */
4151
+ /** Retrieves a specific prompt by name with optional arguments. */
4062
4152
  async getPrompt(params) {
4063
- const { sessionId, name, args } = params;
4064
- const client = await this.getOrCreateClient(sessionId);
4065
- return await client.getPrompt(name, args);
4153
+ const client = await this.getOrCreateClient(params.sessionId);
4154
+ return client.getPrompt(params.name, params.args);
4066
4155
  }
4067
- /**
4068
- * List resources from a session
4069
- */
4156
+ // -----------------------------------------------------------------------
4157
+ // Resources
4158
+ // -----------------------------------------------------------------------
4159
+ /** Lists all resources exposed by the remote MCP server. */
4070
4160
  async listResources(params) {
4071
- const { sessionId } = params;
4072
- const client = await this.getOrCreateClient(sessionId);
4161
+ const client = await this.getOrCreateClient(params.sessionId);
4073
4162
  const result = await client.listResources();
4074
4163
  return { resources: result.resources };
4075
4164
  }
4165
+ /** Reads a specific resource identified by URI. */
4166
+ async readResource(params) {
4167
+ const client = await this.getOrCreateClient(params.sessionId);
4168
+ return client.readResource(params.uri);
4169
+ }
4170
+ // -----------------------------------------------------------------------
4171
+ // Internal Helpers
4172
+ // -----------------------------------------------------------------------
4173
+ /** Resolves client metadata: `getClientMetadata()` → `clientDefaults` → `{}`. */
4174
+ async getResolvedClientMetadata(request) {
4175
+ let metadata = this.options.clientDefaults ? { ...this.options.clientDefaults } : {};
4176
+ if (this.options.getClientMetadata) {
4177
+ metadata = { ...metadata, ...await this.options.getClientMetadata(request) };
4178
+ }
4179
+ return metadata;
4180
+ }
4181
+ /** Ensures the given session exists in storage and throws otherwise. */
4182
+ async requireSession(sessionId) {
4183
+ const session = await sessions.get(this.userId, sessionId, { includeCredentials: true });
4184
+ if (!session) throw new Error(`Session ${sessionId} not found`);
4185
+ return session;
4186
+ }
4187
+ /** Finds an existing session matching the given serverId or serverUrl. */
4188
+ async findExistingSession(serverId, serverUrl) {
4189
+ const all = await sessions.list(this.userId);
4190
+ return all.find((s) => s.serverId === serverId || s.serverUrl === serverUrl);
4191
+ }
4192
+ /** Normalizes a serverId to max 12 chars (DeepSeek/OpenAI 64-char tool-name limit). */
4193
+ normalizeServerId(raw) {
4194
+ return raw && raw.length <= 12 ? raw : generateServerId();
4195
+ }
4076
4196
  /**
4077
- * Read a specific resource
4197
+ * Returns the cached in-memory transport for `sessionId`, or creates one
4198
+ * from the persisted session row (with credentials) and connects it.
4078
4199
  */
4079
- async readResource(params) {
4080
- const { sessionId, uri } = params;
4081
- const client = await this.getOrCreateClient(sessionId);
4082
- return client.readResource(uri);
4200
+ async getOrCreateClient(sessionId) {
4201
+ const existing = this.clients.get(sessionId);
4202
+ if (existing) return existing;
4203
+ const session = await this.requireSession(sessionId);
4204
+ if (session.enabled === false) {
4205
+ throw new Error("Session is disabled \u2014 re-enable it via updateSession to access tools");
4206
+ }
4207
+ const client = this.restoreClient(session);
4208
+ this.attachClientEvents(client);
4209
+ await client.connect();
4210
+ this.clients.set(sessionId, client);
4211
+ return client;
4212
+ }
4213
+ /**
4214
+ * Builds an `MCPClient` from a stored session row.
4215
+ *
4216
+ * Extracts `clientId` and `clientSecret` from the session's credential
4217
+ * fields and passes `hasSession: true` + `cachedCredentials` so the client
4218
+ * can skip redundant existence checks and credential reads.
4219
+ */
4220
+ restoreClient(session) {
4221
+ const clientId = session.clientId ?? void 0;
4222
+ const clientSecret = session.clientInformation?.client_secret ?? void 0;
4223
+ return new MCPClient({
4224
+ userId: this.userId,
4225
+ sessionId: session.sessionId,
4226
+ serverId: session.serverId,
4227
+ serverName: session.serverName,
4228
+ serverUrl: session.serverUrl,
4229
+ callbackUrl: session.callbackUrl,
4230
+ transportType: session.transportType,
4231
+ headers: session.headers,
4232
+ clientId,
4233
+ clientSecret,
4234
+ hasSession: true,
4235
+ cachedCredentials: { tokens: session.tokens ?? void 0 },
4236
+ sessionStore: this.observedStore
4237
+ });
4083
4238
  }
4084
4239
  /**
4085
- * Emit connection event
4240
+ * Wires connection and observability events from the client into the
4241
+ * unified observability channel. Connection events go to `sendEvent`
4242
+ * (SSE stream); observability events go to `emitObs` (user callback
4243
+ * + SSE stream).
4086
4244
  */
4087
- emitConnectionEvent(event) {
4088
- this.sendEvent(event);
4245
+ attachClientEvents(client) {
4246
+ client.onConnectionEvent((e) => this.sendEvent(e));
4247
+ client.onObservabilityEvent((e) => this.sendEvent(e));
4089
4248
  }
4090
4249
  /**
4091
- * Cleanup and close all connections
4250
+ * Registers the client in the in-memory cache and attaches its event
4251
+ * listeners to the unified observability channel.
4092
4252
  */
4093
- async dispose() {
4094
- this.isActive = false;
4095
- if (this.heartbeatTimer) {
4096
- clearInterval(this.heartbeatTimer);
4253
+ cacheClient(sessionId, client) {
4254
+ this.attachClientEvents(client);
4255
+ this.clients.set(sessionId, client);
4256
+ }
4257
+ /**
4258
+ * Attempts a `client.connect()` and, on success, discovers tools.
4259
+ *
4260
+ * If the server responds with `UnauthorizedError`, the session is
4261
+ * treated as pending OAuth — a successful result is returned with
4262
+ * the sessionId so the browser client can redirect to the auth URL.
4263
+ *
4264
+ * For any other error an `error` connection event is emitted and the
4265
+ * client is removed from the in-memory cache before re-throwing.
4266
+ */
4267
+ async connectAndDiscover(client, sessionId, serverId) {
4268
+ try {
4269
+ await client.connect();
4270
+ await this.listPolicyFilteredTools(sessionId);
4271
+ return { sessionId, success: true };
4272
+ } catch (error) {
4273
+ if (error instanceof UnauthorizedError) {
4274
+ this.clients.delete(sessionId);
4275
+ return { sessionId, success: true };
4276
+ }
4277
+ this.sendEvent(connectionErrorEvent(sessionId, serverId, error, "connection"));
4278
+ this.clients.delete(sessionId);
4279
+ throw error;
4097
4280
  }
4098
- await Promise.all(
4099
- Array.from(this.clients.values()).map((client) => client.disconnect())
4100
- );
4101
- this.clients.clear();
4281
+ }
4282
+ /** Starts the periodic heartbeat timer. */
4283
+ startHeartbeat() {
4284
+ const ms = this.options.heartbeatInterval ?? DEFAULT_HEARTBEAT_MS;
4285
+ this.heartbeatTimer = setInterval(() => {
4286
+ if (this.active) {
4287
+ this.sendEvent({ level: "debug", message: "heartbeat", timestamp: Date.now() });
4288
+ }
4289
+ }, ms);
4102
4290
  }
4103
4291
  };
4104
4292
  function createSSEHandler(options) {
@@ -4127,8 +4315,7 @@ function createSSEHandler(options) {
4127
4315
  });
4128
4316
  req.on("end", async () => {
4129
4317
  try {
4130
- const request = JSON.parse(body);
4131
- await manager.handleRequest(request);
4318
+ await manager.handleRequest(JSON.parse(body));
4132
4319
  } catch {
4133
4320
  }
4134
4321
  });
@@ -4334,6 +4521,9 @@ var SSEClient = class {
4334
4521
  async getToolPolicy(sessionId) {
4335
4522
  return this.sendRequest("getToolPolicy", { sessionId });
4336
4523
  }
4524
+ async updateSession(sessionId, enabled) {
4525
+ return this.sendRequest("updateSession", { sessionId, enabled });
4526
+ }
4337
4527
  async listTools(sessionId) {
4338
4528
  return this.sendRequest("listTools", { sessionId });
4339
4529
  }
@@ -6200,6 +6390,6 @@ function globToRegExp(pattern) {
6200
6390
  return new RegExp(regexPattern);
6201
6391
  }
6202
6392
 
6203
- export { APP_HOST_DEFAULTS, AppHost, AuthenticationError, ConfigurationError, ConnectionError, DEFAULT_CLIENT_NAME, DEFAULT_CLIENT_URI, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_LOGO_URI, DEFAULT_MCP_APP_CSP, DEFAULT_POLICY_URI, DORMANT_SESSION_EXPIRATION_MS, DORMANT_SESSION_EXPIRATION_SECONDS, DisposableStore, Emitter, InvalidStateError, MCPClient, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, McpError, MultiSessionClient, NotConnectedError, PENDING_SESSION_EXPIRATION_SECONDS, REDIS_KEY_PREFIX, RpcErrorCodes, SANDBOX_PROXY_READY_METHOD, SANDBOX_RESOURCE_READY_METHOD, SOFTWARE_ID, SOFTWARE_VERSION, SSEClient, SSEConnectionManager, STATE_EXPIRATION_MS, SchemaCompressor, SessionNotFoundError, SessionValidationError, StorageOAuthClientProvider, ToolExecutionError, ToolIndex, ToolRouter, UnauthorizedError, createExecuteToolDefinition, createGetSchemaToolDefinition, createListServersToolDefinition, createNextMcpHandler, createRegexSearchToolDefinition, createSSEHandler, createSearchToolDefinition, executeMetaTool, findToolByName, getToolUiResourceUri, isCallToolSuccess, isConnectAuthRequired, isConnectError, isConnectSuccess, isListToolsSuccess, isMetaTool, onSessionMutation, resolveMetaToolProxy, sanitizeServerLabel, sessions };
6393
+ export { APP_HOST_DEFAULTS, AppHost, AuthenticationError, ConfigurationError, ConnectionError, DEFAULT_CLIENT_NAME, DEFAULT_CLIENT_URI, DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_LOGO_URI, DEFAULT_MCP_APP_CSP, DEFAULT_POLICY_URI, DORMANT_SESSION_EXPIRATION_MS, DORMANT_SESSION_EXPIRATION_SECONDS, DisposableStore, Emitter, InvalidStateError, MCPClient, MCP_CLIENT_NAME, MCP_CLIENT_VERSION, McpError, MultiSessionClient, NotConnectedError, PENDING_SESSION_EXPIRATION_SECONDS, REDIS_KEY_PREFIX, RpcErrorCodes, SANDBOX_PROXY_READY_METHOD, SANDBOX_RESOURCE_READY_METHOD, SOFTWARE_ID, SOFTWARE_VERSION, SSEClient, SSEConnectionManager, STATE_EXPIRATION_MS, SchemaCompressor, SessionNotFoundError, SessionValidationError, StorageOAuthClientProvider, ToolExecutionError, ToolIndex, ToolRouter, UnauthorizedError, createExecuteToolDefinition, createGetSchemaToolDefinition, createListServersToolDefinition, createNextMcpHandler, createRegexSearchToolDefinition, createSSEHandler, createSearchToolDefinition, decryptObject, encryptObject, executeMetaTool, findToolByName, getToolUiResourceUri, isCallToolSuccess, isConnectAuthRequired, isConnectError, isConnectSuccess, isListToolsSuccess, isMetaTool, onSessionMutation, resolveMetaToolProxy, sanitizeServerLabel, sessions, withDbObservability };
6204
6394
  //# sourceMappingURL=index.mjs.map
6205
6395
  //# sourceMappingURL=index.mjs.map