T-133: M2.1c — MCP copilot event_study tool: vault-fenced event study (bars + events → buildEventStudyInput → runEventStudy + trial ledger) in libs/research/src/mcp/tools/

This commit is contained in:
Studio 2026-12-01 00:50:04 -05:00
parent f9ac7024d3
commit 5a36dc8aa6
4 changed files with 245 additions and 19 deletions

View file

@ -434,6 +434,7 @@ describe('MCP event_study QA edge cases', () => {
expect(res.payload?.status).toBe('ok');
expect(res.payload?.vaultExcludedEvents).toBe(2);
expect(res.payload?.panelDiagnostics.vaultExcludedDates).toBe(2);
expect(res.payload?.eventCount).toBe(6);
expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true);
@ -655,4 +656,164 @@ describe('MCP event_study QA edge cases', () => {
expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.');
expect(malformedLedger.insertCalls).toBe(0);
});
test('microsecond-precision from rejects leaked boundary-millisecond event and matches clean run', async () => {
const dates = makeBusinessDates('2023-07-03', 24);
const vaultCutoffDate = dates[23]!;
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
const listingIds = [401, 402, 403, 404, 405, 406];
const bars: BarRecord[] = [];
for (let l = 0; l < listingIds.length; l += 1) {
const id = listingIds[l]!;
let price = 40 + l * 2;
for (let t = 0; t < 23; t += 1) {
// Distinct per-listing returns on dates[3] so admitting listingIds[1] at .123Z
// measurably shifts eventCount, eventsUsed, CAR, and ledger daily_series.
const ret =
t === 3
? l === 1
? 0.25
: 0.05
: t === 9
? 0.03 + l * 0.004
: t === 15
? -0.02 + l * 0.003
: 0.002;
price = Number((price * (1 + ret)).toFixed(6));
const ts = utcMs(dates[t]!, 21);
bars.push({
listingId: id,
ts,
open: price,
high: price,
low: price,
close: price,
volume: 10_000,
knownAt: ts,
});
}
}
// Researcher sets microsecond-precision start on half-day dates[2] (18:00 UTC close, 21:00 UTC bar stamp):
// bars from dates[2]..dates[22] enter the panel, so dates[3] (session index 1) has finite close-to-close returns.
// A leaked filing at 19:00:00.123Z (< .123456Z) would anchor to dates[3] and shift CAR/daily_series if admitted.
// A valid filing at 19:00:00.124Z (> .123456Z) must be admitted and anchored to dates[3].
const microFromIso = `${dates[2]}T19:00:00.123456Z`;
const leakedBoundaryMs = Date.parse(`${dates[2]}T19:00:00.123Z`);
const admittedNextMs = Date.parse(`${dates[2]}T19:00:00.124Z`);
const validRows: TableRow[] = [
// Admitted event at fromMs + 1 (.124Z) -> anchors to dates[3] (after dates[2] 18:00 UTC half-day close)
{
listing_id: listingIds[0]!,
ts: admittedNextMs,
known_at: admittedNextMs,
known_at_source: 'exact',
kind: 'filing',
subtype: '8-K',
payload_json: '{}',
},
// 3 events on dates[9]
...listingIds.slice(0, 3).map(id => ({
listing_id: id,
ts: utcMs(dates[9]!, 14),
known_at: utcMs(dates[9]!, 14),
known_at_source: 'exact',
kind: 'filing' as EventKind,
subtype: '8-K',
payload_json: '{}',
})),
// 3 events on dates[15]
...listingIds.slice(3, 6).map(id => ({
listing_id: id,
ts: utcMs(dates[15]!, 14),
known_at: utcMs(dates[15]!, 14),
known_at_source: 'exact',
kind: 'filing' as EventKind,
subtype: '8-K',
payload_json: '{}',
})),
];
// Leaked out-of-window filing at .123Z (strictly before .123456Z) on listingIds[1] (+25% on dates[3]).
const leakedRow: TableRow = {
listing_id: listingIds[1]!,
ts: leakedBoundaryMs,
known_at: leakedBoundaryMs,
known_at_source: 'exact',
kind: 'filing',
subtype: '8-K',
payload_json: '{}',
};
const resolveExchangeCalendars = async (
q: EventStudyExchangeCalendarQuery
): Promise<EventStudyExchangeCalendars> => {
const sessions = dates
.filter(d => d >= q.fromDate && d <= q.toDate)
.map(date => ({
date,
closeTs: utcMs(date, date === dates[2] ? 18 : 21),
}));
const listingCalendarId = new Map<number, string>();
for (const id of q.listingIds) {
listingCalendarId.set(id, 'XNYS');
}
return { calendars: new Map([['XNYS', sessions]]), listingCalendarId };
};
const runWithRows = async (rows: readonly TableRow[]) => {
const store = createPassThroughStore({
bars,
eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...rows] },
});
const ledger = createFakeLedger();
const server = createMcpServer({
name: 'research-mcp',
version: '1.0.0',
tools: [
createEventStudyTool({
store,
ledger: ledger.executor,
vaultContext: { vaultCutoffTs },
principalId: AGENT_PRINCIPAL,
resolveExchangeCalendars,
}),
],
});
const res = await invoke(server, {
listingIds,
from: microFromIso,
to: dates[22]!,
event: { kinds: ['filing'] },
preDays: 0,
postDays: 1,
benchmark: 'none',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
});
return { res, ledger };
};
const leaky = await runWithRows([leakedRow, ...validRows]);
const clean = await runWithRows(validRows);
expect(leaky.res.isError).toBeUndefined();
expect(clean.res.isError).toBeUndefined();
expect(leaky.res.payload?.status).toBe('ok');
expect(clean.res.payload?.status).toBe('ok');
if (leaky.res.payload?.status !== 'ok' || clean.res.payload?.status !== 'ok') {
throw new Error('Expected ok payloads');
}
// Leaked .123Z row must be excluded; admitted .124Z row + 6 later events = 7 anchored & used events.
expect(leaky.res.payload.eventCount).toBe(7);
expect(clean.res.payload.eventCount).toBe(7);
expect(leaky.res.payload.study.diagnostics.eventsUsed).toBe(7);
expect(clean.res.payload.study.diagnostics.eventsUsed).toBe(7);
expect(leaky.res.payload.study.offsets).toEqual(clean.res.payload.study.offsets);
expect(leaky.res.payload.trial.expressionHash).toBe(clean.res.payload.trial.expressionHash);
expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series);
});
});

