@loop_ouroboros/mcp-hub-lite 1.1.0 → 1.2.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 (100) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +74 -116
  3. package/dist/client/assets/{HomeView-Bu2joUvW.js → HomeView-BBwvy1oj.js} +1 -1
  4. package/dist/client/assets/{ResourceDetailView-BvrhDCD1.js → ResourceDetailView-CZ2aB73w.js} +1 -1
  5. package/dist/client/assets/{ResourcesView-LjqioF_s.js → ResourcesView-CN1NlhWs.js} +1 -1
  6. package/dist/client/assets/{ServerDashboard-FhHJFvUi.js → ServerDashboard-k652Vw4Z.js} +1 -1
  7. package/dist/client/assets/{ServerDetail-BKV-M4qT.js → ServerDetail-BLQ-a4cO.js} +1 -1
  8. package/dist/client/assets/{ServerListView-BXgtDyt3.js → ServerListView-BHrsFD5i.js} +4 -4
  9. package/dist/client/assets/{ServerStatusTags.vue_vue_type_script_setup_true_lang-D-ooYNdN.js → ServerStatusTags.vue_vue_type_script_setup_true_lang-BHhwEuGe.js} +1 -1
  10. package/dist/client/assets/{SettingsView-CMFG91Z4.js → SettingsView-CUOFNXrz.js} +1 -1
  11. package/dist/client/assets/{ToolCallDialog-Bf4Xe4gH.js → ToolCallDialog-BfPjLxfV.js} +1 -1
  12. package/dist/client/assets/ToolsView-BxgXvPC3.css +1 -0
  13. package/dist/client/assets/ToolsView-CyuhYAE2.js +1 -0
  14. package/dist/client/assets/{_baseClone-Bp9Rjwd7.js → _baseClone-DO5qfalW.js} +1 -1
  15. package/dist/client/assets/{el-form-item-DdSUWYsl.js → el-form-item-CcGsD2K_.js} +2 -2
  16. package/dist/client/assets/{el-input-99gMrutP.js → el-input-tYgeiaCT.js} +1 -1
  17. package/dist/client/assets/{el-loading-CIQ5pD5u.js → el-loading-Dwl9E_Vr.js} +1 -1
  18. package/dist/client/assets/{el-overlay-BVM6msGX.js → el-overlay-kqX_BABo.js} +1 -1
  19. package/dist/client/assets/{el-radio-group-DhXWy7ry.js → el-radio-group-D8aWBVOT.js} +1 -1
  20. package/dist/client/assets/el-skeleton-item-BRwIFspE.js +1 -0
  21. package/dist/client/assets/{el-switch-Bu8AQ5uM.js → el-switch-BF8c-xeU.js} +1 -1
  22. package/dist/client/assets/{el-tab-pane-BnGMaV56.js → el-tab-pane-C4Ep94cd.js} +1 -1
  23. package/dist/client/assets/{el-table-column-BMWOaLS_.js → el-table-column-Cog6uCh-.js} +1 -1
  24. package/dist/client/assets/{index-C2V-ZGji.js → index-ByNBhPAR.js} +1 -1
  25. package/dist/client/assets/index-CTB6oe-9.js +2 -0
  26. package/dist/client/assets/omit-CUnDT6sS.js +1 -0
  27. package/dist/client/assets/{raf-C2wXzaVU.js → raf-CmzeRPMd.js} +1 -1
  28. package/dist/client/assets/{vue-vendor-BLHLXXJK.js → vue-vendor-CbgVSHIh.js} +3 -3
  29. package/dist/client/index.html +2 -2
  30. package/dist/server/src/api/mcp/debug-response-wrapper.js +2 -2
  31. package/dist/server/src/api/mcp/gateway.d.ts.map +1 -1
  32. package/dist/server/src/api/mcp/gateway.js +17 -3
  33. package/dist/server/src/api/mcp/session-context-extractor.d.ts.map +1 -1
  34. package/dist/server/src/api/mcp/session-context-extractor.js +14 -5
  35. package/dist/server/src/cli/commands/mcp-tool-use.d.ts +62 -0
  36. package/dist/server/src/cli/commands/mcp-tool-use.d.ts.map +1 -0
  37. package/dist/server/src/cli/commands/mcp-tool-use.js +174 -0
  38. package/dist/server/src/cli/commands/server.d.ts +57 -0
  39. package/dist/server/src/cli/commands/server.d.ts.map +1 -0
  40. package/dist/server/src/cli/commands/server.js +169 -0
  41. package/dist/server/src/cli/commands/tool-use.d.ts +95 -0
  42. package/dist/server/src/cli/commands/tool-use.d.ts.map +1 -0
  43. package/dist/server/src/cli/commands/tool-use.js +255 -0
  44. package/dist/server/src/cli/index.d.ts +4 -2
  45. package/dist/server/src/cli/index.d.ts.map +1 -1
  46. package/dist/server/src/cli/index.js +35 -3
  47. package/dist/server/src/config/config-loader.js +1 -1
  48. package/dist/server/src/config/config-manager.js +1 -1
  49. package/dist/server/src/models/system-tools.constants.d.ts +2 -2
  50. package/dist/server/src/models/system-tools.constants.d.ts.map +1 -1
  51. package/dist/server/src/models/system-tools.constants.js +2 -2
  52. package/dist/server/src/services/connection/tool-cache.d.ts.map +1 -1
  53. package/dist/server/src/services/connection/tool-cache.js +3 -1
  54. package/dist/server/src/services/gateway/gateway.service.d.ts.map +1 -1
  55. package/dist/server/src/services/gateway/gateway.service.js +38 -4
  56. package/dist/server/src/services/gateway/global-transport.d.ts +14 -5
  57. package/dist/server/src/services/gateway/global-transport.d.ts.map +1 -1
  58. package/dist/server/src/services/gateway/global-transport.js +54 -30
  59. package/dist/server/src/services/gateway/request-handlers/initialize-handler.d.ts.map +1 -1
  60. package/dist/server/src/services/gateway/request-handlers/initialize-handler.js +12 -1
  61. package/dist/server/src/services/gateway/request-handlers/system-tools-handler.js +2 -2
  62. package/dist/server/src/services/gateway/request-handlers/tools-handler.d.ts.map +1 -1
  63. package/dist/server/src/services/gateway/request-handlers/tools-handler.js +3 -4
  64. package/dist/server/src/services/hub-tools/system-tool-definitions.d.ts +1 -0
  65. package/dist/server/src/services/hub-tools/system-tool-definitions.d.ts.map +1 -1
  66. package/dist/server/src/services/hub-tools/system-tool-definitions.js +4 -3
  67. package/dist/server/src/services/hub-tools.service.d.ts +3 -2
  68. package/dist/server/src/services/hub-tools.service.d.ts.map +1 -1
  69. package/dist/server/src/services/hub-tools.service.js +36 -19
  70. package/dist/server/src/services/search/search-core.service.d.ts +5 -5
  71. package/dist/server/src/services/search/search-core.service.js +11 -11
  72. package/dist/server/src/services/session/session-manager.d.ts +256 -12
  73. package/dist/server/src/services/session/session-manager.d.ts.map +1 -1
  74. package/dist/server/src/services/session/session-manager.js +585 -23
  75. package/dist/server/src/services/session-tracker.service.d.ts +10 -2
  76. package/dist/server/src/services/session-tracker.service.d.ts.map +1 -1
  77. package/dist/server/src/services/session-tracker.service.js +53 -2
  78. package/dist/server/src/services/system-tool-handler.js +2 -2
  79. package/dist/server/src/utils/index.d.ts +1 -0
  80. package/dist/server/src/utils/index.d.ts.map +1 -1
  81. package/dist/server/src/utils/index.js +1 -0
  82. package/dist/server/src/utils/name-converter.d.ts +17 -0
  83. package/dist/server/src/utils/name-converter.d.ts.map +1 -0
  84. package/dist/server/src/utils/name-converter.js +27 -0
  85. package/dist/server/src/utils/request-context.d.ts +18 -0
  86. package/dist/server/src/utils/request-context.d.ts.map +1 -1
  87. package/dist/server/src/utils/request-context.js +20 -0
  88. package/dist/server/tests/evaluation/evaluation.test.js +9 -10
  89. package/dist/server/tests/integration/api/gateway.test.js +2 -2
  90. package/dist/server/tests/unit/services/hub-tools.service.test.js +1 -1
  91. package/dist/server/tests/unit/utils/name-converter.test.d.ts +2 -0
  92. package/dist/server/tests/unit/utils/name-converter.test.d.ts.map +1 -0
  93. package/dist/server/tests/unit/utils/name-converter.test.js +69 -0
  94. package/dist/server/tests/unit/utils/request-context.test.js +24 -5
  95. package/package.json +3 -1
  96. package/dist/client/assets/ToolsView-DFpha1z0.js +0 -1
  97. package/dist/client/assets/ToolsView-E3Ps9c7i.css +0 -1
  98. package/dist/client/assets/el-skeleton-item-DJz-Us12.js +0 -1
  99. package/dist/client/assets/index-vhkqgpmN.js +0 -2
  100. package/dist/client/assets/omit-CqPQN3XP.js +0 -1
