Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { describe, expect, it } from 'vitest'
3import { z } from 'zod'
4import { createMCPClient } from '../src/client'
5import { ToolInputRequiredError } from '../src/server/context'
6import type { MCPToolContext } from '../src/server/context'
7import { createMCPServer } from '../src/server/create-server'
8import { resourceDefinition } from '../src/server/definitions'
9import { travelClient } from './direct-client-boundary'
10import { travelServer } from './fixtures/travel-server'
11
12function contextServer() {
13 return createMCPServer({
14 name: 'context',
15 version: '1.0.0',
16 sample: async () => 'from-sample',
17 tools: [
18 toolDefinition({
19 name: 'ask',
20 description: 'Asks the user',
21 inputSchema: z.object({ city: z.string() }),
22 }).server<MCPToolContext>(async (_args, ctx) =>
23 String(await ctx.context.requestInput({ message: 'Which day?' })),
24 ),
25 toolDefinition({
26 name: 'draft',
27 description: 'Uses the sample option',
28 }).server<MCPToolContext>(async (_args, ctx) =>
29 String(await ctx.context.sample({ messages: [] })),
30 ),
31 ],
32 })
33}
34
35describe('createMCPClient({ server })', () => {
36 it('calls the tool, the resource, and the prompt on the server object', async () => {
37 const client = await travelClient()
38 const forecast = await client.callTool('get_weather', { city: 'Paris' })
39 const guide = await client.readResource('file:///city-guide.md')
40 const brief = await client.getPrompt('trip_brief', { city: 'Paris' })
41 const typedForecast: string = forecast
42
43 expect(typedForecast).toBe('Sunny in Paris')
44 expect(guide).toEqual({ text: '# Paris\n\nPack a light jacket.' })
45 expect(brief).toEqual([
46 { role: 'user', content: 'Write a one-day plan for Paris.' },
47 ])
48 })
49
50 it('throws when the tool name is not on the server', async () => {
51 const client = await travelClient()
52 const missing = client as {
53 callTool: (name: string, args: { city: string }) => Promise<unknown>
54 }
55 await expect(
56 missing.callTool('missing', { city: 'Paris' }),
57 ).rejects.toThrow('The MCP server has no tool missing.')
58 })
59
60 it('gives the tool ctx.context.requestInput, which throws ToolInputRequiredError', async () => {
61 const client = await createMCPClient({ server: contextServer() })
62 await expect(
63 client.callTool('ask', { city: 'Paris' }),
64 ).rejects.toBeInstanceOf(ToolInputRequiredError)
65 })
66
67 it('gives the tool ctx.context.sample from the server sample option', async () => {
68 const client = await createMCPClient({ server: contextServer() })
69 expect(await client.callTool('draft', {})).toBe('from-sample')
70 })
71
72 it('rejects args that do not match the input schema', async () => {
73 const client = await createMCPClient({ server: contextServer() })
74 const loose = client as {
75 callTool: (name: string, args: unknown) => Promise<unknown>
76 }
77 await expect(loose.callTool('ask', { city: 1 })).rejects.toThrow()
78 })
79
80 it('parses the tool output with its output schema, like the HTTP server', async () => {
81 const server = createMCPServer({
82 name: 'counter',
83 version: '1.0.0',
84 tools: [
85 toolDefinition({
86 name: 'count',
87 description: 'Counts',
88 outputSchema: z.object({
89 n: z.string().transform(Number).pipe(z.number()),
90 }),
91 }).server(async () => ({ n: '3' })),
92 toolDefinition({
93 name: 'broken',
94 description: 'Returns output that fails its schema',
95 outputSchema: z.object({ n: z.number() }),
96 }).server(async () => JSON.parse('{"n":"x"}')),
97 ],
98 })
99 const client = await createMCPClient({ server })
100
101 expect(await client.callTool('count', {})).toEqual({ n: 3 })
102 await expect(client.callTool('broken', {})).rejects.toThrow(
103 'Tool broken returned output that does not match its outputSchema',
104 )
105 })
106
107 it('passes a context to a resource read', async () => {
108 const server = createMCPServer({
109 name: 'tenants',
110 version: '1.0.0',
111 resources: [
112 resourceDefinition({
113 uri: 'myapp://tenant',
114 name: 'tenant',
115 mimeType: 'text/plain',
116 }).read(async (_uri, variables, ctx) => ({
117 text: `${String(ctx.context.tenant)} ${JSON.stringify(variables)}`,
118 })),
119 ],
120 })
121 const client = await createMCPClient({ server })
122
123 expect(
124 await client.readResource('myapp://tenant', { tenant: 'acme' }),
125 ).toEqual({ text: 'acme {}' })
126 expect(await client.readResource('myapp://tenant')).toEqual({
127 text: 'undefined {}',
128 })
129 })
130})
131
132function rejectedCalls() {
133 return travelClient().then((client) => {
134 // @ts-expect-error the tool name is not on this server
135 void client.callTool('missing', { city: 'Paris' })
136 // @ts-expect-error city is a string
137 void client.callTool('get_weather', { city: 1 })
138 // @ts-expect-error the URI is not on this server
139 void client.readResource('file:///missing.md')
140 // @ts-expect-error the prompt name is not on this server
141 void client.getPrompt('missing', { city: 'Paris' })
142 // @ts-expect-error city is a string
143 void client.getPrompt('trip_brief', { city: 1 })
144 })
145}
146
147void rejectedCalls
148void travelServer