import { describe, expect, test } from 'bun:test'; import { z } from 'zod'; import { JSON_RPC_ERROR_CODES, type StdioOutput, createMcpServer, defineMcpTool, runStdioServer, } from '../src/mcp/index'; function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } { const chunks: string[] = []; const output: StdioOutput = { write(chunk: string): boolean { chunks.push(chunk); return true; }, }; return { output, chunks, text: () => chunks.join(''), }; } async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator { for (const chunk of chunks) { yield chunk; } } describe('MCP stdio transport', () => { test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => { const echoTool = defineMcpTool({ name: 'echo_label', description: 'Echoes a UTF-8 label.', inputSchema: z.object({ label: z.string() }).strict(), handler(input) { return { content: [{ type: 'text', text: input.label }], }; }, }); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [echoTool], }); const encoder = new TextEncoder(); const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`; const msg3Bytes = encoder.encode( `${JSON.stringify({ jsonrpc: '2.0', id: 'utf8-2', method: 'tools/call', params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } }, })}\n` ); // Split right in the middle of the multi-byte UTF-8 emoji sequence. const rocketStart = msg3Bytes.indexOf(0xf0); expect(rocketStart).toBeGreaterThan(0); const splitPoint = rocketStart + 2; const input = yieldChunks([ encoder.encode(msg1), encoder.encode(msg2), msg3Bytes.slice(0, splitPoint), msg3Bytes.slice(splitPoint), ]); const sink = createMemoryOutput(); await runStdioServer(server, { input, output: sink.output }); const rawOut = sink.text(); expect(rawOut.endsWith('\n')).toBe(true); const lines = rawOut.slice(0, -1).split('\n'); expect(lines).toHaveLength(2); const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record }; const resp2 = JSON.parse(lines[1] ?? '') as { id: string; result: { content: { type: string; text: string }[] }; }; expect(resp1.id).toBe(1); expect(resp1.result).toEqual({}); expect(resp2.id).toBe('utf8-2'); expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ'); }); test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => { const delayedTool = defineMcpTool({ name: 'delayed', description: 'Resolves after deterministic microtask/timer delay.', inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(), async handler(input) { await new Promise(resolve => { setTimeout(resolve, input.delayMs); }); return { content: [{ type: 'text', text: input.tag }], }; }, }); const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', tools: [delayedTool], }); const payload = [ JSON.stringify({ jsonrpc: '2.0', id: 'first-slow', method: 'tools/call', params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } }, }), JSON.stringify({ jsonrpc: '2.0', id: 'second-fast', method: 'tools/call', params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } }, }), ].join('\n'); const sink = createMemoryOutput(); await runStdioServer(server, { input: yieldChunks([`${payload}\n`]), output: sink.output, }); const lines = sink.text().trimEnd().split('\n'); expect(lines).toHaveLength(2); const first = JSON.parse(lines[0] ?? '') as { id: string }; const second = JSON.parse(lines[1] ?? '') as { id: string }; expect(first.id).toBe('first-slow'); expect(second.id).toBe('second-fast'); }); test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => { const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', }); const input = yieldChunks([ '\n \r\n', `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`, '\n', JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }), ]); const sink = createMemoryOutput(); await runStdioServer(server, { input, output: sink.output }); const lines = sink.text().trimEnd().split('\n'); expect(lines).toHaveLength(2); expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1); expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2); }); test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => { const server = createMcpServer({ name: 'stock-bot-research', version: '0.1.0', }); const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`; const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`; const sink = createMemoryOutput(); await runStdioServer(server, { input: yieldChunks([hugeLine, nextLine]), output: sink.output, maxLineBytes: 128, }); const lines = sink.text().trimEnd().split('\n'); expect(lines).toHaveLength(2); const errResp = JSON.parse(lines[0] ?? '') as { id: null; error: { code: number }; }; const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record }; expect(errResp.id).toBeNull(); expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); expect(okResp.id).toBe(2); expect(okResp.result).toEqual({}); }); });