diff --git a/libs/research/test/mcp-edge-cases.test.ts b/libs/research/test/mcp-edge-cases.test.ts new file mode 100644 index 00000000..c20ec3c5 --- /dev/null +++ b/libs/research/test/mcp-edge-cases.test.ts @@ -0,0 +1,595 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + VaultHoldoutFenceError, +} from '../src/market-data-store'; +import { + type BarsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + JSON_RPC_ERROR_CODES, + type JsonSchemaObject, + QUERY_DATA_MAX_LISTING_IDS, + type QueryDataResultPayload, + type StdioOutput, + createMcpServer, + createQueryDataTool, + defineMcpTool, + runStdioServer, + zodObjectToJsonSchema, +} from '../src/mcp/index'; + +// QA edge cases for T-129 (M2.1a MCP core) not covered by the programmer's suites. + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); + +interface ToolResult { + isError?: boolean; + content: { type: string; text: string }[]; +} + +interface RpcResponse { + id: string | number | null; + result?: unknown; + error?: { code: number; message: string }; +} + +function rpc(id: string | number, method: string, params?: unknown): string { + return JSON.stringify( + params === undefined ? { jsonrpc: '2.0', id, method } : { jsonrpc: '2.0', id, method, params } + ); +} + +function parse(raw: string | null): RpcResponse { + expect(raw).not.toBeNull(); + return JSON.parse(raw as string) as RpcResponse; +} + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 1, + vwap: close, + knownAt, + }; +} + +interface RecordingStore { + readonly store: MarketDataStore; + readonly barsCalls: BarsQuery[]; + readonly universeCalls: UniverseQuery[]; + readonly iteratorClosed: () => boolean; +} + +function createRecordingStore(options: { + batches?: readonly BarBatch[]; + universeIds?: readonly number[]; + universeError?: Error; +}): RecordingStore { + const barsCalls: BarsQuery[] = []; + const universeCalls: UniverseQuery[] = []; + let closed = false; + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + const batches = options.batches ?? []; + return { + async *[Symbol.asyncIterator]() { + try { + for (const batch of batches) { + yield batch; + } + } finally { + closed = true; + } + }, + }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options.universeError !== undefined) { + throw options.universeError; + } + return [...(options.universeIds ?? [])]; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + return { store, barsCalls, universeCalls, iteratorClosed: () => closed }; +} + +async function callQueryData( + rec: RecordingStore, + args: Record, + vaultCutoffTs = VAULT_CUTOFF_TS +): Promise<{ isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'qa', + version: '0.0.0', + tools: [createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs } })], + }); + const resp = parse( + await server.handleMessage(rpc('q', 'tools/call', { name: 'query_data', arguments: args })) + ); + expect(resp.error).toBeUndefined(); + const result = resp.result as ToolResult; + return { isError: result.isError === true, text: result.content[0]?.text ?? '' }; +} + +function memoryOutput(): { output: StdioOutput; chunks: string[] } { + const chunks: string[] = []; + return { + chunks, + output: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + }; +} + +async function* chunksOf(chunks: readonly (string | Uint8Array)[]): AsyncGenerator { + for (const c of chunks) { + yield c; + } +} + +describe('MCP server edge cases (QA)', () => { + test('tools/call sent as a notification returns null and never runs the handler', async () => { + let calls = 0; + const tool = defineMcpTool({ + name: 'side_effect', + description: 'Counts invocations.', + inputSchema: z.object({}).strict(), + handler() { + calls += 1; + return { content: [{ type: 'text', text: 'ran' }] }; + }, + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + method: 'tools/call', + params: { name: 'side_effect', arguments: {} }, + }) + ); + + expect(raw).toBeNull(); + expect(calls).toBe(0); + }); + + test('tools/call with missing or array params returns -32602 echoing the id', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + for (const [id, params] of [ + [7, undefined], + ['arr', [{ name: 'x' }]], + [8, { arguments: {} }], + [9, { name: 'x', arguments: [1, 2] }], + ] as const) { + const resp = parse(await server.handleMessage(rpc(id, 'tools/call', params))); + expect(resp.id).toBe(id); + expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + } + }); + + test('initialize with invalid params returns -32602 and does not crash', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const resp = parse( + await server.handleMessage(rpc('init', 'initialize', { clientInfo: { name: 5 } })) + ); + expect(resp.id).toBe('init'); + expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('non-Error throws and errors with unsafe names are sanitized to a fixed message', async () => { + const throwString = defineMcpTool({ + name: 'throw_string', + description: 'Throws a string.', + inputSchema: z.object({}).strict(), + handler() { + throw '/srv/secret/path leaked'; + }, + }); + const throwBadName = defineMcpTool({ + name: 'throw_bad_name', + description: 'Throws an error whose name contains a path.', + inputSchema: z.object({}).strict(), + async handler() { + const err = new Error('boom /srv/secret/x.ts'); + err.name = '/srv/secret/x.ts'; + throw err; + }, + }); + const server = createMcpServer({ + name: 'qa', + version: '0.0.0', + tools: [throwString, throwBadName], + }); + + for (const [name, expected] of [ + ['throw_string', 'Error: Tool execution failed.'], + ['throw_bad_name', 'Error: Tool execution failed.'], + ] as const) { + const resp = parse(await server.handleMessage(rpc(name, 'tools/call', { name, arguments: {} }))); + const result = resp.result as ToolResult; + expect(result.isError).toBe(true); + expect(result.content[0]?.text).toBe(expected); + expect(result.content[0]?.text).not.toContain('/srv/secret'); + } + }); + + test('responses are single-line JSON even when tool text contains newlines', async () => { + const tool = defineMcpTool({ + name: 'multiline', + description: 'Returns multi-line text.', + inputSchema: z.object({}).strict(), + handler: () => ({ content: [{ type: 'text', text: 'line1\nline2\r\nline3' }] }), + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + const raw = await server.handleMessage( + rpc(1, 'tools/call', { name: 'multiline', arguments: {} }) + ); + expect(raw).not.toContain('\n'); + expect(raw).not.toContain('\r'); + expect((parse(raw).result as ToolResult).content[0]?.text).toBe('line1\nline2\r\nline3'); + }); + + test('explicit jsonSchema override is emitted verbatim by tools/list', async () => { + const override: JsonSchemaObject = { + type: 'object', + properties: { q: { type: 'string', description: 'custom' } }, + required: ['q'], + additionalProperties: false, + }; + const tool = defineMcpTool({ + name: 'with_override', + description: 'Has a hand-written schema.', + inputSchema: z.object({ q: z.string() }).strict(), + jsonSchema: override, + handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + const resp = parse(await server.handleMessage(rpc(1, 'tools/list'))); + const tools = (resp.result as { tools: { inputSchema: unknown }[] }).tools; + expect(tools[0]?.inputSchema).toEqual(override); + }); + + test('zod converter maps nullable, union, literal, exclusive bounds, defaults, arrays and refinements', () => { + const schema = z + .object({ + n: z.number().gt(0).lt(10).describe('open interval'), + s: z.string().length(3), + maybe: z.string().nullable(), + either: z.union([z.string(), z.number().int()]), + lit: z.literal('fixed'), + flag: z.boolean().default(false), + tags: z.array(z.string()).min(1).max(4).optional(), + }) + .strict() + .refine(() => true) + .describe('root'); + + const json = zodObjectToJsonSchema(schema); + + expect(json.type).toBe('object'); + expect(json.additionalProperties).toBe(false); + expect(json.description).toBe('root'); + expect(json.required).toEqual(['n', 's', 'maybe', 'either', 'lit']); + expect(json.properties.n).toEqual({ + type: 'number', + description: 'open interval', + exclusiveMinimum: 0, + exclusiveMaximum: 10, + }); + expect(json.properties.s).toEqual({ type: 'string', minLength: 3, maxLength: 3 }); + expect(json.properties.maybe).toEqual({ anyOf: [{ type: 'string' }, { type: 'null' }] }); + expect(json.properties.either).toEqual({ + anyOf: [{ type: 'string' }, { type: 'integer' }], + }); + expect(json.properties.lit).toEqual({ type: 'string', const: 'fixed' }); + expect(json.properties.flag).toEqual({ type: 'boolean', default: false }); + expect(json.properties.tags).toEqual({ + type: 'array', + items: { type: 'string' }, + minItems: 1, + maxItems: 4, + }); + + expect(() => zodObjectToJsonSchema(z.string())).toThrow(/must be a ZodObject/); + }); + + test('defineMcpTool and createMcpServer reject empty names/descriptions/versions', () => { + const base = { + inputSchema: z.object({}).strict(), + handler: () => ({ content: [{ type: 'text' as const, text: '' }] }), + }; + expect(() => defineMcpTool({ ...base, name: ' ', description: 'd' })).toThrow(); + expect(() => defineMcpTool({ ...base, name: 'n', description: '' })).toThrow(); + expect(() => createMcpServer({ name: '', version: '1' })).toThrow(); + expect(() => createMcpServer({ name: 'n', version: ' ' })).toThrow(); + }); +}); + +describe('MCP stdio edge cases (QA)', () => { + test('oversized frame spread across many chunks yields exactly one -32700 and recovers', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const pad = 'x'.repeat(100); + const sink = memoryOutput(); + + await runStdioServer(server, { + input: chunksOf([ + `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${pad}`, + pad, + pad, + `${pad}"}\n${rpc(2, 'ping')}\n`, + ]), + output: sink.output, + maxLineBytes: 64, + }); + + const lines = sink.chunks.join('').trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const first = JSON.parse(lines[0] ?? '') as RpcResponse; + const second = JSON.parse(lines[1] ?? '') as RpcResponse; + expect(first.id).toBeNull(); + expect(first.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + expect(second.id).toBe(2); + expect(second.result).toEqual({}); + }); + + test('oversized unterminated tail at EOF yields one -32700 and never dispatches it', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([`${rpc(1, 'ping')}\n`, `{"jsonrpc":"2.0","id":2,"method":"ping","p":"${'y'.repeat(200)}"}`]), + output: sink.output, + maxLineBytes: 128, + }); + const lines = sink.chunks.join('').trimEnd().split('\n'); + expect(lines).toHaveLength(2); + expect((JSON.parse(lines[0] ?? '') as RpcResponse).id).toBe(1); + const err = JSON.parse(lines[1] ?? '') as RpcResponse; + expect(err.id).toBeNull(); + expect(err.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('malformed line between valid requests yields -32700 and processing continues in order', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([`${rpc('a', 'ping')}\n{oops\n${rpc('b', 'ping')}\n`]), + output: sink.output, + }); + const lines = sink.chunks.join('').trimEnd().split('\n').map(l => JSON.parse(l) as RpcResponse); + expect(lines.map(l => l.id)).toEqual(['a', null, 'b']); + expect(lines[1]?.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('a stream of only notifications writes zero bytes', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([ + `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`, + `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 1 } })}\n`, + ]), + output: sink.output, + }); + expect(sink.chunks).toEqual([]); + }); + + test('waits for drain when output.write signals backpressure before writing the next response', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const events: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + events.push(`write:${(JSON.parse(chunk) as RpcResponse).id}`); + return false; + }, + once(_event: 'drain', listener: () => void) { + events.push('await-drain'); + queueMicrotask(() => { + events.push('drain'); + listener(); + }); + }, + }; + + await runStdioServer(server, { + input: chunksOf([`${rpc(1, 'ping')}\n${rpc(2, 'ping')}\n`]), + output, + }); + + expect(events).toEqual(['write:1', 'await-drain', 'drain', 'write:2', 'await-drain', 'drain']); + }); + + test('rejects non-positive or non-integer maxLineBytes', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + for (const bad of [0, -1, 1.5, Number.NaN]) { + await expect( + runStdioServer(server, { input: chunksOf([]), output: memoryOutput().output, maxLineBytes: bad }) + ).rejects.toThrow(/maxLineBytes/); + } + }); +}); + +describe('MCP query_data edge cases (QA)', () => { + test('selector rules: both, neither, too many, or non-integer listingIds are rejected with zero store calls', async () => { + const tooMany = Array.from({ length: QUERY_DATA_MAX_LISTING_IDS + 1 }, (_, i) => i + 1); + const cases: Record[] = [ + { listingIds: [1], universe: 'US_EQ', from: '2025-03-01', to: '2025-03-10' }, + { from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: tooMany, from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [1.5], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [2_147_483_648], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [1], from: '2025-03-01', to: '2025-03-10', timeframe: '1w' }, + { listingIds: [1], from: '2025-03-01', to: '2025-03-10', limit: 2.5 }, + ]; + for (const args of cases) { + const rec = createRecordingStore({}); + const res = await callQueryData(rec, args); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "query_data"'); + expect(rec.barsCalls).toHaveLength(0); + expect(rec.universeCalls).toHaveLength(0); + } + + const okRec = createRecordingStore({}); + const ok = await callQueryData(okRec, { + listingIds: tooMany.slice(0, QUERY_DATA_MAX_LISTING_IDS), + from: '2025-03-01', + to: '2025-03-10', + }); + expect(ok.isError).toBe(false); + expect(okRec.barsCalls[0]?.listingIds).toHaveLength(QUERY_DATA_MAX_LISTING_IDS); + }); + + test('from after to maps to MarketDataStoreValidationError with zero store calls', async () => { + const rec = createRecordingStore({}); + const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-10', to: '2025-03-01' }); + expect(res.isError).toBe(true); + expect(res.text).toBe('MarketDataStoreValidationError: Invalid query parameter "from".'); + expect(rec.barsCalls).toHaveLength(0); + }); + + test('exactly limit eligible rows across batches is not truncated; one more is truncated and closes the store stream', async () => { + const base = Date.UTC(2025, 0, 2); + const rowsA = [makeBar(1, base, 1), makeBar(1, base + 1, 2)]; + const rowsB = [makeBar(1, base + 2, 3)]; + + const exact = createRecordingStore({ batches: [{ rows: rowsA }, { rows: rowsB }] }); + const exactRes = await callQueryData(exact, { + listingIds: [1], + from: '2025-01-01', + to: '2025-03-01', + limit: 3, + }); + const exactPayload = JSON.parse(exactRes.text) as QueryDataResultPayload; + expect(exactPayload.rowCount).toBe(3); + expect(exactPayload.truncated).toBe(false); + + const more = createRecordingStore({ + batches: [{ rows: rowsA }, { rows: rowsB }, { rows: [makeBar(1, base + 3, 4)] }, { rows: [makeBar(1, base + 4, 5)] }], + }); + const moreRes = await callQueryData(more, { + listingIds: [1], + from: '2025-01-01', + to: '2025-03-01', + limit: 3, + }); + const morePayload = JSON.parse(moreRes.text) as QueryDataResultPayload; + expect(morePayload.rowCount).toBe(3); + expect(morePayload.truncated).toBe(true); + expect(morePayload.rows.map(r => r.close)).toEqual([1, 2, 3]); + expect(more.iteratorClosed()).toBe(true); + }); + + test('post-cutoff rows dropped by the fence do not count toward the limit or the truncated flag', async () => { + const pre = makeBar(1, Date.UTC(2025, 2, 10), 1); + const leaks = [ + makeBar(1, VAULT_CUTOFF_TS, 9), + makeBar(1, Date.UTC(2025, 2, 11), 9, VAULT_CUTOFF_TS + 5), + makeBar(1, Number.NaN, 9), + ]; + const rec = createRecordingStore({ batches: [{ rows: [pre, ...leaks] }] }); + const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-01', to: '2025-04-30', limit: 1 }); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rows).toEqual([pre]); + expect(payload.truncated).toBe(false); + expect(res.text).not.toContain('"close":9'); + }); + + test('mid-day Vault cutoff: universe date is the last completed UTC day and bars bounds stay below the cutoff', async () => { + const midDayCutoff = Date.UTC(2025, 2, 31, 12, 0, 0, 0); + const rec = createRecordingStore({ + universeIds: [5], + batches: [{ rows: [makeBar(5, Date.UTC(2025, 2, 31, 11, 0), 1), makeBar(5, midDayCutoff, 2)] }], + }); + const res = await callQueryData( + rec, + { universe: 'US_EQ', from: '2025-03-01', to: '2025-04-30' }, + midDayCutoff + ); + expect(res.isError).toBe(false); + expect(rec.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); + const q = rec.barsCalls[0]; + expect(q?.scope).toBe('vault_fenced'); + expect(q?.to).toBe('2025-03-31T11:59:59.999999Z'); + expect(q?.asOf).toBe('2025-03-31T11:59:59.999999Z'); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rows.every(r => r.ts < midDayCutoff && r.knownAt < midDayCutoff)).toBe(true); + expect(payload.rowCount).toBe(1); + }); + + test('in-fence date-only to with omitted asOf resolves universe on the to date', async () => { + const rec = createRecordingStore({ universeIds: [] }); + const res = await callQueryData(rec, { universe: 'CA_EQ', from: '2025-02-01', to: '2025-03-20' }); + expect(res.isError).toBe(false); + expect(rec.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2025-03-20' }]); + expect(rec.barsCalls).toHaveLength(0); + }); + + test('errors thrown by store.universe are mapped or sanitized and bars is never called', async () => { + const fenceRec = createRecordingStore({ + universeError: new VaultHoldoutFenceError('2025-04-01', VAULT_CUTOFF_TS + 1, VAULT_CUTOFF_TS), + }); + const fenceRes = await callQueryData(fenceRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); + expect(fenceRes.isError).toBe(true); + expect(fenceRes.text).toContain('VaultHoldoutFenceError'); + expect(fenceRec.barsCalls).toHaveLength(0); + + const crashRec = createRecordingStore({ + universeError: new Error('connect ECONNREFUSED postgres://user:pw@10.0.0.51:5432/trading_bot'), + }); + const crashRes = await callQueryData(crashRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); + expect(crashRes.isError).toBe(true); + expect(crashRes.text).toBe('Error: Tool execution failed.'); + expect(crashRes.text).not.toContain('postgres://'); + expect(crashRec.barsCalls).toHaveLength(0); + }); + + test('factory rejects invalid store and vault cutoff values eagerly', () => { + const rec = createRecordingStore({}); + for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 1.5, 8_640_000_000_000_000]) { + expect(() => createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs: bad } })).toThrow( + /vaultCutoffTs/ + ); + } + expect(() => + createQueryDataTool({ + store: {} as MarketDataStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }) + ).toThrow(/store/); + }); +});