stock-bot/libs/research/test/mcp-copilot-server.test.ts

1354 lines
45 KiB
TypeScript

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<Row = Record<string, unknown>>(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 fundamentalsRows: readonly TableRow[];
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 fundamentalsRows: TableRow[] = [];
const eventRows: TableRow[] = [];
const fundamentalReleaseIndices = [0, 22, 44, 64];
for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) {
const t = fundamentalReleaseIndices[rIdx]!;
const relDate = allDates[t]!;
const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close
for (let l = 0; l < listingCount; l += 1) {
const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15;
const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25;
fundamentalsRows.push({
listing_id: listingIds[l]!,
effective_known_at: effectiveKnownAt,
known_at_source: 'sec_edgar_filing',
has_estimated_lag: false,
period_end: relDate,
fiscal_period: `Q${(rIdx % 4) + 1}`,
currency: 'USD',
period_known_at: effectiveKnownAt,
revenue,
net_income: Number((revenue * 0.14).toFixed(2)),
operating_cash_flow: Number((revenue * 0.19).toFixed(2)),
total_assets: Number((revenue * 3.8).toFixed(2)),
total_equity: Number((revenue * 1.7).toFixed(2)),
shares_outstanding: 10_000_000,
ttm_revenue: ttmRevenue,
ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)),
ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)),
ttm_period_end: relDate,
ttm_currency: 'USD',
ttm_has_estimated_lag: false,
});
}
}
const eventDayIndices = [12, 20, 28, 38, 48, 58];
const eventSet = new Set<string>();
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<number, number[]>();
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<number, string>();
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,
},
fundamentalsRows,
eventsTable: {
columns: [...EVENTS_COLUMNS],
rows: eventRows,
},
symbols,
exchangeCalendars: {
calendars: { XNYS: xnysSessions },
listingCalendarId,
},
};
}
interface FakeMarketDataStoreHandle {
readonly store: MarketDataStore;
readonly getBarsCalls: () => number;
readonly getShortsCalls: () => number;
readonly getFundamentalsCalls: () => 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 fundamentalsCalls = 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<BarBatch> {
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<Table> {
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<Table> {
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(q): Promise<Table> {
fundamentalsCalls += 1;
const idSet = new Set(q.listingIds);
const asOfMs = parseBoundMs(q.asOf, true);
const allowEstimatedLag = q.allowEstimatedLag ?? false;
const latestByListing = new Map<number, TableRow>();
for (const row of fixture.fundamentalsRows) {
const listingId = row.listing_id as number;
const knownAt = row.effective_known_at as number;
if (!idSet.has(listingId) || knownAt > asOfMs) {
continue;
}
const prev = latestByListing.get(listingId);
if (prev === undefined || knownAt > (prev.effective_known_at as number)) {
latestByListing.set(listingId, row);
}
}
const rows: TableRow[] = [];
for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) {
const row = latestByListing.get(lid)!;
if (!allowEstimatedLag && row.has_estimated_lag === true) {
continue;
}
rows.push(row);
}
if (leaky) {
rows.push({
listing_id: fixture.listingIds[0]!,
effective_known_at: fixture.vaultCutoffTs,
known_at_source: 'sec_edgar_filing',
has_estimated_lag: false,
period_end: fixture.vaultCutoffDate,
fiscal_period: 'Q4',
currency: 'USD',
period_known_at: fixture.vaultCutoffTs,
revenue: 999_999,
ttm_revenue: 999_999,
});
}
return {
columns: [
'listing_id',
'effective_known_at',
'known_at_source',
'has_estimated_lag',
'period_end',
'fiscal_period',
'currency',
'period_known_at',
...q.fields,
],
rows,
};
},
async macroAsOf() {
throw new MarketDataStoreNotImplementedError('macroAsOf');
},
async fx() {
throw new MarketDataStoreNotImplementedError('fx');
},
};
return {
store,
getBarsCalls: () => barsCalls,
getShortsCalls: () => shortsCalls,
getFundamentalsCalls: () => fundamentalsCalls,
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<string, FiledFindingRecord>();
const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] =
[];
const writePort: FindingWritePort = {
async appendFinding(
record: FiledFindingRecord,
idempotencyKey?: string
): Promise<AppendFindingResult> {
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<typeof createFakeTrialLedger>;
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<T>(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 (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => {
const fixture = buildCopilotStudyFixture();
const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture);
const server = createResearchCopilotMcpServer(serverOptions);
const sink = createMemoryOutput();
let shortsTrialRef = '';
let fundamentalsTrialRef = '';
async function* requestStream(): AsyncGenerator<string> {
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: 'analyze_signal',
arguments: {
listingIds: [...fixture.listingIds],
from: fixture.firstDate,
to: fixture.lastPreCutoffDate,
signal: { source: 'fundamentals', field: 'ttm_revenue' },
horizonSessions: 5,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
adjustment: 'raw',
},
},
})}\n`;
yield `${JSON.stringify({
jsonrpc: '2.0',
id: 7,
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: 8,
method: 'tools/call',
params: {
name: 'read_knowledge',
arguments: { source: 'all', query: 'sharpe', limit: 5 },
},
})}\n`;
// Decode both earlier analyze_signal responses written by runStdioServer before
// constructing the file_finding call so both trialRefs are dynamically linked.
expect(sink.lines.length).toBeGreaterThanOrEqual(6);
const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope;
const shortsPayload = decodeToolJson<AnalyzeSignalResultPayload>(shortsResp);
expect(shortsPayload.status).toBe('ok');
if (shortsPayload.status !== 'ok') {
throw new Error('Expected shorts analyze_signal status to be ok.');
}
shortsTrialRef = String(shortsPayload.trial.trialId);
const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope;
const fundamentalsPayload = decodeToolJson<AnalyzeSignalResultPayload>(fundamentalsResp);
expect(fundamentalsPayload.status).toBe('ok');
if (fundamentalsPayload.status !== 'ok') {
throw new Error('Expected fundamentals analyze_signal status to be ok.');
}
fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId);
yield `${JSON.stringify({
jsonrpc: '2.0',
id: 9,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Short-interest and fundamentals signal studies 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: [shortsTrialRef, fundamentalsTrialRef],
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(9);
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, 9]);
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<string, unknown> };
};
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<SearchSymbolsResultPayload>(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<QueryDataResultPayload>(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 (shorts)
const shortsSignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(responses[4]!);
expect(shortsSignalPayload.status).toBe('ok');
if (shortsSignalPayload.status !== 'ok') {
throw new Error('Expected shorts analyze_signal status to be ok.');
}
expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' });
expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef);
// 6. analyze_signal (fundamentals)
const fundamentalsSignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(responses[5]!);
expect(fundamentalsSignalPayload.status).toBe('ok');
if (fundamentalsSignalPayload.status !== 'ok') {
throw new Error('Expected fundamentals analyze_signal status to be ok.');
}
expect(fundamentalsSignalPayload.signal).toEqual({
source: 'fundamentals',
field: 'ttm_revenue',
allowEstimatedLag: false,
});
expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef);
expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe(
shortsSignalPayload.trial.expressionHash
);
expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0);
// 7. event_study
const eventPayload = decodeToolJson<EventStudyResultPayload>(responses[6]!);
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);
// 8. read_knowledge
const knowledgePayload = decodeToolJson<ReadKnowledgeResultPayload>(responses[7]!);
expect(knowledgePayload.rowCount).toBe(1);
expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01');
// 9. file_finding
const findingPayload = decodeToolJson<FileFindingResultPayload>(responses[8]!);
expect(findingPayload).toEqual({
id: FIXED_FINDING_ID,
createdAt: FIXED_NOW_ISO,
created: true,
});
// Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL.
expect(ledger.rows).toHaveLength(3);
expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']);
expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true);
expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId));
expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId));
expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId));
expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash);
// Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials.
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: [shortsTrialRef, fundamentalsTrialRef],
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<QueryDataResultPayload>(
JSON.parse((await cleanServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope
);
const leakyQueryPayload = decodeToolJson<QueryDataResultPayload>(
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<AnalyzeSignalResultPayload>(
JSON.parse((await cleanServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope
);
const leakySignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(
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<string> {
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();
}
});
});