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

call-handler.test.ts

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