// Library searches run a few at a time rather than one behind another, and // the session is renewed before it expires. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const src = fs.readFileSync(path.join(__dirname, '..', 'src/utils/clinicalMcpClient.js'), 'utf8'); test('a bounded number of calls run at once; the rest wait their turn', async () => { // The slot logic on its own, with the environment's default bound. const slice = src.slice(src.indexOf('function acquireSlot'), src.indexOf('async function callMcpTool')); const fn = new Function('MCP_CONCURRENCY', 'var _inFlight = 0, _waiting = [];' + slice + '; return { acquireSlot, releaseSlot, count: () => _inFlight, waiting: () => _waiting.length };')(3); await fn.acquireSlot(); await fn.acquireSlot(); await fn.acquireSlot(); assert.equal(fn.count(), 3); let fourthStarted = false; const fourth = fn.acquireSlot().then(() => { fourthStarted = true; }); await new Promise(r => setTimeout(r, 5)); assert.equal(fourthStarted, false, 'the fourth waits'); assert.equal(fn.waiting(), 1); fn.releaseSlot(); await fourth; assert.equal(fourthStarted, true, 'and runs when a slot frees'); assert.equal(fn.count(), 3, 'the slot passed hands rather than being freed'); fn.releaseSlot(); fn.releaseSlot(); fn.releaseSlot(); assert.equal(fn.count(), 0); }); test('the serial promise chain is gone, the session is kept warm, and the split is logged', () => { assert.doesNotMatch(src, /_mcpCallQueue = queued\.catch/, 'no more one-at-a-time chain'); assert.match(src, /var MCP_CONCURRENCY = positiveInt\(process\.env\.CLINICAL_ASSISTANT_MCP_CONCURRENCY, 3\)/); assert.match(src, /setInterval\(function\(\) \{[\s\S]*?getMcpSession\(\)\.catch/, 'renewed on a timer'); assert.match(src, /_warmTimer\.unref/, 'the timer never keeps the process alive'); assert.match(src, /mcp ' \+ name \+ ': session=' \+ sessionMs \+ 'ms total='/); });