@@ -3,19 +3,35 @@ import { gateway } from '../gateway.service.js';
3
3
  import { logger, LOG_MODULES, formatMcpMessageForLogging, logNotificationMessage } from '../../utils/logger.js';
4
4
  import { configManager } from '../../config/config-manager.js';
5
5
  import { formatDuration } from '../../utils/format-utils.js';
6
+ import { SessionStateSchema, createEmptySessionStore } from '../../../shared/models/session.model.js';
7
+ import { sessionTrackerService } from '../session-tracker.service.js';
6
8
  import { getSessionDebugSetting, getMcpCommDebugSetting } from '../../utils/json-utils.js';
9
+ import * as fs from 'fs';
10
+ import path from 'path';
11
+ import os from 'os';
7
12
  /**
8
- * Lightweight MCP Session Manager with in-memory session management only.
13
+ * Enhanced MCP Session Manager with comprehensive persistence and lifecycle management.
9
14
  *
10
- * This service manages MCP sessions with basic in-memory storage and automatic
11
- * cleanup of stale sessions. It provides session isolation through unique
15
+ * This service manages MCP sessions with full state persistence, automatic cleanup,
16
+ * and graceful shutdown handling. It provides session isolation through unique
12
17
  * server and transport instances per session while maintaining shared resources
13
18
  * for efficiency.
14
19
  *
15
- * Key features:
16
- * - In-memory session storage only (no persistence)
20
+ * Key features include:
21
+ * - Session state persistence to disk with individual session files and index
22
+ * - Dirty tracking with 5-second batch flushing to minimize I/O operations
17
23
  * - Automatic cleanup of stale sessions based on configurable timeout (default 30 minutes)
18
- * - Session ID generation for internal use
24
+ * - Graceful shutdown handling with SIGTERM/SIGINT signal capture
25
+ * - Client metadata integration from client tracker service
26
+ * - Environment variable controlled debugging (SESSION_DEBUG)
27
+ *
28
+ * Session storage structure:
29
+ * ```
30
+ * ~/.mcp-hub-lite/
31
+ * └── sessions/
32
+ * ├── index.json # Session index file
33
+ * └── {sessionId}.json # Individual session state files
34
+ * ```
19
35
  *
20
36
  * @example
21
37
  * ```typescript
@@ -24,10 +40,15 @@ import { getSessionDebugSetting, getMcpCommDebugSetting } from '../../utils/json
24
40
  * // Use session.server and session.transport for MCP communication
25
41
  * ```
26
42
  *
27
- * @since 2.0.0
43
+ * @since 1.0.0
28
44
  */
