Close MCP sessions when they are replaced
All checks were successful
Forgejo Android APK / Build signed APK (push) Successful in 1m48s

The MCP server builds a Nextcloud client per session and closes it only
when the session ends. The clinical assistant replaced its cached session
every time the ten-minute TTL lapsed but never ended the old one, so each
abandoned client held its Nextcloud connections open. The production MCP
container was holding 708 sockets in CLOSE-WAIT against a 1024 descriptor
ceiling, roughly 300 from the point where every clinical search fails.

Expired and server-rejected sessions are now deleted. Session reuse is
unchanged: a live session is still shared across calls, since closing one
still in use would force a re-initialize on every search.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Daniel 2026-08-28 23:45:26 +02:00
parent 3d4a95fea4
commit c1ba6fa798
2 changed files with 90 additions and 0 deletions

View file

@ -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;

View file

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