connection-pool-abort.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /**
  2. * Regression tests for `McpConnectionPool.callTool` abort propagation.
  3. *
  4. * The `image_synthesize` production hang was caused by the pool never
  5. * forwarding the caller's AbortSignal into the SDK's `client.callTool`, so
  6. * an in-flight remote HTTP request sat until the per-server timeout (up to
  7. * 10 min for generation tools) instead of being cancelled the moment the pi
  8. * turn aborted.
  9. *
  10. * We inject a fake `Client` via a stubbed `ResolvedMcpServer` lookup so we
  11. * can observe the exact `RequestOptions` the pool hands to
  12. * `client.callTool(...)` without spinning up any transport.
  13. */
  14. import { describe, expect, it } from 'vitest';
  15. import { McpConnectionPool } from '../src/runtime/connection-pool.js';
  16. import type {
  17. McpConnection,
  18. McpToolCallResult,
  19. McpToolInfo,
  20. ResolvedMcpServer,
  21. } from '../src/runtime/types.js';
  22. interface RecordedCall {
  23. readonly toolName: string;
  24. readonly options?: { timeout?: number; signal?: AbortSignal };
  25. }
  26. interface RecordedList {
  27. readonly options?: { timeout?: number; signal?: AbortSignal };
  28. }
  29. function seedFakeListConnection(
  30. pool: McpConnectionPool,
  31. serverName: string,
  32. behaviour: (options?: { timeout?: number; signal?: AbortSignal }) => Promise<{ tools: McpToolInfo[] }>,
  33. recorded: RecordedList[],
  34. ): void {
  35. const fakeClient = {
  36. async listTools(
  37. _params: undefined,
  38. options?: { timeout?: number; signal?: AbortSignal },
  39. ): Promise<{ tools: McpToolInfo[] }> {
  40. recorded.push({ options });
  41. return behaviour(options);
  42. },
  43. async close(): Promise<void> {},
  44. };
  45. const connection: McpConnection = {
  46. key: JSON.stringify([serverName, null]),
  47. name: serverName,
  48. state: 'connected',
  49. client: fakeClient as unknown as McpConnection['client'],
  50. transport: null,
  51. tools: null,
  52. lastUsed: Date.now(),
  53. };
  54. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  55. (pool as any).connections.set(connection.key, connection);
  56. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  57. (pool as any).connectionServerNames.set(connection.key, serverName);
  58. }
  59. /**
  60. * Wire a stub connection into the pool that captures each `callTool`'s
  61. * options. The pool normally spawns a real Client via `doConnect`; we
  62. * bypass that by pre-populating `pool.connections` and short-circuiting
  63. * `ensureConnection`, avoiding any transport dependency.
  64. */
  65. function seedFakeConnection(
  66. pool: McpConnectionPool,
  67. serverName: string,
  68. behaviour: (options?: { timeout?: number; signal?: AbortSignal }) => Promise<McpToolCallResult>,
  69. recorded: RecordedCall[],
  70. ): void {
  71. const fakeClient = {
  72. async callTool(
  73. params: { name: string; arguments: Record<string, unknown> },
  74. _resultSchema: unknown,
  75. options?: { timeout?: number; signal?: AbortSignal },
  76. ): Promise<McpToolCallResult> {
  77. recorded.push({ toolName: params.name, options });
  78. return behaviour(options);
  79. },
  80. async close(): Promise<void> {},
  81. };
  82. const connection: McpConnection = {
  83. key: JSON.stringify([serverName, null]),
  84. name: serverName,
  85. state: 'connected',
  86. client: fakeClient as unknown as McpConnection['client'],
  87. transport: null,
  88. tools: [] as McpToolInfo[],
  89. lastUsed: Date.now(),
  90. };
  91. // The pool exposes its private state through `disconnect(serverName)`
  92. // bookkeeping and `getStats`; we set the connection directly here.
  93. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  94. (pool as any).connections.set(connection.key, connection);
  95. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  96. (pool as any).connectionServerNames.set(connection.key, serverName);
  97. }
  98. function stubLookup(server: ResolvedMcpServer): { getResolvedServer: () => ResolvedMcpServer } {
  99. return { getResolvedServer: () => server };
  100. }
  101. describe('McpConnectionPool.listTools — abort propagation', () => {
  102. it('forwards the caller signal and releases the permit when tools/list aborts', async () => {
  103. const server: ResolvedMcpServer = {
  104. name: 'broken',
  105. enabled: true,
  106. transport: { type: 'http', url: 'https://example.com/mcp' },
  107. timeout: 60_000,
  108. };
  109. const pool = new McpConnectionPool(stubLookup(server), { maxConcurrency: 1 });
  110. const recorded: RecordedList[] = [];
  111. seedFakeListConnection(
  112. pool,
  113. 'broken',
  114. (options) =>
  115. new Promise<{ tools: McpToolInfo[] }>((_resolve, reject) => {
  116. const signal = options?.signal;
  117. if (signal?.aborted) {
  118. reject(new Error('Request aborted'));
  119. return;
  120. }
  121. signal?.addEventListener('abort', () => reject(new Error('Request aborted')), {
  122. once: true,
  123. });
  124. }),
  125. recorded,
  126. );
  127. const controller = new AbortController();
  128. const discovery = pool.listTools('broken', undefined, {
  129. signal: controller.signal,
  130. timeout: 60_000,
  131. });
  132. await Promise.resolve();
  133. expect(pool.getStats('broken').active).toBe(1);
  134. controller.abort();
  135. await expect(discovery).rejects.toThrow(/Request aborted/);
  136. expect(recorded[0]?.options?.signal).toBe(controller.signal);
  137. expect(recorded[0]?.options?.timeout).toBe(60_000);
  138. expect(pool.getStats('broken')).toMatchObject({ active: 0, pending: 0 });
  139. await pool.shutdown();
  140. });
  141. it('removes an aborted discovery waiter from the semaphore queue', async () => {
  142. const server: ResolvedMcpServer = {
  143. name: 'broken',
  144. enabled: true,
  145. transport: { type: 'http', url: 'https://example.com/mcp' },
  146. timeout: 60_000,
  147. };
  148. const pool = new McpConnectionPool(stubLookup(server), { maxConcurrency: 1 });
  149. const recorded: RecordedList[] = [];
  150. let releaseHead: (() => void) | undefined;
  151. seedFakeListConnection(
  152. pool,
  153. 'broken',
  154. () =>
  155. new Promise<{ tools: McpToolInfo[] }>((resolve) => {
  156. releaseHead = () => resolve({ tools: [] });
  157. }),
  158. recorded,
  159. );
  160. const head = pool.listTools('broken', undefined, { timeout: 60_000 });
  161. await Promise.resolve();
  162. await Promise.resolve();
  163. expect(pool.getStats('broken').active).toBe(1);
  164. const controller = new AbortController();
  165. const queued = pool.listTools('broken', undefined, {
  166. signal: controller.signal,
  167. timeout: 60_000,
  168. });
  169. await Promise.resolve();
  170. await Promise.resolve();
  171. expect(pool.getStats('broken').pending).toBe(1);
  172. controller.abort();
  173. await expect(queued).rejects.toThrow(/aborted before dispatch/);
  174. expect(pool.getStats('broken')).toMatchObject({ active: 1, pending: 0 });
  175. expect(recorded).toHaveLength(1);
  176. releaseHead?.();
  177. await head;
  178. expect(pool.getStats('broken')).toMatchObject({ active: 0, pending: 0 });
  179. await pool.shutdown();
  180. });
  181. it('aborts an in-flight connect during disconnect and rejects its waiter promptly', async () => {
  182. const server: ResolvedMcpServer = {
  183. name: 'broken',
  184. enabled: true,
  185. transport: { type: 'http', url: 'https://example.com/mcp' },
  186. };
  187. const pool = new McpConnectionPool(stubLookup(server));
  188. let connectSignal: AbortSignal | undefined;
  189. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  190. (pool as any).doConnect = async (
  191. _serverName: string,
  192. _connectionKey: string,
  193. _overrides: unknown,
  194. _timeoutMs: number,
  195. signal: AbortSignal,
  196. ) => {
  197. connectSignal = signal;
  198. return new Promise<McpConnection>((_resolve, reject) => {
  199. signal.addEventListener('abort', () => reject(new Error('connect aborted')), { once: true });
  200. });
  201. };
  202. const discovery = pool.listTools('broken');
  203. await Promise.resolve();
  204. await Promise.resolve();
  205. expect(connectSignal?.aborted).toBe(false);
  206. await pool.disconnect('broken');
  207. expect(connectSignal?.aborted).toBe(true);
  208. await expect(discovery).rejects.toThrow(/connect aborted/);
  209. expect(pool.getStats('broken')).toMatchObject({ active: 0, pending: 0 });
  210. });
  211. it('does not let a stale connect cleanup remove a newer pending connect', async () => {
  212. const server: ResolvedMcpServer = {
  213. name: 'broken',
  214. enabled: true,
  215. transport: { type: 'http', url: 'https://example.com/mcp' },
  216. };
  217. const pool = new McpConnectionPool(stubLookup(server), { maxConcurrency: 2 });
  218. const attempts: Array<{
  219. resolve: (connection: McpConnection) => void;
  220. reject: (error: Error) => void;
  221. }> = [];
  222. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  223. (pool as any).doConnect = async () =>
  224. new Promise<McpConnection>((resolve, reject) => {
  225. attempts.push({ resolve, reject });
  226. });
  227. const first = pool.listTools('broken');
  228. await Promise.resolve();
  229. await Promise.resolve();
  230. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  231. const firstPending = (pool as any).connectingPromises.get(JSON.stringify(['broken', null]));
  232. expect(firstPending).toBeDefined();
  233. await pool.disconnect('broken');
  234. const secondController = new AbortController();
  235. const second = pool.listTools('broken', undefined, { signal: secondController.signal });
  236. await Promise.resolve();
  237. await Promise.resolve();
  238. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  239. const secondPending = (pool as any).connectingPromises.get(JSON.stringify(['broken', null]));
  240. expect(secondPending).toBeDefined();
  241. expect(secondPending).not.toBe(firstPending);
  242. attempts[0]?.reject(new Error('stale connect failed'));
  243. await expect(first).rejects.toThrow(/stale connect failed/);
  244. await Promise.resolve();
  245. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  246. expect((pool as any).connectingPromises.get(JSON.stringify(['broken', null]))).toBe(secondPending);
  247. secondController.abort();
  248. await expect(second).rejects.toThrow(/connection wait aborted/);
  249. });
  250. });
  251. describe('McpConnectionPool.callTool — abort propagation', () => {
  252. it('forwards options.signal to client.callTool', async () => {
  253. const server: ResolvedMcpServer = {
  254. name: 'matrix',
  255. enabled: true,
  256. transport: { type: 'http', url: 'https://example.com/mcp' },
  257. };
  258. const pool = new McpConnectionPool(stubLookup(server));
  259. const recorded: RecordedCall[] = [];
  260. seedFakeConnection(
  261. pool,
  262. 'matrix',
  263. async () => ({ content: [{ type: 'text', text: 'ok' }] }),
  264. recorded,
  265. );
  266. const controller = new AbortController();
  267. await pool.callTool('matrix', 'image_synthesize', { prompt: 'x' }, undefined, {
  268. signal: controller.signal,
  269. timeout: 5_000,
  270. });
  271. expect(recorded).toHaveLength(1);
  272. expect(recorded[0]?.options?.signal).toBe(controller.signal);
  273. expect(recorded[0]?.options?.timeout).toBe(5_000);
  274. await pool.shutdown();
  275. });
  276. it('aborts an in-flight call synchronously instead of waiting for timeout', async () => {
  277. const server: ResolvedMcpServer = {
  278. name: 'matrix',
  279. enabled: true,
  280. transport: { type: 'http', url: 'https://example.com/mcp' },
  281. // Very generous timeout — we should NOT wait for it when the signal fires.
  282. timeout: 60_000,
  283. };
  284. const pool = new McpConnectionPool(stubLookup(server));
  285. const recorded: RecordedCall[] = [];
  286. // Fake client mirrors the SDK behaviour: reject when the signal aborts.
  287. seedFakeConnection(
  288. pool,
  289. 'matrix',
  290. (options) =>
  291. new Promise<McpToolCallResult>((_resolve, reject) => {
  292. const signal = options?.signal;
  293. if (!signal) {
  294. setTimeout(
  295. () => reject(new Error('never got signal (pool should have forwarded it)')),
  296. 10_000,
  297. );
  298. return;
  299. }
  300. if (signal.aborted) {
  301. reject(new Error('Request aborted'));
  302. return;
  303. }
  304. signal.addEventListener('abort', () => reject(new Error('Request aborted')), {
  305. once: true,
  306. });
  307. }),
  308. recorded,
  309. );
  310. const controller = new AbortController();
  311. const start = Date.now();
  312. const call = pool.callTool('matrix', 'image_synthesize', { prompt: 'a cat' }, undefined, {
  313. signal: controller.signal,
  314. timeout: 60_000,
  315. });
  316. queueMicrotask(() => controller.abort());
  317. await expect(call).rejects.toThrow(/MCP tool call failed: Request aborted/);
  318. const elapsed = Date.now() - start;
  319. expect(elapsed).toBeLessThan(1_000);
  320. await pool.shutdown();
  321. });
  322. it('short-circuits when the signal is already aborted', async () => {
  323. const server: ResolvedMcpServer = {
  324. name: 'matrix',
  325. enabled: true,
  326. transport: { type: 'http', url: 'https://example.com/mcp' },
  327. };
  328. const pool = new McpConnectionPool(stubLookup(server));
  329. const recorded: RecordedCall[] = [];
  330. seedFakeConnection(
  331. pool,
  332. 'matrix',
  333. async () => ({ content: [{ type: 'text', text: 'should-not-run' }] }),
  334. recorded,
  335. );
  336. const controller = new AbortController();
  337. controller.abort();
  338. await expect(
  339. pool.callTool('matrix', 'image_synthesize', { prompt: 'x' }, undefined, {
  340. signal: controller.signal,
  341. }),
  342. ).rejects.toThrow(/aborted before dispatch/);
  343. // Never dispatched — nothing recorded.
  344. expect(recorded).toEqual([]);
  345. await pool.shutdown();
  346. });
  347. it('aborts a caller queued behind an in-flight call without waiting for the head to release', async () => {
  348. // Reviewer P1 regression: the two `signal.aborted` checks around
  349. // `sem.acquire()` (before/after) do not cover a caller that aborts
  350. // WHILE queued on the semaphore. Before this fix, `Semaphore.acquire`
  351. // was a bare `new Promise((resolve) => queue.push(resolve))` with no
  352. // abort hook — the queued caller had to wait for the in-flight
  353. // long-running call to release the permit, at which point the
  354. // post-acquire check would fire. For a `image_synthesize` head call
  355. // that meant the aborted follow-up sat for the full generation window.
  356. // We now hand the signal to `Semaphore.acquire`, which splices the
  357. // waiter out of the queue on abort and rejects immediately.
  358. const server: ResolvedMcpServer = {
  359. name: 'matrix',
  360. enabled: true,
  361. transport: { type: 'http', url: 'https://example.com/mcp' },
  362. timeout: 60_000,
  363. };
  364. const pool = new McpConnectionPool(stubLookup(server), { maxConcurrency: 1 });
  365. const recorded: RecordedCall[] = [];
  366. // Head call never resolves on its own — we release it manually at the
  367. // end of the test. This proves the queued caller returns BEFORE the
  368. // head does.
  369. let releaseHead: (() => void) | undefined;
  370. const headStarted = new Promise<void>((resolveStarted) => {
  371. seedFakeConnection(
  372. pool,
  373. 'matrix',
  374. () => {
  375. resolveStarted();
  376. return new Promise<McpToolCallResult>((resolveHead) => {
  377. releaseHead = () => resolveHead({ content: [{ type: 'text', text: 'head-done' }] });
  378. });
  379. },
  380. recorded,
  381. );
  382. });
  383. // Fire the head call so it takes the sole permit and blocks the queue.
  384. const headController = new AbortController();
  385. const headPromise = pool.callTool('matrix', 'image_synthesize', { prompt: 'head' }, undefined, {
  386. signal: headController.signal,
  387. timeout: 60_000,
  388. });
  389. await headStarted;
  390. expect(pool.getStats('matrix').active).toBe(1);
  391. // Queue a second caller. Its acquire() sits in the queue behind the head.
  392. const followController = new AbortController();
  393. const followStarted = Date.now();
  394. const followPromise = pool.callTool(
  395. 'matrix',
  396. 'image_synthesize',
  397. { prompt: 'follow' },
  398. undefined,
  399. { signal: followController.signal, timeout: 60_000 },
  400. );
  401. // Yield twice so the follow-up definitely reaches the semaphore's queue.
  402. await Promise.resolve();
  403. await Promise.resolve();
  404. expect(pool.getStats('matrix').pending).toBe(1);
  405. // Abort the queued follow-up. It must reject sub-second — long before
  406. // we release the head call — and without ever dispatching to the
  407. // fake client.
  408. followController.abort();
  409. await expect(followPromise).rejects.toThrow(/aborted before dispatch/);
  410. const followElapsed = Date.now() - followStarted;
  411. expect(followElapsed).toBeLessThan(1_000);
  412. // Only the head reached the client; the queued caller was spliced out
  413. // of the semaphore queue before ever dispatching.
  414. expect(recorded).toHaveLength(1);
  415. expect(recorded[0]?.toolName).toBe('image_synthesize');
  416. // The abort must not have leaked a `running` permit. After the aborted
  417. // waiter is spliced out, `pending` returns to 0 and `active` stays at
  418. // 1 (the head still holds its permit).
  419. expect(pool.getStats('matrix').pending).toBe(0);
  420. expect(pool.getStats('matrix').active).toBe(1);
  421. // Release the head and drain its promise so shutdown() is clean.
  422. releaseHead?.();
  423. await headPromise;
  424. expect(pool.getStats('matrix').active).toBe(0);
  425. await pool.shutdown();
  426. });
  427. it('does not leak a semaphore permit when a queued waiter aborts', async () => {
  428. // Follow-up guard for the fix above: after an aborted waiter is
  429. // spliced out of the queue, subsequent non-aborted callers must still
  430. // be able to acquire the permit exactly `maxConcurrency` at a time.
  431. // A naïve `Promise.race([acquire, abortEvent])` implementation would
  432. // leave the aborted waiter in the queue; `release()` would then hand
  433. // it a permit and bump `running` for no live consumer — silently
  434. // starving future callers by one slot per abort.
  435. const server: ResolvedMcpServer = {
  436. name: 'matrix',
  437. enabled: true,
  438. transport: { type: 'http', url: 'https://example.com/mcp' },
  439. };
  440. const pool = new McpConnectionPool(stubLookup(server), { maxConcurrency: 1 });
  441. const recorded: RecordedCall[] = [];
  442. let releaseHead: (() => void) | undefined;
  443. const headStarted = new Promise<void>((resolveStarted) => {
  444. seedFakeConnection(
  445. pool,
  446. 'matrix',
  447. () => {
  448. resolveStarted();
  449. return new Promise<McpToolCallResult>((resolveHead) => {
  450. releaseHead = () => resolveHead({ content: [{ type: 'text', text: 'ok' }] });
  451. });
  452. },
  453. recorded,
  454. );
  455. });
  456. const headPromise = pool.callTool('matrix', 't', {}, undefined, { timeout: 60_000 });
  457. await headStarted;
  458. // Queue an aborted follow-up.
  459. const abortController = new AbortController();
  460. const abortedPromise = pool.callTool('matrix', 't', {}, undefined, {
  461. signal: abortController.signal,
  462. timeout: 60_000,
  463. });
  464. await Promise.resolve();
  465. await Promise.resolve();
  466. expect(pool.getStats('matrix').pending).toBe(1);
  467. abortController.abort();
  468. await expect(abortedPromise).rejects.toThrow(/aborted before dispatch/);
  469. expect(pool.getStats('matrix').pending).toBe(0);
  470. // Release the head. A leak would have `release()` hand the permit to
  471. // the ghost waiter and bump `running` to 2; the semaphore would then
  472. // starve. The healthy behaviour is `active` drops back to 0.
  473. releaseHead?.();
  474. await headPromise;
  475. expect(pool.getStats('matrix').active).toBe(0);
  476. // A brand-new caller must be admitted without waiting on a phantom
  477. // permit. If the previous abort had leaked, this call would sit in
  478. // the queue instead of running immediately.
  479. let secondReleased: (() => void) | undefined;
  480. seedFakeConnection(
  481. pool,
  482. 'matrix',
  483. () =>
  484. new Promise<McpToolCallResult>((resolveSecond) => {
  485. secondReleased = () => resolveSecond({ content: [{ type: 'text', text: 'second' }] });
  486. }),
  487. recorded,
  488. );
  489. const secondPromise = pool.callTool('matrix', 't', {}, undefined, { timeout: 60_000 });
  490. await Promise.resolve();
  491. await Promise.resolve();
  492. expect(pool.getStats('matrix').active).toBe(1);
  493. expect(pool.getStats('matrix').pending).toBe(0);
  494. secondReleased?.();
  495. await secondPromise;
  496. await pool.shutdown();
  497. });
  498. });