diff --git a/libs/research/README.md b/libs/research/README.md index 8d119484..c4c1dae2 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -224,6 +224,10 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. - **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. +### Copilot Server + +- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. + ### Remaining M2 MCP Items (Later Tasks) - SSE/HTTP transport wrapper in `apps/stock/web-api`. diff --git a/libs/research/src/mcp/copilot-server.ts b/libs/research/src/mcp/copilot-server.ts new file mode 100644 index 00000000..98b412ee --- /dev/null +++ b/libs/research/src/mcp/copilot-server.ts @@ -0,0 +1,110 @@ +import { type McpServer, type McpServerOptions, createMcpServer } from './server'; +import { type AnalyzeSignalToolOptions, createAnalyzeSignalTool } from './tools/analyze-signal'; +import { type EventStudyToolOptions, createEventStudyTool } from './tools/event-study'; +import { type FileFindingToolOptions, createFileFindingTool } from './tools/file-finding'; +import { type QueryDataToolOptions, createQueryDataTool } from './tools/query-data'; +import { type ReadKnowledgeToolOptions, createReadKnowledgeTool } from './tools/read-knowledge'; +import { type SearchSymbolsToolOptions, createSearchSymbolsTool } from './tools/search-symbols'; + +/** + * Fixed, documented registration order of the six MCP tools exposed by + * {@link createResearchCopilotMcpServer}. + */ +export const RESEARCH_COPILOT_TOOL_NAMES = Object.freeze([ + 'search_symbols', + 'query_data', + 'analyze_signal', + 'event_study', + 'file_finding', + 'read_knowledge', +] as const); + +/** + * Composed server options for {@link createResearchCopilotMcpServer}. + * + * Shares the common Vault-fenced `MarketDataStore`, `vaultContext`, + * `TrialLedgerExecutor`, and `principalId` across the tools that consume them + * while passing each tool's remaining injected ports unchanged. + */ +export interface ResearchCopilotMcpServerOptions + extends Pick, + Pick, + Pick { + readonly searchSymbols: Omit; + readonly eventStudy: Pick; + readonly fileFinding: FileFindingToolOptions; + readonly readKnowledge: ReadKnowledgeToolOptions; +} + +/** + * Composes all six research MCP tools (`search_symbols`, `query_data`, + * `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) into a + * single transport-agnostic {@link McpServer}. + * + * Keeps the shared `store`, `vaultContext`, `ledger`, and `principalId` + * authoritative across tools and fails closed if any tool is duplicated, + * missing, unexpected, or out of order. + */ +export function createResearchCopilotMcpServer( + options: ResearchCopilotMcpServerOptions +): McpServer { + if (typeof options !== 'object' || options === null) { + throw new Error('Invalid `options`: expected a ResearchCopilotMcpServerOptions object.'); + } + if (typeof options.searchSymbols !== 'object' || options.searchSymbols === null) { + throw new Error('Invalid `searchSymbols`: expected a SearchSymbolsToolOptions object.'); + } + if (typeof options.eventStudy !== 'object' || options.eventStudy === null) { + throw new Error('Invalid `eventStudy`: expected an EventStudyToolOptions object.'); + } + + const tools = [ + createSearchSymbolsTool({ + ...options.searchSymbols, + vaultContext: options.vaultContext, + }), + createQueryDataTool({ + store: options.store, + vaultContext: options.vaultContext, + }), + createAnalyzeSignalTool({ + store: options.store, + ledger: options.ledger, + vaultContext: options.vaultContext, + principalId: options.principalId, + }), + createEventStudyTool({ + store: options.store, + ledger: options.ledger, + vaultContext: options.vaultContext, + principalId: options.principalId, + resolveExchangeCalendars: options.eventStudy.resolveExchangeCalendars, + }), + createFileFindingTool(options.fileFinding), + createReadKnowledgeTool(options.readKnowledge), + ]; + + const server = createMcpServer({ + name: options.name, + version: options.version, + tools, + }); + + const registered = server.listTools(); + if (registered.length !== RESEARCH_COPILOT_TOOL_NAMES.length) { + throw new Error( + `Research copilot MCP server expected ${RESEARCH_COPILOT_TOOL_NAMES.length} tools, got ${registered.length}.` + ); + } + for (let i = 0; i < RESEARCH_COPILOT_TOOL_NAMES.length; i += 1) { + const expectedName = RESEARCH_COPILOT_TOOL_NAMES[i]; + const actualName = registered[i]?.name; + if (actualName !== expectedName) { + throw new Error( + `Research copilot MCP server tool mismatch at index ${i}: expected "${expectedName}", got "${String(actualName)}".` + ); + } + } + + return server; +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index f228f04a..3ab56692 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,3 +1,4 @@ +export * from './copilot-server'; export * from './protocol'; export * from './server'; export * from './stdio'; diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts new file mode 100644 index 00000000..2bc4ab24 --- /dev/null +++ b/libs/research/test/mcp-copilot-server.test.ts @@ -0,0 +1,1212 @@ +import { describe, expect, spyOn, test } from 'bun:test'; +import type { EventStudyExchangeCalendars } from '../src/event-panel'; +import { + type BarBatch, + type BarRecord, + type EventKind, + type MarketDataStore, + type Table, + type TableRow, +} from '../src/market-data-store'; +import { + EVENTS_COLUMNS, + MarketDataStoreNotImplementedError, +} from '../src/market-data-store-duckdb'; +import { + type AnalyzeSignalResultPayload, + type AppendFindingResult, + type EventStudyResultPayload, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingWritePort, + JSON_RPC_ERROR_CODES, + type KnowledgePort, + type McpToolDescriptor, + type QueryDataResultPayload, + RESEARCH_COPILOT_TOOL_NAMES, + type ReadKnowledgeResultPayload, + type ResearchCopilotMcpServerOptions, + type SearchSymbolsResultPayload, + type StdioOutput, + type SymbolSearchPort, + type SymbolSearchRow, + areFiledFindingPayloadsEqual, + createResearchCopilotMcpServer, + runStdioServer, +} from '../src/mcp/index'; +import * as queryDataToolModule from '../src/mcp/tools/query-data'; +import * as readKnowledgeToolModule from '../src/mcp/tools/read-knowledge'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +// Synthetic headless-study fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-copilot-e2e:seed-20261201:v1` +// - Seed: `20261201` (Mulberry32 PRNG) +// - Universe: 16 synthetic US equity listings (`50001..50016`, XNYS, USD, 21:00 UTC close) +// - Sessions: 80 pre-cutoff + 8 post-cutoff business sessions starting `2022-11-01` +// - Cutoff: `vaultCutoffDate` = `allDates[80]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) +// - Economic assumptions: daily raw close-to-close returns, zero modeled execution/transaction +// costs; `event_study` uses `benchmark: 'equal_weight'` over eligible listing returns. +// - Ownership: Quant research role owns the economic specification; `AGENT_PRINCIPAL` owns +// the recorded `trial_ledger` rows. +const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-e2e:seed-20261201:v1'; +const SEED = 20261201; +const SERVER_NAME = 'stock-bot-research-copilot'; +const SERVER_VERSION = '0.1.0'; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const FIXED_FINDING_ID = 'finding-copilot-e2e-001'; +const FIXED_NOW_ISO = '2024-06-01T15:30:00.000Z'; +const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); + +const EXPECTED_TOOL_NAMES = [ + 'search_symbols', + 'query_data', + 'analyze_signal', + 'event_study', + 'file_finding', + 'read_knowledge', +] as const; + +const SHORTS_COLUMNS = [ + 'listing_id', + 'report_date', + 'known_at', + 'shares_short', + 'net_change', + 'pct_float', + 'source', +] as const; + +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[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); +} + +function parseBoundMs(raw: string, endOfDay: boolean): number { + if (raw.length === 10) { + return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); + } + return Date.parse(raw); +} + +interface StoredTrialRow { + 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 createFakeTrialLedger(): { + readonly executor: TrialLedgerExecutor; + readonly rows: StoredTrialRow[]; + readonly getInsertCalls: () => number; + readonly getSelectCalls: () => number; +} { + const rows: StoredTrialRow[] = []; + let nextTrialId = 1; + let insertCalls = 0; + let selectCalls = 0; + + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + insertCalls += 1; + const p = params ?? []; + const trialId = nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + 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: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + + if (trimmed.startsWith('SELECT')) { + selectCalls += 1; + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + + return { rows: [], rowCount: 0 }; + }, + }; + + return { + executor, + rows, + getInsertCalls: () => insertCalls, + getSelectCalls: () => selectCalls, + }; +} + +interface CopilotStudyFixture { + readonly listingIds: readonly number[]; + readonly allDates: readonly string[]; + readonly preCutoffSessions: number; + readonly firstDate: string; + readonly lastPreCutoffDate: string; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly postCutoffDate: string; + readonly bars: readonly BarRecord[]; + readonly shortsTable: Table; + readonly eventsTable: Table; + readonly symbols: readonly SymbolSearchRow[]; + readonly exchangeCalendars: EventStudyExchangeCalendars; +} + +function buildCopilotStudyFixture(): CopilotStudyFixture { + const rand = createSeededRng(SEED); + const listingCount = 16; + const preCutoffSessions = 80; + const postCutoffSessions = 8; + + const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); + const firstDate = allDates[0]!; + const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + const postCutoffDate = allDates[allDates.length - 1]!; + + const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); + const bars: BarRecord[] = []; + const shortsRows: TableRow[] = []; + const eventRows: TableRow[] = []; + + const eventDayIndices = [12, 20, 28, 38, 48, 58]; + const eventSet = new Set(); + for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { + const t = eventDayIndices[eIdx]!; + const date = allDates[t]!; + const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session + for (let k = 0; k < 2; k += 1) { + const l = (eIdx * 2 + k) % listingCount; + eventSet.add(`${t}:${l}`); + const kind: EventKind = 'filing'; + eventRows.push({ + listing_id: listingIds[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind, + subtype: '8-K', + payload_json: '{}', + }); + } + } + + const publicationLagSessions = 3; + const activeSignal = new Float64Array(listingCount); + const pendingByPublishIdx = new Map(); + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 15 + l * 2.5; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + + const released = pendingByPublishIdx.get(t - 1); + if (released !== undefined) { + for (let l = 0; l < listingCount; l += 1) { + activeSignal[l] = (released[l] ?? 0) / 20_000; + } + } + + const publishIdx = t + publicationLagSessions; + if (t % 5 === 0 && publishIdx < allDates.length) { + const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+3 + const pending: number[] = []; + for (let l = 0; l < listingCount; l += 1) { + const netChange = Math.round((rand() * 2 - 1) * 20_000); + pending.push(netChange); + shortsRows.push({ + listing_id: listingIds[l]!, + report_date: date, + known_at: reportKnownAt, + shares_short: 100_000 + l * 4_000 + Math.round(rand() * 10_000), + net_change: netChange, + pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), + source: 'ceoShorts', + }); + } + pendingByPublishIdx.set(publishIdx, pending); + } + + for (let l = 0; l < listingCount; l += 1) { + let eventDrift = 0; + for (let offset = 0; offset <= 3; offset += 1) { + if (eventSet.has(`${t - offset}:${l}`)) { + eventDrift += 0.006 * (1 + ((l + t) % 3) * 0.25); + } + } + const dailyRet = -0.004 * activeSignal[l]! + eventDrift + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); + const close = Number(prices[l]!.toFixed(4)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: Number((close * 0.995).toFixed(4)), + high: Number((close * 1.01).toFixed(4)), + low: Number((close * 0.99).toFixed(4)), + close, + volume: 50_000 + l * 1_500 + t * 100, + vwap: close, + knownAt: closeTs, + }); + } + } + + const symbols: SymbolSearchRow[] = listingIds.map((listingId, idx) => ({ + listingId, + instrumentId: 80_001 + idx, + ticker: idx === 0 ? 'ACME' : `SYN${idx}`, + classSuffix: null, + name: idx === 0 ? 'Acme Synthetic Corp' : `Synthetic Equity ${idx}`, + mic: 'XNYS', + currency: 'USD', + isin: `US000000${String(idx).padStart(4, '0')}`, + firstBarDate: firstDate, + lastBarDate: postCutoffDate, + delistedAt: null, + })); + + const xnysSessions = allDates.map(date => ({ + date, + closeTs: makeUtcMs(date, 21), + })); + const listingCalendarId = new Map(); + for (const id of listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + + return { + listingIds, + allDates, + preCutoffSessions, + firstDate, + lastPreCutoffDate, + vaultCutoffDate, + vaultCutoffTs, + postCutoffDate, + bars, + shortsTable: { + columns: [...SHORTS_COLUMNS], + rows: shortsRows, + }, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: eventRows, + }, + symbols, + exchangeCalendars: { + calendars: { XNYS: xnysSessions }, + listingCalendarId, + }, + }; +} + +interface FakeMarketDataStoreHandle { + readonly store: MarketDataStore; + readonly getBarsCalls: () => number; + readonly getShortsCalls: () => number; + readonly getEventsCalls: () => number; + readonly getUniverseCalls: () => number; +} + +function createFakeMarketDataStore( + fixture: CopilotStudyFixture, + options?: { + readonly leakyVaultRows?: boolean; + } +): FakeMarketDataStoreHandle { + const leaky = options?.leakyVaultRows ?? false; + let barsCalls = 0; + let shortsCalls = 0; + let eventsCalls = 0; + let universeCalls = 0; + + // Deliberately leaky rows: + // 1) Bar at exact vaultCutoffTs and after vaultCutoffTs (by ts) + // 2) Bar with pre-cutoff ts (early observation) but late knownAt >= vaultCutoffTs + // 3) Short row with pre-cutoff report_date but late known_at >= vaultCutoffTs + const leakyBars: BarRecord[] = [ + { + listingId: fixture.listingIds[0]!, + ts: fixture.vaultCutoffTs, + open: 999, + high: 999, + low: 999, + close: 999, + volume: 1000, + vwap: 999, + knownAt: fixture.vaultCutoffTs, + }, + { + listingId: fixture.listingIds[1]!, + ts: makeUtcMs(fixture.postCutoffDate, 21), + open: 888, + high: 888, + low: 888, + close: 888, + volume: 1000, + vwap: 888, + knownAt: makeUtcMs(fixture.postCutoffDate, 21), + }, + { + listingId: fixture.listingIds[0]!, + ts: makeUtcMs(fixture.lastPreCutoffDate, 21), + open: 777, + high: 777, + low: 777, + close: 777, + volume: 1000, + vwap: 777, + knownAt: fixture.vaultCutoffTs + 60_000, + }, + ]; + + const leakyShortsRows: TableRow[] = [ + { + listing_id: fixture.listingIds[0]!, + report_date: fixture.lastPreCutoffDate, + known_at: fixture.vaultCutoffTs + 120_000, + shares_short: 999_999, + net_change: 500_000, + pct_float: 0.99, + source: 'ceoShorts', + }, + { + listing_id: fixture.listingIds[1]!, + report_date: fixture.vaultCutoffDate, + known_at: fixture.vaultCutoffTs, + shares_short: 888_888, + net_change: -500_000, + pct_float: 0.88, + source: 'ceoShorts', + }, + ]; + + const store: MarketDataStore = { + bars(q): AsyncIterable { + barsCalls += 1; + const idSet = new Set(q.listingIds); + const fromMs = parseBoundMs(q.from, false); + const toMs = parseBoundMs(q.to, true); + const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + + const filtered = fixture.bars.filter( + row => + idSet.has(row.listingId) && + row.ts >= fromMs && + row.ts <= toMs && + row.knownAt <= asOfMs + ); + const out = leaky ? [...filtered, ...leakyBars] : filtered; + + return { + async *[Symbol.asyncIterator]() { + yield { rows: out }; + }, + }; + }, + + async universe() { + universeCalls += 1; + return [...fixture.listingIds]; + }, + + async shortsAsOf(q): Promise { + shortsCalls += 1; + const idSet = new Set(q.listingIds); + const fromDate = q.from.slice(0, 10); + const toDate = q.to.slice(0, 10); + const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + + const filtered = fixture.shortsTable.rows.filter(row => { + const listingId = row.listing_id as number; + const reportDate = row.report_date as string; + const knownAt = row.known_at as number; + return ( + idSet.has(listingId) && + reportDate >= fromDate && + reportDate <= toDate && + knownAt <= asOfMs + ); + }); + + return { + columns: fixture.shortsTable.columns, + rows: leaky ? [...filtered, ...leakyShortsRows] : filtered, + }; + }, + + async events(q): Promise
{ + eventsCalls += 1; + const idSet = q.listingIds !== undefined ? new Set(q.listingIds) : null; + const kindSet = new Set(q.kinds); + const fromMs = parseBoundMs(q.from, false); + const toMs = parseBoundMs(q.to, true); + const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; + + const filtered = fixture.eventsTable.rows.filter(row => { + const listingId = row.listing_id as number; + const kind = row.kind as EventKind; + const ts = row.ts as number; + const knownAt = row.known_at as number; + if (idSet !== null && !idSet.has(listingId)) { + return false; + } + return kindSet.has(kind) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; + }); + + return { + columns: fixture.eventsTable.columns, + rows: filtered, + }; + }, + + 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, + getBarsCalls: () => barsCalls, + getShortsCalls: () => shortsCalls, + getEventsCalls: () => eventsCalls, + getUniverseCalls: () => universeCalls, + }; +} + +interface FakeFindingStore { + readonly stored: FiledFindingRecord[]; + readonly appendCalls: { + readonly record: FiledFindingRecord; + readonly idempotencyKey?: string; + }[]; + readonly writePort: FindingWritePort; +} + +function createFakeFindingStore(): FakeFindingStore { + const stored: FiledFindingRecord[] = []; + const byIdempotencyKey = new Map(); + const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = + []; + + const writePort: FindingWritePort = { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + appendCalls.push({ record, idempotencyKey }); + if (idempotencyKey !== undefined) { + const existing = byIdempotencyKey.get(idempotencyKey); + if (existing !== undefined) { + if (areFiledFindingPayloadsEqual(existing, record)) { + return { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; + } + return { status: 'conflict' }; + } + } + const copy: FiledFindingRecord = { + ...record, + trialRefs: [...record.trialRefs], + evidenceRefs: [...record.evidenceRefs], + }; + stored.push(copy); + if (idempotencyKey !== undefined) { + byIdempotencyKey.set(idempotencyKey, copy); + } + return { status: 'created', id: copy.id, createdAt: copy.createdAt }; + }, + }; + + return { stored, appendCalls, writePort }; +} + +function createMemoryOutput(): { + readonly output: StdioOutput; + readonly lines: string[]; + readonly text: () => string; +} { + const chunks: string[] = []; + const lines: string[] = []; + let pending = ''; + + const output: StdioOutput = { + write(chunk: string): boolean { + chunks.push(chunk); + pending += chunk; + while (true) { + const idx = pending.indexOf('\n'); + if (idx === -1) { + break; + } + lines.push(pending.slice(0, idx)); + pending = pending.slice(idx + 1); + } + return true; + }, + }; + + return { + output, + lines, + text: () => chunks.join(''), + }; +} + +interface JsonRpcResponseEnvelope { + readonly jsonrpc: '2.0'; + readonly id: number | string | null; + readonly result?: unknown; + readonly error?: { + readonly code: number; + readonly message: string; + }; +} + +interface ToolCallEnvelope { + readonly content: readonly { readonly type: 'text'; readonly text: string }[]; + readonly isError?: boolean; +} + +function buildComposedServerOptions( + fixture: CopilotStudyFixture, + options?: { readonly leakyVaultRows?: boolean } +): { + readonly serverOptions: ResearchCopilotMcpServerOptions; + readonly storeHandle: FakeMarketDataStoreHandle; + readonly ledger: ReturnType; + readonly findings: FakeFindingStore; +} { + const storeHandle = createFakeMarketDataStore(fixture, { + leakyVaultRows: options?.leakyVaultRows, + }); + const ledger = createFakeTrialLedger(); + const findings = createFakeFindingStore(); + + const symbolSearchPort: SymbolSearchPort = { + async searchSymbols() { + return fixture.symbols; + }, + }; + + const knowledgePort: KnowledgePort = { + async listLibraryCards() { + return [ + { + id: 'card-dsr-01', + title: 'Deflated Sharpe & Effective Trials', + tags: ['dsr', 'rigor'], + summary: 'Adjust Sharpe ratios for multiple testing across relatedness clusters.', + body: 'Use clusterDeflatedSharpe with pre-Vault series and record every trial.', + }, + ]; + }, + async listFindings() { + return findings.stored; + }, + async listProviderCaveats() { + return [ + { + id: 'caveat-shorts-01', + provider: 'ceoShorts', + dataset: 'shorts', + caveat: 'Short-interest reports carry a multi-session publication lag.', + createdAt: '2024-01-15T00:00:00.000Z', + }, + ]; + }, + }; + + const serverOptions: ResearchCopilotMcpServerOptions = { + name: SERVER_NAME, + version: SERVER_VERSION, + store: storeHandle.store, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + ledger: ledger.executor, + principalId: AGENT_PRINCIPAL, + searchSymbols: { port: symbolSearchPort }, + eventStudy: { + resolveExchangeCalendars: () => fixture.exchangeCalendars, + }, + fileFinding: { + port: findings.writePort, + trialLookup: { + hasResearchVisibleTrial(ref: string): boolean { + return ledger.rows.some( + row => row.trial_id === ref && row.sample_end < fixture.vaultCutoffDate + ); + }, + }, + newId: () => FIXED_FINDING_ID, + now: () => FIXED_NOW_MS, + }, + readKnowledge: { port: knowledgePort }, + }; + + return { serverOptions, storeHandle, ledger, findings }; +} + +function decodeToolJson(response: JsonRpcResponseEnvelope): T { + expect(response.error).toBeUndefined(); + const result = response.result as ToolCallEnvelope; + expect(result.isError).not.toBe(true); + expect(result.content).toHaveLength(1); + return JSON.parse(result.content[0]!.text) as T; +} + +describe('createResearchCopilotMcpServer', () => { + test('tools/list returns the six literal expected tool names in fixed order with object inputSchemas', async () => { + const fixture = buildCopilotStudyFixture(); + const { serverOptions } = buildComposedServerOptions(fixture); + const server = createResearchCopilotMcpServer(serverOptions); + + expect(Object.isFrozen(RESEARCH_COPILOT_TOOL_NAMES)).toBe(true); + expect([...RESEARCH_COPILOT_TOOL_NAMES]).toEqual([...EXPECTED_TOOL_NAMES]); + + const rawResponse = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list' }) + ); + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse!) as JsonRpcResponseEnvelope; + expect(parsed.error).toBeUndefined(); + const tools = (parsed.result as { tools: readonly McpToolDescriptor[] }).tools; + + expect(tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); + expect(tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + + for (const tool of tools) { + expect(tool.inputSchema.type).toBe('object'); + expect(typeof tool.inputSchema.properties).toBe('object'); + expect(tool.inputSchema.properties).not.toBeNull(); + } + }); + + test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { + const fixture = buildCopilotStudyFixture(); + const { serverOptions, ledger, findings } = buildComposedServerOptions(fixture); + const server = createResearchCopilotMcpServer(serverOptions); + const sink = createMemoryOutput(); + + let signalTrialRef = ''; + + async function* requestStream(): AsyncGenerator { + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2024-11-05', + capabilities: {}, + clientInfo: { name: 'headless-copilot-test', version: '1.0.0' }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 3, + method: 'tools/call', + params: { + name: 'search_symbols', + arguments: { query: 'ACME', country: 'US', limit: 5 }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 4, + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [fixture.listingIds[0]!], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + timeframe: '1d', + adjustment: 'raw', + limit: 10, + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 5, + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 6, + method: 'tools/call', + params: { + name: 'event_study', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 5, + benchmark: 'equal_weight', + adjustment: 'raw', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + })}\n`; + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 7, + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { source: 'all', query: 'sharpe', limit: 5 }, + }, + })}\n`; + + // Decode the earlier analyze_signal response written by runStdioServer before + // constructing the file_finding call so the trialRef is dynamically linked. + expect(sink.lines.length).toBeGreaterThanOrEqual(5); + const signalResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; + const signalPayload = decodeToolJson(signalResp); + expect(signalPayload.status).toBe('ok'); + if (signalPayload.status !== 'ok') { + throw new Error('Expected analyze_signal status to be ok.'); + } + signalTrialRef = String(signalPayload.trial.trialId); + + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 8, + method: 'tools/call', + params: { + name: 'file_finding', + arguments: { + kind: 'finding', + title: 'Short-interest net_change study on synthetic US_EQ panel', + summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, + trialRefs: [signalTrialRef], + evidenceRefs: [FIXTURE_DATASET_ID], + idempotencyKey: 'copilot-e2e-finding-1', + }, + }, + })}\n`; + } + + await runStdioServer(server, { input: requestStream(), output: sink.output }); + + const rawOut = sink.text(); + expect(rawOut.endsWith('\n')).toBe(true); + expect(sink.lines).toHaveLength(8); + + const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); + expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); + for (const resp of responses) { + expect(resp.error).toBeUndefined(); + } + + // 1. initialize + const initResult = responses[0]!.result as { + serverInfo: { name: string; version: string }; + capabilities: { tools: Record }; + }; + expect(initResult.serverInfo).toEqual({ name: SERVER_NAME, version: SERVER_VERSION }); + expect(initResult.capabilities.tools).toEqual({}); + + // 2. tools/list + const listResult = responses[1]!.result as { tools: readonly McpToolDescriptor[] }; + expect(listResult.tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); + + // 3. search_symbols + const searchPayload = decodeToolJson(responses[2]!); + expect(searchPayload.scope).toBe('vault_fenced'); + expect(searchPayload.rowCount).toBe(1); + expect(searchPayload.rows[0]?.ticker).toBe('ACME'); + expect(searchPayload.rows[0]?.listingId).toBe(fixture.listingIds[0]); + + // 4. query_data + const queryPayload = decodeToolJson(responses[3]!); + expect(queryPayload.scope).toBe('vault_fenced'); + expect(queryPayload.rowCount).toBe(10); + expect(queryPayload.truncated).toBe(true); + expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); + + // 5. analyze_signal + const signalPayload = decodeToolJson(responses[4]!); + expect(signalPayload.status).toBe('ok'); + if (signalPayload.status !== 'ok') { + throw new Error('Expected analyze_signal status to be ok.'); + } + expect(String(signalPayload.trial.trialId)).toBe(signalTrialRef); + + // 6. event_study + const eventPayload = decodeToolJson(responses[5]!); + expect(eventPayload.status).toBe('ok'); + if (eventPayload.status !== 'ok') { + throw new Error('Expected event_study status to be ok.'); + } + expect(eventPayload.benchmark).toBe('equal_weight'); + expect(eventPayload.study.hasBenchmark).toBe(true); + + // 7. read_knowledge + const knowledgePayload = decodeToolJson(responses[6]!); + expect(knowledgePayload.rowCount).toBe(1); + expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); + + // 8. file_finding + const findingPayload = decodeToolJson(responses[7]!); + expect(findingPayload).toEqual({ + id: FIXED_FINDING_ID, + createdAt: FIXED_NOW_ISO, + created: true, + }); + + // Verify trial_ledger recorded both stages under AGENT_PRINCIPAL and matches responses. + expect(ledger.rows).toHaveLength(2); + expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); + expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); + expect(ledger.rows[0]?.trial_id).toBe(String(signalPayload.trial.trialId)); + expect(ledger.rows[1]?.trial_id).toBe(String(eventPayload.trial.trialId)); + + // Verify FindingWritePort recorded exactly one pending_review finding referencing signal trial. + expect(findings.appendCalls).toHaveLength(1); + expect(findings.stored).toHaveLength(1); + expect(findings.stored[0]).toMatchObject({ + id: findingPayload.id, + createdAt: findingPayload.createdAt, + kind: 'finding', + status: 'pending_review', + trialRefs: [signalTrialRef], + evidenceRefs: [FIXTURE_DATASET_ID], + }); + }); + + test('enforces the Vault fence on straddling and post-cutoff query_data and analyze_signal calls (clean vs leaky store)', async () => { + const fixture = buildCopilotStudyFixture(); + const clean = buildComposedServerOptions(fixture, { leakyVaultRows: false }); + const leaky = buildComposedServerOptions(fixture, { leakyVaultRows: true }); + + const cleanServer = createResearchCopilotMcpServer(clean.serverOptions); + const leakyServer = createResearchCopilotMcpServer(leaky.serverOptions); + + // Straddling query_data: ends after vaultCutoffDate with explicit post-cutoff asOf + const straddlingQueryReq = JSON.stringify({ + jsonrpc: '2.0', + id: 'q-straddle', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [fixture.listingIds[0]!, fixture.listingIds[1]!], + from: fixture.firstDate, + to: fixture.postCutoffDate, + asOf: fixture.postCutoffDate, + timeframe: '1d', + adjustment: 'raw', + limit: 500, + }, + }, + }); + + const cleanQueryPayload = decodeToolJson( + JSON.parse((await cleanServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope + ); + const leakyQueryPayload = decodeToolJson( + JSON.parse((await leakyServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope + ); + + for (const payload of [cleanQueryPayload, leakyQueryPayload]) { + expect(payload.scope).toBe('vault_fenced'); + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.toMs).toBe(fixture.vaultCutoffTs - 1); + expect(payload.asOfMs).toBe(fixture.vaultCutoffTs - 1); + expect(payload.rows.every(r => r.ts < fixture.vaultCutoffTs && r.knownAt < fixture.vaultCutoffTs)).toBe( + true + ); + } + expect(leakyQueryPayload.rows).toEqual(cleanQueryPayload.rows); + + // Straddling analyze_signal: clean vs deliberately leaky store must produce identical payload & trial row + const straddlingSignalReq = JSON.stringify({ + jsonrpc: '2.0', + id: 'sig-straddle', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.postCutoffDate, + asOf: fixture.postCutoffDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + }); + + const cleanSignalPayload = decodeToolJson( + JSON.parse((await cleanServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope + ); + const leakySignalPayload = decodeToolJson( + JSON.parse((await leakyServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope + ); + + expect(cleanSignalPayload.status).toBe('ok'); + expect(leakySignalPayload.status).toBe('ok'); + expect(leakySignalPayload).toEqual(cleanSignalPayload); + expect(leakySignalPayload.scope).toBe('vault_fenced'); + expect(leakySignalPayload.clampedTo).toBe(true); + expect(leakySignalPayload.clampedAsOf).toBe(true); + expect(leakySignalPayload.toMs).toBe(fixture.vaultCutoffTs - 1); + expect(leakySignalPayload.asOfMs).toBe(fixture.vaultCutoffTs - 1); + + expect(clean.ledger.rows).toHaveLength(1); + expect(leaky.ledger.rows).toHaveLength(1); + expect(leaky.ledger.rows[0]).toEqual(clean.ledger.rows[0]); + + // Last forward-return endpoint must remain strictly before vaultCutoffDate. + const lastSampleEnd = leaky.ledger.rows[0]!.sample_end; + const lastSampleIdx = fixture.allDates.indexOf(lastSampleEnd); + expect(lastSampleIdx).toBeGreaterThanOrEqual(0); + expect(lastSampleIdx + 5).toBeLessThan(fixture.preCutoffSessions); + expect(fixture.allDates[lastSampleIdx + 5]! < fixture.vaultCutoffDate).toBe(true); + + // Wholly post-cutoff range must return VaultHoldoutFenceError with zero store reads and zero ledger writes. + const postCutoffCheck = buildComposedServerOptions(fixture); + const postCutoffServer = createResearchCopilotMcpServer(postCutoffCheck.serverOptions); + + const postQueryResp = JSON.parse( + (await postCutoffServer.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'q-post', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [fixture.listingIds[0]!], + from: fixture.vaultCutoffDate, + to: fixture.postCutoffDate, + timeframe: '1d', + adjustment: 'raw', + }, + }, + }) + ))! + ) as JsonRpcResponseEnvelope; + const postQueryTool = postQueryResp.result as ToolCallEnvelope; + expect(postQueryTool.isError).toBe(true); + expect(postQueryTool.content[0]?.text).toContain('VaultHoldoutFenceError'); + + const postSignalResp = JSON.parse( + (await postCutoffServer.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'sig-post', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...fixture.listingIds], + from: fixture.vaultCutoffDate, + to: fixture.postCutoffDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + adjustment: 'raw', + }, + }, + }) + ))! + ) as JsonRpcResponseEnvelope; + const postSignalTool = postSignalResp.result as ToolCallEnvelope; + expect(postSignalTool.isError).toBe(true); + expect(postSignalTool.content[0]?.text).toContain('VaultHoldoutFenceError'); + + expect(postCutoffCheck.storeHandle.getBarsCalls()).toBe(0); + expect(postCutoffCheck.storeHandle.getShortsCalls()).toBe(0); + expect(postCutoffCheck.storeHandle.getUniverseCalls()).toBe(0); + expect(postCutoffCheck.ledger.getInsertCalls()).toBe(0); + }); + + test('returns INVALID_PARAMS for unknown tool in stdio session and continues processing ping', async () => { + const fixture = buildCopilotStudyFixture(); + const { serverOptions } = buildComposedServerOptions(fixture); + const server = createResearchCopilotMcpServer(serverOptions); + const sink = createMemoryOutput(); + + async function* input(): AsyncGenerator { + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-tool', + method: 'tools/call', + params: { name: 'nonexistent_tool', arguments: {} }, + })}\n`; + yield `${JSON.stringify({ + jsonrpc: '2.0', + id: 'keep-alive', + method: 'ping', + })}\n`; + } + + await runStdioServer(server, { input: input(), output: sink.output }); + + expect(sink.lines).toHaveLength(2); + const errResp = JSON.parse(sink.lines[0]!) as JsonRpcResponseEnvelope; + const pingResp = JSON.parse(sink.lines[1]!) as JsonRpcResponseEnvelope; + + expect(errResp.id).toBe('bad-tool'); + expect(errResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + expect(errResp.error?.message).toBe('Unknown tool: "nonexistent_tool".'); + + expect(pingResp.id).toBe('keep-alive'); + expect(pingResp.error).toBeUndefined(); + expect(pingResp.result).toEqual({}); + }); + + test('throws on duplicate or missing/unexpected tool name during server composition', () => { + const fixture = buildCopilotStudyFixture(); + const { serverOptions } = buildComposedServerOptions(fixture); + + const dupSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => ({ + name: 'search_symbols', + description: 'Duplicate name entry', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + async execute() { + return { content: [{ type: 'text', text: '{}' }] }; + }, + })); + try { + expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( + /Duplicate MCP tool name/ + ); + } finally { + dupSpy.mockRestore(); + } + + const missingSpy = spyOn(readKnowledgeToolModule, 'createReadKnowledgeTool').mockImplementation( + () => ({ + name: 'unexpected_tool', + description: 'Unexpected name entry leaving read_knowledge missing', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + async execute() { + return { content: [{ type: 'text', text: '{}' }] }; + }, + }) + ); + try { + expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( + /expected "read_knowledge", got "unexpected_tool"/ + ); + } finally { + missingSpy.mockRestore(); + } + }); +});