diff --git a/package.json b/package.json index 0e2a41b8..e295375c 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "clean:fresh:force": "./scripts/clean.sh --fresh --force", "backtest": "turbo run backtest", "benchmark:dataset": "bun run scripts/benchmark-dataset.ts", + "mcp:research-copilot": "bun run scripts/research-copilot-mcp.ts", "docker:start": "./scripts/docker.sh start --dev", "docker:stop": "./scripts/docker.sh stop --dev", "docker:restart": "./scripts/docker.sh restart --dev", diff --git a/scripts/research-copilot-mcp.ts b/scripts/research-copilot-mcp.ts new file mode 100644 index 00000000..391d5f00 --- /dev/null +++ b/scripts/research-copilot-mcp.ts @@ -0,0 +1,112 @@ +/** + * Runnable stdio entrypoint for the headless MCP research copilot server. + * + * Parses `RESEARCH_MCP_*` environment variables, composes the Vault-fenced + * PostgreSQL executor, DuckDB market data store, and read-only library card + * reader, and serves newline-delimited JSON-RPC 2.0 over stdio. + * + * Fail-closed: configuration or host errors write a single fixed line to + * stderr and exit with code 1 without exposing DSNs, passwords, or raw error + * objects. Stdout carries only MCP protocol bytes. + */ + +import { randomUUID } from 'node:crypto'; +import { + type LibraryCardReaderHandle, + type ManagedMarketDataStore, + type ManagedPostgresExecutor, + type ResearchCopilotHostConfig, + type ResearchCopilotStdioHostDeps, + type StdioInput, + type StdioOutput, + createLibraryCardReader, + createNodeLibraryCardFs, + parseResearchCopilotHostConfig, + runResearchCopilotStdioHost, +} from '@stock-bot/research/mcp'; + +export const RESEARCH_COPILOT_CONFIG_ERROR_LINE = + 'Research copilot MCP server failed: invalid RESEARCH_MCP_* configuration.\n'; + +export const RESEARCH_COPILOT_HOST_ERROR_LINE = + 'Research copilot MCP server failed while running stdio host.\n'; + +export interface ResearchCopilotStderr { + write(chunk: string): boolean; +} + +export interface ResearchCopilotMcpDeps { + readonly env?: Readonly>; + readonly input?: StdioInput; + readonly output?: StdioOutput; + readonly stderr?: ResearchCopilotStderr; + readonly openExecutor?: ResearchCopilotStdioHostDeps['openExecutor']; + readonly openStore?: ResearchCopilotStdioHostDeps['openStore']; + readonly createLibraryCardReader?: ResearchCopilotStdioHostDeps['createLibraryCardReader']; + readonly newId?: () => string; + readonly now?: () => Date | number; +} + +async function defaultOpenExecutor( + config: ResearchCopilotHostConfig +): Promise { + const { openResearchCopilotExecutor } = await import( + '../libs/data/postgres/src/research-copilot-executor' + ); + return openResearchCopilotExecutor(config); +} + +async function defaultOpenStore( + config: ResearchCopilotHostConfig +): Promise { + const { openResearchCopilotStore } = await import( + '../libs/data/duckdb/src/research-copilot-store' + ); + return openResearchCopilotStore(config); +} + +function defaultCreateLibraryCardReader( + config: ResearchCopilotHostConfig +): LibraryCardReaderHandle { + return createLibraryCardReader({ + root: config.libraryRoot, + fs: createNodeLibraryCardFs(), + }); +} + +export async function runResearchCopilotMcp( + deps: ResearchCopilotMcpDeps = {} +): Promise { + const stderr = deps.stderr ?? process.stderr; + + let config: ResearchCopilotHostConfig; + try { + config = parseResearchCopilotHostConfig(deps.env ?? process.env); + } catch { + stderr.write(RESEARCH_COPILOT_CONFIG_ERROR_LINE); + return 1; + } + + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: deps.openExecutor ?? defaultOpenExecutor, + openStore: deps.openStore ?? defaultOpenStore, + createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader, + newId: deps.newId ?? randomUUID, + now: deps.now ?? Date.now, + stdio: { + input: deps.input ?? process.stdin, + output: deps.output ?? process.stdout, + }, + }); + return 0; + } catch { + stderr.write(RESEARCH_COPILOT_HOST_ERROR_LINE); + return 1; + } +} + +if (import.meta.main) { + process.exitCode = await runResearchCopilotMcp(); +} diff --git a/scripts/test/research-copilot-mcp-defaults.test.ts b/scripts/test/research-copilot-mcp-defaults.test.ts new file mode 100644 index 00000000..429f5672 --- /dev/null +++ b/scripts/test/research-copilot-mcp-defaults.test.ts @@ -0,0 +1,332 @@ +import { describe, expect, test } from 'bun:test'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +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, + type ReadKnowledgeResultPayload, + RESEARCH_COPILOT_TOOL_NAMES, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; +import { + RESEARCH_COPILOT_HOST_ERROR_LINE, + runResearchCopilotMcp, +} from '../research-copilot-mcp'; + +const FAKE_PASSWORD = 's3cr@t-default-pw#42'; +const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD); +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 createMemoryWriter(): { + readonly stream: StdioOutput; + text(): string; +} { + const chunks: string[] = []; + return { + stream: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + 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 []; + }, + }; +} + +describe('scripts/research-copilot-mcp.ts default factory wiring', () => { + test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-')); + try { + await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true }); + await writeFile( + join(tempDir, 'library.yml'), + 'id: research-lib\nsections:\n quant: Quantitative Methods\n', + 'utf8' + ); + await writeFile( + join(tempDir, 'cards', 'quant', 'dsr-basics.md'), + [ + '---', + 'title: "Deflated Sharpe Ratio"', + 'summary: "Adjusts Sharpe for multiple testing."', + 'matches: ["dsr", "sharpe"]', + '---', + '', + 'Use DSR to account for trial count.', + ].join('\n'), + 'utf8' + ); + + 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: 'defaults-test', version: '1.0.0' }, + }, + }), + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { + source: 'library', + id: 'research-lib:quant/dsr-basics', + }, + }, + }), + ]); + + const exitCode = await runResearchCopilotMcp({ + env: { + RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, + RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: tempDir, + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + openStore: () => ({ + store: createFakeStore(), + close: () => { + closed.push('store'); + }, + }), + // Intentionally omit createLibraryCardReader to exercise the default factory. + newId: () => '00000000-0000-4000-8000-000000000002', + now: () => FIXED_NOW_MS, + }); + + expect(exitCode).toBe(0); + expect(stderr.text()).toBe(''); + expect(closed).toEqual(['store', 'executor']); + + const responses = stdout + .text() + .trim() + .split('\n') + .map(line => JSON.parse(line) as Record); + expect(responses).toHaveLength(2); + + const callResp = responses[1] as { + id: number; + result: { + isError?: boolean; + content: Array<{ type: string; text: string }>; + }; + }; + expect(callResp.id).toBe(2); + expect(callResp.result.isError).not.toBe(true); + const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.rows).toHaveLength(1); + const firstRow = payload.rows[0]; + expect(firstRow?.source).toBe('library'); + if (firstRow?.source === 'library') { + expect(firstRow.id).toBe('research-lib:quant/dsr-basics'); + expect(firstRow.title).toBe('Deflated Sharpe Ratio'); + } + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => { + // Passes parseResearchCopilotHostConfig (valid scheme + host), but fails + // openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool. + const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`; + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + let openStoreCalled = false; + + const exitCode = await runResearchCopilotMcp({ + env: { + RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase, + RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + // Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor. + openStore: () => { + openStoreCalled = true; + return { store: createFakeStore(), close: () => undefined }; + }, + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE); + expect(stderr.text()).not.toContain(FAKE_PASSWORD); + expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD); + expect(stderr.text()).not.toContain(urlWithoutDatabase); + expect(openStoreCalled).toBe(false); + }); + + test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => { + const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-')); + try { + 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: 'defaults-store-test', 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: { + RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, + RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot, + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + // Intentionally omit openStore to exercise lazy import of openResearchCopilotStore. + createLibraryCardReader: () => createFakeLibraryReader(), + newId: () => '00000000-0000-4000-8000-000000000003', + now: () => FIXED_NOW_MS, + }); + + expect(exitCode).toBe(0); + expect(stderr.text()).toBe(''); + expect(closed).toEqual(['executor']); + + const responses = stdout + .text() + .trim() + .split('\n') + .map(line => JSON.parse(line) as Record); + expect(responses).toHaveLength(2); + const listResp = responses[1] as { + id: number; + result: { tools: Array<{ name: string }> }; + }; + expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + } finally { + await rm(tempCuratedRoot, { recursive: true, force: true }); + } + }); +}); diff --git a/scripts/test/research-copilot-mcp.test.ts b/scripts/test/research-copilot-mcp.test.ts new file mode 100644 index 00000000..a92f6f8d --- /dev/null +++ b/scripts/test/research-copilot-mcp.test.ts @@ -0,0 +1,391 @@ +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); + }); +});