import { describe, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store'; import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb'; import { type LibraryCardReaderHandle, MCP_PROTOCOL_VERSION, type PostgresResearchCopilotExecutor, RESEARCH_COPILOT_HOST_NAME, RESEARCH_COPILOT_HOST_VERSION, RESEARCH_COPILOT_TOOL_NAMES, type StdioInput, type StdioOutput, } from '@stock-bot/research/mcp'; import { RESEARCH_COPILOT_CONFIG_ERROR_LINE, RESEARCH_COPILOT_HOST_ERROR_LINE, runResearchCopilotMcp, } from '../research-copilot-mcp'; const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!'; const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`; const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); function buildValidEnv( overrides: Readonly> = {} ): Record { return { PATH: '/usr/local/bin:/usr/bin', NODE_ENV: 'test', RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', RESEARCH_MCP_CURATED_ROOT: '/tmp/fake-curated-root-secret-path', RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, RESEARCH_MCP_LIBRARY_ROOT: '/tmp/fake-library-root-secret-path', RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101], }), ...overrides, }; } function createMemoryWriter(): { readonly stream: StdioOutput; readonly chunks: string[]; text(): string; } { const chunks: string[] = []; return { stream: { write(chunk: string): boolean { chunks.push(chunk); return true; }, }, chunks, text: () => chunks.join(''), }; } function createMemoryInput(lines: readonly string[]): StdioInput { return { async *[Symbol.asyncIterator](): AsyncIterator { for (const line of lines) { yield `${line}\n`; } }, }; } function createFakeExecutor(): PostgresResearchCopilotExecutor { return { async query>(): Promise<{ readonly rows: readonly Row[] }> { return { rows: [] }; }, }; } function createFakeStore(): MarketDataStore { return { async *bars(q: BarQuery): AsyncIterable { yield { listingId: q.listingIds[0] ?? 0, timeframe: q.timeframe, rows: [], }; }, async crossSection() { throw new MarketDataStoreNotImplementedError('crossSection'); }, async fundamentalsAsOf() { throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); }, async events() { throw new MarketDataStoreNotImplementedError('events'); }, async shortsAsOf() { throw new MarketDataStoreNotImplementedError('shortsAsOf'); }, async macroAsOf() { throw new MarketDataStoreNotImplementedError('macroAsOf'); }, async fx() { throw new MarketDataStoreNotImplementedError('fx'); }, async universe() { return []; }, }; } function createFakeLibraryReader(): LibraryCardReaderHandle { return { async listLibraryCards() { return []; }, }; } function assertSingleFixedLineNoSecrets( stderrText: string, expectedLine: string, env: Readonly> ): void { expect(stderrText).toBe(expectedLine); expect(stderrText.endsWith('\n')).toBe(true); expect(stderrText.slice(0, -1)).not.toContain('\n'); const forbidden = [ FAKE_POSTGRES_URL, FAKE_ENCODED_PASSWORD, FAKE_DECODED_PASSWORD, env.RESEARCH_MCP_POSTGRES_URL, env.RESEARCH_MCP_CURATED_ROOT, env.RESEARCH_MCP_LIBRARY_ROOT, env.RESEARCH_MCP_PRINCIPAL_ID, ].filter((value): value is string => typeof value === 'string' && value.length > 0); for (const secret of forbidden) { expect(stderrText).not.toContain(secret); } } describe('scripts/research-copilot-mcp.ts', () => { test('package.json defines mcp:research-copilot pointing to scripts/research-copilot-mcp.ts', () => { const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as { scripts?: Record; }; expect(pkg.scripts?.['mcp:research-copilot']).toBe('bun run scripts/research-copilot-mcp.ts'); }); test('missing required RESEARCH_MCP_* env returns exit code 1, one fixed stderr line, and zero stdout bytes', async () => { const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: undefined }); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); let openExecutorCalled = false; let openStoreCalled = false; const exitCode = await runResearchCopilotMcp({ env, input: createMemoryInput([]), output: stdout.stream, stderr: stderr.stream, openExecutor: () => { openExecutorCalled = true; return { executor: createFakeExecutor(), close: () => undefined }; }, openStore: () => { openStoreCalled = true; return { store: createFakeStore(), close: () => undefined }; }, createLibraryCardReader: () => createFakeLibraryReader(), }); expect(exitCode).toBe(1); expect(stdout.text()).toBe(''); assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); expect(openExecutorCalled).toBe(false); expect(openStoreCalled).toBe(false); }); test('invalid RESEARCH_MCP_* env fails closed with one fixed stderr line and zero stdout bytes', async () => { const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: `http://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, }); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); const exitCode = await runResearchCopilotMcp({ env, input: createMemoryInput([]), output: stdout.stream, stderr: stderr.stream, openExecutor: () => ({ executor: createFakeExecutor(), close: () => undefined }), openStore: () => ({ store: createFakeStore(), close: () => undefined }), createLibraryCardReader: () => createFakeLibraryReader(), }); expect(exitCode).toBe(1); expect(stdout.text()).toBe(''); assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); }); test('openExecutor failure returns 1 with fixed stderr line leaking no DSN, password, or env values', async () => { const env = buildValidEnv(); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); let openStoreCalled = false; const exitCode = await runResearchCopilotMcp({ env, input: createMemoryInput([]), output: stdout.stream, stderr: stderr.stream, openExecutor: () => { throw new Error( `connect failed for ${FAKE_POSTGRES_URL} (pw=${FAKE_DECODED_PASSWORD}) root=${env.RESEARCH_MCP_CURATED_ROOT}` ); }, openStore: () => { openStoreCalled = true; return { store: createFakeStore(), close: () => undefined }; }, createLibraryCardReader: () => createFakeLibraryReader(), }); expect(exitCode).toBe(1); expect(stdout.text()).toBe(''); assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); expect(openStoreCalled).toBe(false); }); test('openStore failure closes already-opened executor and returns 1 with fixed stderr line', async () => { const env = buildValidEnv(); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); const closed: string[] = []; const exitCode = await runResearchCopilotMcp({ env, input: createMemoryInput([]), output: stdout.stream, stderr: stderr.stream, openExecutor: () => ({ executor: createFakeExecutor(), close: () => { closed.push('executor'); }, }), openStore: () => { throw new Error(`DuckDB failed for ${env.RESEARCH_MCP_CURATED_ROOT} ${FAKE_POSTGRES_URL}`); }, createLibraryCardReader: () => createFakeLibraryReader(), }); expect(exitCode).toBe(1); expect(stdout.text()).toBe(''); assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); expect(closed).toEqual(['executor']); }); test('stdio host failure closes store and executor in reverse order and leaks no secrets', async () => { const env = buildValidEnv(); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); const closed: string[] = []; const failingInput: StdioInput = { async *[Symbol.asyncIterator](): AsyncIterator { throw new Error(`stdin boom ${FAKE_POSTGRES_URL} ${FAKE_DECODED_PASSWORD}`); }, }; const exitCode = await runResearchCopilotMcp({ env, input: failingInput, output: stdout.stream, stderr: stderr.stream, openExecutor: () => ({ executor: createFakeExecutor(), close: () => { closed.push('executor'); }, }), openStore: () => ({ store: createFakeStore(), close: () => { closed.push('store'); }, }), createLibraryCardReader: () => createFakeLibraryReader(), }); expect(exitCode).toBe(1); expect(stdout.text()).toBe(''); assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); expect(closed).toEqual(['store', 'executor']); }); test('MCP initialize + tools/list round trip returns all 6 copilot tools on stdout, exit 0, and closes resources', async () => { const env = buildValidEnv(); const stdout = createMemoryWriter(); const stderr = createMemoryWriter(); const closed: string[] = []; const input = createMemoryInput([ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'test-client', version: '1.0.0' }, }, }), JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized', }), JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {}, }), ]); const exitCode = await runResearchCopilotMcp({ env, input, output: stdout.stream, stderr: stderr.stream, openExecutor: () => ({ executor: createFakeExecutor(), close: () => { closed.push('executor'); }, }), openStore: () => ({ store: createFakeStore(), close: () => { closed.push('store'); }, }), createLibraryCardReader: () => createFakeLibraryReader(), newId: () => '00000000-0000-4000-8000-000000000001', now: () => FIXED_NOW_MS, }); expect(exitCode).toBe(0); expect(stderr.text()).toBe(''); expect(closed).toEqual(['store', 'executor']); const lines = stdout .text() .trim() .split('\n') .map(line => JSON.parse(line) as Record); expect(lines).toHaveLength(2); const initResp = lines[0] as { id: number; result: { protocolVersion: string; serverInfo: { name: string; version: string }; }; }; expect(initResp.id).toBe(1); expect(initResp.result.protocolVersion).toBe(MCP_PROTOCOL_VERSION); expect(initResp.result.serverInfo).toEqual({ name: RESEARCH_COPILOT_HOST_NAME, version: RESEARCH_COPILOT_HOST_VERSION, }); const listResp = lines[1] as { id: number; result: { tools: Array<{ name: string }> }; }; expect(listResp.id).toBe(2); expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); expect(listResp.result.tools).toHaveLength(6); }); });