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; });