Open History to see the last commit
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)
20}
21
22function startChildServer() {
23 const server = createMCPServer({
24 name: 'weather',
25 version: '1.0.0',
26 tools: [echoTool()],
27 })
28 serveMCPStdio(server)
29}
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 })
70}
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)
88}
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 // The wrapper below hides the server from serveMCPStdio, so set it here.
96 sessions: 'memory',
97 tools: [echoTool()],
98 })
99 let opens = 0
100 serveMCPStdio({
101 fetch(request) {
102 if (request.method !== 'GET') return server.fetch(request)
103 opens += 1
104 console.error(`stream open ${opens}`)
105 if (opens === 1) return Promise.reject(new Error('stream open failed'))
106 return server.fetch(request)
107 },
108 })
109}
110
111function askTool() {
112 return toolDefinition({
113 name: 'ask',
114 description: 'Ask for a city',
115 inputSchema: z.object({}),
116 }).server<MCPToolContext>(async (_args, ctx) => {
117 const answer = await ctx.context.requestInput({ message: 'Which city?' })
118 return typeof answer === 'string' ? answer : 'missing'
119 })
120}
121
122function startInputServer() {
123 const server = createMCPServer({
124 name: 'weather',
125 version: '1.0.0',
126 tools: [askTool()],
127 })
128 serveMCPStdio(server)
129}
130
131function clientFor(era: '2025' | '2026') {
132 if (era === '2026') {
133 return new Client(
134 { name: 'tester', version: '1.0.0' },
135 { versionNegotiation: { mode: { pin: '2026-07-28' } } },
136 )
137 }
138 return new Client(
139 { name: 'tester', version: '1.0.0' },
140 { versionNegotiation: { mode: 'legacy' } },
141 )
142}
143
144async function echoOverStdio(
145 era: '2025' | '2026',
146 mode: '1' | 'flaky-stream' | 'auth' = '1',
147) {
148 const testFile = fileURLToPath(import.meta.url)
149 const packageRoot = fileURLToPath(new URL('../..', import.meta.url))
150 const stderrChunks: Array<string> = []
151 const transport = new StdioClientTransport({
152 command: process.execPath,
153 args: ['--import', 'jiti/register', testFile],
154 cwd: packageRoot,
155 env: { [childEnv]: mode },
156 stderr: 'pipe',
157 })
158 transport.stderr?.on('data', (chunk) => {
159 stderrChunks.push(chunkText(chunk))
160 })
161 const client = clientFor(era)
162 try {
163 await client.connect(transport)
164 const listed = await client.listTools()
165 const echoed = await client.callTool({
166 name: 'echo',
167 arguments: { text: 'hi' },
168 })
169 return {
170 names: listed.tools.map((tool) => tool.name),
171 content: echoed.content,
172 stderr: stderrChunks.join(''),
173 }
174 } catch (error) {
175 const detail =
176 error instanceof Error ? error.message : 'The stdio client failed.'
177 throw new Error(`${detail}\n${stderrChunks.join('')}`)
178 } finally {
179 try {
180 await client.close()
181 } catch {
182 // close rejects when connect did not finish.
183 }
184 }
185}
186
187async function askOverStdio() {
188 const testFile = fileURLToPath(import.meta.url)
189 const packageRoot = fileURLToPath(new URL('../..', import.meta.url))
190 const stderrChunks: Array<string> = []
191 const transport = new StdioClientTransport({
192 command: process.execPath,
193 args: ['--import', 'jiti/register', testFile],
194 cwd: packageRoot,
195 env: { [childEnv]: 'input' },
196 stderr: 'pipe',
197 })
198 transport.stderr?.on('data', (chunk) => {
199 stderrChunks.push(chunkText(chunk))
200 })
201 const client = new Client(
202 { name: 'tester', version: '1.0.0' },
203 {
204 capabilities: { elicitation: { form: {} } },
205 versionNegotiation: { mode: 'legacy' },
206 },
207 )
208 client.setRequestHandler('elicitation/create', async () => ({
209 action: 'accept',
210 content: { value: 'Paris' },
211 }))
212 try {
213 await client.connect(transport)
214 const answered = await client.callTool({ name: 'ask', arguments: {} })
215 return answered.content
216 } catch (error) {
217 const detail =
218 error instanceof Error ? error.message : 'The stdio client failed.'
219 throw new Error(`${detail}\n${stderrChunks.join('')}`)
220 } finally {
221 try {
222 await client.close()
223 } catch {
224 // close rejects when connect did not finish.
225 }
226 }
227}
228
229function chunkText(chunk: unknown) {
230 if (typeof chunk === 'string') return chunk
231 if (chunk instanceof Uint8Array) return new TextDecoder().decode(chunk)
232 return ''
233}