diff --git a/libs/research/README.md b/libs/research/README.md index b22d581a..a6b9bb6e 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -280,6 +280,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported ### 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. +- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`. ### Remaining M2 MCP Items (Later Tasks) diff --git a/libs/research/src/mcp/adapters/postgres-copilot.ts b/libs/research/src/mcp/adapters/postgres-copilot.ts new file mode 100644 index 00000000..ca571894 --- /dev/null +++ b/libs/research/src/mcp/adapters/postgres-copilot.ts @@ -0,0 +1,173 @@ +/** + * PostgreSQL composition root for the MCP research copilot server. + * + * Wires a single injected {@link PostgresResearchCopilotExecutor} into all + * PostgreSQL-backed MCP adapters (`search_symbols`, `file_finding`, + * `read_knowledge`, `event_study` listing calendars, and `trial_ledger`) with + * one authoritative Vault cutoff (`vaultContext.vaultCutoffTs`). + * + * Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution, + * market data store, library-card reader, session-date port, ID generator, and + * clock are all injected by the caller. + */ + +import { + type ResearchCopilotMcpServerOptions, + createResearchCopilotMcpServer, +} from '../copilot-server'; +import type { McpServer } from '../server'; +import type { KnowledgePort } from '../tools/read-knowledge'; +import { + type EarlyCloseOverrides, + type SessionDatesPort, + createExchangeCalendarResolver, + createPostgresListingCalendarPort, +} from './exchange-calendars'; +import { + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, +} from './postgres-findings'; +import { createPostgresSymbolSearchPort } from './postgres-symbol-search'; +import { createPostgresTrialRefPort } from './postgres-trial-ref'; + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface shared by + * all PostgreSQL-backed MCP copilot adapters and `trial_ledger`. + * + * Assignable without casts to `SymbolSearchExecutor`, `TrialRefExecutor`, + * `PostgresFindingsExecutor`, `ListingCalendarExecutor`, and + * `TrialLedgerExecutor`. + */ +export interface PostgresResearchCopilotExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** + * Composition options for {@link createPostgresResearchCopilotServer}. + * + * Uses `vaultContext.vaultCutoffTs` as the single authoritative Vault cutoff + * across all Vault-fenced tools and `trial_ledger` visibility lookups. + */ +export interface PostgresResearchCopilotServerOptions + extends Pick< + ResearchCopilotMcpServerOptions, + 'name' | 'version' | 'store' | 'vaultContext' | 'principalId' + > { + readonly executor: PostgresResearchCopilotExecutor; + /** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */ + readonly schema?: string; + readonly listLibraryCards: KnowledgePort['listLibraryCards']; + readonly sessionDates: SessionDatesPort; + readonly earlyCloses?: EarlyCloseOverrides; + readonly newId: () => string; + readonly now: () => Date | number; +} + +function validateOptions(options: PostgresResearchCopilotServerOptions): void { + if (typeof options !== 'object' || options === null) { + throw new Error( + 'Invalid `options`: expected a PostgresResearchCopilotServerOptions object.' + ); + } + if ( + typeof options.executor !== 'object' || + options.executor === null || + typeof options.executor.query !== 'function' + ) { + throw new Error( + 'Invalid `executor`: expected an object with a callable query(text, params?) method.' + ); + } + if (typeof options.vaultContext !== 'object' || options.vaultContext === null) { + throw new Error('Invalid `vaultContext`: expected a VaultFenceContext object.'); + } + if (typeof options.listLibraryCards !== 'function') { + throw new Error('Invalid `listLibraryCards`: expected a callable function.'); + } + if ( + typeof options.sessionDates !== 'object' || + options.sessionDates === null || + typeof options.sessionDates.listSessionDates !== 'function' + ) { + throw new Error( + 'Invalid `sessionDates`: expected an object with a callable listSessionDates(query) method.' + ); + } + if (typeof options.newId !== 'function') { + throw new Error('Invalid `newId`: expected a callable function.'); + } + if (typeof options.now !== 'function') { + throw new Error('Invalid `now`: expected a callable function.'); + } +} + +/** + * Composes all six research copilot MCP tools into a single {@link McpServer} + * backed by one shared PostgreSQL executor and one authoritative Vault cutoff. + * + * Schema-aware adapters (`search_symbols`, `trial_ledger` visibility lookup, + * `findings`, `provider_caveats`, and listing-to-exchange calendars) qualify + * their tables with `options.schema` when supplied; `trial_ledger` writes and + * cluster DSR reads resolve through the executor's `search_path`. + */ +export function createPostgresResearchCopilotServer( + options: PostgresResearchCopilotServerOptions +): McpServer { + validateOptions(options); + + const pgAdapterOptions = + options.schema === undefined + ? { executor: options.executor } + : { executor: options.executor, schema: options.schema }; + + const symbolSearchPort = createPostgresSymbolSearchPort(pgAdapterOptions); + const trialRefPort = createPostgresTrialRefPort({ + ...pgAdapterOptions, + vaultCutoffTs: options.vaultContext.vaultCutoffTs, + }); + const findingWritePort = createPostgresFindingWritePort(pgAdapterOptions); + const knowledgeReaders = createPostgresKnowledgeReaders(pgAdapterOptions); + const listingCalendars = createPostgresListingCalendarPort(pgAdapterOptions); + + const resolveExchangeCalendars = createExchangeCalendarResolver( + options.earlyCloses === undefined + ? { listingCalendars, sessionDates: options.sessionDates } + : { + listingCalendars, + sessionDates: options.sessionDates, + earlyCloses: options.earlyCloses, + } + ); + + const knowledgePort: KnowledgePort = { + listLibraryCards: options.listLibraryCards, + ...knowledgeReaders, + }; + + return createResearchCopilotMcpServer({ + name: options.name, + version: options.version, + store: options.store, + vaultContext: options.vaultContext, + ledger: options.executor, + principalId: options.principalId, + searchSymbols: { + port: symbolSearchPort, + }, + eventStudy: { + resolveExchangeCalendars, + }, + fileFinding: { + port: findingWritePort, + trialLookup: trialRefPort, + newId: options.newId, + now: options.now, + }, + readKnowledge: { + port: knowledgePort, + }, + }); +} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index af5eb583..76d441d4 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -12,3 +12,4 @@ export * from './tools/file-finding'; export * from './tools/query-data'; export * from './tools/read-knowledge'; export * from './tools/search-symbols'; +export * from './adapters/postgres-copilot'; diff --git a/libs/research/test/mcp-postgres-copilot.test.ts b/libs/research/test/mcp-postgres-copilot.test.ts new file mode 100644 index 00000000..3070eab0 --- /dev/null +++ b/libs/research/test/mcp-postgres-copilot.test.ts @@ -0,0 +1,993 @@ +import { describe, expect, test } from 'bun:test'; +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 EventStudyResultPayload, + type FileFindingResultPayload, + type KnowledgePort, + type LibraryCardQuery, + type LibraryCardRecord, + type ListingCalendarExecutor, + type McpServer, + type PostgresFindingsExecutor, + type PostgresResearchCopilotExecutor, + type PostgresResearchCopilotServerOptions, + RESEARCH_COPILOT_TOOL_NAMES, + type ReadKnowledgeResultPayload, + type SearchSymbolsResultPayload, + type SessionDatesPort, + type SessionDatesQuery, + type SymbolSearchExecutor, + type TrialRefExecutor, + createPostgresResearchCopilotServer, +} from '../src/mcp/index'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +// Synthetic PostgreSQL copilot composition fixture metadata (pinned for reproducibility): +// - Dataset ID: `synthetic:mcp-postgres-copilot:seed-20261202:v1` +// - Seed: `20261202` (Mulberry32 PRNG) +// - Universe: 8 synthetic US equity listings (`60001..60008`, XNYS, USD, 21:00 UTC close) +// - Sessions: 40 pre-cutoff + 5 post-cutoff business sessions starting `2023-01-03` +// - Cutoff: `vaultCutoffDate` = `allDates[40]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) +// - Economic assumptions: daily raw close-to-close returns, equal-weight benchmark over +// eligible listing returns, zero modeled execution/transaction costs. +// - Ownership: Quant research role owns the study assumptions; `AGENT_PRINCIPAL` owns +// recorded `trial_ledger` rows. +const FIXTURE_DATASET_ID = 'synthetic:mcp-postgres-copilot:seed-20261202:v1'; +const SEED = 20261202; +const SERVER_NAME = 'stock-bot-pg-copilot'; +const SERVER_VERSION = '0.1.0'; +const AGENT_PRINCIPAL = 'agent:22222222-3333-4444-8555-666666666666'; +const FIXED_FINDING_ID = 'finding-pg-copilot-001'; +const FIXED_NOW_ISO = '2024-06-15T12:00:00.000Z'; +const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); + +// Compile-time assertions: +// 1) PostgresResearchCopilotExecutor is assignable to all five existing executor interfaces without casts. +function _assertExecutorAssignability(executor: PostgresResearchCopilotExecutor) { + const asSymbolSearch: SymbolSearchExecutor = executor; + const asTrialRef: TrialRefExecutor = executor; + const asFindings: PostgresFindingsExecutor = executor; + const asListingCalendar: ListingCalendarExecutor = executor; + const asTrialLedger: TrialLedgerExecutor = executor; + return [asSymbolSearch, asTrialRef, asFindings, asListingCalendar, asTrialLedger] as const; +} +void _assertExecutorAssignability; + +// 2) PostgresResearchCopilotServerOptions has no separate `vaultCutoffTs` key. +type HasSeparateVaultCutoffTs = 'vaultCutoffTs' extends keyof PostgresResearchCopilotServerOptions + ? true + : false; +const _noSeparateVaultCutoffTs: HasSeparateVaultCutoffTs = false; +void _noSeparateVaultCutoffTs; + +interface RecordedSqlCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +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[]; +} + +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 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 EventStudyFixture { + readonly listingIds: readonly number[]; + readonly allDates: readonly string[]; + readonly preCutoffDates: readonly string[]; + readonly firstDate: string; + readonly lastPreCutoffDate: string; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: readonly BarRecord[]; + readonly eventsTable: Table; +} + +function buildEventStudyFixture(): EventStudyFixture { + const rand = createSeededRng(SEED); + const listingCount = 8; + const preCutoffSessions = 40; + const postCutoffSessions = 5; + + const allDates = makeBusinessDates('2023-01-03', preCutoffSessions + postCutoffSessions); + const preCutoffDates = allDates.slice(0, preCutoffSessions); + const firstDate = allDates[0]!; + const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); + const bars: BarRecord[] = []; + const eventRows: TableRow[] = []; + + const eventDayIndices = [8, 14, 20, 26, 32]; + 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 + 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 prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 20 + l * 3; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + for (let l = 0; l < listingCount; l += 1) { + let drift = 0; + for (let offset = 0; offset <= 2; offset += 1) { + if (eventSet.has(`${t - offset}:${l}`)) { + drift += 0.008 * (1 + ((l + t) % 3) * 0.2); + } + } + const ret = drift + (rand() * 2 - 1) * 0.01; + prices[l] = Math.max(1.0, prices[l]! * (1 + ret)); + 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: 100_000 + l * 1_000 + t * 50, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + preCutoffDates, + firstDate, + lastPreCutoffDate, + vaultCutoffDate, + vaultCutoffTs, + bars, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: eventRows, + }, + }; +} + +function createFakeMarketDataStore(fixture: EventStudyFixture): MarketDataStore { + return { + bars(q): AsyncIterable { + 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 + ); + return { + async *[Symbol.asyncIterator]() { + yield { rows: filtered }; + }, + }; + }, + async universe() { + return [...fixture.listingIds]; + }, + async events(q): Promise { + 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 shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; +} + +class RecordingPostgresExecutor implements PostgresResearchCopilotExecutor { + readonly calls: RecordedSqlCall[] = []; + readonly ledgerRows: StoredTrialRow[] = []; + readonly visibleTrialsById: Map; + private nextTrialId = 100; + + constructor(options?: { readonly trials?: readonly { readonly id: string; readonly sampleEnd: string }[] }) { + this.visibleTrialsById = new Map(); + for (const trial of options?.trials ?? [{ id: '42', sampleEnd: '2024-05-01' }]) { + this.visibleTrialsById.set(trial.id, { sampleEnd: trial.sampleEnd }); + } + } + + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + // Use `this` explicitly so receiver loss would immediately fail tests. + this.calls.push({ text, params }); + const normalized = text.trim(); + + // 1. Symbol search (`listing` + `instrument` + `exchange` + `listing_symbol_history`) + if (normalized.includes('listing_symbol_history') && normalized.includes('canonical_name')) { + return { + rows: [ + { + listing_id: 60_001, + instrument_id: 90_001, + ticker: 'ACME', + class_suffix: null, + name: 'Acme Holdings Inc', + mic: 'XNYS', + currency: 'USD', + isin: 'US0000000001', + first_bar_date: '2020-01-02', + last_bar_date: '2024-05-31', + delisted_at: null, + } as unknown as Row, + ], + }; + } + + // 2. Trial-ref visibility lookup (`SELECT 1 AS visible FROM ...trial_ledger`) + if (normalized.startsWith('SELECT 1 AS visible FROM')) { + const trialId = String(params?.[0] ?? ''); + const cutoffDate = String(params?.[1] ?? ''); + const trial = this.visibleTrialsById.get(trialId); + if (trial !== undefined && trial.sampleEnd < cutoffDate) { + return { rows: [{ visible: 1 } as unknown as Row] }; + } + return { rows: [] }; + } + + // 3. Findings insert (`INSERT INTO ...findings`) + if (normalized.startsWith('INSERT INTO') && normalized.includes('findings (')) { + const id = String(params?.[0] ?? ''); + const createdAt = String(params?.[5] ?? FIXED_NOW_ISO); + return { + rows: [{ id, created_at: createdAt } as unknown as Row], + }; + } + + // 4. Findings reader (`SELECT ... FROM ...findings`) + if (normalized.startsWith('SELECT') && normalized.includes('trial_refs') && normalized.includes('evidence_refs')) { + return { + rows: [ + { + id: 'finding-existing-01', + title: 'Short-interest drift finding', + status: 'approved', + created_at: '2024-05-10T10:00:00.000Z', + summary: 'Pre-Vault empirical finding on filing drift.', + trial_refs: ['42'], + evidence_refs: ['snap-01'], + } as unknown as Row, + ], + }; + } + + // 5. Provider caveats reader (`SELECT ... FROM ...provider_caveats`) + if (normalized.startsWith('SELECT') && normalized.includes('caveat') && normalized.includes('provider_caveats')) { + return { + rows: [ + { + id: 'caveat-eodhd-01', + provider: 'eodhd', + dataset: 'bars_1d', + caveat: 'Splits require un-adjustment before raw close storage.', + created_at: '2024-03-01T00:00:00.000Z', + } as unknown as Row, + ], + }; + } + + // 6. Listing calendar lookup (`SELECT ... e.calendar_code AS calendar_code`) + if (normalized.startsWith('SELECT') && normalized.includes('e.calendar_code AS calendar_code')) { + const requested = (params?.[0] as readonly number[] | undefined) ?? []; + return { + rows: requested.map( + listingId => + ({ + listing_id: listingId, + calendar_code: 'XNYS', + }) as unknown as Row + ), + }; + } + + // 7. Trial ledger insert (`INSERT INTO trial_ledger`) + if (normalized.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = this.nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId % 60)); + 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, + }; + this.ledgerRows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + }; + } + + // 8. Trial ledger cluster/target reads (`SELECT ... FROM trial_ledger`) + if (normalized.startsWith('SELECT') && normalized.includes('FROM trial_ledger')) { + if (normalized.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = this.ledgerRows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[] }; + } + if (normalized.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = this.ledgerRows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[] }; + } + } + + throw new Error(`Unexpected SQL statement in RecordingPostgresExecutor:\n${text}`); + } +} + +async function callMcpTool( + server: McpServer, + id: number, + name: string, + args: Record +): Promise<{ readonly envelope: ToolCallEnvelope; readonly parsed: T | null }> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { name, arguments: args }, + }) + ); + if (raw === null) { + throw new Error(`Expected JSON-RPC response for tool "${name}", got null.`); + } + const rpc = JSON.parse(raw) as JsonRpcResponseEnvelope; + expect(rpc.error).toBeUndefined(); + const envelope = rpc.result as ToolCallEnvelope; + const text = envelope.content[0]?.text ?? ''; + if (envelope.isError === true) { + return { envelope, parsed: null }; + } + return { envelope, parsed: JSON.parse(text) as T }; +} + +function makeDefaultLibraryCards(): readonly LibraryCardRecord[] { + return [ + { + id: 'card-dsr-01', + title: 'Deflated Sharpe Ratio', + tags: ['dsr', 'rigor'], + summary: 'Adjust Sharpe ratios for multiple testing.', + body: 'Always record trials before reading results.', + }, + ]; +} + +function buildValidOptions(overrides?: { + readonly executor?: RecordingPostgresExecutor; + readonly schema?: string; + readonly vaultCutoffTs?: number; + readonly fixture?: EventStudyFixture; + readonly listLibraryCards?: KnowledgePort['listLibraryCards']; + readonly sessionDates?: SessionDatesPort; +}): { + readonly options: PostgresResearchCopilotServerOptions; + readonly executor: RecordingPostgresExecutor; + readonly fixture: EventStudyFixture; + readonly sessionDateCalls: SessionDatesQuery[]; + readonly libraryCardCalls: LibraryCardQuery[]; +} { + const fixture = overrides?.fixture ?? buildEventStudyFixture(); + const executor = overrides?.executor ?? new RecordingPostgresExecutor(); + const sessionDateCalls: SessionDatesQuery[] = []; + const libraryCardCalls: LibraryCardQuery[] = []; + + const defaultSessionDates: SessionDatesPort = { + listSessionDates(query: SessionDatesQuery) { + sessionDateCalls.push(query); + return fixture.allDates.filter(d => d >= query.fromDate && d <= query.toDate); + }, + }; + + const defaultListLibraryCards: KnowledgePort['listLibraryCards'] = async ( + q: LibraryCardQuery + ) => { + libraryCardCalls.push(q); + return makeDefaultLibraryCards(); + }; + + const base: PostgresResearchCopilotServerOptions = { + name: SERVER_NAME, + version: SERVER_VERSION, + executor, + ...(overrides?.schema !== undefined ? { schema: overrides.schema } : {}), + store: createFakeMarketDataStore(fixture), + vaultContext: { vaultCutoffTs: overrides?.vaultCutoffTs ?? fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + listLibraryCards: overrides?.listLibraryCards ?? defaultListLibraryCards, + sessionDates: overrides?.sessionDates ?? defaultSessionDates, + newId: () => FIXED_FINDING_ID, + now: () => FIXED_NOW_MS, + }; + + return { + options: base, + executor, + fixture, + sessionDateCalls, + libraryCardCalls, + }; +} + +describe('createPostgresResearchCopilotServer', () => { + test('registers all six MCP tools in RESEARCH_COPILOT_TOOL_NAMES order with zero queries at construction', () => { + const { options, executor } = buildValidOptions(); + const server = createPostgresResearchCopilotServer(options); + + expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + expect(executor.calls).toHaveLength(0); + }); + + test('routes search_symbols, file_finding, and read_knowledge (findings + provider_caveats) through the same executor', async () => { + const cutoffTs = Date.UTC(2024, 6, 1, 0, 0, 0, 0); // 2024-07-01 + const { options, executor } = buildValidOptions({ vaultCutoffTs: cutoffTs }); + const server = createPostgresResearchCopilotServer(options); + + // 1) search_symbols + const beforeSearch = executor.calls.length; + const searchRes = await callMcpTool(server, 1, 'search_symbols', { + query: 'ACME', + country: 'US', + includeDelisted: false, + limit: 5, + }); + expect(searchRes.envelope.isError).toBeUndefined(); + expect(searchRes.parsed?.rows).toHaveLength(1); + expect(searchRes.parsed?.rows[0]?.ticker).toBe('ACME'); + const searchCalls = executor.calls.slice(beforeSearch); + expect(searchCalls).toHaveLength(1); + // createSearchSymbolsTool always queries the port with includeDelisted: true so + // post-cutoff delistings cannot hide listings that were active as of the cutoff. + expect(searchCalls[0]?.params).toEqual(['2024-07-01', '%ACME%', 'ACME', 'US', true]); + + // 2) file_finding with trial_ledger ref '42' + const beforeFile = executor.calls.length; + const fileRes = await callMcpTool(server, 2, 'file_finding', { + kind: 'finding', + title: 'Filing drift effect', + summary: 'Pre-Vault event study shows positive post-filing drift.', + trialRefs: ['42'], + evidenceRefs: [FIXTURE_DATASET_ID], + }); + expect(fileRes.envelope.isError).toBeUndefined(); + expect(fileRes.parsed).toEqual({ + id: FIXED_FINDING_ID, + createdAt: FIXED_NOW_ISO, + created: true, + }); + const fileCalls = executor.calls.slice(beforeFile); + expect(fileCalls).toHaveLength(2); + // Visibility lookup must run before finding insert + expect(fileCalls[0]?.text).toContain('SELECT 1 AS visible FROM trial_ledger'); + expect(fileCalls[0]?.params).toEqual(['42', '2024-07-01']); + expect(fileCalls[1]?.text).toContain('INSERT INTO findings'); + expect(fileCalls[1]?.params?.[0]).toBe(FIXED_FINDING_ID); + expect(fileCalls[1]?.params?.[5]).toBe(FIXED_NOW_ISO); + + // 3) read_knowledge (findings) + const beforeFindings = executor.calls.length; + const findingsRes = await callMcpTool(server, 3, 'read_knowledge', { + source: 'findings', + query: 'drift', + }); + expect(findingsRes.envelope.isError).toBeUndefined(); + expect(findingsRes.parsed?.rows).toHaveLength(1); + expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); + const findingsCalls = executor.calls.slice(beforeFindings); + expect(findingsCalls).toHaveLength(1); + expect(findingsCalls[0]?.text).toContain('FROM findings'); + expect(findingsCalls[0]?.params).toEqual(['%drift%']); + + // 4) read_knowledge (provider_caveats) + const beforeCaveats = executor.calls.length; + const caveatsRes = await callMcpTool(server, 4, 'read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + query: 'split', + }); + expect(caveatsRes.envelope.isError).toBeUndefined(); + expect(caveatsRes.parsed?.rows).toHaveLength(1); + expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); + const caveatsCalls = executor.calls.slice(beforeCaveats); + expect(caveatsCalls).toHaveLength(1); + expect(caveatsCalls[0]?.text).toContain('FROM provider_caveats'); + expect(caveatsCalls[0]?.params).toEqual(['eodhd', '%split%']); + }); + + test('qualifies every schema-aware adapter table when schema is provided and leaves them unqualified when omitted', async () => { + const runAllSqlTools = async (schema?: string) => { + const fixture = buildEventStudyFixture(); + const executor = new RecordingPostgresExecutor({ + trials: [{ id: '42', sampleEnd: '2023-01-10' }], + }); + const { options } = buildValidOptions({ + executor, + fixture, + schema, + }); + const server = createPostgresResearchCopilotServer(options); + + const s1 = await callMcpTool(server, 1, 'search_symbols', { + query: 'ACME', + }); + expect(s1.envelope.isError).toBeUndefined(); + + const s2 = await callMcpTool(server, 2, 'file_finding', { + kind: 'finding', + title: 'Schema test finding', + summary: 'Verifies schema qualification across adapters.', + trialRefs: ['42'], + }); + expect(s2.envelope.isError).toBeUndefined(); + + const s3 = await callMcpTool(server, 3, 'read_knowledge', { + source: 'findings', + id: 'finding-existing-01', + }); + expect(s3.envelope.isError).toBeUndefined(); + + const s4 = await callMcpTool(server, 4, 'read_knowledge', { + source: 'provider_caveats', + provider: 'eodhd', + }); + expect(s4.envelope.isError).toBeUndefined(); + + const s5 = await callMcpTool(server, 5, 'event_study', { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: fixture.lastPreCutoffDate, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'equal_weight', + }); + expect(s5.envelope.isError).toBeUndefined(); + + return executor.calls; + }; + + // With schema: 'research_x' + const qualifiedCalls = await runAllSqlTools('research_x'); + const symbolSql = qualifiedCalls.find(c => c.text.includes('listing_symbol_history'))?.text ?? ''; + expect(symbolSql).toContain('FROM "research_x".listing l'); + expect(symbolSql).toContain('INNER JOIN "research_x".instrument i'); + expect(symbolSql).toContain('INNER JOIN "research_x".exchange e'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_any'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h_past'); + expect(symbolSql).toContain('FROM "research_x".listing_symbol_history h'); + + const trialLookupSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT 1 AS visible'))?.text ?? ''; + expect(trialLookupSql).toContain('FROM "research_x".trial_ledger'); + + const findingInsertSql = + qualifiedCalls.find(c => c.text.startsWith('INSERT INTO') && c.text.includes('findings (')) + ?.text ?? ''; + expect(findingInsertSql).toContain('INSERT INTO "research_x".findings'); + + const findingsReadSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('trial_refs'))?.text ?? + ''; + expect(findingsReadSql).toContain('FROM "research_x".findings'); + + const caveatsReadSql = + qualifiedCalls.find(c => c.text.startsWith('SELECT') && c.text.includes('provider_caveats')) + ?.text ?? ''; + expect(caveatsReadSql).toContain('FROM "research_x".provider_caveats'); + + const calendarSql = + qualifiedCalls.find(c => c.text.includes('e.calendar_code AS calendar_code'))?.text ?? ''; + expect(calendarSql).toContain('FROM "research_x".listing l'); + expect(calendarSql).toContain('INNER JOIN "research_x".exchange e'); + + // Ledger SQL resolves via executor's search_path (unqualified even when schema is set) + const ledgerInsertSql = + qualifiedCalls.find(c => c.text.trim().startsWith('INSERT INTO trial_ledger'))?.text ?? ''; + expect(ledgerInsertSql).toContain('INSERT INTO trial_ledger'); + expect(ledgerInsertSql).not.toContain('"research_x".'); + + // With schema omitted + const unqualifiedCalls = await runAllSqlTools(undefined); + expect(unqualifiedCalls.length).toBeGreaterThanOrEqual(7); + for (const call of unqualifiedCalls) { + expect(call.text).not.toMatch(/"[a-z_][a-z0-9_]*"\./); + } + }); + + test('derives trial-ref visibility cutoff exclusively from vaultContext.vaultCutoffTs', async () => { + // Trial '42' ends on 2024-06-01: + // - Under cutoff 2024-06-01: sample_end < '2024-06-01' is false -> rejected with zero inserts. + // - Under cutoff 2024-07-01: sample_end < '2024-07-01' is true -> accepted and inserted. + const trialFixture = [{ id: '42', sampleEnd: '2024-06-01' }] as const; + + const blockedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); + const blockedSetup = buildValidOptions({ + executor: blockedExecutor, + vaultCutoffTs: Date.UTC(2024, 5, 1, 0, 0, 0, 0), // 2024-06-01 + }); + const blockedServer = createPostgresResearchCopilotServer(blockedSetup.options); + + const blockedRes = await callMcpTool(blockedServer, 1, 'file_finding', { + kind: 'finding', + title: 'Holdout-boundary trial', + summary: 'Must be rejected when sample_end equals cutoff.', + trialRefs: ['42'], + }); + expect(blockedRes.envelope.isError).toBe(true); + expect(blockedExecutor.calls).toHaveLength(1); + expect(blockedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); + expect(blockedExecutor.calls[0]?.params).toEqual(['42', '2024-06-01']); + + const allowedExecutor = new RecordingPostgresExecutor({ trials: trialFixture }); + const allowedSetup = buildValidOptions({ + executor: allowedExecutor, + vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), // 2024-07-01 + }); + const allowedServer = createPostgresResearchCopilotServer(allowedSetup.options); + + const allowedRes = await callMcpTool(allowedServer, 2, 'file_finding', { + kind: 'finding', + title: 'Pre-cutoff trial', + summary: 'Allowed once cutoff moves past sample_end.', + trialRefs: ['42'], + }); + expect(allowedRes.envelope.isError).toBeUndefined(); + expect(allowedRes.parsed?.created).toBe(true); + expect(allowedExecutor.calls).toHaveLength(2); + expect(allowedExecutor.calls[0]?.text).toContain('sample_end < $2::date'); + expect(allowedExecutor.calls[0]?.params).toEqual(['42', '2024-07-01']); + expect(allowedExecutor.calls[1]?.text).toContain('INSERT INTO findings'); + }); + + test('isolates library reads from PostgreSQL and prevents smuggling listFindings or listProviderCaveats', async () => { + const libraryCalls: LibraryCardQuery[] = []; + let smuggledFindingsCalled = false; + let smuggledCaveatsCalled = false; + + const baseLibraryFn: KnowledgePort['listLibraryCards'] = async (q: LibraryCardQuery) => { + libraryCalls.push(q); + return makeDefaultLibraryCards(); + }; + + const smuggledFn = Object.assign(baseLibraryFn, { + listFindings: async () => { + smuggledFindingsCalled = true; + throw new Error('Smuggled listFindings must never be called'); + }, + listProviderCaveats: async () => { + smuggledCaveatsCalled = true; + throw new Error('Smuggled listProviderCaveats must never be called'); + }, + }); + + const { options, executor } = buildValidOptions({ listLibraryCards: smuggledFn }); + const server = createPostgresResearchCopilotServer(options); + + // source: 'library' -> calls injected listLibraryCards and issues zero executor queries + const libRes = await callMcpTool(server, 1, 'read_knowledge', { + source: 'library', + query: 'Sharpe', + }); + expect(libRes.envelope.isError).toBeUndefined(); + expect(libRes.parsed?.rows).toHaveLength(1); + expect(libRes.parsed?.rows[0]?.id).toBe('card-dsr-01'); + expect(libraryCalls).toHaveLength(1); + expect(executor.calls).toHaveLength(0); + + // source: 'findings' -> uses PostgreSQL reader, never calls smuggled property + const findingsRes = await callMcpTool(server, 2, 'read_knowledge', { + source: 'findings', + }); + expect(findingsRes.envelope.isError).toBeUndefined(); + expect(findingsRes.parsed?.rows[0]?.id).toBe('finding-existing-01'); + expect(smuggledFindingsCalled).toBe(false); + + // source: 'provider_caveats' -> uses PostgreSQL reader, never calls smuggled property + const caveatsRes = await callMcpTool(server, 3, 'read_knowledge', { + source: 'provider_caveats', + }); + expect(caveatsRes.envelope.isError).toBeUndefined(); + expect(caveatsRes.parsed?.rows[0]?.id).toBe('caveat-eodhd-01'); + expect(smuggledCaveatsCalled).toBe(false); + expect(executor.calls).toHaveLength(2); + }); + + test('wires event_study calendar resolution through shared executor and injected sessionDates and records trial under principalId', async () => { + const fixture = buildEventStudyFixture(); + const { options, executor, sessionDateCalls } = buildValidOptions({ fixture }); + const server = createPostgresResearchCopilotServer({ + ...options, + earlyCloses: { XNYS: { [fixture.firstDate]: 780 } }, + }); + + // Pass `to` past vaultCutoffDate to verify Vault clamping reaches sessionDates. + const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; + const res = await callMcpTool(server, 1, 'event_study', { + listingIds: [...fixture.listingIds], + from: fixture.firstDate, + to: postCutoffTo, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + preDays: 2, + postDays: 3, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + benchmark: 'equal_weight', + }); + + expect(res.envelope.isError).toBeUndefined(); + expect(res.parsed?.status).toBe('ok'); + + // Listing-calendar query ran through the shared executor with bound listing IDs + const calendarCalls = executor.calls.filter(c => + c.text.includes('e.calendar_code AS calendar_code') + ); + expect(calendarCalls).toHaveLength(1); + expect(calendarCalls[0]?.params).toEqual([[...fixture.listingIds]]); + + // Injected sessionDates received XNYS and a Vault-clamped date range (< vaultCutoffDate) + expect(sessionDateCalls).toHaveLength(1); + expect(sessionDateCalls[0]?.calendarCode).toBe('XNYS'); + expect(sessionDateCalls[0]?.fromDate).toBe(fixture.firstDate); + expect(sessionDateCalls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); + + // Trial ledger append ran through the same shared executor under AGENT_PRINCIPAL + expect(executor.ledgerRows).toHaveLength(1); + expect(executor.ledgerRows[0]?.principal_id).toBe(AGENT_PRINCIPAL); + expect(executor.ledgerRows[0]?.stage).toBe('event_study'); + expect(executor.ledgerRows[0]!.sample_end < fixture.vaultCutoffDate).toBe(true); + }); + + describe('fail-closed option validation', () => { + const invalidCases: readonly { + readonly label: string; + readonly field: string; + readonly mutate: (valid: PostgresResearchCopilotServerOptions) => unknown; + }[] = [ + { label: 'options is undefined', field: 'options', mutate: () => undefined }, + { label: 'options is null', field: 'options', mutate: () => null }, + { label: 'options is primitive', field: 'options', mutate: () => 'invalid' }, + { + label: 'executor is undefined', + field: 'executor', + mutate: valid => ({ ...valid, executor: undefined }), + }, + { + label: 'executor is null', + field: 'executor', + mutate: valid => ({ ...valid, executor: null }), + }, + { + label: 'executor missing query', + field: 'executor', + mutate: valid => ({ ...valid, executor: {} }), + }, + { + label: 'executor.query is not callable', + field: 'executor', + mutate: valid => ({ ...valid, executor: { query: 'not-a-function' } }), + }, + { + label: 'vaultContext is null', + field: 'vaultContext', + mutate: valid => ({ ...valid, vaultContext: null }), + }, + { + label: 'listLibraryCards is undefined', + field: 'listLibraryCards', + mutate: valid => ({ ...valid, listLibraryCards: undefined }), + }, + { + label: 'listLibraryCards is not callable', + field: 'listLibraryCards', + mutate: valid => ({ ...valid, listLibraryCards: {} }), + }, + { + label: 'sessionDates is undefined', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: undefined }), + }, + { + label: 'sessionDates is null', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: null }), + }, + { + label: 'sessionDates missing listSessionDates', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: {} }), + }, + { + label: 'sessionDates.listSessionDates is not callable', + field: 'sessionDates', + mutate: valid => ({ ...valid, sessionDates: { listSessionDates: 123 } }), + }, + { + label: 'newId is undefined', + field: 'newId', + mutate: valid => ({ ...valid, newId: undefined }), + }, + { + label: 'newId is not callable', + field: 'newId', + mutate: valid => ({ ...valid, newId: 'id-1' }), + }, + { + label: 'now is undefined', + field: 'now', + mutate: valid => ({ ...valid, now: undefined }), + }, + { + label: 'now is not callable', + field: 'now', + mutate: valid => ({ ...valid, now: FIXED_NOW_MS }), + }, + ]; + + for (const testCase of invalidCases) { + test(`throws an Error naming "${testCase.field}" when ${testCase.label}`, () => { + const { options, executor } = buildValidOptions(); + const badInput = testCase.mutate(options) as PostgresResearchCopilotServerOptions; + + expect(() => createPostgresResearchCopilotServer(badInput)).toThrow( + new RegExp(testCase.field) + ); + expect(executor.calls).toHaveLength(0); + }); + } + }); +});