diff --git a/src/utils/clinicalMcpClient.js b/src/utils/clinicalMcpClient.js index be30a17..12f4d75 100644 --- a/src/utils/clinicalMcpClient.js +++ b/src/utils/clinicalMcpClient.js @@ -15,6 +15,23 @@ function positiveInt(value, fallback) { return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback; } +// The MCP server builds a Nextcloud client per session and closes it only when the +// session ends. A session is replaced every time the TTL expires, so without this +// the abandoned clients hold their Nextcloud connections open in CLOSE-WAIT until +// the server runs out of file descriptors and every search fails. +// Best effort by design: the session being discarded is already unusable, so a +// failed teardown must never surface to the caller. +async function endMcpSession(session) { + if (!session || !session.sessionId) return; + try { + await axios.delete(session.mcpUrl || _lastGoodMcpUrl, { + headers: { 'Accept': 'application/json, text/event-stream', 'mcp-session-id': session.sessionId }, + timeout: MCP_INITIALIZE_TIMEOUT_MS, + validateStatus: function() { return true; } + }); + } catch (e) { /* the server reaps abandoned sessions on its own schedule */ } +} + async function semanticSearch(query, opts) { opts = opts || {}; return callMcpTool('nc_semantic_search', { @@ -72,7 +89,9 @@ async function callMcpToolUnlocked(name, args) { search = await mcpRequest(payload, session.sessionId, session.mcpUrl); } catch (e) { if (!isInvalidMcpSessionError(e)) throw e; + var rejected = _mcpSession; _mcpSession = null; + if (rejected) endMcpSession(rejected); session = await getMcpSession(); payload.id = nextMcpRequestId(); search = await mcpRequest(payload, session.sessionId, session.mcpUrl); @@ -90,8 +109,12 @@ async function getMcpSession() { var now = Date.now(); if (_mcpSession && _mcpSession.sessionId && _mcpSession.expiresAt > now) return _mcpSession; if (_mcpSessionPromise) return _mcpSessionPromise; + // Captured before the replacement lands so the expired session can be closed. + var stale = _mcpSession; + _mcpSession = null; _mcpSessionPromise = initializeMcpSession().then(function(session) { _mcpSession = session; + if (stale) endMcpSession(stale); return session; }).finally(function() { _mcpSessionPromise = null; diff --git a/test/clinical-mcp-session-lifecycle.test.js b/test/clinical-mcp-session-lifecycle.test.js new file mode 100644 index 0000000..114ce7a --- /dev/null +++ b/test/clinical-mcp-session-lifecycle.test.js @@ -0,0 +1,67 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const Module = require('node:module'); + +// The MCP server closes its Nextcloud client only when a session ends. These tests +// pin the teardown, because without it expired sessions leak sockets until the +// server exhausts its file descriptors and every clinical search fails. +function loadClientWithFakeAxios(calls) { + const axiosStub = { + post: async function(url, payload, config) { + calls.push({ method: 'POST', url, payload, headers: (config || {}).headers || {} }); + return { + status: 200, + config: { url }, + headers: { 'mcp-session-id': 'session-' + calls.filter(c => c.payload && c.payload.method === 'initialize').length }, + data: JSON.stringify({ jsonrpc: '2.0', result: { content: [] } }) + }; + }, + delete: async function(url, config) { + calls.push({ method: 'DELETE', url, headers: (config || {}).headers || {} }); + return { status: 204 }; + }, + get: async function(url) { calls.push({ method: 'GET', url }); return { status: 200, data: {} }; } + }; + + const target = require.resolve('../src/utils/clinicalMcpClient'); + delete require.cache[target]; + const original = Module._load; + Module._load = function(request, parent, isMain) { + if (request === 'axios') return axiosStub; + return original.apply(this, arguments); + }; + try { return require(target); } finally { Module._load = original; } +} + +test('an expired session is closed when it is replaced, not abandoned', async () => { + const calls = []; + process.env.CLINICAL_ASSISTANT_MCP_SESSION_TTL_MS = '1'; + const client = loadClientWithFakeAxios(calls); + + await client.semanticSearch('bronchiolitis', { limit: 4 }); + await new Promise(resolve => setTimeout(resolve, 5)); // let the 1ms TTL lapse + await client.semanticSearch('croup', { limit: 4 }); + + const deletes = calls.filter(c => c.method === 'DELETE'); + assert.equal(deletes.length, 1, 'the expired session should be deleted exactly once'); + assert.equal(deletes[0].headers['mcp-session-id'], 'session-1'); + + const initializes = calls.filter(c => c.payload && c.payload.method === 'initialize'); + assert.equal(initializes.length, 2, 'a lapsed TTL should open a fresh session'); + delete process.env.CLINICAL_ASSISTANT_MCP_SESSION_TTL_MS; +}); + +test('a live session is reused and never closed between calls', async () => { + const calls = []; + process.env.CLINICAL_ASSISTANT_MCP_SESSION_TTL_MS = String(10 * 60 * 1000); + const client = loadClientWithFakeAxios(calls); + + await client.semanticSearch('asthma', { limit: 4 }); + await client.semanticSearch('sepsis', { limit: 4 }); + + assert.equal(calls.filter(c => c.method === 'DELETE').length, 0, + 'deleting a session still in use would force a re-initialize on every search'); + assert.equal(calls.filter(c => c.payload && c.payload.method === 'initialize').length, 1); + delete process.env.CLINICAL_ASSISTANT_MCP_SESSION_TTL_MS; +});