Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

call-handler.test.ts

615 lines21.1 KB

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