Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import type { MCPClient } from '../../src/client'
3import type { MCPClients } from '../../src/pool'
4import type { TransportConfig } from '../../src/transport'
5
6const callToolMock = vi.fn(async () => ({
7 content: [{ type: 'text', text: 'ok' }],
8}))
9const closeMock = vi.fn(async () => {})
10
11// tools() returns ServerTool-like objects: at least `name` and optionally
12// `metadata.mcp.serverToolName` (the UNPREFIXED server-native tool name).
13type MockTool = {
14 name: string
15 needsApproval?: boolean
16 metadata?: { mcp?: { serverToolName?: string } }
17}
18// Per-test variable so individual tests can override the exposed tool list.
19let mockToolsList: Array<MockTool> = [{ name: 'place_order' }]
20
21vi.mock('../../src/client', () => ({
22 createMCPClient: vi.fn(async () => ({
23 tools: async () => mockToolsList,
24 callTool: callToolMock,
25 close: closeMock,
26 })),
27}))
28
29import { createMcpAppCallHandler } from '../../src/apps/call-handler'
30import { createMCPClient } from '../../src/client'
31import { inMemoryMcpSessionStore } from '../../src/apps/session-store'
32
33type TransportDescriptor = TransportConfig
34type ServerInfo = {
35 transport: TransportDescriptor | undefined
36 prefix: string | undefined
37 toolFilter?: (tool: { name: string }) => boolean
38 needsApproval?: (tool: { name: string }) => boolean
39 toolName?: (tool: { name: string }) => string
40 requestOptions?: { timeout?: number; resetTimeoutOnProgress?: boolean }
41}
42
43// A method the call handler must never reach in these tests. Calling it is a
44// test bug, so it fails loudly instead of silently returning undefined.
45function unreached(method: string) {
46 return vi.fn(() => {
47 throw new Error(`unexpected call to ${method}() in call-handler test`)
48 })
49}
50
51// Fake pool. The handler only reads `getServers` from a pool (detected
52// structurally via `'getServers' in entry`); the remaining members are present
53// so the object genuinely satisfies MCPClients — no cast needed — but throw if
54// ever exercised.
55function fakePool(servers: Record<string, ServerInfo>): MCPClients {
56 return {
57 clients: {},
58 tools: unreached('tools'),
59 readResource: unreached('readResource'),
60 getServers: () => servers,
61 close: unreached('close'),
62 [Symbol.asyncDispose]: unreached('asyncDispose'),
63 }
64}
65
66// Fake single client. The handler only reads `getInfo`; the rest are real
67// members that throw if reached.
68function fakeClient(info: ServerInfo): MCPClient {
69 return {
70 capabilities: {},
71 tools: unreached('tools'),
72 resources: unreached('resources'),
73 readResource: unreached('readResource'),
74 resourceTemplates: unreached('resourceTemplates'),
75 prompts: unreached('prompts'),
76 getPrompt: unreached('getPrompt'),
77 callTool: unreached('callTool'),
78 request: unreached('request'),
79 getInfo: () => info,
80 close: unreached('close'),
81 [Symbol.asyncDispose]: unreached('asyncDispose'),
82 }
83}
84
85const WEATHER_HTTP: ServerInfo = {
86 transport: { type: 'http', url: 'https://x/mcp' },
87 prefix: 'weather',
88}
89
90// The most common fixture: a handler over a single-server `weather` pool.
91// `extra` threads through store/allowTool for the tests that need them.
92function weatherPoolHandler(
93 extra: Partial<Parameters<typeof createMcpAppCallHandler>[0]> = {},
94) {
95 return createMcpAppCallHandler({
96 clients: fakePool({ weather: WEATHER_HTTP }),
97 ...extra,
98 })
99}
100
101describe('createMcpAppCallHandler', () => {
102 beforeEach(() => {
103 // Reset module-level mocks so tests don't depend on file order.
104 callToolMock.mockClear()
105 closeMock.mockClear()
106 vi.mocked(createMCPClient).mockClear()
107 mockToolsList = [{ name: 'place_order' }]
108 })
109
110 it('pool path: reconnects, enforces native-name allowlist, calls the tool, and closes', async () => {
111 const handler = weatherPoolHandler()
112 const res = await handler({
113 threadId: 't1',
114 serverId: 'weather',
115 toolName: 'place_order',
116 args: { qty: 1 },
117 })
118 expect(res).toEqual({ ok: true, result: expect.anything() })
119 expect(createMCPClient).toHaveBeenCalledWith({
120 transport: { type: 'http', url: 'https://x/mcp' },
121 prefix: 'weather',
122 })
123 expect(callToolMock).toHaveBeenCalledWith('place_order', { qty: 1 })
124 expect(closeMock).toHaveBeenCalled()
125 })
126
127 it('reconnects with the client toolFilter so widgets see the same tools as the model', async () => {
128 const toolFilter = (tool: { name: string }) => tool.name !== 'place_order'
129 const handler = createMcpAppCallHandler({
130 clients: fakePool({ weather: { ...WEATHER_HTTP, toolFilter } }),
131 })
132 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
133 expect(createMCPClient).toHaveBeenCalledWith({
134 transport: { type: 'http', url: 'https://x/mcp' },
135 prefix: 'weather',
136 toolFilter,
137 })
138 })
139
140 it('keeps the client toolFilter when a store returns a descriptor without it', async () => {
141 // A persistent store serializes descriptors, and a function does not survive that.
142 const toolFilter = (tool: { name: string }) => tool.name !== 'place_order'
143 const store = inMemoryMcpSessionStore()
144 await store.set('t1', { weather: JSON.parse(JSON.stringify(WEATHER_HTTP)) })
145 const handler = createMcpAppCallHandler({
146 clients: fakePool({ weather: { ...WEATHER_HTTP, toolFilter } }),
147 store,
148 })
149 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
150 expect(createMCPClient).toHaveBeenCalledWith({
151 transport: { type: 'http', url: 'https://x/mcp' },
152 prefix: 'weather',
153 toolFilter,
154 })
155 })
156
157 it('rejects a tool that the client needsApproval marks, without calling callTool', async () => {
158 // A widget call has no approval step, so it must not run a tool that the
159 // model can run only after approval.
160 const needsApproval = (tool: { name: string }) =>
161 tool.name === 'place_order'
162 mockToolsList = [{ name: 'place_order', needsApproval: true }]
163 const handler = createMcpAppCallHandler({
164 clients: fakePool({ weather: { ...WEATHER_HTTP, needsApproval } }),
165 })
166 const res = await handler({
167 threadId: 't1',
168 serverId: 'weather',
169 toolName: 'place_order',
170 })
171 expect(res).toEqual({
172 ok: false,
173 error: 'Tool needs approval: place_order',
174 })
175 expect(createMCPClient).toHaveBeenCalledWith({
176 transport: { type: 'http', url: 'https://x/mcp' },
177 prefix: 'weather',
178 needsApproval,
179 })
180 expect(callToolMock).not.toHaveBeenCalled()
181 })
182
183 it('keeps the client needsApproval when a store returns a descriptor without it', async () => {
184 const needsApproval = (tool: { name: string }) =>
185 tool.name === 'place_order'
186 const store = inMemoryMcpSessionStore()
187 await store.set('t1', { weather: JSON.parse(JSON.stringify(WEATHER_HTTP)) })
188 const handler = createMcpAppCallHandler({
189 clients: fakePool({ weather: { ...WEATHER_HTTP, needsApproval } }),
190 store,
191 })
192 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
193 expect(createMCPClient).toHaveBeenCalledWith({
194 transport: { type: 'http', url: 'https://x/mcp' },
195 prefix: 'weather',
196 needsApproval,
197 })
198 })
199
200 it('reconnects with the client toolName', async () => {
201 const toolName = (tool: { name: string }) => `mcp__weather__${tool.name}`
202 const handler = createMcpAppCallHandler({
203 clients: fakePool({ weather: { ...WEATHER_HTTP, toolName } }),
204 })
205 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
206 expect(createMCPClient).toHaveBeenCalledWith({
207 transport: { type: 'http', url: 'https://x/mcp' },
208 prefix: 'weather',
209 toolName,
210 })
211 })
212
213 it('keeps the client toolName when a store returns a descriptor without it', async () => {
214 const toolName = (tool: { name: string }) => `mcp__weather__${tool.name}`
215 const store = inMemoryMcpSessionStore()
216 await store.set('t1', { weather: JSON.parse(JSON.stringify(WEATHER_HTTP)) })
217 const handler = createMcpAppCallHandler({
218 clients: fakePool({ weather: { ...WEATHER_HTTP, toolName } }),
219 store,
220 })
221 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
222 expect(createMCPClient).toHaveBeenCalledWith({
223 transport: { type: 'http', url: 'https://x/mcp' },
224 prefix: 'weather',
225 toolName,
226 })
227 })
228
229 it('reconnects with the client requestOptions', async () => {
230 const requestOptions = { timeout: 5000 }
231 const handler = createMcpAppCallHandler({
232 clients: fakePool({ weather: { ...WEATHER_HTTP, requestOptions } }),
233 })
234 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
235 expect(createMCPClient).toHaveBeenCalledWith({
236 transport: { type: 'http', url: 'https://x/mcp' },
237 prefix: 'weather',
238 requestOptions,
239 })
240 })
241
242 it('keeps the client requestOptions when a store returns a descriptor without them', async () => {
243 const requestOptions = { timeout: 5000 }
244 const store = inMemoryMcpSessionStore()
245 await store.set('t1', { weather: JSON.parse(JSON.stringify(WEATHER_HTTP)) })
246 const handler = createMcpAppCallHandler({
247 clients: fakePool({ weather: { ...WEATHER_HTTP, requestOptions } }),
248 store,
249 })
250 await handler({ threadId: 't1', serverId: 'weather', toolName: 'x' })
251 expect(createMCPClient).toHaveBeenCalledWith({
252 transport: { type: 'http', url: 'https://x/mcp' },
253 prefix: 'weather',
254 requestOptions,
255 })
256 })
257
258 it('single-client path: defaults to the sole unnamed client when serverId is undefined', async () => {
259 const handler = createMcpAppCallHandler({
260 clients: fakeClient({
261 transport: { type: 'http', url: 'https://x/mcp' },
262 prefix: undefined,
263 }),
264 })
265 const res = await handler({
266 threadId: 't1',
267 toolName: 'place_order',
268 })
269 expect(res).toEqual({ ok: true, result: expect.anything() })
270 expect(callToolMock).toHaveBeenCalledWith('place_order', {})
271 expect(closeMock).toHaveBeenCalled()
272 })
273
274 it('array-of-clients: merges a pool and a single client into one registry', async () => {
275 const handler = createMcpAppCallHandler({
276 clients: [
277 fakePool({
278 weather: {
279 transport: { type: 'http', url: 'https://weather/mcp' },
280 prefix: 'weather',
281 },
282 }),
283 fakeClient({
284 transport: { type: 'http', url: 'https://orders/mcp' },
285 prefix: 'orders',
286 }),
287 ],
288 })
289
290 const viaPool = await handler({
291 threadId: 't1',
292 serverId: 'weather',
293 toolName: 'place_order',
294 })
295 expect(viaPool).toEqual({ ok: true, result: expect.anything() })
296
297 const viaClient = await handler({
298 threadId: 't1',
299 serverId: 'orders',
300 toolName: 'place_order',
301 })
302 expect(viaClient).toEqual({ ok: true, result: expect.anything() })
303
304 expect(createMCPClient).toHaveBeenCalledWith({
305 transport: { type: 'http', url: 'https://weather/mcp' },
306 prefix: 'weather',
307 })
308 expect(createMCPClient).toHaveBeenCalledWith({
309 transport: { type: 'http', url: 'https://orders/mcp' },
310 prefix: 'orders',
311 })
312 })
313
314 it('rejects a tool the server does not expose (allowlist) without calling callTool', async () => {
315 // Server only exposes 'place_order' (the beforeEach default), not
316 // 'delete_everything'.
317 const handler = weatherPoolHandler()
318 const res = await handler({
319 threadId: 't1',
320 serverId: 'weather',
321 toolName: 'delete_everything',
322 })
323 expect(res).toEqual({
324 ok: false,
325 error: expect.stringContaining('not allowed'),
326 })
327 // The disallowed tool must NOT be forwarded to the server...
328 expect(callToolMock).not.toHaveBeenCalled()
329 // ...but the client must still be closed in finally.
330 expect(closeMock).toHaveBeenCalled()
331 })
332
333 it('matches the UNPREFIXED native name and forwards it UNCHANGED to callTool', async () => {
334 // prefix `github`, native tool `github_search`: the widget sends the native
335 // name, which must match and be forwarded VERBATIM (no prefix-strip).
336 mockToolsList = [
337 {
338 name: 'github_github_search',
339 metadata: { mcp: { serverToolName: 'github_search' } },
340 },
341 ]
342
343 const handler = createMcpAppCallHandler({
344 clients: fakePool({
345 github: {
346 transport: { type: 'http', url: 'https://x/mcp' },
347 prefix: 'github',
348 },
349 }),
350 })
351 const res = await handler({
352 threadId: 't1',
353 serverId: 'github',
354 toolName: 'github_search',
355 })
356 expect(res).toEqual({ ok: true, result: expect.anything() })
357 expect(callToolMock).toHaveBeenCalledWith('github_search', {})
358 })
359
360 it('pool entry keyed by its prefix (≠ config key): widget serverId = prefix resolves and reconnects with that prefix', async () => {
361 // The config key is `wx` but the server's prefix is `weather`. The widget
362 // sends `serverId: weather` (the prefix), so the registry must key by the
363 // prefix, NOT the config key.
364 const handler = createMcpAppCallHandler({
365 clients: fakePool({
366 wx: {
367 transport: { type: 'http', url: 'https://x/mcp' },
368 prefix: 'weather',
369 },
370 }),
371 })
372 const res = await handler({
373 threadId: 't1',
374 serverId: 'weather',
375 toolName: 'place_order',
376 })
377 expect(res).toEqual({ ok: true, result: expect.anything() })
378 expect(createMCPClient).toHaveBeenCalledWith({
379 transport: { type: 'http', url: 'https://x/mcp' },
380 prefix: 'weather',
381 })
382 // The config key must NOT resolve, since the widget never sees it.
383 expect(createMCPClient).not.toHaveBeenCalledWith(
384 expect.objectContaining({ prefix: 'wx' }),
385 )
386 })
387
388 it('throws at construction when two entries resolve to the same prefix', async () => {
389 expect(() =>
390 createMcpAppCallHandler({
391 clients: [
392 fakePool({
393 a: {
394 transport: { type: 'http', url: 'https://a/mcp' },
395 prefix: 'dup',
396 },
397 }),
398 fakeClient({
399 transport: { type: 'http', url: 'https://b/mcp' },
400 prefix: 'dup',
401 }),
402 ],
403 }),
404 ).toThrow(/duplicate serverId "dup"/)
405 })
406
407 it('throws at construction when more than one entry has no prefix', async () => {
408 expect(() =>
409 createMcpAppCallHandler({
410 clients: [
411 fakeClient({
412 transport: { type: 'http', url: 'https://a/mcp' },
413 prefix: undefined,
414 }),
415 fakeClient({
416 transport: { type: 'http', url: 'https://b/mcp' },
417 prefix: '',
418 }),
419 ],
420 }),
421 ).toThrow(/multiple clients without a prefix/)
422 })
423
424 it('falls back to the clients registry when the store returns null (store wins only when present)', async () => {
425 // The store has no entry for this thread, so get() returns null. The
426 // handler must fall back to the `clients` registry rather than rejecting.
427 const store = inMemoryMcpSessionStore()
428 const handler = weatherPoolHandler({ store })
429 const res = await handler({
430 threadId: 't-unknown',
431 serverId: 'weather',
432 toolName: 'place_order',
433 })
434 expect(res).toEqual({ ok: true, result: expect.anything() })
435 // Reconnected from the registry's descriptor, not the (empty) store.
436 expect(createMCPClient).toHaveBeenCalledWith({
437 transport: { type: 'http', url: 'https://x/mcp' },
438 prefix: 'weather',
439 })
440 })
441
442 it('rejects an unknown serverId without connecting', async () => {
443 const handler = createMcpAppCallHandler({ clients: fakePool({}) })
444 const res = await handler({
445 threadId: 't1',
446 serverId: 'ghost',
447 toolName: 'x',
448 })
449 expect(res).toEqual({
450 ok: false,
451 error: expect.stringContaining('serverId'),
452 })
453 // createMCPClient must NOT have been called (no connection for unknown server)
454 expect(createMCPClient).not.toHaveBeenCalled()
455 })
456
457 it('resolves the descriptor via the store (store wins over clients)', async () => {
458 const store = inMemoryMcpSessionStore()
459 await store.set('t1', {
460 weather: { transport: { type: 'http', url: 'https://store/mcp' } },
461 })
462
463 // The pool's transport (https://x/mcp) differs from the store's, proving
464 // the store wins.
465 const handler = weatherPoolHandler({ store })
466 const res = await handler({
467 threadId: 't1',
468 serverId: 'weather',
469 toolName: 'place_order',
470 })
471 expect(res).toEqual({ ok: true, result: expect.anything() })
472 expect(createMCPClient).toHaveBeenCalledWith({
473 transport: { type: 'http', url: 'https://store/mcp' },
474 prefix: undefined,
475 })
476 expect(callToolMock).toHaveBeenCalledWith('place_order', {})
477 })
478
479 it('rejects when a custom allowTool returns false (without calling callTool)', async () => {
480 const handler = weatherPoolHandler({ allowTool: () => false })
481 const res = await handler({
482 threadId: 't1',
483 serverId: 'weather',
484 toolName: 'place_order',
485 })
486 expect(res).toEqual({
487 ok: false,
488 error: expect.stringContaining('not allowed'),
489 })
490 expect(callToolMock).not.toHaveBeenCalled()
491 })
492
493 it('rejects a malformed args payload instead of coercing it to {}', async () => {
494 const handler = weatherPoolHandler()
495 const res = await handler({
496 threadId: 't1',
497 serverId: 'weather',
498 toolName: 'place_order',
499 args: [1, 2, 3],
500 })
501 expect(res).toEqual({
502 ok: false,
503 error: expect.stringContaining('Invalid args'),
504 })
505 expect(callToolMock).not.toHaveBeenCalled()
506 // The client is still opened (allowlist check) but closed in finally.
507 expect(closeMock).toHaveBeenCalled()
508 })
509
510 it('treats absent args as an empty object', async () => {
511 const handler = weatherPoolHandler()
512 const res = await handler({
513 threadId: 't1',
514 serverId: 'weather',
515 toolName: 'place_order',
516 })
517 expect(res).toEqual({ ok: true, result: expect.anything() })
518 expect(callToolMock).toHaveBeenCalledWith('place_order', {})
519 })
520
521 it('rejects a client whose descriptor has no reconnectable transport', async () => {
522 const handler = createMcpAppCallHandler({
523 // Built from a raw Transport: getInfo().transport is undefined.
524 clients: fakeClient({ transport: undefined, prefix: undefined }),
525 })
526 const res = await handler({
527 threadId: 't1',
528 toolName: 'place_order',
529 })
530 expect(res).toEqual({
531 ok: false,
532 error: expect.stringContaining('no reconnectable transport descriptor'),
533 })
534 expect(createMCPClient).not.toHaveBeenCalled()
535 })
536
537 describe('onError observability hook', () => {
538 it('invokes onError with phase "call" on a proxied-call failure and still returns ok:false', async () => {
539 const boom = new Error('upstream MCP exploded')
540 callToolMock.mockRejectedValueOnce(boom)
541 const onError = vi.fn()
542 const handler = weatherPoolHandler({ onError })
543
544 const res = await handler({
545 threadId: 't1',
546 serverId: 'weather',
547 toolName: 'place_order',
548 args: { qty: 1 },
549 })
550
551 expect(res).toEqual({ ok: false, error: 'upstream MCP exploded' })
552 expect(onError).toHaveBeenCalledWith(boom, {
553 phase: 'call',
554 req: expect.objectContaining({ toolName: 'place_order' }),
555 })
556 })
557
558 it('does not let a synchronously-throwing onError break the handler result', async () => {
559 callToolMock.mockRejectedValueOnce(new Error('upstream'))
560 const onError = vi.fn(() => {
561 // A sync-throwing observability hook must never escape the handler.
562 throw new Error('logger blew up')
563 })
564 const handler = weatherPoolHandler({ onError })
565
566 // Resolves to a normal fail-soft result rather than rejecting.
567 await expect(
568 handler({
569 threadId: 't1',
570 serverId: 'weather',
571 toolName: 'place_order',
572 }),
573 ).resolves.toEqual({ ok: false, error: 'upstream' })
574 expect(onError).toHaveBeenCalledOnce()
575 })
576
577 it('does not let an asynchronously-rejecting onError break the handler result', async () => {
578 callToolMock.mockRejectedValueOnce(new Error('upstream'))
579 const onError = vi.fn(async () => {
580 throw new Error('async logger blew up')
581 })
582 const handler = weatherPoolHandler({ onError })
583
584 await expect(
585 handler({
586 threadId: 't1',
587 serverId: 'weather',
588 toolName: 'place_order',
589 }),
590 ).resolves.toEqual({ ok: false, error: 'upstream' })
591 expect(onError).toHaveBeenCalledOnce()
592 })
593
594 it('reports a failing client.close() via phase "close" without affecting the result', async () => {
595 closeMock.mockRejectedValueOnce(new Error('socket stuck'))
596 const onError = vi.fn()
597 const handler = weatherPoolHandler({ onError })
598
599 const res = await handler({
600 threadId: 't1',
601 serverId: 'weather',
602 toolName: 'place_order',
603 args: { qty: 1 },
604 })
605
606 // The successful call result is unaffected by the close failure.
607 expect(res).toEqual({ ok: true, result: expect.anything() })
608 expect(onError).toHaveBeenCalledWith(expect.any(Error), {
609 phase: 'close',
610 req: expect.objectContaining({ toolName: 'place_order' }),
611 })
612 })
613 })
614})