diff --git a/libs/research/test/mcp-copilot-server-qa.test.ts b/libs/research/test/mcp-copilot-server-qa.test.ts new file mode 100644 index 00000000..893c62ec --- /dev/null +++ b/libs/research/test/mcp-copilot-server-qa.test.ts @@ -0,0 +1,740 @@ +import { describe, expect, spyOn, test } from 'bun:test'; +import type { EventStudyExchangeCalendars } from '../src/event-panel'; +import type { + BarBatch, + BarRecord, + BarsQuery, + EventsQuery, + MarketDataStore, + ShortsAsOfQuery, + Table, + TableRow, +} from '../src/market-data-store'; +import { EVENTS_COLUMNS, MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; +import { + type AnalyzeSignalResultPayload, + type EventStudyResultPayload, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, + type KnowledgePort, + type McpServer, + RESEARCH_COPILOT_TOOL_NAMES, + type ReadKnowledgeResultPayload, + type ResearchCopilotMcpServerOptions, + type SearchSymbolsResultPayload, + type StdioOutput, + areFiledFindingPayloadsEqual, + createResearchCopilotMcpServer, + runStdioServer, +} from '../src/mcp/index'; +import * as analyzeSignalToolModule from '../src/mcp/tools/analyze-signal'; +import * as queryDataToolModule from '../src/mcp/tools/query-data'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +// QA fixture for T-144 (composed research copilot MCP server), pinned for reproducibility: +// - Dataset ID: `synthetic:mcp-copilot-qa:seed-424242:v1` (Mulberry32 seed 424242) +// - Universe: 12 synthetic XNYS listings (`60001..60012`), daily bars at 21:00 UTC +// - Sessions: 60 pre-cutoff + 6 post-cutoff weekdays starting 2023-01-02; +// vault cutoff = 00:00 UTC on session index 60 +// - Shorts reported every 5 sessions (indices 0,5,...), known_at = 22:00 UTC on report+3, +// so the first actionable signal session is index 4 (first close strictly after known_at) +// - Study assumptions: raw close-to-close returns, zero modeled costs, 5-session horizon, +// event_study equal-weight benchmark on 8-K filings +const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-qa:seed-424242:v1'; +const SEED = 424242; +const LISTING_COUNT = 12; +const PRE_CUTOFF_SESSIONS = 60; +const POST_CUTOFF_SESSIONS = 6; +const HORIZON = 5; +const AGENT_PRINCIPAL = 'agent:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; +const FIXED_NOW_MS = Date.parse('2024-07-01T09:00:00.000Z'); + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = []; + const current = new Date(`${startDate}T00:00:00.000Z`); + while (out.length < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out.push(current.toISOString().slice(0, 10)); + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function utcMs(date: string, hour: number): number { + return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); +} + +/** Parses store bound strings (date-only, ms or µs ISO) to epoch ms, truncating sub-ms digits. */ +function boundMs(raw: string, endOfDay: boolean): number { + if (raw.length === 10) { + return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); + } + const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(raw); + if (m === null) { + throw new Error(`Unparseable bound: ${raw}`); + } + const frac = (m[2] ?? '').padEnd(3, '0').slice(0, 3); + return Date.parse(`${m[1]}.${frac}Z`); +} + +interface Fixture { + readonly listingIds: readonly number[]; + readonly dates: readonly string[]; + readonly cutoffDate: string; + readonly cutoffTs: number; + readonly lastPreDate: string; + readonly lastDate: string; + readonly bars: readonly BarRecord[]; + readonly shorts: Table; + readonly events: Table; + readonly calendars: EventStudyExchangeCalendars; +} + +function buildFixture(): Fixture { + const rand = createSeededRng(SEED); + const dates = makeBusinessDates('2023-01-02', PRE_CUTOFF_SESSIONS + POST_CUTOFF_SESSIONS); + const listingIds = Array.from({ length: LISTING_COUNT }, (_, i) => 60_001 + i); + const cutoffDate = dates[PRE_CUTOFF_SESSIONS]!; + const bars: BarRecord[] = []; + const shortsRows: TableRow[] = []; + const eventRows: TableRow[] = []; + + const eventDays = [10, 18, 26, 34, 42, 50, 62]; + const eventKey = new Set(); + eventDays.forEach((t, e) => { + const ts = utcMs(dates[t]!, 14); + for (let k = 0; k < 2; k += 1) { + const l = (e * 2 + k) % LISTING_COUNT; + eventKey.add(`${t}:${l}`); + eventRows.push({ + listing_id: listingIds[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }); + } + }); + + const prices = listingIds.map((_, l) => 20 + l * 3); + for (let t = 0; t < dates.length; t += 1) { + const date = dates[t]!; + if (t % 5 === 0 && t + 3 < dates.length) { + for (let l = 0; l < LISTING_COUNT; l += 1) { + shortsRows.push({ + listing_id: listingIds[l]!, + report_date: date, + known_at: utcMs(dates[t + 3]!, 22), + shares_short: 200_000 + l * 1_000 + Math.round(rand() * 5_000), + net_change: Math.round((rand() * 2 - 1) * 15_000), + pct_float: Number((0.01 + rand() * 0.05).toFixed(4)), + source: 'ceoShorts', + }); + } + } + const closeTs = utcMs(date, 21); + for (let l = 0; l < LISTING_COUNT; l += 1) { + const drift = eventKey.has(`${t}:${l}`) || eventKey.has(`${t - 1}:${l}`) ? 0.008 : 0; + prices[l] = Math.max(1, prices[l]! * (1 + drift + (rand() * 2 - 1) * 0.01)); + const close = Number(prices[l]!.toFixed(4)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 10_000 + t, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + dates, + cutoffDate, + cutoffTs: utcMs(cutoffDate, 0), + lastPreDate: dates[PRE_CUTOFF_SESSIONS - 1]!, + lastDate: dates[dates.length - 1]!, + bars, + shorts: { + columns: [ + 'listing_id', + 'report_date', + 'known_at', + 'shares_short', + 'net_change', + 'pct_float', + 'source', + ], + rows: shortsRows, + }, + events: { columns: [...EVENTS_COLUMNS], rows: eventRows }, + calendars: { + calendars: { XNYS: dates.map(date => ({ date, closeTs: utcMs(date, 21) })) }, + listingCalendarId: new Map(listingIds.map(id => [id, 'XNYS'])), + }, + }; +} + +interface RecordingStore { + readonly store: MarketDataStore; + readonly barsQueries: BarsQuery[]; + readonly shortsQueries: ShortsAsOfQuery[]; + readonly eventsQueries: EventsQuery[]; +} + +/** Honest in-memory store that records every query it receives. */ +function createRecordingStore(fx: Fixture): RecordingStore { + const barsQueries: BarsQuery[] = []; + const shortsQueries: ShortsAsOfQuery[] = []; + const eventsQueries: EventsQuery[] = []; + const store: MarketDataStore = { + bars(q): AsyncIterable { + barsQueries.push(q); + const ids = new Set(q.listingIds); + const from = boundMs(q.from, false); + const to = boundMs(q.to, true); + const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + const rows = fx.bars.filter( + r => ids.has(r.listingId) && r.ts >= from && r.ts <= to && r.knownAt <= asOf + ); + return { + async *[Symbol.asyncIterator]() { + yield { rows }; + }, + }; + }, + async universe() { + return [...fx.listingIds]; + }, + async shortsAsOf(q) { + shortsQueries.push(q); + const ids = new Set(q.listingIds); + const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + const from = q.from.slice(0, 10); + const to = q.to.slice(0, 10); + return { + columns: fx.shorts.columns, + rows: fx.shorts.rows.filter( + r => + ids.has(r.listing_id as number) && + (r.report_date as string) >= from && + (r.report_date as string) <= to && + (r.known_at as number) <= asOf + ), + }; + }, + async events(q) { + eventsQueries.push(q); + const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; + const from = boundMs(q.from, false); + const to = boundMs(q.to, true); + const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + return { + columns: fx.events.columns, + rows: fx.events.rows.filter( + r => + (ids === null || ids.has(r.listing_id as number)) && + q.kinds.includes(r.kind as never) && + (r.ts as number) >= from && + (r.ts as number) <= to && + (r.known_at as number) <= asOf + ), + }; + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + return { store, barsQueries, shortsQueries, eventsQueries }; +} + +interface LedgerRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createLedger(): { readonly executor: TrialLedgerExecutor; readonly rows: LedgerRow[] } { + const rows: LedgerRow[] = []; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const p = params ?? []; + if (text.trimStart().startsWith('INSERT INTO trial_ledger')) { + const id = rows.length + 1; + const row: LedgerRow = { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 6, 1, 0, 0, id)), + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(row); + return { + rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], + rowCount: 1, + }; + } + if (text.includes('WHERE trial_id = $1::bigint')) { + const m = rows.filter(r => r.trial_id === String(p[0])); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const m = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, rows }; +} + +interface Harness { + readonly options: ResearchCopilotMcpServerOptions; + readonly store: RecordingStore; + readonly ledger: ReturnType; + readonly stored: FiledFindingRecord[]; + readonly appendCalls: () => number; +} + +function buildHarness(fx: Fixture): Harness { + const store = createRecordingStore(fx); + const ledger = createLedger(); + const stored: FiledFindingRecord[] = []; + const byKey = new Map(); + let appends = 0; + let nextFinding = 1; + + const writePort: FindingWritePort = { + async appendFinding(record, key) { + appends += 1; + if (key !== undefined) { + const prior = byKey.get(key); + if (prior !== undefined) { + return areFiledFindingPayloadsEqual(prior, record) + ? { status: 'replayed', id: prior.id, createdAt: prior.createdAt } + : { status: 'conflict' }; + } + } + const copy = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs] }; + stored.push(copy); + if (key !== undefined) { + byKey.set(key, copy); + } + return { status: 'created', id: copy.id, createdAt: copy.createdAt }; + }, + }; + + const knowledge: KnowledgePort = { + async listLibraryCards() { + return []; + }, + async listFindings() { + return stored; + }, + async listProviderCaveats() { + return []; + }, + }; + + const options: ResearchCopilotMcpServerOptions = { + name: 'copilot-qa', + version: '0.0.1', + store: store.store, + vaultContext: { vaultCutoffTs: fx.cutoffTs }, + ledger: ledger.executor, + principalId: AGENT_PRINCIPAL, + searchSymbols: { + port: { + async searchSymbols() { + return fx.listingIds.map((listingId, i) => ({ + listingId, + instrumentId: 90_000 + i, + ticker: i === 0 ? 'QAQA' : `QA${i}`, + classSuffix: null, + name: `QA Equity ${i}`, + mic: 'XNYS', + currency: 'USD', + isin: null, + firstBarDate: fx.dates[0]!, + lastBarDate: fx.lastDate, + delistedAt: null, + })); + }, + }, + }, + eventStudy: { resolveExchangeCalendars: () => fx.calendars }, + fileFinding: { + port: writePort, + trialLookup: { + hasResearchVisibleTrial: ref => + ledger.rows.some(r => r.trial_id === ref && r.sample_end < fx.cutoffDate), + }, + newId: () => `finding-qa-${nextFinding++}`, + now: () => FIXED_NOW_MS, + }, + readKnowledge: { port: knowledge }, + }; + + return { options, store, ledger, stored, appendCalls: () => appends }; +} + +interface ToolEnvelope { + readonly content: readonly { readonly text: string }[]; + readonly isError?: boolean; +} + +async function callTool( + server: McpServer, + name: string, + args: Record +): Promise { + const raw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: name, method: 'tools/call', params: { name, arguments: args } }) + ); + const parsed = JSON.parse(raw!) as { result?: ToolEnvelope; error?: unknown }; + expect(parsed.error).toBeUndefined(); + return parsed.result!; +} + +function okJson(env: ToolEnvelope): T { + expect(env.isError).not.toBe(true); + return JSON.parse(env.content[0]!.text) as T; +} + +function signalArgs(fx: Fixture, overrides: Record = {}): Record { + return { + listingIds: [...fx.listingIds], + from: fx.dates[0]!, + to: fx.lastPreDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: HORIZON, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + ...overrides, + }; +} + +function eventArgs(fx: Fixture, overrides: Record = {}): Record { + return { + listingIds: [...fx.listingIds], + from: fx.dates[0]!, + to: fx.lastPreDate, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 5, + benchmark: 'equal_weight', + adjustment: 'raw', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + ...overrides, + }; +} + +describe('createResearchCopilotMcpServer QA', () => { + test('straddling query_data, analyze_signal and event_study send only clamped pre-cutoff bounds to the store', async () => { + const fx = buildFixture(); + const h = buildHarness(fx); + const server = createResearchCopilotMcpServer(h.options); + + await callTool(server, 'query_data', { + listingIds: [fx.listingIds[0]!], + from: fx.dates[0]!, + to: fx.lastDate, + asOf: fx.lastDate, + timeframe: '1d', + adjustment: 'raw', + }); + const sig = okJson( + await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) + ); + const ev = okJson( + await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) + ); + + expect(sig.status).toBe('ok'); + expect(ev.status).toBe('ok'); + expect(ev.clampedTo).toBe(true); + expect(ev.toMs).toBe(fx.cutoffTs - 1); + + // query_data + analyze_signal + event_study each read bars once. + expect(h.store.barsQueries).toHaveLength(3); + expect(h.store.shortsQueries).toHaveLength(1); + expect(h.store.eventsQueries).toHaveLength(1); + const all: { readonly to: string; readonly asOf?: string }[] = [ + ...h.store.barsQueries, + ...h.store.shortsQueries, + ...h.store.eventsQueries, + ]; + for (const q of all) { + expect(q.to.startsWith(new Date(fx.cutoffTs - 1).toISOString().slice(0, 19))).toBe(true); + expect(boundMs(q.to, true)).toBe(fx.cutoffTs - 1); + expect(q.asOf).toBeDefined(); + expect(boundMs(q.asOf!, true)).toBe(fx.cutoffTs - 1); + } + for (const q of h.store.barsQueries) { + expect(q.scope).toBe('vault_fenced'); + } + // Event-study trial stays pre-cutoff too. + expect(h.ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); + for (const row of h.ledger.rows) { + expect(row.sample_end < fx.cutoffDate).toBe(true); + } + }); + + test('analyze_signal trial covers the exact pinned formation window (first actionable session through cutoff minus horizon)', async () => { + const fx = buildFixture(); + const h = buildHarness(fx); + const server = createResearchCopilotMcpServer(h.options); + + const sig = okJson( + await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate })) + ); + expect(sig.status).toBe('ok'); + if (sig.status !== 'ok') { + throw new Error('expected ok'); + } + + // First report (index 0) becomes known 22:00 UTC on index 3, after that day's 21:00 close, + // so the first eligible formation session is index 4. The last formation session whose + // 5-session forward endpoint is still pre-cutoff is index 59 - 5 = 54. + const expectedStart = fx.dates[4]!; + const expectedEnd = fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON]!; + expect(fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON + HORIZON]).toBe(fx.lastPreDate); + + expect(h.ledger.rows).toHaveLength(1); + const row = h.ledger.rows[0]!; + expect(row.trial_id).toBe(String(sig.trial.trialId)); + expect(row.principal_id).toBe(AGENT_PRINCIPAL); + expect(row.sample_start).toBe(expectedStart); + expect(row.sample_end).toBe(expectedEnd); + // One daily IC observation per formation session, none dropped. + expect(row.daily_series).toHaveLength(PRE_CUTOFF_SESSIONS - HORIZON - 4); + expect(row.n_obs).toBe(row.daily_series.length); + }); + + test('a replay on fresh servers with the same inputs produces an identical stdio transcript and ledger', async () => { + const fx = buildFixture(); + + async function runSession(): Promise<{ readonly lines: string[]; readonly ledger: LedgerRow[] }> { + const h = buildHarness(fx); + const server = createResearchCopilotMcpServer(h.options); + const lines: string[] = []; + let buf = ''; + const output: StdioOutput = { + write(chunk: string) { + buf += chunk; + let i = buf.indexOf('\n'); + while (i !== -1) { + lines.push(buf.slice(0, i)); + buf = buf.slice(i + 1); + i = buf.indexOf('\n'); + } + return true; + }, + }; + async function* input(): AsyncGenerator { + const calls: [string, Record][] = [ + ['analyze_signal', signalArgs(fx)], + ['event_study', eventArgs(fx)], + ]; + let id = 1; + for (const [name, args] of calls) { + yield `${JSON.stringify({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } })}\n`; + } + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: id++, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Replay finding', + summary: `Dataset ${FIXTURE_DATASET_ID}, pre-Vault only.`, + trialRefs: ['1'], + evidenceRefs: [FIXTURE_DATASET_ID], + }, + }, + })}\n`; + } + await runStdioServer(server, { input: input(), output }); + return { lines, ledger: h.ledger.rows }; + } + + const a = await runSession(); + const b = await runSession(); + expect(a.lines).toHaveLength(3); + expect(b.lines).toEqual(a.lines); + expect(b.ledger).toEqual(a.ledger); + expect(JSON.parse(a.lines[2]!).result.isError).not.toBe(true); + }); + + test('file_finding through the composed server rejects unknown trial refs, replays idempotent retries, and read_knowledge reads the filed record back', async () => { + const fx = buildFixture(); + const h = buildHarness(fx); + const server = createResearchCopilotMcpServer(h.options); + + const unknown = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'No trial yet', + summary: 'Should be rejected.', + trialRefs: ['999'], + }); + expect(unknown.isError).toBe(true); + expect(h.appendCalls()).toBe(0); + + const sig = okJson(await callTool(server, 'analyze_signal', signalArgs(fx))); + if (sig.status !== 'ok') { + throw new Error('expected ok'); + } + const args = { + kind: 'finding', + title: 'Shorts net_change IC', + summary: `Dataset ${FIXTURE_DATASET_ID}.`, + trialRefs: [String(sig.trial.trialId)], + evidenceRefs: [FIXTURE_DATASET_ID], + idempotencyKey: 'qa-key-1', + }; + const first = okJson(await callTool(server, 'file_finding', args)); + const retry = okJson(await callTool(server, 'file_finding', args)); + expect(first.created).toBe(true); + expect(retry).toEqual({ id: first.id, createdAt: first.createdAt, created: false }); + expect(h.stored).toHaveLength(1); + + const conflict = await callTool(server, 'file_finding', { ...args, title: 'Different title' }); + expect(conflict.isError).toBe(true); + expect(h.stored).toHaveLength(1); + + const read = okJson( + await callTool(server, 'read_knowledge', { source: 'findings', id: first.id }) + ); + expect(read.rowCount).toBe(1); + expect(read.rows[0]?.id).toBe(first.id); + }); + + test('shared vaultContext and store stay authoritative over stray per-tool overrides', async () => { + const fx = buildFixture(); + const h = buildHarness(fx); + const throwingStore = new Proxy( + {}, + { + get() { + throw new Error('per-tool store override must not be used'); + }, + } + ); + const options = { + ...h.options, + // Runtime callers can bypass the Omit/Pick types; the composed server must ignore these. + searchSymbols: { + ...h.options.searchSymbols, + vaultContext: { vaultCutoffTs: utcMs(fx.lastDate, 23) + 86_400_000 }, + }, + eventStudy: { ...h.options.eventStudy, store: throwingStore, vaultContext: { vaultCutoffTs: 8.64e15 } }, + } as unknown as ResearchCopilotMcpServerOptions; + const server = createResearchCopilotMcpServer(options); + + const search = okJson( + await callTool(server, 'search_symbols', { query: 'QAQA', limit: 5 }) + ); + expect(search.rows[0]?.lastBarDate).toBe(fx.cutoffDate); + + const ev = okJson( + await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate })) + ); + expect(ev.status).toBe('ok'); + expect(ev.toMs).toBe(fx.cutoffTs - 1); + expect(h.store.eventsQueries).toHaveLength(1); + }); + + test('rejects invalid option objects and out-of-order tool registration', () => { + const fx = buildFixture(); + const h = buildHarness(fx); + + expect(() => createResearchCopilotMcpServer(null as never)).toThrow(/Invalid `options`/); + expect(() => + createResearchCopilotMcpServer({ ...h.options, searchSymbols: null } as never) + ).toThrow(/Invalid `searchSymbols`/); + expect(() => + createResearchCopilotMcpServer({ ...h.options, eventStudy: undefined } as never) + ).toThrow(/Invalid `eventStudy`/); + + const realQuery = queryDataToolModule.createQueryDataTool(h.options); + const realSignal = analyzeSignalToolModule.createAnalyzeSignalTool(h.options); + const qSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => realSignal); + const sSpy = spyOn(analyzeSignalToolModule, 'createAnalyzeSignalTool').mockImplementation( + () => realQuery + ); + try { + expect(() => createResearchCopilotMcpServer(h.options)).toThrow( + /index 1: expected "query_data", got "analyze_signal"/ + ); + } finally { + qSpy.mockRestore(); + sSpy.mockRestore(); + } + + // Restored spies: composition succeeds again with the fixed order. + const server = createResearchCopilotMcpServer(h.options); + expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + }); + + test('is importable through the @stock-bot/research/mcp package subpath', async () => { + const mod = await import('@stock-bot/research/mcp'); + expect(mod.createResearchCopilotMcpServer).toBe(createResearchCopilotMcpServer); + expect(mod.RESEARCH_COPILOT_TOOL_NAMES).toBe(RESEARCH_COPILOT_TOOL_NAMES); + }); +});