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

@ -214,7 +214,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
### `event_study` Tool (Vault-Fenced)
- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`).
- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter capped at `EVENT_STUDY_MAX_SUBTYPES = 100` entries and `EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128` chars each) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`).
- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars.
- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`.

View file

@ -70,6 +70,12 @@ export const EVENT_STUDY_MAX_PRE_DAYS = 60;
/** Hard maximum post-event window length in trading sessions. */
export const EVENT_STUDY_MAX_POST_DAYS = 60;
/** Hard maximum number of event subtype entries accepted in `event.subtypes`. */
export const EVENT_STUDY_MAX_SUBTYPES = 100;
/** Hard maximum character length of each event subtype string in `event.subtypes`. */
export const EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128;
const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const AGENT_PRINCIPAL_RE =
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
@ -101,10 +107,13 @@ const eventFilterSpecSchema = z
'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).'
),
subtypes: z
.array(z.string().min(1))
.array(z.string().min(1).max(EVENT_STUDY_MAX_SUBTYPE_LENGTH))
.min(1)
.max(EVENT_STUDY_MAX_SUBTYPES)
.optional()
.describe('Optional non-empty exact-match allow-list of event subtypes.'),
.describe(
`Optional non-empty exact-match allow-list of event subtypes (max ${EVENT_STUDY_MAX_SUBTYPES} entries, ${EVENT_STUDY_MAX_SUBTYPE_LENGTH} chars each).`
),
})
.strict()
.describe('Event kind and optional subtype filter specification.');
@ -421,29 +430,40 @@ function filterEligibleBars(
bars: readonly BarRecord[],
listingIdSet: ReadonlySet<number>,
fromMs: number,
fromSubMs: number,
toMs: number,
asOfMs: number,
vaultCutoffTs: number,
vaultCutoffDate: string
): BarRecord[] {
): { readonly bars: BarRecord[]; readonly prePanelVaultExcludedDates: number } {
const eligible: BarRecord[] = [];
const vaultExcludedDates = new Set<string>();
const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs;
for (let i = 0; i < bars.length; i += 1) {
const row = bars[i];
if (typeof row !== 'object' || row === null) {
eligible.push(row as unknown as BarRecord);
continue;
}
if (isValidEpochMs(row.ts)) {
if (
row.ts < fromMs ||
row.ts > toMs ||
row.ts > asOfMs ||
row.ts >= vaultCutoffTs ||
utcDateOf(row.ts) >= vaultCutoffDate
) {
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
continue;
}
const tsValid = isValidEpochMs(row.ts);
const tsDate = tsValid ? utcDateOf(row.ts) : null;
const tsInVault = tsValid && (row.ts >= vaultCutoffTs || (tsDate as string) >= vaultCutoffDate);
if (tsInVault) {
vaultExcludedDates.add(tsDate as string);
continue;
}
if (tsValid) {
if (row.ts < minTsMs || row.ts > toMs || row.ts > asOfMs) {
continue;
}
}
if (isValidEpochMs(row.knownAt)) {
if (
row.knownAt > asOfMs ||
@ -453,12 +473,14 @@ function filterEligibleBars(
continue;
}
}
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
continue;
}
eligible.push(row);
}
return eligible;
return {
bars: eligible,
prePanelVaultExcludedDates: vaultExcludedDates.size,
};
}
function filterEligibleEventsTable(params: {
@ -467,6 +489,7 @@ function filterEligibleEventsTable(params: {
readonly kindSet: ReadonlySet<string>;
readonly subtypeSet: ReadonlySet<string> | null;
readonly fromMs: number;
readonly fromSubMs: number;
readonly toMs: number;
readonly asOfMs: number;
readonly vaultCutoffTs: number;
@ -478,6 +501,7 @@ function filterEligibleEventsTable(params: {
kindSet,
subtypeSet,
fromMs,
fromSubMs,
toMs,
asOfMs,
vaultCutoffTs,
@ -495,6 +519,11 @@ function filterEligibleEventsTable(params: {
const eligibleRows: TableRow[] = [];
let prePanelVaultExcludedEvents = 0;
// TableRow timestamps carry integer epoch-ms precision. When the effective start
// has non-zero microseconds (fromSubMs > 0), any row stamped at `fromMs` is either
// strictly earlier (e.g. `.123Z < .123456Z`) or ambiguous at the boundary ms, so
// require `ts >= fromMs + 1` conservatively.
const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs;
for (let i = 0; i < table.rows.length; i += 1) {
const row = table.rows[i];
@ -541,7 +570,7 @@ function filterEligibleEventsTable(params: {
}
if (isValidEpochMs(ts)) {
if (ts < fromMs || ts > toMs) {
if (ts < minTsMs || ts > toMs) {
continue;
}
} else {
@ -837,10 +866,11 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt
const kindSet = new Set<string>(canonicalKinds);
const subtypeSet = canonicalSubtypes !== undefined ? new Set<string>(canonicalSubtypes) : null;
const eligibleBars = filterEligibleBars(
const { bars: eligibleBars, prePanelVaultExcludedDates } = filterEligibleBars(
rawBars,
listingIdSet,
fenced.fromMs,
fenced.fromSubMs,
fenced.toMs,
fenced.asOfMs,
vaultCutoffTs,
@ -854,6 +884,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt
kindSet,
subtypeSet,
fromMs: fenced.fromMs,
fromSubMs: fenced.fromSubMs,
toMs: fenced.toMs,
asOfMs: fenced.asOfMs,
vaultCutoffTs,
@ -877,6 +908,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt
if (fromDate > calendarToDate) {
const panelDiagnostics: EventPanelDiagnostics = {
...ZERO_EVENT_PANEL_DIAGNOSTICS,
vaultExcludedDates: prePanelVaultExcludedDates,
vaultExcludedEvents: prePanelVaultExcludedEvents,
droppedUnknownListing: events.length,
};
@ -918,6 +950,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt
const combinedPanelDiagnostics: EventPanelDiagnostics = {
...built.diagnostics,
vaultExcludedDates: prePanelVaultExcludedDates + built.diagnostics.vaultExcludedDates,
vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents,
};

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 },