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

stdio.test.ts

231 lines6.9 KB

1import { fileURLToPath } from 'node:url'
2import { Client } from '@modelcontextprotocol/client'
3import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
4import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'
5import { toolDefinition } from '@tanstack/ai'
6import { describe, expect, it } from 'vitest'
7import { z } from 'zod'
8import { createMCPServer } from '../../src/server/create-server'
9import type { MCPToolContext } from '../../src/server/context'
10import { serveMCPStdio } from '../../src/server/stdio'
11​
12const childEnv = 'TANSTACK_AI_MCP_STDIO_CHILD'
13​
14function echoTool() {
15 return toolDefinition({
16 name: 'echo',
17 description: 'Echo text',
18 inputSchema: z.object({ text: z.string() }),
19 }).server(async (args) => args.text)
21​
22function startChildServer() {
23 const server = createMCPServer({
24 name: 'weather',
25 version: '1.0.0',
26 tools: [echoTool()],
27 })
28 serveMCPStdio(server)
30​
31if (process.env[childEnv] === '1') {
32 startChildServer()
33} else if (process.env[childEnv] === 'input') {
34 startInputServer()
35} else if (process.env[childEnv] === 'flaky-stream') {
36 startFlakyStreamServer()
37} else if (process.env[childEnv] === 'auth') {
38 startAuthServer()
39} else {
40 describe('serveMCPStdio', () => {
41 it('lists and calls the tool for a spec 2025 stdio client', async () => {
42 const result = await echoOverStdio('2025')
43 expect(result.names).toEqual(['echo'])
44 expect(result.content).toEqual([{ type: 'text', text: 'hi' }])
45 }, 60000)
46​
47 it('lists and calls the tool for a spec 2026 stdio client', async () => {
48 const result = await echoOverStdio('2026')
49 expect(result.names).toEqual(['echo'])
50 expect(result.content).toEqual([{ type: 'text', text: 'hi' }])
51 }, 60000)
52​
53 it('answers a spec 2025 input request while the tool is still running', async () => {
54 const result = await askOverStdio()
55 expect(result).toEqual([{ type: 'text', text: 'Paris' }])
56 }, 60000)
57​
58 it('keeps the answer and opens the spec 2025 stream again after a failed open', async () => {
59 const result = await echoOverStdio('2025', 'flaky-stream')
60 expect(result.content).toEqual([{ type: 'text', text: 'hi' }])
61 expect(result.stderr).toContain('stream open 2')
62 }, 60000)
63​
64 it('answers with a JSON-RPC error when the server returns an empty 401', async () => {
65 // A pinned 2026 client reports any discover failure as a version
66 // mismatch. The legacy handshake shows the error text as is.
67 await expect(echoOverStdio('2025', 'auth')).rejects.toThrow(/HTTP 401/)
68 }, 60000)
69 })
71​
72// Every request gets an empty 401. The host must still get an answer.
73function startAuthServer() {
74 const server = createMCPServer({
75 name: 'weather',
76 version: '1.0.0',
77 tools: [echoTool()],
78 auth: {
79 verifier: {
80 verifyAccessToken: () =>
81 Promise.reject(
82 new OAuthError(OAuthErrorCode.InvalidToken, 'Unknown token'),
83 ),
84 },
85 },
86 })
87 serveMCPStdio(server)
89​
90// The first GET stream throws. The next message must open a new one.
91function startFlakyStreamServer() {
92 const server = createMCPServer({
93 name: 'weather',
94 version: '1.0.0',
95 tools: [echoTool()],
96 })
97 let opens = 0
98 serveMCPStdio({
99 fetch(request) {
100 if (request.method !== 'GET') return server.fetch(request)
101 opens += 1
102 console.error(`stream open ${opens}`)
103 if (opens === 1) return Promise.reject(new Error('stream open failed'))
104 return server.fetch(request)
105 },
106 })
108​
109function askTool() {
110 return toolDefinition({
111 name: 'ask',
112 description: 'Ask for a city',
113 inputSchema: z.object({}),
114 }).server<MCPToolContext>(async (_args, ctx) => {
115 const answer = await ctx.context.requestInput({ message: 'Which city?' })
116 return typeof answer === 'string' ? answer : 'missing'
117 })
119​
120function startInputServer() {
121 const server = createMCPServer({
122 name: 'weather',
123 version: '1.0.0',
124 tools: [askTool()],
125 })
126 serveMCPStdio(server)
128​
129function clientFor(era: '2025' | '2026') {
130 if (era === '2026') {
131 return new Client(
132 { name: 'tester', version: '1.0.0' },
133 { versionNegotiation: { mode: { pin: '2026-07-28' } } },
134 )
135 }
136 return new Client(
137 { name: 'tester', version: '1.0.0' },
138 { versionNegotiation: { mode: 'legacy' } },
139 )
141​
142async function echoOverStdio(
143 era: '2025' | '2026',
144 mode: '1' | 'flaky-stream' | 'auth' = '1',
145) {
146 const testFile = fileURLToPath(import.meta.url)
147 const packageRoot = fileURLToPath(new URL('../..', import.meta.url))
148 const stderrChunks: Array<string> = []
149 const transport = new StdioClientTransport({
150 command: process.execPath,
151 args: ['--import', 'jiti/register', testFile],
152 cwd: packageRoot,
153 env: { [childEnv]: mode },
154 stderr: 'pipe',
155 })
156 transport.stderr?.on('data', (chunk) => {
157 stderrChunks.push(chunkText(chunk))
158 })
159 const client = clientFor(era)
160 try {
161 await client.connect(transport)
162 const listed = await client.listTools()
163 const echoed = await client.callTool({
164 name: 'echo',
165 arguments: { text: 'hi' },
166 })
167 return {
168 names: listed.tools.map((tool) => tool.name),
169 content: echoed.content,
170 stderr: stderrChunks.join(''),
171 }
172 } catch (error) {
173 const detail =
174 error instanceof Error ? error.message : 'The stdio client failed.'
175 throw new Error(`${detail}\n${stderrChunks.join('')}`)
176 } finally {
177 try {
178 await client.close()
179 } catch {
180 // close rejects when connect did not finish.
181 }
182 }
184​
185async function askOverStdio() {
186 const testFile = fileURLToPath(import.meta.url)
187 const packageRoot = fileURLToPath(new URL('../..', import.meta.url))
188 const stderrChunks: Array<string> = []
189 const transport = new StdioClientTransport({
190 command: process.execPath,
191 args: ['--import', 'jiti/register', testFile],
192 cwd: packageRoot,
193 env: { [childEnv]: 'input' },
194 stderr: 'pipe',
195 })
196 transport.stderr?.on('data', (chunk) => {
197 stderrChunks.push(chunkText(chunk))
198 })
199 const client = new Client(
200 { name: 'tester', version: '1.0.0' },
201 {
202 capabilities: { elicitation: { form: {} } },
203 versionNegotiation: { mode: 'legacy' },
204 },
205 )
206 client.setRequestHandler('elicitation/create', async () => ({
207 action: 'accept',
208 content: { value: 'Paris' },
209 }))
210 try {
211 await client.connect(transport)
212 const answered = await client.callTool({ name: 'ask', arguments: {} })
213 return answered.content
214 } catch (error) {
215 const detail =
216 error instanceof Error ? error.message : 'The stdio client failed.'
217 throw new Error(`${detail}\n${stderrChunks.join('')}`)
218 } finally {
219 try {
220 await client.close()
221 } catch {
222 // close rejects when connect did not finish.
223 }
224 }
226​
227function chunkText(chunk: unknown) {
228 if (typeof chunk === 'string') return chunk
229 if (chunk instanceof Uint8Array) return new TextDecoder().decode(chunk)
230 return ''