Open History to see the last commit
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
63}
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
79}
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 }
161}
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
167}
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
183}
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')
196}
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
214}
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 { threadId: 'thread-1', 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!(
527 {},
528 { threadId: 'thread-1', toolCallId: 't', emitCustomEvent: () => {} },
529 ),
530 ).rejects.toThrow(/always_fails.*boom/)
531 await client.close()
532 })
533
534 it('throws the bare error message (no dangling colon) when the error detail is empty', async () => {
535 // A ui://-only error body normalizes to '' — treat it like undefined and
536 // throw "returned an error" with no trailing colon.
537 const callTool = vi.fn().mockResolvedValue({
538 isError: true,
539 content: [{ type: 'resource', resource: { uri: 'ui://widget' } }],
540 })
541 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false)
542 await expect(execute({})).rejects.toThrow(/MCP tool "x" returned an error$/)
543 })
544
545 it('forwards the abortSignal to client.callTool', async () => {
546 const callTool = vi
547 .fn()
548 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
549 const client = fakeMcpClient(callTool)
550 const controller = new AbortController()
551 const execute = makeMcpExecute(client, 'x', false)
552 await expect(execute({}, { abortSignal: controller.signal })).resolves.toBe(
553 'ok',
554 )
555 expect(callTool).toHaveBeenCalledWith(
556 { name: 'x', arguments: {} },
557 { signal: controller.signal, allowInputRequired: true },
558 )
559 })
560
561 it('sends requestOptions with the abortSignal to client.callTool', async () => {
562 const callTool = vi
563 .fn()
564 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
565 const controller = new AbortController()
566 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false, false, {
567 timeout: 5000,
568 resetTimeoutOnProgress: true,
569 })
570 await expect(execute({}, { abortSignal: controller.signal })).resolves.toBe(
571 'ok',
572 )
573 expect(callTool).toHaveBeenCalledWith(
574 { name: 'x', arguments: {} },
575 {
576 timeout: 5000,
577 resetTimeoutOnProgress: true,
578 // The SDK asks the server for progress only with an onprogress callback.
579 onprogress: expect.any(Function),
580 signal: controller.signal,
581 allowInputRequired: true,
582 },
583 )
584 })
585
586 it('adds no onprogress when resetTimeoutOnProgress is not set', async () => {
587 const callTool = vi
588 .fn()
589 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
590 const execute = makeMcpExecute(fakeMcpClient(callTool), 'x', false, false, {
591 timeout: 5000,
592 })
593 await execute({})
594 expect(callTool).toHaveBeenCalledWith(
595 { name: 'x', arguments: {} },
596 { timeout: 5000, allowInputRequired: true },
597 )
598 })
599
600 it('rejects without calling the server when the signal is already aborted', async () => {
601 const callTool = vi.fn()
602 const client = fakeMcpClient(callTool)
603 const controller = new AbortController()
604 controller.abort()
605 const execute = makeMcpExecute(client, 'x', false)
606 await expect(
607 execute({}, { abortSignal: controller.signal }),
608 ).rejects.toThrow()
609 expect(callTool).not.toHaveBeenCalled()
610 })
611
612 it('prefers structuredContent when the tool declares an outputSchema', async () => {
613 const callTool = vi.fn().mockResolvedValue({
614 content: [{ type: 'text', text: '{"temperature":72}' }],
615 structuredContent: { temperature: 72 },
616 })
617 const client = fakeMcpClient(callTool)
618 const execute = makeMcpExecute(client, 'x', true)
619 await expect(execute({})).resolves.toEqual({ temperature: 72 })
620 })
621
622 it('falls back to content[] when preferStructured is false', async () => {
623 const callTool = vi.fn().mockResolvedValue({
624 content: [{ type: 'text', text: 'plain' }],
625 structuredContent: { ignored: true },
626 })
627 const client = fakeMcpClient(callTool)
628 const execute = makeMcpExecute(client, 'x', false)
629 await expect(execute({})).resolves.toBe('plain')
630 })
631})
632
633describe('toServerTools — MCP Apps metadata', () => {
634 it('captures serverId (prefix) and the _meta.ui.resourceUri link', () => {
635 const tool = toServerTools(
636 fakeMcpClient(vi.fn()),
637 [
638 mcpToolDef({
639 name: 'show_widget',
640 description: 'show',
641 _meta: { ui: { resourceUri: 'ui://srv/widget' } },
642 }),
643 ],
644 { prefix: 'weather' },
645 )[0]!
646 expect(tool.name).toBe('weather_show_widget')
647 expect(tool.metadata).toMatchObject({
648 mcp: {
649 serverToolName: 'show_widget',
650 serverId: 'weather',
651 uiResourceUri: 'ui://srv/widget',
652 },
653 })
654 })
655
656 it('leaves uiResourceUri undefined for plain tools', () => {
657 const tool = toServerTools(
658 fakeMcpClient(vi.fn()),
659 [mcpToolDef({ name: 't' })],
660 {},
661 )[0]!
662 // `toServerTools` returns `McpServerTool`s, so `metadata.mcp` reads
663 // straight through — no annotation, no non-null assertion, no cast.
664 const mcp = tool.metadata.mcp
665 expect(mcp.uiResourceUri).toBeUndefined()
666 expect(mcp.serverId).toBeUndefined()
667 })
668})
669
670describe('toServerTools — annotations + title', () => {
671 it('forwards the server annotations verbatim', () => {
672 const annotations = {
673 title: 'Weather Lookup',
674 readOnlyHint: true,
675 destructiveHint: false,
676 idempotentHint: true,
677 openWorldHint: true,
678 }
679 const tool = toServerTools(
680 fakeMcpClient(vi.fn()),
681 [mcpToolDef({ name: 'get_weather', description: 'w', annotations })],
682 {},
683 )[0]!
684 expect(tool.metadata.mcp.annotations).toEqual(annotations)
685 })
686
687 it('omits annotations entirely when the server declares none', () => {
688 const tool = toServerTools(
689 fakeMcpClient(vi.fn()),
690 [mcpToolDef({ name: 'get_weather' })],
691 {},
692 )[0]!
693 // `toServerTools` returns `McpServerTool`s, so `metadata.mcp` reads
694 // straight through — no annotation, no non-null assertion, no cast.
695 const mcp = tool.metadata.mcp
696 expect(mcp.annotations).toBeUndefined()
697 // Omitted, not present-with-undefined — the explicit tools(defs) path
698 // merges this block over caller-supplied metadata.
699 expect('annotations' in mcp).toBe(false)
700 })
701
702 it('resolves title with MCP precedence: title > annotations.title > name', () => {
703 const [both, annotationsOnly, neither] = toServerTools(
704 fakeMcpClient(vi.fn()),
705 [
706 mcpToolDef({
707 name: 'a',
708 title: 'Top Level',
709 annotations: { title: 'Legacy' },
710 }),
711 mcpToolDef({ name: 'b', annotations: { title: 'Legacy' } }),
712 mcpToolDef({ name: 'c' }),
713 ],
714 {},
715 )
716 expect(both!.metadata.mcp.title).toBe('Top Level')
717 expect(annotationsOnly!.metadata.mcp.title).toBe('Legacy')
718 expect(neither!.metadata.mcp.title).toBe('c')
719 })
720
721 it('keeps the prefixed tool name independent of the display title', () => {
722 const tool = toServerTools(
723 fakeMcpClient(vi.fn()),
724 [mcpToolDef({ name: 'get_weather', title: 'Weather Lookup' })],
725 { prefix: 'wx' },
726 )[0]!
727 // The title is display-only — it must never leak into the model-facing name.
728 expect(tool.name).toBe('wx_get_weather')
729 expect(tool.metadata.mcp.title).toBe('Weather Lookup')
730 })
731
732 it('gives a frozen copy of the title and all 5 annotation fields', () => {
733 const annotations = {
734 title: 'Weather Lookup',
735 readOnlyHint: true,
736 destructiveHint: false,
737 idempotentHint: true,
738 openWorldHint: false,
739 }
740 const def = mcpToolDef({ name: 'get_weather', annotations })
741 const [tool] = toServerTools(fakeMcpClient(vi.fn()), [def], {})
742 const mcp = tool!.metadata.mcp
743 expect(mcp.title).toBe('Weather Lookup')
744 expect(mcp.annotations).toStrictEqual({
745 title: 'Weather Lookup',
746 readOnlyHint: true,
747 destructiveHint: false,
748 idempotentHint: true,
749 openWorldHint: false,
750 })
751 expect(Object.isFrozen(mcp.annotations)).toBe(true)
752 // A copy: the server's own object stays as it was.
753 expect(mcp.annotations).not.toBe(def.annotations)
754 expect(Object.isFrozen(def.annotations)).toBe(false)
755 })
756})
757
758describe('toServerTools — input schema defaults', () => {
759 it('adds properties: {} to a schema without properties', () => {
760 const [tool] = toServerTools(
761 fakeMcpClient(vi.fn()),
762 [mcpToolDef({ name: 'ping', inputSchema: { type: 'object' } })],
763 {},
764 )
765 expect(tool!.inputSchema).toEqual({ type: 'object', properties: {} })
766 })
767
768 it("adds type: 'object' to a schema without type and keeps its other keys", () => {
769 const [tool] = toServerTools(
770 fakeMcpClient(vi.fn()),
771 [
772 mcpToolDef({
773 name: 'search',
774 inputSchema: {
775 properties: { query: { type: 'string' } },
776 required: ['query'],
777 },
778 }),
779 ],
780 {},
781 )
782 expect(tool!.inputSchema).toEqual({
783 type: 'object',
784 properties: { query: { type: 'string' } },
785 required: ['query'],
786 })
787 })
788
789 it('gives a tool without an input schema an empty object schema', () => {
790 const def = mcpToolDef({ name: 'bare' })
791 Reflect.deleteProperty(def, 'inputSchema')
792 const [tool] = toServerTools(fakeMcpClient(vi.fn()), [def], {})
793 expect(tool!.inputSchema).toEqual({ type: 'object', properties: {} })
794 })
795
796 it('keeps a full schema as the server sent it', () => {
797 const inputSchema = {
798 type: 'object' as const,
799 properties: { city: { type: 'string' } },
800 required: ['city'],
801 }
802 const [tool] = toServerTools(
803 fakeMcpClient(vi.fn()),
804 [mcpToolDef({ name: 'get_weather', inputSchema })],
805 {},
806 )
807 expect(tool!.inputSchema).toEqual(inputSchema)
808 })
809})
810
811describe('toServerTools — toolName', () => {
812 it('names each tool with toolName, which wins over the prefix', () => {
813 const [tool] = toServerTools(
814 fakeMcpClient(vi.fn()),
815 [mcpToolDef({ name: 'get_weather' })],
816 { prefix: 'wx', toolName: (def) => `mcp__wx__${def.name}` },
817 )
818 expect(tool!.name).toBe('mcp__wx__get_weather')
819 expect(tool!.metadata.mcp).toMatchObject({
820 serverToolName: 'get_weather',
821 serverId: 'wx',
822 })
823 })
824
825 it('calls the server tool by its own name', async () => {
826 const callTool = vi
827 .fn()
828 .mockResolvedValue({ content: [{ type: 'text', text: 'ok' }] })
829 const [tool] = toServerTools(
830 fakeMcpClient(callTool),
831 [mcpToolDef({ name: 'get_weather' })],
832 { toolName: () => 'renamed' },
833 )
834 expect(tool!.name).toBe('renamed')
835 await expect(tool!.execute!({})).resolves.toBe('ok')
836 expect(callTool).toHaveBeenCalledWith(
837 { name: 'get_weather', arguments: {} },
838 expect.anything(),
839 )
840 })
841})
842
843describe('toServerTools', () => {
844 it('discovers tools and proxies execute to callTool', async () => {
845 const { clientTransport } = await makeServerWithWeatherTool()
846 const client = new Client({ name: 'test', version: '1.0.0' })
847 await client.connect(clientTransport)
848
849 const defs = (await client.listTools()).tools
850 const tools = toServerTools(client, defs, {
851 prefix: undefined,
852 lazy: false,
853 })
854
855 expect(tools.map((t) => t.name)).toContain('get_weather')
856 const tool = tools.find((t) => t.name === 'get_weather')!
857 const result = await tool.execute!(
858 { city: 'Brooklyn' },
859 {
860 threadId: 'thread-1',
861 toolCallId: 't',
862 emitCustomEvent: () => {},
863 },
864 )
865 expect(JSON.stringify(result)).toContain('Sunny in Brooklyn')
866 await client.close()
867 })
868
869 it('keeps task-optional tools on ordinary callTool execution', async () => {
870 const callTool = vi
871 .fn()
872 .mockResolvedValue({ content: [{ type: 'text', text: 'plain' }] })
873 const tools = toServerTools(
874 fakeMcpClient(callTool),
875 [
876 mcpToolDef({
877 name: 'optional_task',
878 execution: { taskSupport: 'optional' },
879 }),
880 ],
881 {},
882 )
883
884 await expect(tools[0]!.execute!({})).resolves.toBe('plain')
885 expect(callTool).toHaveBeenCalledOnce()
886 })
887
888 it('applies a prefix', async () => {
889 const { clientTransport } = await makeServerWithWeatherTool()
890 const client = new Client({ name: 'test', version: '1.0.0' })
891 await client.connect(clientTransport)
892 const defs = (await client.listTools()).tools
893 const tools = toServerTools(client, defs, { prefix: 'wx', lazy: false })
894 expect(tools.map((t) => t.name)).toContain('wx_get_weather')
895 await client.close()
896 })
897})
898
899type RawMessage = { id: string; params: Record<string, unknown> }
900
901/**
902 * A spec 2026 client whose transport answers each raw request at once with
903 * the messages `reply` returns. Like `fakeMcpClient`, the partial needs the
904 * `unknown` bridge.
905 */
906function scriptedModernClient(
907 reply: (message: RawMessage) => Array<unknown>,
908 extra: Record<string, unknown> = {},
909) {
910 const sent: Array<RawMessage> = []
911 const transport: {
912 onmessage?: (message: unknown) => void
913 send: (message: RawMessage) => Promise<void>
914 } = {
915 async send(message) {
916 sent.push(message)
917 for (const answer of reply(message)) transport.onmessage?.(answer)
918 if (extra.sendError instanceof Error) throw extra.sendError
919 },
920 }
921 const client = {
922 getProtocolEra: () => 'modern',
923 transport,
924 ...extra,
925 } as unknown as Client
926 return { client, sent }
927}
928
929function answerWith(result: unknown) {
930 return (message: RawMessage) => [{ jsonrpc: '2.0', id: message.id, result }]
931}
932
933/** A spec 2025 client. Each SDK request is answered by `answers[method]`. */
934function scriptedLegacyClient(
935 answers: Record<string, (signal?: AbortSignal) => unknown>,
936) {
937 return {
938 getProtocolEra: () => 'legacy',
939 async request(
940 rpc: { method: string },
941 _schema: unknown,
942 options?: { signal?: AbortSignal },
943 ) {
944 const answer = answers[rpc.method]
945 if (answer === undefined) throw new Error(`No answer for ${rpc.method}`)
946 return answer(options?.signal)
947 },
948 } as unknown as Client
949}
950
951const okResult = { content: [{ type: 'text', text: 'ok' }] }
952const missingResult = 'ended without a result or error'
953
954describe('callMcpTool — spec 2026 raw requests', () => {
955 it('fails when the reply has no tool result, and sends the envelope', async () => {
956 const { client, sent } = scriptedModernClient(answerWith(null), {
957 _outboundMetaEnvelope: () => ({ version: '2026-07-28' }),
958 })
959
960 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toThrow(
961 missingResult,
962 )
963 expect(sent[0]?.params._meta).toEqual({ version: '2026-07-28' })
964 })
965
966 it('sends no envelope when the client gives none', async () => {
967 for (const extra of [{}, { _outboundMetaEnvelope: () => 'x' }]) {
968 const { client, sent } = scriptedModernClient(answerWith(okResult), extra)
969 await expect(callMcpTool(client, 'ask', {}, false)).resolves.toEqual(
970 okResult,
971 )
972 expect(sent[0]?.params._meta).toBeUndefined()
973 }
974 })
975
976 it('uses defaults for a JSON-RPC error without code or message', async () => {
977 const { client } = scriptedModernClient((message) => [
978 { jsonrpc: '2.0', id: message.id, error: {} },
979 ])
980
981 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toMatchObject({
982 code: ProtocolErrorCode.InternalError,
983 message: 'The MCP request failed.',
984 })
985 })
986
987 it('ignores messages for other requests', async () => {
988 const { client } = scriptedModernClient((message) => [
989 { jsonrpc: '2.0', id: 'other', result: {} },
990 { jsonrpc: '2.0', id: message.id, result: okResult },
991 ])
992
993 await expect(callMcpTool(client, 'ask', {}, false)).resolves.toEqual(
994 okResult,
995 )
996 })
997
998 it('keeps the answer when send fails after it, and fails without one', async () => {
999 const sendError = new Error('send failed')
1000 const answered = scriptedModernClient(answerWith(okResult), { sendError })
1001 await expect(
1002 callMcpTool(answered.client, 'ask', {}, false),
1003 ).resolves.toEqual(okResult)
1004
1005 const silent = scriptedModernClient(() => [], { sendError })
1006 await expect(callMcpTool(silent.client, 'ask', {}, false)).rejects.toBe(
1007 sendError,
1008 )
1009 })
1010
1011 it('fails when the client has no transport', async () => {
1012 const client = { getProtocolEra: () => 'modern' } as unknown as Client
1013
1014 await expect(callMcpTool(client, 'ask', {}, false)).rejects.toThrow(
1015 'The MCP client is not connected.',
1016 )
1017 })
1018
1019 it('stops on abort and resolves with a signal that never fires', async () => {
1020 const answered = scriptedModernClient(answerWith(okResult))
1021 await expect(
1022 callMcpTool(
1023 answered.client,
1024 'ask',
1025 {},
1026 false,
1027 new AbortController().signal,
1028 ),
1029 ).resolves.toEqual(okResult)
1030
1031 const silent = scriptedModernClient(() => [])
1032 const controller = new AbortController()
1033 const pending = callMcpTool(
1034 silent.client,
1035 'ask',
1036 {},
1037 false,
1038 controller.signal,
1039 )
1040 controller.abort(new Error('stop'))
1041 await expect(pending).rejects.toThrow('stop')
1042 })
1043
1044 it('times out when the reply never comes', async () => {
1045 vi.useFakeTimers()
1046 try {
1047 const { client } = scriptedModernClient(() => [])
1048 const pending = expect(
1049 callMcpTool(client, 'ask', {}, false),
1050 ).rejects.toThrow(/timed out/)
1051 await vi.advanceTimersByTimeAsync(DEFAULT_REQUEST_TIMEOUT_MSEC)
1052 await pending
1053 } finally {
1054 vi.useRealTimers()
1055 }
1056 })
1057
1058 it('uses the requestOptions timeout', async () => {
1059 vi.useFakeTimers()
1060 try {
1061 const { client } = scriptedModernClient(() => [])
1062 const outcome = callMcpTool(
1063 client,
1064 'ask',
1065 {},
1066 false,
1067 undefined,
1068 undefined,
1069 {
1070 timeout: 1000,
1071 },
1072 ).catch((error: unknown) => error)
1073 await vi.advanceTimersByTimeAsync(1000)
1074 const error = await outcome
1075 expect(error).toBeInstanceOf(Error)
1076 expect(String(error)).toContain('timed out after 1000 ms')
1077 } finally {
1078 vi.useRealTimers()
1079 }
1080 })
1081
1082 it('reads every input request shape', async () => {
1083 const call = (result: unknown) =>
1084 callMcpTool(
1085 scriptedModernClient(answerWith(result)).client,
1086 'ask',
1087 {},
1088 false,
1089 )
1090
1091 await expect(
1092 call({
1093 resultType: 'input_required',
1094 inputRequests: { a: { method: 'roots/list', params: {} } },
1095 }),
1096 ).rejects.toThrow('unsupported input: roots/list')
1097
1098 const noRecord = { resultType: 'input_required', inputRequests: 'x' }
1099 const fallback = await inputRequiredFrom(() => call(noRecord))
1100 expect(fallback.request).toEqual(noRecord)
1101
1102 const bare = { method: 'elicitation/create', message: 'City?' }
1103 const flat = await inputRequiredFrom(() =>
1104 call({ status: 'input_required', inputRequests: { a: 1, b: bare } }),
1105 )
1106 expect(flat.kind).toBe('form')
1107 expect(flat.request).toEqual(bare)
1108
1109 const invalid = { status: 'input_required', inputRequests: { a: 1 } }
1110 expect((await inputRequiredFrom(() => call(invalid))).request).toEqual(
1111 invalid,
1112 )
1113
1114 await expect(
1115 call({ status: 'input_required', inputRequests: {} }),
1116 ).rejects.toThrow(missingResult)
1117 })
1118
1119 async function retrySent(
1120 inputRequests: Record<string, unknown> | undefined,
1121 inputResponse: Parameters<typeof callMcpTool>[5],
1122 requestState?: string,
1123 ) {
1124 const { client, sent } = scriptedModernClient((message) => [
1125 {
1126 jsonrpc: '2.0',
1127 id: message.id,
1128 result:
1129 sent.length === 1
1130 ? { resultType: 'input_required', inputRequests, requestState }
1131 : okResult,
1132 },
1133 ])
1134 await callMcpTool(client, 'draft', {}, false, undefined, inputResponse)
1135 return sent[1]?.params
1136 }
1137
1138 it('answers a sampling request with text, a result object, or a cancel', async () => {
1139 const sampling = { draft: { method: 'sampling/createMessage', params: {} } }
1140
1141 expect(
1142 await retrySent(sampling, { status: 'resolved', payload: 'Sunny' }, 's1'),
1143 ).toMatchObject({
1144 requestState: 's1',
1145 inputResponses: {
1146 draft: {
1147 role: 'assistant',
1148 content: { type: 'text', text: 'Sunny' },
1149 model: 'user',
1150 },
1151 },
1152 })
1153
1154 const custom = { role: 'assistant', content: { type: 'text', text: 'x' } }
1155 expect(
1156 (await retrySent(sampling, { status: 'resolved', payload: custom }))
1157 ?.inputResponses,
1158 ).toEqual({ draft: custom })
1159
1160 await expect(retrySent(sampling, { status: 'cancelled' })).rejects.toThrow(
1161 'The user cancelled the MCP sampling request.',
1162 )
1163 })
1164
1165 it('passes an ElicitResult as is and retries without requests', async () => {
1166 const form = { city: { method: 'elicitation/create', params: {} } }
1167 expect(
1168 (
1169 await retrySent(form, {
1170 status: 'resolved',
1171 payload: { action: 'decline' },
1172 })
1173 )?.inputResponses,
1174 ).toEqual({ city: { action: 'decline' } })
1175
1176 const params = await retrySent(
1177 undefined,
1178 { status: 'resolved', payload: 'x' },
1179 's1',
1180 )
1181 expect(params).toEqual({ name: 'draft', arguments: {}, requestState: 's1' })
1182 })
1183})
1184
1185describe('callMcpTool — spec 2025 task replies', () => {
1186 const working = (pollInterval: number) => () => ({
1187 task: { taskId: 't', status: 'working', pollInterval },
1188 })
1189 const completed = () => ({ taskId: 't', status: 'completed' })
1190
1191 it('throws MCPInputRequiredError when tasks/get asks for input', async () => {
1192 const client = scriptedLegacyClient({
1193 'tools/call': working(0),
1194 'tasks/get': () => ({
1195 status: 'input_required',
1196 inputRequests: {
1197 a: { method: 'elicitation/create', params: { message: 'City?' } },
1198 },
1199 }),
1200 })
1201
1202 const error = await inputRequiredFrom(() =>
1203 callMcpTool(client, 'job', {}, true),
1204 )
1205 expect(error.request).toEqual({ message: 'City?' })
1206 })
1207
1208 it('fails on a task body it cannot read', async () => {
1209 for (const body of [{}, { taskId: 't', status: 'weird' }]) {
1210 const client = scriptedLegacyClient({
1211 'tools/call': working(0),
1212 'tasks/get': () => body,
1213 })
1214 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
1215 missingResult,
1216 )
1217 }
1218 })
1219
1220 it('fails when tools/call or tasks/result has no tool result', async () => {
1221 const noTask = scriptedLegacyClient({ 'tools/call': () => ({}) })
1222 await expect(callMcpTool(noTask, 'job', {}, true)).rejects.toThrow(
1223 missingResult,
1224 )
1225
1226 const noResult = scriptedLegacyClient({
1227 'tools/call': working(0),
1228 'tasks/get': completed,
1229 'tasks/result': () => ({}),
1230 })
1231 await expect(callMcpTool(noResult, 'job', {}, true)).rejects.toThrow(
1232 missingResult,
1233 )
1234 })
1235
1236 it('names a failed task without a status message', async () => {
1237 const client = scriptedLegacyClient({
1238 'tools/call': () => ({ task: { taskId: 't', status: 'failed' } }),
1239 })
1240
1241 await expect(callMcpTool(client, 'job', {}, true)).rejects.toThrow(
1242 'MCP task "t" failed.',
1243 )
1244 })
1245
1246 it('waits the poll interval without a signal', async () => {
1247 const client = scriptedLegacyClient({
1248 'tools/call': working(1),
1249 'tasks/get': completed,
1250 'tasks/result': () => okResult,
1251 })
1252
1253 await expect(callMcpTool(client, 'job', {}, true)).resolves.toEqual(
1254 okResult,
1255 )
1256 })
1257
1258 it('sends requestOptions with the task tools/call', async () => {
1259 const seen: Array<unknown> = []
1260 const client = {
1261 getProtocolEra: () => 'legacy',
1262 async request(_rpc: unknown, _schema: unknown, options?: unknown) {
1263 seen.push(options)
1264 return okResult
1265 },
1266 } as unknown as Client
1267 await expect(
1268 callMcpTool(client, 'job', {}, true, undefined, undefined, {
1269 timeout: 5000,
1270 }),
1271 ).resolves.toEqual(okResult)
1272 expect(seen).toEqual([{ timeout: 5000 }])
1273 })
1274
1275 it('throws the abort reason when the request fails after an abort', async () => {
1276 const controller = new AbortController()
1277 const client = scriptedLegacyClient({
1278 'tools/call': (signal) =>
1279 new Promise((_, reject) => {
1280 signal?.addEventListener('abort', () =>
1281 reject(new Error('socket closed')),
1282 )
1283 }),
1284 })
1285 const pending = callMcpTool(client, 'job', {}, true, controller.signal)
1286 controller.abort(new Error('stop'))
1287
1288 await expect(pending).rejects.toThrow('stop')
1289 })
1290})
1291
1292describe('extractUiResourceUri', () => {
1293 it('returns undefined when _meta.ui is not an object', () => {
1294 expect(
1295 extractUiResourceUri({
1296 ...mcpToolDef({ name: 'a' }),
1297 _meta: { ui: 'x' },
1298 }),
1299 ).toBeUndefined()
1300 })
1301})