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

tools.test.ts

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