29
45
  export class McpSessionManager {
30
46
  sessions = new Map();
47
+ sessionStates = new Map();
48
+ dirtySessions = new Set();
49
+ sessionsPath;
50
+ flushTimeout = null; // Replace with one-time delay
51
+ isInitialized = false;
31
52
  get SESSION_TIMEOUT() {
32
53
  return configManager.getConfig().security.sessionTimeout;
33
54
  }
@@ -35,15 +56,430 @@ export class McpSessionManager {
35
56
  return configManager.getConfig().security.sessionFlushInterval;
36
57
  }
37
58
  constructor() {
59
+ // Initialize sessions directory path
60
+ const configPath = process.env.MCP_HUB_CONFIG_PATH ||
61
+ path.join(os.homedir(), '.mcp-hub-lite', 'config', '.mcp-hub.json');
62
+ const mcpHubDir = path.dirname(path.dirname(configPath)); // Get ~/.mcp-hub-lite directory
63
+ this.sessionsPath = path.join(mcpHubDir, 'sessions');
64
+ logger.info(`Using sessions directory: ${this.sessionsPath}`, LOG_MODULES.SESSION_MANAGER);
38
65
  // Start cleanup interval
39
66
  setInterval(() => this.cleanup(), this.CLEANUP_INTERVAL);
67
+ // Register graceful shutdown handler
68
+ this.registerShutdownHandler();
69
+ // Initialize by restoring sessions
70
+ this.restoreSessions().catch((error) => {
71
+ logger.error('Failed to restore sessions during initialization:', error, LOG_MODULES.SESSION_MANAGER);
72
+ });
73
+ }
74
+ /**
75
+ * Registers process shutdown handlers for graceful session cleanup.
76
+ *
77
+ * This method sets up event listeners for SIGTERM and SIGINT signals to ensure
78
+ * that all dirty sessions are flushed to disk before the process terminates.
79
+ * This prevents data loss during unexpected shutdowns or service restarts.
80
+ *
81
+ * The shutdown handler performs a final flush of all dirty sessions and
82
+ * clears any pending flush timeouts to ensure clean termination.
83
+ *
84
+ * @returns {void}
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * // Called automatically in constructor
89
+ * sessionManager.registerShutdownHandler();
90
+ * ```
91
+ */
92
+ registerShutdownHandler() {
93
+ const gracefulShutdown = async () => {
94
+ logger.info('Shutting down, flushing dirty sessions...', LOG_MODULES.SESSION_MANAGER);
95
+ try {
96
+ await this.flushDirtySessions();
97
+ }
98
+ catch (error) {
99
+ logger.error('Error during shutdown flush:', error, LOG_MODULES.SESSION_MANAGER);
100
+ }
101
+ if (this.flushTimeout) {
102
+ clearTimeout(this.flushTimeout);
103
+ }
104
+ };
105
+ process.on('SIGTERM', gracefulShutdown);
106
+ process.on('SIGINT', gracefulShutdown);
107
+ }
108
+ /**
109
+ * Marks a session as dirty, indicating it needs to be persisted to disk.
110
+ *
111
+ * This method adds the session ID to the dirty sessions set and initiates
112
+ * a delayed batch flush operation with a 5-second timeout. This optimization
113
+ * prevents excessive I/O operations by batching multiple session updates
114
+ * that occur in quick succession.
115
+ *
116
+ * When the SESSION_DEBUG environment variable is set, detailed logging
117
+ * is enabled for debugging session persistence behavior.
118
+ *
119
+ * @param {string} sessionId - Unique identifier of the session to mark as dirty
120
+ * @returns {void}
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * sessionManager.markAsDirty('my-session-id');
125
+ * // Session will be flushed to disk within 5 seconds
126
+ * ```
127
+ */
128
+ markAsDirty(sessionId) {
129
+ this.dirtySessions.add(sessionId);
130
+ if (getSessionDebugSetting()) {
131
+ logger.debug(`Session marked as dirty: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
132
+ }
133
+ // Set one-time delayed flush to avoid frequent writes (configurable delay, batch processing)
134
+ if (!this.flushTimeout) {
135
+ const flushInterval = configManager.getConfig().security.sessionFlushInterval || 5000;
136
+ this.flushTimeout = setTimeout(() => {
137
+ this.flushDirtySessions();
138
+ this.flushTimeout = null;
139
+ }, flushInterval);
140
+ }
141
+ }
142
+ /**
143
+ * Loads the complete session store from disk, including all individual session files.
144
+ *
145
+ * This method reads the sessions index file and loads each individual session state
146
+ * file, validating each session state against the SessionStateSchema. Invalid
147
+ * session states are skipped with warning logs, ensuring robust recovery from
148
+ * corrupted data.
149
+ *
150
+ * The method creates the sessions directory and index file if they don't exist,
151
+ * providing a clean initialization path for first-time usage.
152
+ *
153
+ * @returns {Promise<SessionStore>} Complete session store with all valid sessions
154
+ * @throws {Error} If critical I/O operations fail (non-recoverable errors)
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * const store = await sessionManager.loadSessionStore();
159
+ * console.log(`Loaded ${Object.keys(store.sessions).length} sessions`);
160
+ * ```
161
+ */
162
+ async loadSessionStore() {
163
+ try {
164
+ if (!fs.existsSync(this.sessionsPath)) {
165
+ if (getSessionDebugSetting()) {
166
+ logger.debug('Sessions directory not found, creating new one', LOG_MODULES.SESSION_MANAGER);
167
+ }
168
+ fs.mkdirSync(this.sessionsPath, { recursive: true });
169
+ return createEmptySessionStore();
170
+ }
171
+ const indexPath = path.join(this.sessionsPath, 'index.json');
172
+ if (!fs.existsSync(indexPath)) {
173
+ if (getSessionDebugSetting()) {
174
+ logger.debug('Sessions index file not found, creating new one', LOG_MODULES.SESSION_MANAGER);
175
+ }
176
+ return createEmptySessionStore();
177
+ }
178
+ const indexContent = fs.readFileSync(indexPath, 'utf-8');
179
+ const index = JSON.parse(indexContent);
180
+ if (!index.sessions || !Array.isArray(index.sessions)) {
181
+ logger.error('Invalid sessions index file, creating new one', LOG_MODULES.SESSION_MANAGER);
182
+ return createEmptySessionStore();
183
+ }
184
+ const store = createEmptySessionStore();
185
+ for (const sessionId of index.sessions) {
186
+ const sessionPath = path.join(this.sessionsPath, `${sessionId}.json`);
187
+ if (fs.existsSync(sessionPath)) {
188
+ try {
189
+ const sessionContent = fs.readFileSync(sessionPath, 'utf-8');
190
+ const sessionState = JSON.parse(sessionContent);
191
+ const validated = SessionStateSchema.parse(sessionState);
192
+ store.sessions[sessionId] = validated;
193
+ }
194
+ catch (error) {
195
+ logger.warn(`Failed to load session ${sessionId}:`, error, LOG_MODULES.SESSION_MANAGER);
196
+ }
197
+ }
198
+ }
199
+ if (getSessionDebugSetting()) {
200
+ logger.debug(`Loaded ${Object.keys(store.sessions).length} sessions from store`, LOG_MODULES.SESSION_MANAGER);
201
+ }
202
+ return store;
203
+ }
204
+ catch (error) {
205
+ logger.error('Failed to load sessions store:', error, LOG_MODULES.SESSION_MANAGER);
206
+ return createEmptySessionStore();
207
+ }
208
+ }
209
+ /**
210
+ * Saves the complete session store to disk, writing individual session files and index.
211
+ *
212
+ * This method persists all session states by writing individual JSON files for each
213
+ * session and updating the sessions index file. The operation is atomic at the
214
+ * file level, ensuring data integrity even if the process is interrupted.
215
+ *
216
+ * @param {SessionStore} store - Complete session store to persist
217
+ * @returns {Promise<void>} Resolves when all files are successfully written
218
+ * @throws {Error} If any file write operations fail
219
+ *
220
+ * @example
221
+ * ```typescript
222
+ * await sessionManager.saveSessionStore(mySessionStore);
223
+ * console.log('Session store saved successfully');
224
+ * ```
225
+ */
226
+ async saveSessionStore(store) {
227
+ try {
228
+ if (!fs.existsSync(this.sessionsPath)) {
229
+ fs.mkdirSync(this.sessionsPath, { recursive: true });
230
+ }
231
+ // Save individual session files
232
+ for (const [sessionId, state] of Object.entries(store.sessions)) {
233
+ const sessionPath = path.join(this.sessionsPath, `${sessionId}.json`);
234
+ fs.writeFileSync(sessionPath, JSON.stringify(state, null, 2));
235
+ }
236
+ // Save index file
237
+ const indexPath = path.join(this.sessionsPath, 'index.json');
238
+ fs.writeFileSync(indexPath, JSON.stringify({
239
+ sessions: Object.keys(store.sessions)
240
+ }, null, 2));
241
+ }
242
+ catch (error) {
243
+ logger.error('Failed to save sessions store:', error, LOG_MODULES.SESSION_MANAGER);
244
+ throw error;
245
+ }
246
+ }
247
+ /**
248
+ * Restores all sessions from disk during service startup.
249
+ *
250
+ * This method is called automatically during initialization to recover session states
251
+ * from persistent storage. It loads the session store, validates each session state,
252
+ * and populates the in-memory session state cache. Invalid sessions are skipped
253
+ * with warning logs to ensure robust startup even with corrupted data.
254
+ *
255
+ * The method ensures idempotent execution by checking the initialization flag,
256
+ * preventing multiple restoration attempts.
257
+ *
258
+ * @returns {Promise<void>} Resolves when all valid sessions are restored
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * await sessionManager.restoreSessions();
263
+ * console.log('Sessions restored from disk');
264
+ * ```
265
+ */
266
+ async restoreSessions() {
267
+ if (this.isInitialized) {
268
+ return;
269
+ }
270
+ try {
271
+ logger.info('Restoring sessions from disk...', LOG_MODULES.SESSION_MANAGER);
272
+ const store = await this.loadSessionStore();
273
+ let restoredCount = 0;
274
+ let expiredCount = 0;
275
+ const now = Date.now();
276
+ for (const [sessionId, state] of Object.entries(store.sessions)) {
277
+ try {
278
+ // Validate individual session state
279
+ const validatedState = SessionStateSchema.parse(state);
280
+ // Check if session has expired
281
+ if (now - validatedState.lastAccessedAt > this.SESSION_TIMEOUT) {
282
+ expiredCount++;
283
+ if (getSessionDebugSetting()) {
284
+ logger.debug(`Expired session: ${sessionId} (last accessed ${formatDuration(now - validatedState.lastAccessedAt)} ago)`, LOG_MODULES.SESSION_MANAGER);
285
+ }
286
+ }
287
+ else {
288
+ restoredCount++;
289
+ }
290
+ // Always restore to memory - cleanup() will handle deletion
291
+ this.sessionStates.set(sessionId, validatedState);
292
+ if (getSessionDebugSetting()) {
293
+ logger.debug(`Restored session state: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
294
+ }
295
+ }
296
+ catch (error) {
297
+ logger.warn(`Skipping invalid session state for ${sessionId}:`, error, LOG_MODULES.SESSION_MANAGER);
298
+ }
299
+ }
300
+ this.isInitialized = true;
301
+ logger.info(`Successfully restored ${restoredCount} valid, ${expiredCount} expired session(s)`, LOG_MODULES.SESSION_MANAGER);
302
+ // Immediately run cleanup on startup to clean up any expired sessions
303
+ this.cleanup();
304
+ }
305
+ catch (error) {
306
+ logger.error('Failed to restore sessions:', error, LOG_MODULES.SESSION_MANAGER);
307
+ // Continue with empty state rather than failing
308
+ this.isInitialized = true;
309
+ }
310
+ }
311
+ /**
312
+ * Flushes all dirty sessions to disk in a single batch operation.
313
+ *
314
+ * This method collects all sessions marked as dirty, loads the current session store,
315
+ * updates it with the dirty sessions, and saves the complete store back to disk.
316
+ * This batch approach minimizes I/O operations and ensures data consistency.
317
+ *
318
+ * The method includes comprehensive error handling to prevent partial writes and
319
+ * maintains detailed logging for debugging and monitoring purposes.
320
+ *
321
+ * @returns {Promise<void>} Resolves when all dirty sessions are successfully flushed
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * await sessionManager.flushDirtySessions();
326
+ * console.log('All dirty sessions flushed to disk');
327
+ * ```
328
+ */
329
+ async flushDirtySessions() {
330
+ if (this.dirtySessions.size === 0) {
331
+ return;
332
+ }
333
+ try {
334
+ logger.info(`Flushing ${this.dirtySessions.size} dirty session(s) to disk`, LOG_MODULES.SESSION_MANAGER);
335
+ // Load current store
336
+ const currentStore = await this.loadSessionStore();
337
+ const newStore = {
338
+ ...currentStore,
339
+ sessions: { ...currentStore.sessions }
340
+ };
341
+ // Process all dirty sessions
342
+ for (const sessionId of this.dirtySessions) {
343
+ const sessionState = this.sessionStates.get(sessionId);
344
+ if (sessionState) {
345
+ // Session exists - update it
346
+ newStore.sessions[sessionId] = sessionState;
347
+ }
348
+ else {
349
+ // Session does not exist - remove it
350
+ delete newStore.sessions[sessionId];
351
+ // Also remove the individual session file
352
+ const sessionPath = path.join(this.sessionsPath, `${sessionId}.json`);
353
+ if (fs.existsSync(sessionPath)) {
354
+ fs.unlinkSync(sessionPath);
355
+ logger.debug(`Deleted session file: ${sessionId}.json`, LOG_MODULES.SESSION_MANAGER);
356
+ }
357
+ }
358
+ }
359
+ await this.saveSessionStore(newStore);
360
+ const flushedCount = this.dirtySessions.size;
361
+ this.dirtySessions.clear();
362
+ logger.info(`Successfully flushed ${flushedCount} session(s)`, LOG_MODULES.SESSION_MANAGER);
363
+ }
364
+ catch (error) {
365
+ logger.error('Failed to flush dirty sessions:', error, LOG_MODULES.SESSION_MANAGER);
366
+ }
367
+ }
368
+ /**
369
+ * Updates session metadata by retrieving client information from the client tracker service.
370
+ *
371
+ * This method fetches current client information including name, version, working directory,
372
+ * and project context from the client tracker service and returns a partial session state
373
+ * update object containing only the relevant metadata fields.
374
+ *
375
+ * @param {string} sessionId - Unique identifier of the session to update
376
+ * @returns {Partial<SessionState>} Partial session state with updated client metadata
377
+ *
378
+ * @example
379
+ * ```typescript
380
+ * const metadata = sessionManager.updateSessionMetadataFromClient('my-session-id');
381
+ * console.log('Updated client metadata:', metadata);
382
+ * ```
383
+ */
384
+ updateSessionMetadataFromClient(sessionId) {
385
+ const sessionInfo = sessionTrackerService.getSession(sessionId);
386
+ return {
387
+ clientName: sessionInfo?.clientName,
388
+ clientVersion: sessionInfo?.clientVersion,
389
+ protocolVersion: sessionInfo?.protocolVersion,
390
+ capabilities: sessionInfo?.capabilities,
391
+ cwd: sessionInfo?.cwd,
392
+ project: sessionInfo?.project,
393
+ userAgent: sessionInfo?.userAgent,
394
+ ip: sessionInfo?.ip
395
+ };
396
+ }
397
+ /**
398
+ * Creates or updates a session state with current metadata and timestamps.
399
+ *
400
+ * This method merges existing session state (if any) with current client metadata
401
+ * from the client tracker service, updates access timestamps, and ensures proper
402
+ * session state structure. The updated state is stored in memory and marked as dirty
403
+ * for persistence.
404
+ *
405
+ * @param {string} sessionId - Unique identifier of the session to create or update
406
+ * @returns {SessionState} Complete updated session state object
407
+ *
408
+ * @example
409
+ * ```typescript
410
+ * const state = sessionManager.upsertSessionState('my-session-id');
411
+ * console.log('Session state updated:', state);
412
+ * ```
413
+ */
414
+ upsertSessionState(sessionId) {
415
+ const existing = this.sessionStates.get(sessionId);
416
+ const now = Date.now();
417
+ const clientMetadata = this.updateSessionMetadataFromClient(sessionId);
418
+ const state = {
419
+ sessionId,
420
+ clientName: clientMetadata.clientName || existing?.clientName,
421
+ clientVersion: clientMetadata.clientVersion || existing?.clientVersion,
422
+ protocolVersion: clientMetadata.protocolVersion || existing?.protocolVersion,
423
+ capabilities: clientMetadata.capabilities || existing?.capabilities,
424
+ cwd: clientMetadata.cwd || existing?.cwd,
425
+ project: clientMetadata.project || existing?.project,
426
+ userAgent: clientMetadata.userAgent || existing?.userAgent,
427
+ ip: clientMetadata.ip || existing?.ip,
428
+ createdAt: existing?.createdAt || now,
429
+ lastAccessedAt: now,
430
+ metadata: existing?.metadata || {}
431
+ };
432
+ this.sessionStates.set(sessionId, state);
433
+ this.markAsDirty(sessionId);
434
+ return state;
435
+ }
436
+ /**
437
+ * Updates session metadata explicitly with provided key-value pairs.
438
+ *
439
+ * This method merges the provided metadata object with existing session metadata,
440
+ * updates the last accessed timestamp, and marks the session as dirty for persistence.
441
+ * It's useful for storing custom session-specific information that needs to be persisted.
442
+ *
443
+ * @param {string} sessionId - Unique identifier of the session to update
444
+ * @param {Record<string, unknown>} metadata - Key-value pairs to merge into session metadata
445
+ * @returns {Promise<void>} Resolves when metadata is updated and marked for persistence
446
+ *
447
+ * @example
448
+ * ```typescript
449
+ * await sessionManager.updateSessionMetadata('my-session-id', {
450
+ * userPreferences: { theme: 'dark' },
451
+ * lastProject: 'my-project'
452
+ * });
453
+ * ```
454
+ */
455
+ async updateSessionMetadata(sessionId, metadata) {
456
+ const existing = this.sessionStates.get(sessionId);
457
+ if (existing) {
458
+ const now = Date.now();
459
+ const updated = {
460
+ ...existing,
461
+ lastAccessedAt: now,
462
+ metadata: {
463
+ ...existing.metadata,
464
+ ...metadata
465
+ }
466
+ };
467
+ this.sessionStates.set(sessionId, updated);
468
+ this.markAsDirty(sessionId);
469
+ if (getSessionDebugSetting()) {
470
+ logger.debug(`Updated metadata for session: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
471
+ }
472
+ }
40
473
  }
41
474
  /**
42
475
  * Retrieves an existing session or creates a new one if it doesn't exist.
43
476
  *
44
477
  * This method provides access to active sessions, creating new ones on demand with
45
478
  * proper initialization based on the requireInitialize parameter. It updates session
46
- * access timestamps.
479
+ * access timestamps and persists session state changes to ensure data consistency.
480
+ *
481
+ * The method includes optimization to prevent excessive timestamp updates for rapid
482
+ * successive requests by only updating when at least 100ms have passed since the last access.
47
483
  *
48
484
  * @param {string} sessionId - Unique identifier of the session to retrieve or create
49
485
  * @param {boolean} [requireInitialize=true] - Whether to require MCP protocol initialization
@@ -53,28 +489,48 @@ export class McpSessionManager {
53
489
  * ```typescript
54
490
  * // Get or create session with default initialization
55
491
  * const session = await sessionManager.getSession('my-session-id');
492
+ *
493
+ * // Get or create session without requiring initialization (for restored sessions)
494
+ * const restoredSession = await sessionManager.getSession('restored-session-id', false);
56
495
  * ```
57
496
  */
58
497
  async getSession(sessionId, requireInitialize = true) {
59
498
  if (getSessionDebugSetting()) {
499
+ const hasSessionState = this.sessionStates.has(sessionId);
60
500
  const hasSessionObject = this.sessions.has(sessionId);
61
- logger.debug(`getSession called for ${sessionId} (requireInitialize: ${requireInitialize}). Object exists: ${hasSessionObject}`, LOG_MODULES.SESSION_MANAGER);
501
+ logger.debug(`getSession called for ${sessionId} (requireInitialize: ${requireInitialize}). State exists: ${hasSessionState}, Object exists: ${hasSessionObject}`, LOG_MODULES.SESSION_MANAGER);
62
502
  }
63
503
  let session = this.sessions.get(sessionId);
64
- if (!session) {
504
+ // Check if session state exists but session object doesn't (inconsistency case)
505
+ const hasSessionState = this.sessionStates.has(sessionId);
506
+ const hasSessionObject = this.sessions.has(sessionId);
507
+ if (hasSessionState && !hasSessionObject) {
508
+ // Session state exists but session object is missing - recreate session
509
+ if (getSessionDebugSetting()) {
510
+ logger.debug(`Session state exists but session object missing for ${sessionId}, recreating...`, LOG_MODULES.SESSION_MANAGER);
511
+ }
512
+ session = await this.createSession(sessionId, requireInitialize);
513
+ this.sessions.set(sessionId, session);
514
+ }
515
+ else if (!session) {
65
516
  // Normal case: create new session
66
517
  session = await this.createSession(sessionId, requireInitialize);
67
518
  this.sessions.set(sessionId, session);
68
519
  }
69
520
  else {
70
- // Ensure transport session state is correctly initialized
521
+ // Enhanced check: ensure transport session state is correctly initialized
522
+ // This fixes the "Session not found" error when transport has lost session context
523
+ const hasRestoredState = this.sessionStates.has(sessionId);
524
+ const shouldManuallyInitialize = !requireInitialize || hasRestoredState;
525
+ // Always ensure sessionId is set on transport, regardless of initialization status
526
+ // This fixes the "Session not found" error for non-initialization requests
71
527
  const webTransport = session.transport
72
528
  ._webStandardTransport;
73
529
  if (webTransport) {
74
530
  const currentSessionId = webTransport.sessionId;
75
531
  const isInitialized = webTransport._initialized;
76
532
  if (getSessionDebugSetting()) {
77
- logger.debug(`Transport state check - Expected: ${sessionId} (initialized: ${!requireInitialize}), Actual: ${currentSessionId} (initialized: ${isInitialized})`, LOG_MODULES.SESSION_MANAGER);
533
+ logger.debug(`Transport state check - Expected: ${sessionId} (initialized: ${shouldManuallyInitialize}), Actual: ${currentSessionId} (initialized: ${isInitialized})`, LOG_MODULES.SESSION_MANAGER);
78
534
  }
79
535
  if (webTransport.sessionId !== sessionId) {
80
536
  logger.warn(`Session ID mismatch detected for ${sessionId}. Resetting transport sessionId.`, LOG_MODULES.SESSION_MANAGER);
@@ -83,7 +539,7 @@ export class McpSessionManager {
83
539
  webTransport._session = sessionId;
84
540
  }
85
541
  }
86
- if (!requireInitialize && !webTransport._initialized) {
542
+ if (shouldManuallyInitialize && !webTransport._initialized) {
87
543
  logger.warn(`Session initialization state mismatch detected for ${sessionId}. Setting initialized flag.`, LOG_MODULES.SESSION_MANAGER);
88
544
  webTransport._initialized = true;
89
545
  }
@@ -92,14 +548,56 @@ export class McpSessionManager {
92
548
  const now = Date.now();
93
549
  const timeDiff = Math.abs(now - session.lastAccessed);
94
550
  // Only update lastAccessed if meaningful time has passed
551
+ // This prevents excessive updates for rapid successive requests
95
552
  if (timeDiff >= 100) {
96
553
  session.lastAccessed = now;
554
+ // Also update and persist session state
555
+ this.upsertSessionState(sessionId);
97
556
  }
98
557
  if (getSessionDebugSetting()) {
99
558
  logger.debug(`Returning session for ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
100
559
  }
101
560
  return session;
102
561
  }
562
+ /**
563
+ * Retrieves all persisted session states for API exposure.
564
+ *
565
+ * This method returns an array of all current session states, providing a complete
566
+ * snapshot of all active sessions and their metadata. It's primarily used by the
567
+ * web API to expose session information to clients.
568
+ *
569
+ * @returns {SessionState[]} Array of all current session states
570
+ *
571
+ * @example
572
+ * ```typescript
573
+ * const allStates = sessionManager.getAllSessionStates();
574
+ * console.log(`Total active sessions: ${allStates.length}`);
575
+ * ```
576
+ */
577
+ getAllSessionStates() {
578
+ return Array.from(this.sessionStates.values());
579
+ }
580
+ /**
581
+ * Retrieves a specific session state by session ID for API exposure.
582
+ *
583
+ * This method returns the current state of a specific session or undefined if
584
+ * the session doesn't exist. It's primarily used by the web API to provide
585
+ * detailed information about individual sessions.
586
+ *
587
+ * @param {string} sessionId - Unique identifier of the session to retrieve
588
+ * @returns {SessionState | undefined} Session state object or undefined if not found
589
+ *
590
+ * @example
591
+ * ```typescript
592
+ * const state = sessionManager.getSessionState('my-session-id');
593
+ * if (state) {
594
+ * console.log('Session client:', state.clientName);
595
+ * }
596
+ * ```
597
+ */
598
+ getSessionState(sessionId) {
599
+ return this.sessionStates.get(sessionId);
600
+ }
103
601
  /**
104
602
  * Checks if a session object exists in the active sessions map.
105
603
  *
@@ -110,9 +608,11 @@ export class McpSessionManager {
110
608
  return this.sessions.has(sessionId);
111
609
  }
112
610
  /**
113
- * Deletes a session from memory.
611
+ * Deletes a session and removes it from persistent storage.
114
612
  *
115
- * This method gracefully closes the session's MCP server and removes it from memory.
613
+ * This method gracefully closes the session's MCP server, removes it from memory,
614
+ * and ensures it's removed from persistent storage by marking it as dirty and
615
+ * performing an immediate flush. It returns true if the session existed and was deleted.
116
616
  *
117
617
  * @param {string} sessionId - Unique identifier of the session to delete
118
618
  * @returns {Promise<boolean>} True if session existed and was deleted, false otherwise
@@ -135,15 +635,30 @@ export class McpSessionManager {
135
635
  logger.error(`Error closing session ${sessionId}:`, e, LOG_MODULES.SESSION_MANAGER);
136
636
  }
137
637
  this.sessions.delete(sessionId);
138
- return true;
139
638
  }
140
- return false;
639
+ const existed = this.sessionStates.has(sessionId);
640
+ if (existed) {
641
+ this.sessionStates.delete(sessionId);
642
+ // Mark as dirty to remove from persistence
643
+ this.markAsDirty(sessionId);
644
+ // Flush immediately to remove from disk
645
+ await this.flushDirtySessions();
646
+ }
647
+ return existed;
141
648
  }
142
649
  /**
143
650
  * Creates a new MCP session with proper initialization and transport setup.
144
651
  *
145
652
  * This method sets up a complete MCP session including server, transport, and
146
- * communication logging.
653
+ * communication logging. It handles both fresh sessions and restored sessions,
654
+ * with special logic for skipping initialization when appropriate.
655
+ *
656
+ * Key features:
657
+ * - Creates StreamableHTTPServerTransport with custom session ID generation
658
+ * - Sets up comprehensive message logging for debugging
659
+ * - Handles restored sessions by manually initializing transport state
660
+ * - Integrates with client tracker service for metadata
661
+ * - Creates/updates session state and marks as dirty for persistence
147
662
  *
148
663
  * @param {string} sessionId - Unique identifier for the new session
149
664
  * @param {boolean} [requireInitialize=true] - Whether to require MCP protocol initialization
@@ -173,26 +688,46 @@ export class McpSessionManager {
173
688
  }
174
689
  });
175
690
  // Directly set sessionId property to avoid validateSession failure
691
+ // because WebStandardStreamableHTTPServerTransport only calls sessionIdGenerator during initialize
176
692
  const webTransport = transport._webStandardTransport;
177
693
  if (webTransport) {
178
694
  webTransport.sessionId = sessionId;
695
+ // Do not set _initialized = true here because it will cause initialize request to fail
696
+ // _initialized flag will be set as needed in the shouldManuallyInitialize logic
179
697
  if (getSessionDebugSetting()) {
180
698
  logger.debug(`Directly set sessionId on transport: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
181
699
  }
182
700
  }
183
- // For sessions that need to skip initialization, manually set the initialized flag
184
- if (!requireInitialize) {
701
+ // Check if we have a restored state for this session
702
+ const restoredState = this.sessionStates.get(sessionId);
703
+ if (restoredState) {
704
+ logger.info(`Reusing restored session state for: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
705
+ }
706
+ // For restored sessions or when explicitly requested to skip initialization, manually set the initialized flag
707
+ // This allows sending requests like tools/list directly without needing to initialize first
708
+ const shouldManuallyInitialize = !requireInitialize || !!restoredState;
709
+ if (getSessionDebugSetting()) {
710
+ logger.debug(`shouldManuallyInitialize: ${shouldManuallyInitialize} (!requireInitialize: ${!requireInitialize} || restored: ${!!restoredState})`, LOG_MODULES.SESSION_MANAGER);
711
+ }
712
+ if (shouldManuallyInitialize) {
185
713
  const webTransport = transport._webStandardTransport;
186
714
  if (webTransport) {
187
715
  webTransport.sessionId = sessionId;
188
716
  webTransport._initialized = true;
717
+ // Ensure session property is also set if it exists
189
718
  if (webTransport._session !== undefined) {
190
719
  webTransport._session = sessionId;
191
720
  }
192
721
  if (getSessionDebugSetting()) {
193
- logger.debug(`Manually initialized transport for session: ${sessionId} (skipInitialize: ${!requireInitialize}`, LOG_MODULES.SESSION_MANAGER);
722
+ logger.debug(`Manually initialized transport for session: ${sessionId} (skipInitialize: ${!requireInitialize}, restored: ${!!restoredState})`, LOG_MODULES.SESSION_MANAGER);
723
+ logger.debug(`Transport state after manual init - sessionId: ${webTransport.sessionId}, _initialized: ${webTransport._initialized}, _session: ${webTransport._session}`, LOG_MODULES.SESSION_MANAGER);
194
724
  }
195
725
  }
726
+ else {
727
+ logger.error(`Failed to get _webStandardTransport from transport!`, LOG_MODULES.SESSION_MANAGER);
728
+ // Even if we can't manually initialize, continue with normal initialization
729
+ // The transport will be initialized when the first request arrives
730
+ }
196
731
  }
197
732
  // Always set up message handler for notifications/message
198
733
  transport.onmessage = (message) => {
@@ -222,9 +757,14 @@ export class McpSessionManager {
222
757
  const server = gateway.createConnectionServer();
223
758
  // Ensure server is fully connected before returning session
224
759
  await server.connect(transport);
760
+ // Note: StreamableHTTPServerTransport's onsessioninitialized callback is triggered
761
+ // when the first actual request (GET /mcp) arrives, not during connect().
762
+ // Therefore, we don't need to wait for this event - the transport is ready to receive requests.
225
763
  if (getSessionDebugSetting()) {
226
764
  logger.debug(`StreamableHTTPServerTransport ready for session: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
227
765
  }
766
+ // Create/update session state
767
+ this.upsertSessionState(sessionId);
228
768
  logger.info(`MCP session created successfully: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
229
769
  const session = {
230
770
  server,
@@ -237,11 +777,14 @@ export class McpSessionManager {
237
777
  /**
238
778
  * Cleans up stale sessions based on the configured session timeout.
239
779
  *
240
- * This method is called periodically to identify and close
780
+ * This method is called periodically (every 60 seconds) to identify and close
241
781
  * sessions that haven't been accessed within the configured timeout period
242
782
  * (default 30 minutes). It gracefully closes MCP servers and removes sessions
243
783
  * from memory to prevent resource leaks.
244
784
  *
785
+ * The method logs detailed information about cleaned sessions and maintains
786
+ * active session count for monitoring purposes.
787
+ *
245
788
  * @returns {void}
246
789
  *
247
790
  * @example
@@ -267,8 +810,27 @@ export class McpSessionManager {
267
810
  this.sessions.delete(sessionId);
268
811
  }
269
812
  }
813
+ // Cleanup persisted session states
814
+ const expiredSessionIds = [];
815
+ for (const [sessionId, session] of this.sessionStates.entries()) {
816
+ if (now - session.lastAccessedAt > this.SESSION_TIMEOUT) {
817
+ expiredSessionIds.push(sessionId);
818
+ cleanedCount++;
819
+ }
820
+ }
821
+ for (const sessionId of expiredSessionIds) {
822
+ this.sessionStates.delete(sessionId);
823
+ this.markAsDirty(sessionId);
824
+ logger.debug(`Marking expired session for deletion: ${sessionId}`, LOG_MODULES.SESSION_MANAGER);
825
+ }
826
+ // Immediately flush to delete session files from disk
827
+ if (expiredSessionIds.length > 0) {
828
+ this.flushDirtySessions().catch((error) => {
829
+ logger.error('Failed to flush expired sessions:', error, LOG_MODULES.SESSION_MANAGER);
830
+ });
831
+ }
270
832
  if (cleanedCount > 0) {
271
- logger.info(`Cleaned up ${cleanedCount} stale sessions. Active sessions: ${this.sessions.size}`, LOG_MODULES.SESSION_MANAGER);
833
+ logger.info(`Cleaned up ${cleanedCount} stale sessions. Active sessions: ${this.sessions.size}, Persisted states: ${this.sessionStates.size}`, LOG_MODULES.SESSION_MANAGER);
272
834
  }
273
835
  }
274
836
  }