View file

@ -28,6 +28,8 @@ import {
EVENT_STUDY_MAX_LISTING_IDS,
EVENT_STUDY_MAX_POST_DAYS,
EVENT_STUDY_MAX_PRE_DAYS,
EVENT_STUDY_MAX_SUBTYPES,
EVENT_STUDY_MAX_SUBTYPE_LENGTH,
type EventStudyExchangeCalendarQuery,
type EventStudyResultPayload,
createEventStudyTool,
@ -472,6 +474,8 @@ describe('MCP event_study tool', () => {
expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500);
expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60);
expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60);
expect(EVENT_STUDY_MAX_SUBTYPES).toBe(100);
expect(EVENT_STUDY_MAX_SUBTYPE_LENGTH).toBe(128);
const raw = await server.handleMessage(
JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} })
@ -501,8 +505,20 @@ describe('MCP event_study tool', () => {
expect(props.vaultCutoffDate).toBeUndefined();
expect(props.vault_evaluation_only).toBeUndefined();
const eventSchema = props.event as { additionalProperties?: boolean };
const eventSchema = props.event as {
additionalProperties?: boolean;
properties?: {
subtypes?: {
maxItems?: number;
items?: { maxLength?: number };
};
};
};
expect(eventSchema.additionalProperties).toBe(false);
expect(eventSchema.properties?.subtypes?.maxItems).toBe(EVENT_STUDY_MAX_SUBTYPES);
expect(eventSchema.properties?.subtypes?.items?.maxLength).toBe(
EVENT_STUDY_MAX_SUBTYPE_LENGTH
);
});
test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => {
@ -843,6 +859,7 @@ describe('MCP event_study tool', () => {
expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs);
expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs);
expect(leakyPayload.vaultExcludedEvents).toBe(2);
expect(leakyPayload.panelDiagnostics.vaultExcludedDates).toBe(1);
expect(leakyPayload.eventCount).toBe(12);
// Verify no store call received a bound >= vaultCutoffTs
@ -883,6 +900,7 @@ describe('MCP event_study tool', () => {
});
const cleanPayload = cleanRes.payload as Extract<EventStudyResultPayload, { status: 'ok' }>;
expect(cleanPayload.panelDiagnostics.vaultExcludedDates).toBe(0);
expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets);
expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash);
expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series);
@ -984,6 +1002,20 @@ describe('MCP event_study tool', () => {
{ ...validBase, event: { kinds: [] } },
{ ...validBase, event: { kinds: ['unknown_kind'] } },
{ ...validBase, event: { kinds: ['filing'], subtypes: [] } },
{
...validBase,
event: {
kinds: ['filing'],
subtypes: Array.from({ length: EVENT_STUDY_MAX_SUBTYPES + 1 }, (_, i) => `SUB_${i}`),
},
},
{
...validBase,
event: {
kinds: ['filing'],
subtypes: ['x'.repeat(EVENT_STUDY_MAX_SUBTYPE_LENGTH + 1)],
},
},
{ ...validBase, preDays: -1 },
{ ...validBase, preDays: 61 },
{ ...validBase, preDays: 1.5 },