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

tools.test.ts

1,297 lines39.2 KB

1import { describe, expect, it, vi } from 'vitest'
2import {
3 Client,
4 DEFAULT_REQUEST_TIMEOUT_MSEC,
5 InMemoryTransport,
6 SUPPORTED_PROTOCOL_VERSIONS,
7} from '@modelcontextprotocol/client'
8import {
9 ProtocolError,
10 ProtocolErrorCode,
11 inputRequired,
12 Server,
13} from '@modelcontextprotocol/server'
14import { MCPInputRequiredError } from '../src/input-required'
15import {
16 callMcpTool,
17 extractUiResourceUri,
18 makeMcpExecute,
19 mcpContentToTanstack,
20 toServerTools,
21} from '../src/tools'
22import {
23 makeServerWithFailingTool,
24 makeServerWithPendingTaskTool,
25 makeServerWithTaskRequiredTool,
26 makeServerWithWeatherTool,
27} from './helpers/in-memory-server'
28import type {
29 CallToolResult,
30 Tool as McpToolDef,
31 Transport,
32} from '@modelcontextprotocol/client'
33​
34/**
35 * Build an MCP tool definition for `toServerTools`. The MCP-Apps `_meta.ui`
36 * link is a custom extension not present in the SDK's base `Tool` schema, so
37 * the assembled literal needs one cast to `McpToolDef` — centralized here
38 * instead of scattering `as never` across each test def.
39 */
40function mcpToolDef(def: {
41 name: string
42 title?: string
43 description?: string
44 inputSchema?: {
45 type?: 'object'
46 properties?: Record<string, unknown>
47 required?: Array<string>
48 }
49 execution?: { taskSupport?: 'optional' | 'required' | 'forbidden' }
50 annotations?: {
51 title?: string
52 readOnlyHint?: boolean
53 destructiveHint?: boolean
54 idempotentHint?: boolean
55 openWorldHint?: boolean
56 }
57 _meta?: { ui?: { resourceUri?: string } }
58}): McpToolDef {
59 return {
60 inputSchema: { type: 'object', properties: {} },
61 ...def,
62 } as McpToolDef
64​
65/**
66 * Build a fake MCP `Client` that only implements the methods these tests call.
67 * `Client` is a concrete class, so a partial object is not assignable.
68 * The `unknown` bridge is the only way to pass the partial.
69 * `callTool` itself stays fully typed.
70 */
71function fakeMcpClient(
72 callTool: (...args: Array<any>) => Promise<CallToolResult>,
73): Client {
74 return {
75 callTool,
76 getServerCapabilities: () => undefined,
77 getProtocolEra: () => undefined,
78 } as unknown as Client
80​
81describe('mcpContentToTanstack', () => {
82 it('returns a plain string for a single text block', () => {
83 expect(mcpContentToTanstack([{ type: 'text', text: 'hello' }])).toBe(
84 'hello',
85 )
86 })
87​
88 it('maps multi-block arrays to ContentParts', () => {
89 expect(
90 mcpContentToTanstack([
91 { type: 'text', text: 'a' },
92 { type: 'text', text: 'b' },
93 ]),
94 ).toEqual([
95 { type: 'text', content: 'a' },
96 { type: 'text', content: 'b' },
97 ])
98 })
99​
100 it('maps image blocks to data-source image parts', () => {
101 const image = { type: 'image', data: 'aGk=', mimeType: 'image/png' }
102 expect(
103 mcpContentToTanstack([image, { type: 'text', text: 'caption' }]),
104 ).toEqual([
105 {
106 type: 'image',
107 source: { type: 'data', value: 'aGk=', mimeType: 'image/png' },
108 },
109 { type: 'text', content: 'caption' },
110 ])
111 })
112​
113 it('stringifies resource blocks as text parts', () => {
114 const resource = {
115 type: 'resource',
116 resource: { uri: 'file:///x.txt', text: 'x' },
117 }
118 expect(
119 mcpContentToTanstack([resource, { type: 'text', text: 'y' }]),
120 ).toEqual([
121 { type: 'text', content: JSON.stringify(resource.resource) },
122 { type: 'text', content: 'y' },
123 ])
124 })
125​
126 it('stringifies unknown block types as text parts', () => {
127 const unknown = { type: 'audio', data: 'zzz' }
128 expect(
129 mcpContentToTanstack([unknown, { type: 'text', text: 'y' }]),
130 ).toEqual([
131 { type: 'text', content: JSON.stringify(unknown) },
132 { type: 'text', content: 'y' },
133 ])
134 })
135​
136 it('returns "" when content is undefined (structuredContent-only result)', () => {
137 expect(mcpContentToTanstack(undefined)).toBe('')
138 })
139​
140 it('excludes ui:// resource blocks from model-facing text', () => {
141 // ui:// resources are display widgets — they must never leak into the
142 // model's context as text. A mixed array that contains a ui:// resource
143 // alongside a normal text block should return only the text part.
144 expect(
145 mcpContentToTanstack([
146 {
147 type: 'resource',
148 resource: { uri: 'ui://x', mimeType: 'text/html', text: '<b>w</b>' },
149 },
150 { type: 'text', text: 'hello' },
151 ]),
152 ).toEqual([{ type: 'text', content: 'hello' }])
153 })
154})
155​
156const modernProtocolVersions = [...SUPPORTED_PROTOCOL_VERSIONS, '2026-07-28']
157​
158function taskClock() {
159 const now = new Date().toISOString()
160 return { createdAt: now, lastUpdatedAt: now }
162​
163async function connectClient(transport: Transport) {
164 const client = new Client({ name: 'test', version: '1.0.0' })
165 await client.connect(transport)
166 return client
168​
169/**
170 * The in-memory server answers `server/discover` only after its era is modern.
171 * The server has no public setter for that era.
172 */
173function modernInputServer() {
174 const server = new Server(
175 { name: 'ask', version: '1.0.0' },
176 {
177 capabilities: { tools: {} },
178 supportedProtocolVersions: modernProtocolVersions,
179 },
180 )
181 Object.assign(server, { _negotiatedProtocolVersion: '2026-07-28' })
182 return server
184​
185async function inputRequiredFrom(run: () => Promise<unknown>) {
186 try {
187 await run()
188 } catch (error) {
189 expect(error).toBeInstanceOf(MCPInputRequiredError)
190 if (!(error instanceof MCPInputRequiredError)) {
191 throw new Error('expected MCPInputRequiredError')
192 }
193 return error
194 }
195 throw new Error('expected MCPInputRequiredError')
197​
198async function connectModernClient(server: Server) {
199 const [clientTransport, serverTransport] =
200 InMemoryTransport.createLinkedPair()
201 await server.connect(serverTransport)
202 const client = new Client(
203 { name: 'test', version: '1.0.0' },
204 {
205 versionNegotiation: { mode: { pin: '2026-07-28' } },
206 capabilities: {
207 elicitation: { form: {} },
208 sampling: {},
209 },
210 },
211 )
212 await client.connect(clientTransport)
213 return client
215​
216describe('callMcpTool', () => {
217 it('returns a normal tool result when a spec 2025 task ends', async () => {
218 const { clientTransport, server } = await makeServerWithTaskRequiredTool()
219 const client = await connectClient(clientTransport)
220 try {
221 const defs = (await client.listTools()).tools
222 const tools = toServerTools(client, defs, {
223 prefix: undefined,
224 lazy: false,
225 })
226 const tool = tools.find((item) => item.name === 'research_task')
227 expect(tool).toBeDefined()
228 const result = await tool!.execute!(
229 { query: 'tide' },
230 { toolCallId: 't', emitCustomEvent: () => {} },
231 )
232 expect(result).toBe('Research complete: tide')
233 } finally {
234 await client.close()
235 await server.close()
236 }
237 })
238​
239 it('throws when a spec 2025 task fails', async () => {
240 const clock = taskClock()
241 const server = new Server(
242 { name: 'job', version: '1.0.0' },
243 {
244 capabilities: {
245 tools: {},
246 tasks: { requests: { tools: { call: {} } } },
247 },
248 },
249 )
250 server.setRequestHandler('tools/call', () => ({
251 content: [{ type: 'text', text: 'nope' }],
252 task: {
253 taskId: 'job-1',
254 status: 'failed',
255 statusMessage: 'rate limit',
256 ttl: null,
257 pollInterval: 1,
258 ...clock,
259 },
260 }))
261 const [clientTransport, serverTransport] =
262 InMemoryTransport.createLinkedPair()
263 await server.connect(serverTransport)
264 const client = await connectClient(clientTransport)
265 try {
266 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
267 /rate limit/,
268 )
269 } finally {
270 await client.close()
271 await server.close()
272 }
273 })
274​
275 it('cancels the remote task when the wait is aborted', async () => {
276 const { clientTransport, server, taskStore } =
277 await makeServerWithPendingTaskTool()
278 const client = await connectClient(clientTransport)
279 const controller = new AbortController()
280 const pending = callMcpTool(
281 client,
282 'slow_task',
283 { query: 'x' },
284 true,
285 controller.signal,
286 )
287 try {
288 await vi.waitFor(async () => {
289 const listed = await taskStore.listTasks()
290 expect(listed.tasks.length).toBeGreaterThan(0)
291 })
292 controller.abort()
293 await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
294 await vi.waitFor(async () => {
295 const listed = await taskStore.listTasks()
296 expect(listed.tasks[0]?.status).toBe('cancelled')
297 })
298 } finally {
299 await client.close()
300 await server.close()
301 }
302 })
303​
304 it('throws MCPInputRequiredError with kind form for a user input request', async () => {
305 const form = {
306 message: 'Which city?',
307 requestedSchema: {
308 type: 'object' as const,
309 properties: { city: { type: 'string' as const } },
310 },
311 }
312 const server = modernInputServer()
313 server.setRequestHandler('tools/call', () =>
314 inputRequired({
315 inputRequests: { city: inputRequired.elicit(form) },
316 }),
317 )
318 const client = await connectModernClient(server)
319 try {
320 const execute = makeMcpExecute(client, 'ask', false)
321 const error = await inputRequiredFrom(() => execute({}))
322 expect(error.kind).toBe('form')
323 expect(error.name).toBe('MCPInputRequiredError')
324 expect(error.request).toEqual({
325 mode: 'form',
326 message: 'Which city?',
327 requestedSchema: form.requestedSchema,
328 })
329 } finally {
330 await client.close()
331 await server.close()
332 }
333 })
334​
335 it('throws MCPInputRequiredError with kind sampling for a model request', async () => {
336 const request = {
337 messages: [
338 {
339 role: 'user' as const,
340 content: { type: 'text' as const, text: 'Hi' },
341 },
342 ],
343 maxTokens: 16,
344 }
345 const server = modernInputServer()
346 server.setRequestHandler('tools/call', () =>
347 inputRequired({
348 inputRequests: { draft: inputRequired.createMessage(request) },
349 }),
350 )
351 const client = await connectModernClient(server)
352 try {
353 const execute = makeMcpExecute(client, 'draft', false)
354 const error = await inputRequiredFrom(() => execute({}))
355 expect(error.kind).toBe('sampling')
356 expect(error.request).toEqual(request)
357 } finally {
358 await client.close()
359 await server.close()
360 }
361 })
362​
363 async function answerCityWith(
364 inputResponse:
365 | { status: 'resolved'; payload: unknown }
366 | { status: 'cancelled' },
367 ) {
368 const seen: Array<{ responses: unknown; state: unknown }> = []
369 const server = modernInputServer()
370 server.setRequestHandler('tools/call', (_request, ctx) => {
371 const responses = ctx.mcpReq.inputResponses
372 if (responses === undefined) {
373 return inputRequired({
374 inputRequests: {
375 city: inputRequired.elicit({
376 message: 'Which city?',
377 requestedSchema: {
378 type: 'object',
379 properties: { city: { type: 'string' } },
380 },
381 }),
382 },
383 requestState: 'state-1',
384 })
385 }
386 seen.push({ responses, state: ctx.mcpReq.requestState() })
387 return { content: [{ type: 'text', text: 'answered' }] }
388 })
389 const client = await connectModernClient(server)
390 try {
391 const execute = makeMcpExecute(client, 'ask', false)
392 const result = await execute(
393 {},
394 { abortSignal: undefined, inputResponse },
395 )
396 return { result, seen }
397 } finally {
398 await client.close()
399 await server.close()
400 }
401 }
402​
403 it('sends the answer back with inputResponses and requestState', async () => {
404 const { result, seen } = await answerCityWith({
405 status: 'resolved',
406 payload: { city: 'Paris' },
407 })
408​
409 expect(result).toBe('answered')
410 expect(seen).toEqual([
411 {
412 responses: { city: { action: 'accept', content: { city: 'Paris' } } },
413 state: 'state-1',
414 },
415 ])
416 })
417​
418 it('sends a cancel when the user cancels the form', async () => {
419 const { seen } = await answerCityWith({ status: 'cancelled' })
420​
421 expect(seen[0]?.responses).toEqual({ city: { action: 'cancel' } })
422 })
423​
424 it('fails with a clear error when the server asks a second input round', async () => {
425 let calls = 0
426 const server = modernInputServer()
427 server.setRequestHandler('tools/call', () => {
428 calls += 1
429 return inputRequired({
430 inputRequests: {
431 [`round${calls}`]: inputRequired.elicit({
432 message: `Question ${calls}?`,
433 requestedSchema: { type: 'object', properties: {} },
434 }),
435 },
436 requestState: `state-${calls}`,
437 })
438 })
439 const client = await connectModernClient(server)
440 try {
441 const execute = makeMcpExecute(client, 'ask', false)
442 // A pause here would reuse the same interrupt id and loop forever.
443 await expect(
444 execute(
445 {},
446 {
447 abortSignal: undefined,
448 inputResponse: { status: 'resolved', payload: {} },
449 },
450 ),
451 ).rejects.toThrow('asked for input a second time')
452 expect(calls).toBe(2)
453 } finally {
454 await client.close()
455 await server.close()
456 }
457 })
458​
459 it('stops a spec 2025 task that needs input instead of polling forever', async () => {
460 const clock = taskClock()
461 const server = new Server(
462 { name: 'job', version: '1.0.0' },
463 {
464 capabilities: {
465 tools: {},
466 tasks: { requests: { tools: { call: {} } } },
467 },
468 },
469 )
470 server.setRequestHandler('tools/call', () => ({
471 content: [],
472 task: {
473 taskId: 'job-1',
474 status: 'input_required',
475 ttl: null,
476 pollInterval: 1,
477 ...clock,
478 },
479 }))
480 const [clientTransport, serverTransport] =
481 InMemoryTransport.createLinkedPair()
482 await server.connect(serverTransport)
483 const client = await connectClient(clientTransport)
484 try {
485 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
486 /needs input/,
487 )
488 } finally {
489 await client.close()
490 await server.close()
491 }
492 })
493​
494 it('keeps the JSON-RPC error code on a spec 2026 call', async () => {
495 const server = modernInputServer()
496 server.setRequestHandler('tools/call', () => {
497 throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown tool')
498 })
499 const client = await connectModernClient(server)
500 try {
501 await expect(
502 callMcpTool(client, 'nope', {}, false),
503 ).rejects.toMatchObject({
504 code: ProtocolErrorCode.InvalidParams,
505 message: 'Unknown tool',
506 })
507 } finally {
508 await client.close()
509 await server.close()
510 }
511 })
512})
513​
514describe('makeMcpExecute', () => {
515 it('throws an error naming the tool when the MCP tool returns isError', async () => {
516 const { clientTransport } = await makeServerWithFailingTool()
517 const client = new Client({ name: 'test', version: '1.0.0' })
518 await client.connect(clientTransport)
519 const defs = (await client.listTools()).tools
520 const tools = toServerTools(client, defs, {
521 prefix: undefined,
522 lazy: false,
523 })
524 const tool = tools.find((t) => t.name === 'always_fails')!
525 await expect(
526 tool.execute!({}, { toolCallId: 't', emitCustomEvent: () => {} }),
527 ).rejects.toThrow(/always_fails.*boom/)
528 await client.close()
529 })
530​
531 it('throws the bare error message (no dangling colon) when the error detail is empty', async () => {
532 // A ui://-only error body normalizes to '' — treat it like undefined and
533 // throw "returned an error" with no trailing colon.
534 const callTool = vi.fn().mockResolvedValue({
535 isError: true,
536 content: [{ type: 'resource', resource: { uri: 'ui://widget' } }],
537 })
538 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false)
539 await expect(execute({})).rejects.toThrow(/MCP tool "x" returned an error$/)
540 })
541​
542 it('forwards the abortSignal to client.callTool', async () => {
543 const callTool = vi
544 .fn()
545 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
546 const client = fakeMcpClient(callTool)
547 const controller = new AbortController()
548 const execute = makeMcpExecute(client, 'x', false)
549 await expect(execute({}, { abortSignal: controller.signal })).resolves.toBe(
550 'ok',
551 )
552 expect(callTool).toHaveBeenCalledWith(
553 { name: 'x', arguments: {} },
554 { signal: controller.signal, allowInputRequired: true },
555 )
556 })
557​
558 it('sends requestOptions with the abortSignal to client.callTool', async () => {
559 const callTool = vi
560 .fn()
561 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
562 const controller = new AbortController()
563 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false, false, {
564 timeout: 5000,
565 resetTimeoutOnProgress: true,
566 })
567 await expect(execute({}, { abortSignal: controller.signal })).resolves.toBe(
568 'ok',
569 )
570 expect(callTool).toHaveBeenCalledWith(
571 { name: 'x', arguments: {} },
572 {
573 timeout: 5000,
574 resetTimeoutOnProgress: true,
575 // The SDK asks the server for progress only with an onprogress callback.
576 onprogress: expect.any(Function),
577 signal: controller.signal,
578 allowInputRequired: true,
579 },
580 )
581 })
582​
583 it('adds no onprogress when resetTimeoutOnProgress is not set', async () => {
584 const callTool = vi
585 .fn()
586 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
587 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false, false, {
588 timeout: 5000,
589 })
590 await execute({})
591 expect(callTool).toHaveBeenCalledWith(
592 { name: 'x', arguments: {} },
593 { timeout: 5000, allowInputRequired: true },
594 )
595 })
596​
597 it('rejects without calling the server when the signal is already aborted', async () => {
598 const callTool = vi.fn()
599 const client = fakeMcpClient(callTool)
600 const controller = new AbortController()
601 controller.abort()
602 const execute = makeMcpExecute(client, 'x', false)
603 await expect(
604 execute({}, { abortSignal: controller.signal }),
605 ).rejects.toThrow()
606 expect(callTool).not.toHaveBeenCalled()
607 })
608​
609 it('prefers structuredContent when the tool declares an outputSchema', async () => {
610 const callTool = vi.fn().mockResolvedValue({
611 content: [{ type: 'text', text: '{"temperature":72}' }],
612 structuredContent: { temperature: 72 },
613 })
614 const client = fakeMcpClient(callTool)
615 const execute = makeMcpExecute(client, 'x', true)
616 await expect(execute({})).resolves.toEqual({ temperature: 72 })
617 })
618​
619 it('falls back to content[] when preferStructured is false', async () => {
620 const callTool = vi.fn().mockResolvedValue({
621 content: [{ type: 'text', text: 'plain' }],
622 structuredContent: { ignored: true },
623 })
624 const client = fakeMcpClient(callTool)
625 const execute = makeMcpExecute(client, 'x', false)
626 await expect(execute({})).resolves.toBe('plain')
627 })
628})
629​
630describe('toServerTools — MCP Apps metadata', () => {
631 it('captures serverId (prefix) and the _meta.ui.resourceUri link', () => {
632 const tool = toServerTools(
633 fakeMcpClient(vi.fn()),
634 [
635 mcpToolDef({
636 name: 'show_widget',
637 description: 'show',
638 _meta: { ui: { resourceUri: 'ui://srv/widget' } },
639 }),
640 ],
641 { prefix: 'weather' },
642 )[0]!
643 expect(tool.name).toBe('weather_show_widget')
644 expect(tool.metadata).toMatchObject({
645 mcp: {
646 serverToolName: 'show_widget',
647 serverId: 'weather',
648 uiResourceUri: 'ui://srv/widget',
649 },
650 })
651 })
652​
653 it('leaves uiResourceUri undefined for plain tools', () => {
654 const tool = toServerTools(
655 fakeMcpClient(vi.fn()),
656 [mcpToolDef({ name: 't' })],
657 {},
658 )[0]!
659 // `toServerTools` returns `McpServerTool`s, so `metadata.mcp` reads
660 // straight through — no annotation, no non-null assertion, no cast.
661 const mcp = tool.metadata.mcp
662 expect(mcp.uiResourceUri).toBeUndefined()
663 expect(mcp.serverId).toBeUndefined()
664 })
665})
666​
667describe('toServerTools — annotations + title', () => {
668 it('forwards the server annotations verbatim', () => {
669 const annotations = {
670 title: 'Weather Lookup',
671 readOnlyHint: true,
672 destructiveHint: false,
673 idempotentHint: true,
674 openWorldHint: true,
675 }
676 const tool = toServerTools(
677 fakeMcpClient(vi.fn()),
678 [mcpToolDef({ name: 'get_weather', description: 'w', annotations })],
679 {},
680 )[0]!
681 expect(tool.metadata.mcp.annotations).toEqual(annotations)
682 })
683​
684 it('omits annotations entirely when the server declares none', () => {
685 const tool = toServerTools(
686 fakeMcpClient(vi.fn()),
687 [mcpToolDef({ name: 'get_weather' })],
688 {},
689 )[0]!
690 // `toServerTools` returns `McpServerTool`s, so `metadata.mcp` reads
691 // straight through — no annotation, no non-null assertion, no cast.
692 const mcp = tool.metadata.mcp
693 expect(mcp.annotations).toBeUndefined()
694 // Omitted, not present-with-undefined — the explicit tools(defs) path
695 // merges this block over caller-supplied metadata.
696 expect('annotations' in mcp).toBe(false)
697 })
698​
699 it('resolves title with MCP precedence: title > annotations.title > name', () => {
700 const [both, annotationsOnly, neither] = toServerTools(
701 fakeMcpClient(vi.fn()),
702 [
703 mcpToolDef({
704 name: 'a',
705 title: 'Top Level',
706 annotations: { title: 'Legacy' },
707 }),
708 mcpToolDef({ name: 'b', annotations: { title: 'Legacy' } }),
709 mcpToolDef({ name: 'c' }),
710 ],
711 {},
712 )
713 expect(both!.metadata.mcp.title).toBe('Top Level')
714 expect(annotationsOnly!.metadata.mcp.title).toBe('Legacy')
715 expect(neither!.metadata.mcp.title).toBe('c')
716 })
717​
718 it('keeps the prefixed tool name independent of the display title', () => {
719 const tool = toServerTools(
720 fakeMcpClient(vi.fn()),
721 [mcpToolDef({ name: 'get_weather', title: 'Weather Lookup' })],
722 { prefix: 'wx' },
723 )[0]!
724 // The title is display-only — it must never leak into the model-facing name.
725 expect(tool.name).toBe('wx_get_weather')
726 expect(tool.metadata.mcp.title).toBe('Weather Lookup')
727 })
728​
729 it('gives a frozen copy of the title and all 5 annotation fields', () => {
730 const annotations = {
731 title: 'Weather Lookup',
732 readOnlyHint: true,
733 destructiveHint: false,
734 idempotentHint: true,
735 openWorldHint: false,
736 }
737 const def = mcpToolDef({ name: 'get_weather', annotations })
738 const [tool] = toServerTools(fakeMcpClient(vi.fn()), [def], {})
739 const mcp = tool!.metadata.mcp
740 expect(mcp.title).toBe('Weather Lookup')
741 expect(mcp.annotations).toStrictEqual({
742 title: 'Weather Lookup',
743 readOnlyHint: true,
744 destructiveHint: false,
745 idempotentHint: true,
746 openWorldHint: false,
747 })
748 expect(Object.isFrozen(mcp.annotations)).toBe(true)
749 // A copy: the server's own object stays as it was.
750 expect(mcp.annotations).not.toBe(def.annotations)
751 expect(Object.isFrozen(def.annotations)).toBe(false)
752 })
753})
754​
755describe('toServerTools — input schema defaults', () => {
756 it('adds properties: {} to a schema without properties', () => {
757 const [tool] = toServerTools(
758 fakeMcpClient(vi.fn()),
759 [mcpToolDef({ name: 'ping', inputSchema: { type: 'object' } })],
760 {},
761 )
762 expect(tool!.inputSchema).toEqual({ type: 'object', properties: {} })
763 })
764​
765 it("adds type: 'object' to a schema without type and keeps its other keys", () => {
766 const [tool] = toServerTools(
767 fakeMcpClient(vi.fn()),
768 [
769 mcpToolDef({
770 name: 'search',
771 inputSchema: {
772 properties: { query: { type: 'string' } },
773 required: ['query'],
774 },
775 }),
776 ],
777 {},
778 )
779 expect(tool!.inputSchema).toEqual({
780 type: 'object',
781 properties: { query: { type: 'string' } },
782 required: ['query'],
783 })
784 })
785​
786 it('gives a tool without an input schema an empty object schema', () => {
787 const def = mcpToolDef({ name: 'bare' })
788 Reflect.deleteProperty(def, 'inputSchema')
789 const [tool] = toServerTools(fakeMcpClient(vi.fn()), [def], {})
790 expect(tool!.inputSchema).toEqual({ type: 'object', properties: {} })
791 })
792​
793 it('keeps a full schema as the server sent it', () => {
794 const inputSchema = {
795 type: 'object' as const,
796 properties: { city: { type: 'string' } },
797 required: ['city'],
798 }
799 const [tool] = toServerTools(
800 fakeMcpClient(vi.fn()),
801 [mcpToolDef({ name: 'get_weather', inputSchema })],
802 {},
803 )
804 expect(tool!.inputSchema).toEqual(inputSchema)
805 })
806})
807​
808describe('toServerTools — toolName', () => {
809 it('names each tool with toolName, which wins over the prefix', () => {
810 const [tool] = toServerTools(
811 fakeMcpClient(vi.fn()),
812 [mcpToolDef({ name: 'get_weather' })],
813 { prefix: 'wx', toolName: (def) => `mcp__wx__${def.name}` },
814 )
815 expect(tool!.name).toBe('mcp__wx__get_weather')
816 expect(tool!.metadata.mcp).toMatchObject({
817 serverToolName: 'get_weather',
818 serverId: 'wx',
819 })
820 })
821​
822 it('calls the server tool by its own name', async () => {
823 const callTool = vi
824 .fn()
825 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
826 const [tool] = toServerTools(
827 fakeMcpClient(callTool),
828 [mcpToolDef({ name: 'get_weather' })],
829 { toolName: () => 'renamed' },
830 )
831 expect(tool!.name).toBe('renamed')
832 await expect(tool!.execute!({})).resolves.toBe('ok')
833 expect(callTool).toHaveBeenCalledWith(
834 { name: 'get_weather', arguments: {} },
835 expect.anything(),
836 )
837 })
838})
839​
840describe('toServerTools', () => {
841 it('discovers tools and proxies execute to callTool', async () => {
842 const { clientTransport } = await makeServerWithWeatherTool()
843 const client = new Client({ name: 'test', version: '1.0.0' })
844 await client.connect(clientTransport)
845​
846 const defs = (await client.listTools()).tools
847 const tools = toServerTools(client, defs, {
848 prefix: undefined,
849 lazy: false,
850 })
851​
852 expect(tools.map((t) => t.name)).toContain('get_weather')
853 const tool = tools.find((t) => t.name === 'get_weather')!
854 const result = await tool.execute!(
855 { city: 'Brooklyn' },
856 {
857 toolCallId: 't',
858 emitCustomEvent: () => {},
859 },
860 )
861 expect(JSON.stringify(result)).toContain('Sunny in Brooklyn')
862 await client.close()
863 })
864​
865 it('keeps task-optional tools on ordinary callTool execution', async () => {
866 const callTool = vi
867 .fn()
868 .mockResolvedValue({ content: [{ type: 'text', text: 'plain' }] })
869 const tools = toServerTools(
870 fakeMcpClient(callTool),
871 [
872 mcpToolDef({
873 name: 'optional_task',
874 execution: { taskSupport: 'optional' },
875 }),
876 ],
877 {},
878 )
879​
880 await expect(tools[0]!.execute!({})).resolves.toBe('plain')
881 expect(callTool).toHaveBeenCalledOnce()
882 })
883​
884 it('applies a prefix', async () => {
885 const { clientTransport } = await makeServerWithWeatherTool()
886 const client = new Client({ name: 'test', version: '1.0.0' })
887 await client.connect(clientTransport)
888 const defs = (await client.listTools()).tools
889 const tools = toServerTools(client, defs, { prefix: 'wx', lazy: false })
890 expect(tools.map((t) => t.name)).toContain('wx_get_weather')
891 await client.close()
892 })
893})
894​
895type RawMessage = { id: string; params: Record<string, unknown> }
896​
897/**
898 * A spec 2026 client whose transport answers each raw request at once with
899 * the messages `reply` returns. Like `fakeMcpClient`, the partial needs the
900 * `unknown` bridge.
901 */
902function scriptedModernClient(
903 reply: (message: RawMessage) => Array<unknown>,
904 extra: Record<string, unknown> = {},
905) {
906 const sent: Array<RawMessage> = []
907 const transport: {
908 onmessage?: (message: unknown) => void
909 send: (message: RawMessage) => Promise<void>
910 } = {
911 async send(message) {
912 sent.push(message)
913 for (const answer of reply(message)) transport.onmessage?.(answer)
914 if (extra.sendError instanceof Error) throw extra.sendError
915 },
916 }
917 const client = {
918 getProtocolEra: () => 'modern',
919 transport,
920 ...extra,
921 } as unknown as Client
922 return { client, sent }
924​
925function answerWith(result: unknown) {
926 return (message: RawMessage) => [{ jsonrpc: '2.0', id: message.id, result }]
928​
929/** A spec 2025 client. Each SDK request is answered by `answers[method]`. */
930function scriptedLegacyClient(
931 answers: Record<string, (signal?: AbortSignal) => unknown>,
932) {
933 return {
934 getProtocolEra: () => 'legacy',
935 async request(
936 rpc: { method: string },
937 _schema: unknown,
938 options?: { signal?: AbortSignal },
939 ) {
940 const answer = answers[rpc.method]
941 if (answer === undefined) throw new Error(`No answer for ${rpc.method}`)
942 return answer(options?.signal)
943 },
944 } as unknown as Client
946​
947const okResult = { content: [{ type: 'text', text: 'ok' }] }
948const missingResult = 'ended without a result or error'
949​
950describe('callMcpTool — spec 2026 raw requests', () => {
951 it('fails when the reply has no tool result, and sends the envelope', async () => {
952 const { client, sent } = scriptedModernClient(answerWith(null), {
953 _outboundMetaEnvelope: () => ({ version: '2026-07-28' }),
954 })
955​
956 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toThrow(
957 missingResult,
958 )
959 expect(sent[0]?.params._meta).toEqual({ version: '2026-07-28' })
960 })
961​
962 it('sends no envelope when the client gives none', async () => {
963 for (const extra of [{}, { _outboundMetaEnvelope: () => 'x' }]) {
964 const { client, sent } = scriptedModernClient(answerWith(okResult), extra)
965 await expect(callMcpTool(client, 'ask', {}, false)).resolves.toEqual(
966 okResult,
967 )
968 expect(sent[0]?.params._meta).toBeUndefined()
969 }
970 })
971​
972 it('uses defaults for a JSON-RPC error without code or message', async () => {
973 const { client } = scriptedModernClient((message) => [
974 { jsonrpc: '2.0', id: message.id, error: {} },
975 ])
976​
977 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toMatchObject({
978 code: ProtocolErrorCode.InternalError,
979 message: 'The MCP request failed.',
980 })
981 })
982​
983 it('ignores messages for other requests', async () => {
984 const { client } = scriptedModernClient((message) => [
985 { jsonrpc: '2.0', id: 'other', result: {} },
986 { jsonrpc: '2.0', id: message.id, result: okResult },
987 ])
988​
989 await expect(callMcpTool(client, 'ask', {}, false)).resolves.toEqual(
990 okResult,
991 )
992 })
993​
994 it('keeps the answer when send fails after it, and fails without one', async () => {
995 const sendError = new Error('send failed')
996 const answered = scriptedModernClient(answerWith(okResult), { sendError })
997 await expect(
998 callMcpTool(answered.client, 'ask', {}, false),
999 ).resolves.toEqual(okResult)
1000​
1001 const silent = scriptedModernClient(() => [], { sendError })
1002 await expect(callMcpTool(silent.client, 'ask', {}, false)).rejects.toBe(
1003 sendError,
1005 })
1006​
1007 it('fails when the client has no transport', async () => {
1008 const client = { getProtocolEra: () => 'modern' } as unknown as Client
1009​
1010 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toThrow(
1011 'The MCP client is not connected.',
1013 })
1014​
1015 it('stops on abort and resolves with a signal that never fires', async () => {
1016 const answered = scriptedModernClient(answerWith(okResult))
1017 await expect(
1018 callMcpTool(
1019 answered.client,
1020 'ask',
1021 {},
1022 false,
1023 new AbortController().signal,
1024 ),
1025 ).resolves.toEqual(okResult)
1026​
1027 const silent = scriptedModernClient(() => [])
1028 const controller = new AbortController()
1029 const pending = callMcpTool(
1030 silent.client,
1031 'ask',
1032 {},
1033 false,
1034 controller.signal,
1036 controller.abort(new Error('stop'))
1037 await expect(pending).rejects.toThrow('stop')
1038 })
1039​
1040 it('times out when the reply never comes', async () => {
1041 vi.useFakeTimers()
1042 try {
1043 const { client } = scriptedModernClient(() => [])
1044 const pending = expect(
1045 callMcpTool(client, 'ask', {}, false),
1046 ).rejects.toThrow(/timed out/)
1047 await vi.advanceTimersByTimeAsync(DEFAULT_REQUEST_TIMEOUT_MSEC)
1048 await pending
1049 } finally {
1050 vi.useRealTimers()
1052 })
1053​
1054 it('uses the requestOptions timeout', async () => {
1055 vi.useFakeTimers()
1056 try {
1057 const { client } = scriptedModernClient(() => [])
1058 const outcome = callMcpTool(
1059 client,
1060 'ask',
1061 {},
1062 false,
1063 undefined,
1064 undefined,
1066 timeout: 1000,
1067 },
1068 ).catch((error: unknown) => error)
1069 await vi.advanceTimersByTimeAsync(1000)
1070 const error = await outcome
1071 expect(error).toBeInstanceOf(Error)
1072 expect(String(error)).toContain('timed out after 1000 ms')
1073 } finally {
1074 vi.useRealTimers()
1076 })
1077​
1078 it('reads every input request shape', async () => {
1079 const call = (result: unknown) =>
1080 callMcpTool(
1081 scriptedModernClient(answerWith(result)).client,
1082 'ask',
1083 {},
1084 false,
1086​
1087 await expect(
1088 call({
1089 resultType: 'input_required',
1090 inputRequests: { a: { method: 'roots/list', params: {} } },
1091 }),
1092 ).rejects.toThrow('unsupported input: roots/list')
1093​
1094 const noRecord = { resultType: 'input_required', inputRequests: 'x' }
1095 const fallback = await inputRequiredFrom(() => call(noRecord))
1096 expect(fallback.request).toEqual(noRecord)
1097​
1098 const bare = { method: 'elicitation/create', message: 'City?' }
1099 const flat = await inputRequiredFrom(() =>
1100 call({ status: 'input_required', inputRequests: { a: 1, b: bare } }),
1102 expect(flat.kind).toBe('form')
1103 expect(flat.request).toEqual(bare)
1104​
1105 const invalid = { status: 'input_required', inputRequests: { a: 1 } }
1106 expect((await inputRequiredFrom(() => call(invalid))).request).toEqual(
1107 invalid,
1109​
1110 await expect(
1111 call({ status: 'input_required', inputRequests: {} }),
1112 ).rejects.toThrow(missingResult)
1113 })
1114​
1115 async function retrySent(
1116 inputRequests: Record<string, unknown> | undefined,
1117 inputResponse: Parameters<typeof callMcpTool>[5],
1118 requestState?: string,
1119 ) {
1120 const { client, sent } = scriptedModernClient((message) => [
1122 jsonrpc: '2.0',
1123 id: message.id,
1124 result:
1125 sent.length === 1
1126 ? { resultType: 'input_required', inputRequests, requestState }
1127 : okResult,
1128 },
1129 ])
1130 await callMcpTool(client, 'draft', {}, false, undefined, inputResponse)
1131 return sent[1]?.params
1133​
1134 it('answers a sampling request with text, a result object, or a cancel', async () => {
1135 const sampling = { draft: { method: 'sampling/createMessage', params: {} } }
1136​
1137 expect(
1138 await retrySent(sampling, { status: 'resolved', payload: 'Sunny' }, 's1'),
1139 ).toMatchObject({
1140 requestState: 's1',
1141 inputResponses: {
1142 draft: {
1143 role: 'assistant',
1144 content: { type: 'text', text: 'Sunny' },
1145 model: 'user',
1146 },
1147 },
1148 })
1149​
1150 const custom = { role: 'assistant', content: { type: 'text', text: 'x' } }
1151 expect(
1152 (await retrySent(sampling, { status: 'resolved', payload: custom }))
1153 ?.inputResponses,
1154 ).toEqual({ draft: custom })
1155​
1156 await expect(retrySent(sampling, { status: 'cancelled' })).rejects.toThrow(
1157 'The user cancelled the MCP sampling request.',
1159 })
1160​
1161 it('passes an ElicitResult as is and retries without requests', async () => {
1162 const form = { city: { method: 'elicitation/create', params: {} } }
1163 expect(
1165 await retrySent(form, {
1166 status: 'resolved',
1167 payload: { action: 'decline' },
1168 })
1169 )?.inputResponses,
1170 ).toEqual({ city: { action: 'decline' } })
1171​
1172 const params = await retrySent(
1173 undefined,
1174 { status: 'resolved', payload: 'x' },
1175 's1',
1177 expect(params).toEqual({ name: 'draft', arguments: {}, requestState: 's1' })
1178 })
1180​
1181describe('callMcpTool — spec 2025 task replies', () => {
1182 const working = (pollInterval: number) => () => ({
1183 task: { taskId: 't', status: 'working', pollInterval },
1184 })
1185 const completed = () => ({ taskId: 't', status: 'completed' })
1186​
1187 it('throws MCPInputRequiredError when tasks/get asks for input', async () => {
1188 const client = scriptedLegacyClient({
1189 'tools/call': working(0),
1190 'tasks/get': () => ({
1191 status: 'input_required',
1192 inputRequests: {
1193 a: { method: 'elicitation/create', params: { message: 'City?' } },
1194 },
1195 }),
1196 })
1197​
1198 const error = await inputRequiredFrom(() =>
1199 callMcpTool(client, 'job', {}, true),
1201 expect(error.request).toEqual({ message: 'City?' })
1202 })
1203​
1204 it('fails on a task body it cannot read', async () => {
1205 for (const body of [{}, { taskId: 't', status: 'weird' }]) {
1206 const client = scriptedLegacyClient({
1207 'tools/call': working(0),
1208 'tasks/get': () => body,
1209 })
1210 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
1211 missingResult,
1214 })
1215​
1216 it('fails when tools/call or tasks/result has no tool result', async () => {
1217 const noTask = scriptedLegacyClient({ 'tools/call': () => ({}) })
1218 await expect(callMcpTool(noTask, 'job', {}, true)).rejects.toThrow(
1219 missingResult,
1221​
1222 const noResult = scriptedLegacyClient({
1223 'tools/call': working(0),
1224 'tasks/get': completed,
1225 'tasks/result': () => ({}),
1226 })
1227 await expect(callMcpTool(noResult, 'job', {}, true)).rejects.toThrow(
1228 missingResult,
1230 })
1231​
1232 it('names a failed task without a status message', async () => {
1233 const client = scriptedLegacyClient({
1234 'tools/call': () => ({ task: { taskId: 't', status: 'failed' } }),
1235 })
1236​
1237 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
1238 'MCP task "t" failed.',
1240 })
1241​
1242 it('waits the poll interval without a signal', async () => {
1243 const client = scriptedLegacyClient({
1244 'tools/call': working(1),
1245 'tasks/get': completed,
1246 'tasks/result': () => okResult,
1247 })
1248​
1249 await expect(callMcpTool(client, 'job', {}, true)).resolves.toEqual(
1250 okResult,
1252 })
1253​
1254 it('sends requestOptions with the task tools/call', async () => {
1255 const seen: Array<unknown> = []
1256 const client = {
1257 getProtocolEra: () => 'legacy',
1258 async request(_rpc: unknown, _schema: unknown, options?: unknown) {
1259 seen.push(options)
1260 return okResult
1261 },
1262 } as unknown as Client
1263 await expect(
1264 callMcpTool(client, 'job', {}, true, undefined, undefined, {
1265 timeout: 5000,
1266 }),
1267 ).resolves.toEqual(okResult)
1268 expect(seen).toEqual([{ timeout: 5000 }])
1269 })
1270​
1271 it('throws the abort reason when the request fails after an abort', async () => {
1272 const controller = new AbortController()
1273 const client = scriptedLegacyClient({
1274 'tools/call': (signal) =>
1275 new Promise((_, reject) => {
1276 signal?.addEventListener('abort', () =>
1277 reject(new Error('socket closed')),
1279 }),
1280 })
1281 const pending = callMcpTool(client, 'job', {}, true, controller.signal)
1282 controller.abort(new Error('stop'))
1283​
1284 await expect(pending).rejects.toThrow('stop')
1285 })
1287​
1288describe('extractUiResourceUri', () => {
1289 it('returns undefined when _meta.ui is not an object', () => {
1290 expect(
1291 extractUiResourceUri({
1292 ...mcpToolDef({ name: 'a' }),
1293 _meta: { ui: 'x' },
1294 }),
1295 ).toBeUndefined()
1296 })