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:
parent
e70b4b1a7d
commit
f9ac7024d3
5 changed files with 3084 additions and 1 deletions
|
|
@ -212,8 +212,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`).
|
||||
- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class.
|
||||
|
||||
### `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'`).
|
||||
- **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`.
|
||||
|
||||
### Remaining M2 MCP Items (Later Tasks)
|
||||
|
||||
- Additional research tools: `search_symbols`, `analyze_signal`, `event_study`, `file_finding`, and `read_knowledge`.
|
||||
- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`.
|
||||
- SSE/HTTP transport wrapper in `apps/stock/web-api`.
|
||||
- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters.
|
||||
|
|
|
|||
|
|
@ -2,4 +2,5 @@ export * from './protocol';
|
|||
export * from './server';
|
||||
export * from './stdio';
|
||||
export * from './tools/analyze-signal';
|
||||
export * from './tools/event-study';
|
||||
export * from './tools/query-data';
|
||||
|
|
|
|||
999
libs/research/src/mcp/tools/event-study.ts
Normal file
999
libs/research/src/mcp/tools/event-study.ts
Normal file
|
|
@ -0,0 +1,999 @@
|
|||
import type {
|
||||
EventStudyDiagnostics,
|
||||
EventStudyRecencyResult,
|
||||
EventStudyResult,
|
||||
NeweyWestResult,
|
||||
} from '@stock-bot/calculations';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
type EventPanelDiagnostics,
|
||||
EventPanelError,
|
||||
type EventPanelErrorCode,
|
||||
type EventStudyBenchmarkMode,
|
||||
type EventStudyExchangeCalendars,
|
||||
buildEventStudyInput,
|
||||
eventsTableToEventRows,
|
||||
} from '../../event-panel';
|
||||
import {
|
||||
type BarRecord,
|
||||
type EventKind,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
type TableRow,
|
||||
type VaultFenceContext,
|
||||
} from '../../market-data-store';
|
||||
import { EVENT_KINDS } from '../../market-data-store-duckdb';
|
||||
import { collectBars } from '../../signal-panel';
|
||||
import {
|
||||
type RunEventStudyInsufficientDataReason,
|
||||
SignalStudyError,
|
||||
type SignalStudyErrorCode,
|
||||
type SignalStudyExpression,
|
||||
type StudyTrialSummary,
|
||||
runEventStudy,
|
||||
} from '../../signal-study';
|
||||
import {
|
||||
type ClusterDeflatedSharpeResult,
|
||||
HORIZON_BUCKETS,
|
||||
type HorizonBucket,
|
||||
TrialLedgerError,
|
||||
type TrialLedgerErrorCode,
|
||||
type TrialLedgerExecutor,
|
||||
UNIVERSE_MARKETS,
|
||||
type UniverseMarket,
|
||||
} from '../../trial-ledger';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
import { type McpToolEntry, defineMcpTool } from '../server';
|
||||
import {
|
||||
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||||
MAX_ECMASCRIPT_EPOCH_MS,
|
||||
MCP_MAX_LISTING_IDS,
|
||||
MS_PER_DAY,
|
||||
createListingIdsFieldSchema,
|
||||
createUniverseFieldSchema,
|
||||
fenceVaultQueryBounds,
|
||||
formatMappedStoreError,
|
||||
hasExclusiveListingSelector,
|
||||
isValidUtcBoundString,
|
||||
resolvePreStartUniverseDate,
|
||||
utcDateOf,
|
||||
validateVaultCutoffTs,
|
||||
} from './vault-fenced-input';
|
||||
|
||||
/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */
|
||||
export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
|
||||
|
||||
/** Hard maximum pre-event window length in trading sessions. */
|
||||
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;
|
||||
|
||||
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}$/;
|
||||
const UTC_BOUND_ERROR_MESSAGE =
|
||||
'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.';
|
||||
const EVENT_KIND_SET: ReadonlySet<string> = new Set<string>(EVENT_KINDS);
|
||||
|
||||
function canonicalDailyHorizonBucket(postDays: number): HorizonBucket {
|
||||
return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus';
|
||||
}
|
||||
|
||||
function isValidEpochMs(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isFinite(value) &&
|
||||
Number.isSafeInteger(value) &&
|
||||
Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS
|
||||
);
|
||||
}
|
||||
|
||||
const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE);
|
||||
|
||||
const eventFilterSpecSchema = z
|
||||
.object({
|
||||
kinds: z
|
||||
.array(z.enum(EVENT_KINDS))
|
||||
.min(1)
|
||||
.describe(
|
||||
'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).'
|
||||
),
|
||||
subtypes: z
|
||||
.array(z.string().min(1))
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Optional non-empty exact-match allow-list of event subtypes.'),
|
||||
})
|
||||
.strict()
|
||||
.describe('Event kind and optional subtype filter specification.');
|
||||
|
||||
/**
|
||||
* Strict Zod input schema for the `event_study` MCP tool.
|
||||
*
|
||||
* Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and
|
||||
* `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them
|
||||
* or any other unknown top-level or nested key.
|
||||
*/
|
||||
export const eventStudyInputSchema = z
|
||||
.object({
|
||||
listingIds: createListingIdsFieldSchema(
|
||||
'Explicit INT32 listing IDs to study (mutually exclusive with universe).'
|
||||
),
|
||||
universe: createUniverseFieldSchema(
|
||||
'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'
|
||||
),
|
||||
from: utcBoundStringSchema.describe(
|
||||
'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'
|
||||
),
|
||||
to: utcBoundStringSchema.describe(
|
||||
'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'
|
||||
),
|
||||
asOf: utcBoundStringSchema
|
||||
.optional()
|
||||
.describe(
|
||||
'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'
|
||||
),
|
||||
event: eventFilterSpecSchema,
|
||||
preDays: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(EVENT_STUDY_MAX_PRE_DAYS)
|
||||
.describe(
|
||||
`Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).`
|
||||
),
|
||||
postDays: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(EVENT_STUDY_MAX_POST_DAYS)
|
||||
.describe(
|
||||
`Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).`
|
||||
),
|
||||
benchmark: z
|
||||
.enum(['equal_weight', 'none'])
|
||||
.default('equal_weight')
|
||||
.describe(
|
||||
'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).'
|
||||
),
|
||||
adjustment: z
|
||||
.enum(['raw', 'split', 'total'])
|
||||
.default('raw')
|
||||
.describe('Bar price adjustment mode (default raw).'),
|
||||
universeMarket: z
|
||||
.enum(UNIVERSE_MARKETS)
|
||||
.describe('Relatedness-cluster market bucket recorded in trial_ledger.'),
|
||||
horizonBucket: z
|
||||
.enum(HORIZON_BUCKETS)
|
||||
.describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'),
|
||||
campaignId: z
|
||||
.string()
|
||||
.regex(LEDGER_UUID_RE, 'Expected a UUID string.')
|
||||
.optional()
|
||||
.describe('Optional research campaign UUID recorded in trial_ledger.'),
|
||||
hypothesisId: z
|
||||
.string()
|
||||
.regex(LEDGER_UUID_RE, 'Expected a UUID string.')
|
||||
.optional()
|
||||
.describe('Optional research hypothesis UUID recorded in trial_ledger.'),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, ctx) => {
|
||||
if (!hasExclusiveListingSelector(data)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||||
});
|
||||
}
|
||||
|
||||
const expectedBucket = canonicalDailyHorizonBucket(data.postDays);
|
||||
if (data.horizonBucket !== expectedBucket) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['horizonBucket'],
|
||||
message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`,
|
||||
});
|
||||
}
|
||||
|
||||
if (data.universe !== undefined && data.universeMarket !== data.universe) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['universeMarket'],
|
||||
message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type EventStudyToolInput = z.infer<typeof eventStudyInputSchema>;
|
||||
|
||||
/** Query passed to the server-injected exchange-calendar resolver. */
|
||||
export interface EventStudyExchangeCalendarQuery {
|
||||
readonly listingIds: readonly number[];
|
||||
readonly fromDate: string;
|
||||
readonly toDate: string;
|
||||
}
|
||||
|
||||
/** Server-injected exchange-calendar resolver returning actual session close calendars. */
|
||||
export type EventStudyExchangeCalendarResolver = (
|
||||
query: EventStudyExchangeCalendarQuery
|
||||
) => Promise<EventStudyExchangeCalendars> | EventStudyExchangeCalendars;
|
||||
|
||||
/** Server-side injected configuration for {@link createEventStudyTool}. */
|
||||
export interface EventStudyToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
readonly ledger: TrialLedgerExecutor;
|
||||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||||
readonly principalId: string;
|
||||
readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver;
|
||||
}
|
||||
|
||||
/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */
|
||||
export interface EventStudyOffsetSummary {
|
||||
readonly offset: number;
|
||||
readonly n: number;
|
||||
readonly aar: number;
|
||||
readonly caar: number;
|
||||
readonly caarFromZero: number | null;
|
||||
}
|
||||
|
||||
/** Bounded date-clustered CAR summary without raw per-date typed arrays. */
|
||||
export interface EventStudyClusteredSummary {
|
||||
readonly nDates: number;
|
||||
readonly carMean: number;
|
||||
readonly neweyWest: NeweyWestResult;
|
||||
}
|
||||
|
||||
/** Bounded summary projection of {@link EventStudyResult}. */
|
||||
export interface EventStudySummary {
|
||||
readonly preDays: number;
|
||||
readonly postDays: number;
|
||||
readonly hasBenchmark: boolean;
|
||||
readonly offsets: readonly EventStudyOffsetSummary[];
|
||||
readonly clustered: EventStudyClusteredSummary | null;
|
||||
readonly recency: EventStudyRecencyResult | null;
|
||||
readonly diagnostics: EventStudyDiagnostics;
|
||||
}
|
||||
|
||||
interface EventStudyResultBase {
|
||||
readonly scope: 'vault_fenced';
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly event: {
|
||||
readonly kinds: readonly EventKind[];
|
||||
readonly subtypes: readonly string[] | null;
|
||||
};
|
||||
readonly preDays: number;
|
||||
readonly postDays: number;
|
||||
readonly benchmark: EventStudyBenchmarkMode;
|
||||
readonly adjustment: 'raw' | 'split' | 'total';
|
||||
readonly universeMarket: UniverseMarket;
|
||||
readonly horizonBucket: HorizonBucket;
|
||||
readonly fromMs: number;
|
||||
readonly toMs: number;
|
||||
readonly asOfMs: number;
|
||||
readonly effectiveFrom: string;
|
||||
readonly effectiveTo: string;
|
||||
readonly effectiveAsOf: string;
|
||||
readonly clampedTo: boolean;
|
||||
readonly clampedAsOf: boolean;
|
||||
readonly listingCount: number;
|
||||
readonly eventCount: number;
|
||||
readonly vaultExcludedEvents: number;
|
||||
readonly panelDiagnostics: EventPanelDiagnostics;
|
||||
readonly study: EventStudySummary;
|
||||
}
|
||||
|
||||
/** Structured JSON payload serialized into the `event_study` MCP text result. */
|
||||
export type EventStudyResultPayload =
|
||||
| (EventStudyResultBase & {
|
||||
readonly status: 'ok';
|
||||
readonly trial: StudyTrialSummary;
|
||||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
})
|
||||
| (EventStudyResultBase & {
|
||||
readonly status: 'insufficient_data';
|
||||
readonly reason: RunEventStudyInsufficientDataReason;
|
||||
});
|
||||
|
||||
class ExchangeCalendarResolverError extends Error {
|
||||
override readonly name = 'ExchangeCalendarResolverError';
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(cause: unknown) {
|
||||
super('Exchange calendar resolution failed.', { cause });
|
||||
this.cause = cause;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = {
|
||||
vaultExcludedDates: 0,
|
||||
vaultExcludedEvents: 0,
|
||||
droppedUnknownListing: 0,
|
||||
droppedAfterLastSession: 0,
|
||||
droppedMissingCalendarSession: 0,
|
||||
duplicateEvents: 0,
|
||||
duplicateBars: 0,
|
||||
nonPositiveCloseReturns: 0,
|
||||
};
|
||||
|
||||
const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = {
|
||||
eventsIn: 0,
|
||||
eventsUsed: 0,
|
||||
droppedUnknownEntity: 0,
|
||||
droppedWindowOutOfRange: 0,
|
||||
droppedMissingReturns: 0,
|
||||
duplicateEventsCollapsed: 0,
|
||||
};
|
||||
|
||||
const EVENT_PANEL_ERROR_MESSAGES: Readonly<Record<EventPanelErrorCode, string>> = {
|
||||
invalid_input: 'Invalid event panel input.',
|
||||
invalid_date: 'Invalid event panel date.',
|
||||
invalid_bar: 'Market bar data failed event panel validation.',
|
||||
invalid_event: 'Event table data failed event panel validation.',
|
||||
invalid_option: 'Invalid event panel option.',
|
||||
duplicate_bar: 'Conflicting duplicate daily bars detected.',
|
||||
};
|
||||
|
||||
const SIGNAL_STUDY_ERROR_MESSAGES: Readonly<Record<SignalStudyErrorCode, string>> = {
|
||||
invalid_request: 'Invalid event study request.',
|
||||
empty_panel: 'Event study session grid is empty.',
|
||||
invalid_date: 'Invalid event study date.',
|
||||
unsorted_dates: 'Event study session dates are not strictly ascending.',
|
||||
duplicate_date: 'Duplicate date detected in event study session grid.',
|
||||
invalid_panel: 'Event study panel failed validation.',
|
||||
invalid_option: 'Invalid event study option.',
|
||||
dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.',
|
||||
};
|
||||
|
||||
const TRIAL_LEDGER_ERROR_MESSAGES: Readonly<Partial<Record<TrialLedgerErrorCode, string>>> = {
|
||||
VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.',
|
||||
INVALID_PRINCIPAL: 'Invalid trial ledger principal.',
|
||||
INVALID_UUID: 'Invalid trial ledger UUID.',
|
||||
INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.',
|
||||
INVALID_DATE: 'Invalid trial ledger date.',
|
||||
SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.',
|
||||
ZERO_VARIANCE_SERIES: 'Observation series has zero variance.',
|
||||
TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.',
|
||||
};
|
||||
|
||||
function sortAndDedupeListingIds(ids: readonly number[]): number[] {
|
||||
return [...new Set(ids)].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function sortAndDedupeStrings<T extends string>(items: readonly T[]): T[] {
|
||||
return [...new Set(items)].sort() as T[];
|
||||
}
|
||||
|
||||
function makeEmptyStudySummary(
|
||||
preDays: number,
|
||||
postDays: number,
|
||||
hasBenchmark: boolean
|
||||
): EventStudySummary {
|
||||
return {
|
||||
preDays,
|
||||
postDays,
|
||||
hasBenchmark,
|
||||
offsets: [],
|
||||
clustered: null,
|
||||
recency: null,
|
||||
diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS,
|
||||
};
|
||||
}
|
||||
|
||||
function projectStudySummary(study: EventStudyResult): EventStudySummary {
|
||||
if (study.status === 'insufficient_data') {
|
||||
return {
|
||||
preDays: study.preDays,
|
||||
postDays: study.postDays,
|
||||
hasBenchmark: study.hasBenchmark,
|
||||
offsets: [],
|
||||
clustered: null,
|
||||
recency: null,
|
||||
diagnostics: study.diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
preDays: study.preDays,
|
||||
postDays: study.postDays,
|
||||
hasBenchmark: study.hasBenchmark,
|
||||
offsets: study.offsets.map(o => ({
|
||||
offset: o.offset,
|
||||
n: o.n,
|
||||
aar: o.aar,
|
||||
caar: o.caar,
|
||||
caarFromZero: o.caarFromZero,
|
||||
})),
|
||||
clustered: {
|
||||
nDates: study.clustered.nDates,
|
||||
carMean: study.clustered.carMean,
|
||||
neweyWest: study.clustered.neweyWest,
|
||||
},
|
||||
recency: study.recency,
|
||||
diagnostics: study.diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
function filterEligibleBars(
|
||||
bars: readonly BarRecord[],
|
||||
listingIdSet: ReadonlySet<number>,
|
||||
fromMs: number,
|
||||
toMs: number,
|
||||
asOfMs: number,
|
||||
vaultCutoffTs: number,
|
||||
vaultCutoffDate: string
|
||||
): BarRecord[] {
|
||||
const eligible: BarRecord[] = [];
|
||||
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
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (isValidEpochMs(row.knownAt)) {
|
||||
if (
|
||||
row.knownAt > asOfMs ||
|
||||
row.knownAt >= vaultCutoffTs ||
|
||||
utcDateOf(row.knownAt) >= vaultCutoffDate
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
|
||||
continue;
|
||||
}
|
||||
eligible.push(row);
|
||||
}
|
||||
return eligible;
|
||||
}
|
||||
|
||||
function filterEligibleEventsTable(params: {
|
||||
readonly table: Table;
|
||||
readonly listingIdSet: ReadonlySet<number>;
|
||||
readonly kindSet: ReadonlySet<string>;
|
||||
readonly subtypeSet: ReadonlySet<string> | null;
|
||||
readonly fromMs: number;
|
||||
readonly toMs: number;
|
||||
readonly asOfMs: number;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } {
|
||||
const {
|
||||
table,
|
||||
listingIdSet,
|
||||
kindSet,
|
||||
subtypeSet,
|
||||
fromMs,
|
||||
toMs,
|
||||
asOfMs,
|
||||
vaultCutoffTs,
|
||||
vaultCutoffDate,
|
||||
} = params;
|
||||
|
||||
if (
|
||||
typeof table !== 'object' ||
|
||||
table === null ||
|
||||
!Array.isArray(table.columns) ||
|
||||
!Array.isArray(table.rows)
|
||||
) {
|
||||
return { table, prePanelVaultExcludedEvents: 0 };
|
||||
}
|
||||
|
||||
const eligibleRows: TableRow[] = [];
|
||||
let prePanelVaultExcludedEvents = 0;
|
||||
|
||||
for (let i = 0; i < table.rows.length; i += 1) {
|
||||
const row = table.rows[i];
|
||||
if (typeof row !== 'object' || row === null || Array.isArray(row)) {
|
||||
eligibleRows.push(row as TableRow);
|
||||
continue;
|
||||
}
|
||||
|
||||
const listingId = row.listing_id;
|
||||
if (typeof listingId === 'number' && !listingIdSet.has(listingId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions.
|
||||
// Malformed kind/subtype values fall through so eventsTableToEventRows rejects them.
|
||||
const kind = row.kind;
|
||||
if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) {
|
||||
continue;
|
||||
}
|
||||
if (subtypeSet !== null) {
|
||||
const subtype = row.subtype;
|
||||
if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const knownAt = row.known_at;
|
||||
const knownAtInVault =
|
||||
isValidEpochMs(knownAt) &&
|
||||
(knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate);
|
||||
|
||||
const ts = row.ts;
|
||||
const tsInVault =
|
||||
isValidEpochMs(ts) &&
|
||||
(ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate);
|
||||
|
||||
if (knownAtInVault || tsInVault) {
|
||||
prePanelVaultExcludedEvents += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isValidEpochMs(knownAt) && knownAt > asOfMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isValidEpochMs(ts)) {
|
||||
if (ts < fromMs || ts > toMs) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
throw new EventPanelError(
|
||||
'invalid_event',
|
||||
`Invalid ts in events table row[${i}]: ${String(ts)}.`
|
||||
);
|
||||
}
|
||||
|
||||
eligibleRows.push(row);
|
||||
}
|
||||
|
||||
return {
|
||||
table: {
|
||||
columns: table.columns,
|
||||
rows: eligibleRows,
|
||||
},
|
||||
prePanelVaultExcludedEvents,
|
||||
};
|
||||
}
|
||||
|
||||
function buildCanonicalEventStudyExpression(params: {
|
||||
readonly input: EventStudyToolInput;
|
||||
readonly canonicalKinds: readonly EventKind[];
|
||||
readonly canonicalSubtypes: readonly string[] | undefined;
|
||||
readonly listingIds: readonly number[];
|
||||
readonly universeSnapshotDate: string | null;
|
||||
readonly effectiveFrom: string;
|
||||
readonly effectiveTo: string;
|
||||
readonly effectiveAsOf: string;
|
||||
}): SignalStudyExpression {
|
||||
const {
|
||||
input,
|
||||
canonicalKinds,
|
||||
canonicalSubtypes,
|
||||
listingIds,
|
||||
universeSnapshotDate,
|
||||
effectiveFrom,
|
||||
effectiveTo,
|
||||
effectiveAsOf,
|
||||
} = params;
|
||||
|
||||
return {
|
||||
expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`,
|
||||
params: {
|
||||
version: 1,
|
||||
kinds: canonicalKinds,
|
||||
subtypes: canonicalSubtypes ?? null,
|
||||
preDays: input.preDays,
|
||||
postDays: input.postDays,
|
||||
benchmark: input.benchmark,
|
||||
adjustment: input.adjustment,
|
||||
effectiveFrom,
|
||||
effectiveTo,
|
||||
effectiveAsOf,
|
||||
},
|
||||
universe:
|
||||
input.universe !== undefined
|
||||
? {
|
||||
kind: 'universe',
|
||||
ref: input.universe,
|
||||
snapshotDate: universeSnapshotDate,
|
||||
listingIds,
|
||||
}
|
||||
: {
|
||||
kind: 'listingIds',
|
||||
listingIds,
|
||||
},
|
||||
horizon: `${input.postDays}d`,
|
||||
};
|
||||
}
|
||||
|
||||
function formatMappedEventStudyError(err: unknown): McpToolCallResult {
|
||||
const storeMapped = formatMappedStoreError(err);
|
||||
if (storeMapped !== null) {
|
||||
return storeMapped;
|
||||
}
|
||||
|
||||
if (err instanceof ExchangeCalendarResolverError) {
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof EventPanelError) {
|
||||
const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code)
|
||||
? EVENT_PANEL_ERROR_MESSAGES[err.code]
|
||||
: 'Event panel construction failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `EventPanelError: ${detail}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof SignalStudyError) {
|
||||
const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code)
|
||||
? SIGNAL_STUDY_ERROR_MESSAGES[err.code]
|
||||
: 'Event study execution failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `SignalStudyError: ${detail}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof TrialLedgerError) {
|
||||
const detail =
|
||||
Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) &&
|
||||
TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined
|
||||
? TRIAL_LEDGER_ERROR_MESSAGES[err.code]
|
||||
: 'Trial ledger operation failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: 'Error: Tool execution failed.' }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: EventStudyToolOptions): number {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `options`: expected an EventStudyToolOptions object.',
|
||||
'options'
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.store !== 'object' ||
|
||||
options.store === null ||
|
||||
typeof options.store.bars !== 'function' ||
|
||||
typeof options.store.events !== 'function' ||
|
||||
typeof options.store.universe !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.',
|
||||
'store'
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.ledger !== 'object' ||
|
||||
options.ledger === null ||
|
||||
typeof options.ledger.query !== 'function'
|
||||
) {
|
||||
throw new SignalStudyError(
|
||||
'invalid_request',
|
||||
'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.'
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof options.resolveExchangeCalendars !== 'function') {
|
||||
throw new EventPanelError(
|
||||
'invalid_option',
|
||||
'Invalid `resolveExchangeCalendars`: expected a function.'
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof options.principalId !== 'string' ||
|
||||
(options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId))
|
||||
) {
|
||||
throw new TrialLedgerError(
|
||||
'INVALID_PRINCIPAL',
|
||||
`Invalid \`principalId\`: "${String(options.principalId)}".`
|
||||
);
|
||||
}
|
||||
|
||||
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the Vault-fenced `event_study` MCP tool backed by an injected
|
||||
* {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar
|
||||
* resolver.
|
||||
*
|
||||
* Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call,
|
||||
* resolves named universes strictly prior to the study start date, filters
|
||||
* bars and events defensively against the effective window and Vault cutoff,
|
||||
* anchors events using actual exchange close calendars, runs `runEventStudy`
|
||||
* under the injected research principal, and returns a bounded summary payload.
|
||||
*/
|
||||
export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry {
|
||||
const vaultCutoffTs = validateFactoryOptions(options);
|
||||
const { store, ledger, principalId, resolveExchangeCalendars } = options;
|
||||
|
||||
return defineMcpTool({
|
||||
name: 'event_study',
|
||||
description:
|
||||
'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.',
|
||||
inputSchema: eventStudyInputSchema,
|
||||
async handler(input: EventStudyToolInput): Promise<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = fenceVaultQueryBounds(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
},
|
||||
vaultCutoffTs
|
||||
);
|
||||
|
||||
const canonicalKinds = sortAndDedupeStrings(input.event.kinds);
|
||||
const canonicalSubtypes =
|
||||
input.event.subtypes !== undefined
|
||||
? sortAndDedupeStrings(input.event.subtypes)
|
||||
: undefined;
|
||||
|
||||
let listingIds: number[];
|
||||
let universeSnapshotDate: string | null = null;
|
||||
|
||||
if (input.universe !== undefined) {
|
||||
universeSnapshotDate = resolvePreStartUniverseDate(
|
||||
fenced.fromMs,
|
||||
fenced.asOfMs,
|
||||
fenced.asOfSubMs
|
||||
);
|
||||
const resolved = await store.universe({
|
||||
ref: input.universe,
|
||||
date: universeSnapshotDate,
|
||||
});
|
||||
listingIds = sortAndDedupeListingIds(resolved);
|
||||
} else {
|
||||
listingIds = sortAndDedupeListingIds(input.listingIds ?? []);
|
||||
}
|
||||
|
||||
const hasBenchmark = input.benchmark === 'equal_weight';
|
||||
const basePayloadFields = {
|
||||
scope: 'vault_fenced' as const,
|
||||
vaultCutoffTs,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
event: {
|
||||
kinds: canonicalKinds,
|
||||
subtypes: canonicalSubtypes ?? null,
|
||||
},
|
||||
preDays: input.preDays,
|
||||
postDays: input.postDays,
|
||||
benchmark: input.benchmark,
|
||||
adjustment: input.adjustment,
|
||||
universeMarket: input.universeMarket,
|
||||
horizonBucket: input.horizonBucket,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
effectiveFrom: fenced.canonicalFrom,
|
||||
effectiveTo: fenced.canonicalTo,
|
||||
effectiveAsOf: fenced.canonicalAsOf,
|
||||
clampedTo: fenced.clampedTo,
|
||||
clampedAsOf: fenced.clampedAsOf,
|
||||
listingCount: listingIds.length,
|
||||
};
|
||||
|
||||
if (listingIds.length === 0) {
|
||||
const payload: EventStudyResultPayload = {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: 'below_min_events',
|
||||
eventCount: 0,
|
||||
vaultExcludedEvents: 0,
|
||||
panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS,
|
||||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
const rawBars = await collectBars(
|
||||
store.bars({
|
||||
listingIds,
|
||||
timeframe: '1d',
|
||||
from: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
scope: 'vault_fenced',
|
||||
})
|
||||
);
|
||||
|
||||
const rawEventsTable = await store.events({
|
||||
kinds: canonicalKinds,
|
||||
listingIds,
|
||||
from: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
});
|
||||
|
||||
const listingIdSet = new Set<number>(listingIds);
|
||||
const kindSet = new Set<string>(canonicalKinds);
|
||||
const subtypeSet = canonicalSubtypes !== undefined ? new Set<string>(canonicalSubtypes) : null;
|
||||
|
||||
const eligibleBars = filterEligibleBars(
|
||||
rawBars,
|
||||
listingIdSet,
|
||||
fenced.fromMs,
|
||||
fenced.toMs,
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
|
||||
const { table: eligibleEventsTable, prePanelVaultExcludedEvents } =
|
||||
filterEligibleEventsTable({
|
||||
table: rawEventsTable,
|
||||
listingIdSet,
|
||||
kindSet,
|
||||
subtypeSet,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
});
|
||||
|
||||
const events = eventsTableToEventRows(eligibleEventsTable, {
|
||||
kinds: canonicalKinds,
|
||||
...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}),
|
||||
});
|
||||
|
||||
const fromDate = utcDateOf(fenced.fromMs);
|
||||
const toDate = utcDateOf(fenced.toMs);
|
||||
const asOfDate = utcDateOf(fenced.asOfMs);
|
||||
const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY;
|
||||
const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY);
|
||||
const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) =>
|
||||
a < b ? a : b
|
||||
);
|
||||
|
||||
if (fromDate > calendarToDate) {
|
||||
const panelDiagnostics: EventPanelDiagnostics = {
|
||||
...ZERO_EVENT_PANEL_DIAGNOSTICS,
|
||||
vaultExcludedEvents: prePanelVaultExcludedEvents,
|
||||
droppedUnknownListing: events.length,
|
||||
};
|
||||
const payload: EventStudyResultPayload = {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: 'below_min_events',
|
||||
eventCount: 0,
|
||||
vaultExcludedEvents: prePanelVaultExcludedEvents,
|
||||
panelDiagnostics,
|
||||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
let exchangeCalendars: EventStudyExchangeCalendars;
|
||||
try {
|
||||
exchangeCalendars = await resolveExchangeCalendars({
|
||||
listingIds,
|
||||
fromDate,
|
||||
toDate: calendarToDate,
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof EventPanelError) {
|
||||
throw err;
|
||||
}
|
||||
throw new ExchangeCalendarResolverError(err);
|
||||
}
|
||||
|
||||
const built = buildEventStudyInput({
|
||||
bars: eligibleBars,
|
||||
events,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
benchmark: input.benchmark,
|
||||
exchangeCalendars,
|
||||
});
|
||||
|
||||
const combinedPanelDiagnostics: EventPanelDiagnostics = {
|
||||
...built.diagnostics,
|
||||
vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents,
|
||||
};
|
||||
|
||||
if (built.input.sessionDates.length === 0) {
|
||||
const payload: EventStudyResultPayload = {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: 'below_min_events',
|
||||
eventCount: 0,
|
||||
vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents,
|
||||
panelDiagnostics: combinedPanelDiagnostics,
|
||||
study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark),
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
const expression = buildCanonicalEventStudyExpression({
|
||||
input,
|
||||
canonicalKinds,
|
||||
canonicalSubtypes,
|
||||
listingIds,
|
||||
universeSnapshotDate,
|
||||
effectiveFrom: fenced.canonicalFrom,
|
||||
effectiveTo: fenced.canonicalTo,
|
||||
effectiveAsOf: fenced.canonicalAsOf,
|
||||
});
|
||||
|
||||
const studyResult = await runEventStudy(ledger, {
|
||||
principalId,
|
||||
...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}),
|
||||
...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}),
|
||||
universeMarket: input.universeMarket,
|
||||
horizonBucket: input.horizonBucket,
|
||||
expression,
|
||||
input: built.input,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
options: {
|
||||
preDays: input.preDays,
|
||||
postDays: input.postDays,
|
||||
},
|
||||
});
|
||||
|
||||
const totalVaultExcludedEvents =
|
||||
combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents;
|
||||
const studySummary = projectStudySummary(studyResult.study);
|
||||
|
||||
const payload: EventStudyResultPayload =
|
||||
studyResult.status === 'ok'
|
||||
? {
|
||||
...basePayloadFields,
|
||||
status: 'ok',
|
||||
eventCount: built.input.events.length,
|
||||
vaultExcludedEvents: totalVaultExcludedEvents,
|
||||
panelDiagnostics: combinedPanelDiagnostics,
|
||||
study: studySummary,
|
||||
trial: studyResult.trial,
|
||||
deflatedSharpe: studyResult.deflatedSharpe,
|
||||
}
|
||||
: {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: studyResult.reason,
|
||||
eventCount: built.input.events.length,
|
||||
vaultExcludedEvents: totalVaultExcludedEvents,
|
||||
panelDiagnostics: combinedPanelDiagnostics,
|
||||
study: studySummary,
|
||||
};
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
return formatMappedEventStudyError(err);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
658
libs/research/test/mcp-event-study-qa.test.ts
Normal file
658
libs/research/test/mcp-event-study-qa.test.ts
Normal file
|
|
@ -0,0 +1,658 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { EventStudyExchangeCalendars } from '../src/event-panel';
|
||||
import type {
|
||||
BarBatch,
|
||||
BarRecord,
|
||||
EventKind,
|
||||
MarketDataStore,
|
||||
Table,
|
||||
TableRow,
|
||||
} from '../src/market-data-store';
|
||||
import {
|
||||
type BarsQuery,
|
||||
EVENTS_COLUMNS,
|
||||
type EventsQuery,
|
||||
MarketDataStoreNotImplementedError,
|
||||
type UniverseQuery,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
type EventStudyExchangeCalendarQuery,
|
||||
type EventStudyResultPayload,
|
||||
createEventStudyTool,
|
||||
createMcpServer,
|
||||
} from '../src/mcp/index';
|
||||
import type { TrialLedgerExecutor } from '../src/trial-ledger';
|
||||
|
||||
// QA fixture: deterministic synthetic equity bars & events with explicit
|
||||
// half-day closes, intraday Vault cutoffs, exact boundary timestamps, and
|
||||
// malformed rows. Models gross daily close-to-close returns, raw adjustment,
|
||||
// no fills or transaction costs.
|
||||
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
while (out.length < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out.push(current.toISOString().slice(0, 10));
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function utcMs(date: string, hour: number, minute = 0, second = 0, ms = 0): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hour, minute, second, ms);
|
||||
}
|
||||
|
||||
function createFakeLedger(): {
|
||||
executor: TrialLedgerExecutor;
|
||||
insertCalls: number;
|
||||
rows: Array<{ expression_hash: string; daily_series: number[] }>;
|
||||
} {
|
||||
const rows: Array<{ expression_hash: string; daily_series: number[] }> = [];
|
||||
let nextId = 1;
|
||||
const state = {
|
||||
rows,
|
||||
insertCalls: 0,
|
||||
executor: null as unknown as TrialLedgerExecutor,
|
||||
};
|
||||
|
||||
state.executor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
state.insertCalls += 1;
|
||||
const p = params ?? [];
|
||||
const id = nextId++;
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
rows.push({
|
||||
expression_hash: p[6] as string,
|
||||
daily_series: dailySeries,
|
||||
});
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
trial_id: String(id),
|
||||
created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, id)),
|
||||
} as unknown as Row,
|
||||
],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
const storedRows = rows.map((r, idx) => ({
|
||||
trial_id: String(idx + 1),
|
||||
created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, idx + 1)),
|
||||
principal_id: AGENT_PRINCIPAL,
|
||||
campaign_id: null,
|
||||
stage: 'event_study',
|
||||
universe_market: 'US_EQ',
|
||||
horizon_bucket: 'swing_1_10d',
|
||||
hypothesis_id: null,
|
||||
expression_hash: r.expression_hash,
|
||||
sample_start: '2023-01-02',
|
||||
sample_end: '2023-02-01',
|
||||
n_obs: r.daily_series.length,
|
||||
sharpe_unann: 0.5,
|
||||
skewness: 0,
|
||||
kurtosis: 3,
|
||||
daily_series: r.daily_series,
|
||||
}));
|
||||
return { rows: storedRows as unknown as Row[], rowCount: storedRows.length };
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
function createPassThroughStore(params: {
|
||||
bars: readonly BarRecord[];
|
||||
eventsTable: Table;
|
||||
}): MarketDataStore {
|
||||
return {
|
||||
bars(_q: BarsQuery): AsyncIterable<BarBatch> {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield { rows: [...params.bars] };
|
||||
},
|
||||
};
|
||||
},
|
||||
async events(_q: EventsQuery): Promise<Table> {
|
||||
return params.eventsTable;
|
||||
},
|
||||
async universe(_q: UniverseQuery): Promise<number[]> {
|
||||
return [];
|
||||
},
|
||||
crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
},
|
||||
shortsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
||||
},
|
||||
macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
},
|
||||
fx() {
|
||||
throw new MarketDataStoreNotImplementedError('fx');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
server: ReturnType<typeof createMcpServer>,
|
||||
args: Record<string, unknown>
|
||||
): Promise<{
|
||||
isError?: boolean;
|
||||
text: string;
|
||||
payload?: EventStudyResultPayload;
|
||||
}> {
|
||||
const raw = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: { name: 'event_study', arguments: args },
|
||||
})
|
||||
);
|
||||
const rpc = JSON.parse(raw!) as {
|
||||
result: { content: Array<{ type: string; text: string }>; isError?: boolean };
|
||||
};
|
||||
const text = rpc.result.content[0]!.text;
|
||||
return {
|
||||
isError: rpc.result.isError,
|
||||
text,
|
||||
payload: rpc.result.isError ? undefined : (JSON.parse(text) as EventStudyResultPayload),
|
||||
};
|
||||
}
|
||||
|
||||
describe('MCP event_study QA edge cases', () => {
|
||||
test('event released after a half-day close anchors to the next trading session, not the half-day', async () => {
|
||||
const dates = makeBusinessDates('2023-05-01', 25);
|
||||
const vaultCutoffDate = dates[24]!;
|
||||
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
|
||||
const listingIds = [101, 102, 103, 104, 105, 106];
|
||||
|
||||
// Make day index 8 a half-day (closes at 18:00 UTC = 13:00 ET instead of 21:00 UTC).
|
||||
// Place 6 events across days 8 and 14, released at 19:00 UTC (after 18:00 UTC half-day close,
|
||||
// before 21:00 UTC bar stamp). For half-day (index 8), events must anchor to index 9!
|
||||
// Put a +10% jump on index 9 and +20% jump on index 15 (next day after 14, also half-day),
|
||||
// and 0% return on index 8 and 14 so AAR at offset 0 proves next-session anchoring.
|
||||
const halfDayIndices = new Set([8, 14]);
|
||||
const jumpDayReturns = new Map<number, number>([
|
||||
[9, 0.1],
|
||||
[15, 0.2],
|
||||
]);
|
||||
|
||||
const bars: BarRecord[] = [];
|
||||
for (const id of listingIds) {
|
||||
let price = 100;
|
||||
for (let t = 0; t < 24; t += 1) {
|
||||
const ret = jumpDayReturns.get(t) ?? 0;
|
||||
price = Number((price * (1 + ret)).toFixed(6));
|
||||
const ts = utcMs(dates[t]!, 21); // bars_1d always stamped 16:00 ET (21:00 UTC)
|
||||
bars.push({
|
||||
listingId: id,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 10_000,
|
||||
knownAt: ts,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventRows: TableRow[] = [];
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
// Released at 19:00 UTC on half-day index 8 -> anchors to index 9 (+10%)
|
||||
eventRows.push({
|
||||
listing_id: listingIds[i]!,
|
||||
ts: utcMs(dates[8]!, 19),
|
||||
known_at: utcMs(dates[8]!, 19),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing' as EventKind,
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
});
|
||||
}
|
||||
for (let i = 3; i < 6; i += 1) {
|
||||
// Released at 19:00 UTC on half-day index 14 -> anchors to index 15 (+20%)
|
||||
eventRows.push({
|
||||
listing_id: listingIds[i]!,
|
||||
ts: utcMs(dates[14]!, 19),
|
||||
known_at: utcMs(dates[14]!, 19),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing' as EventKind,
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
});
|
||||
}
|
||||
|
||||
const store = createPassThroughStore({
|
||||
bars,
|
||||
eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows },
|
||||
});
|
||||
const ledger = createFakeLedger();
|
||||
|
||||
const resolveExchangeCalendars = async (
|
||||
q: EventStudyExchangeCalendarQuery
|
||||
): Promise<EventStudyExchangeCalendars> => {
|
||||
const sessions = dates
|
||||
.filter(d => d >= q.fromDate && d <= q.toDate)
|
||||
.map((date, _idx) => {
|
||||
const globalIdx = dates.indexOf(date);
|
||||
const closeHour = halfDayIndices.has(globalIdx) ? 18 : 21;
|
||||
return { date, closeTs: utcMs(date, closeHour) };
|
||||
});
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (const id of q.listingIds) {
|
||||
listingCalendarId.set(id, 'XNYS');
|
||||
}
|
||||
return {
|
||||
calendars: new Map([['XNYS', sessions]]),
|
||||
listingCalendarId,
|
||||
};
|
||||
};
|
||||
|
||||
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: dates[0]!,
|
||||
to: dates[23]!,
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 1,
|
||||
postDays: 1,
|
||||
benchmark: 'none',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
|
||||
expect(res.isError).toBeUndefined();
|
||||
expect(res.payload?.status).toBe('ok');
|
||||
if (res.payload?.status !== 'ok') {
|
||||
throw new Error('Expected ok');
|
||||
}
|
||||
|
||||
// Offset -1 is the half-day itself (0% return); Offset 0 is the next session (mean of +10% and +20% = +15%).
|
||||
const offsetMinus1 = res.payload.study.offsets.find(o => o.offset === -1)!;
|
||||
const offset0 = res.payload.study.offsets.find(o => o.offset === 0)!;
|
||||
expect(offsetMinus1.aar).toBeCloseTo(0, 8);
|
||||
expect(offset0.aar).toBeCloseTo(0.15, 8);
|
||||
});
|
||||
|
||||
test('intraday Vault cutoff excludes rows on the cutoff UTC day and handles start-on-cutoff-day safely', async () => {
|
||||
const dates = makeBusinessDates('2023-06-01', 25);
|
||||
const cutoffDate = dates[20]!;
|
||||
// Intraday Vault cutoff at 12:00 UTC on cutoffDate
|
||||
const vaultCutoffTs = utcMs(cutoffDate, 12);
|
||||
const listingIds = [201, 202, 203, 204, 205, 206];
|
||||
|
||||
const bars: BarRecord[] = [];
|
||||
for (const id of listingIds) {
|
||||
let price = 50;
|
||||
for (let t = 0; t < 22; t += 1) {
|
||||
price = Number((price * (1 + (t % 3 === 0 ? 0.02 : -0.005))).toFixed(6));
|
||||
const ts = t === 20 ? utcMs(dates[t]!, 10) : utcMs(dates[t]!, 21); // Bar on cutoff day at 10:00 UTC (< cutoffTs!)
|
||||
bars.push({
|
||||
listingId: id,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 5_000,
|
||||
knownAt: ts,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const baseEvents: TableRow[] = [
|
||||
// 6 valid pre-cutoff events across 2 dates
|
||||
...listingIds.slice(0, 3).map(id => ({
|
||||
listing_id: id,
|
||||
ts: utcMs(dates[6]!, 14),
|
||||
known_at: utcMs(dates[6]!, 14),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
})),
|
||||
...listingIds.slice(3, 6).map(id => ({
|
||||
listing_id: id,
|
||||
ts: utcMs(dates[12]!, 14),
|
||||
known_at: utcMs(dates[12]!, 14),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
})),
|
||||
];
|
||||
|
||||
const intradayCutoffEvents: TableRow[] = [
|
||||
// Event on cutoff UTC day BEFORE intraday vaultCutoffTs (10:00 UTC < 12:00 UTC) -> MUST be excluded!
|
||||
{
|
||||
listing_id: listingIds[0]!,
|
||||
ts: utcMs(cutoffDate, 10),
|
||||
known_at: utcMs(cutoffDate, 10),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// Valid ts earlier, but known_at on cutoff UTC day at 09:00 UTC (< 12:00 UTC) -> MUST be excluded!
|
||||
{
|
||||
listing_id: listingIds[1]!,
|
||||
ts: utcMs(dates[10]!, 14),
|
||||
known_at: utcMs(cutoffDate, 9),
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// Unrequested valid kind on cutoff day -> MUST NOT inflate vaultExcludedEvents
|
||||
{
|
||||
listing_id: listingIds[2]!,
|
||||
ts: utcMs(cutoffDate, 10),
|
||||
known_at: utcMs(cutoffDate, 10),
|
||||
known_at_source: 'exact',
|
||||
kind: 'ceo_post',
|
||||
subtype: null,
|
||||
payload_json: '{}',
|
||||
},
|
||||
];
|
||||
|
||||
const calendarCalls: EventStudyExchangeCalendarQuery[] = [];
|
||||
const resolveExchangeCalendars = async (
|
||||
q: EventStudyExchangeCalendarQuery
|
||||
): Promise<EventStudyExchangeCalendars> => {
|
||||
calendarCalls.push(q);
|
||||
const sessions = dates
|
||||
.filter(d => d >= q.fromDate && d <= q.toDate)
|
||||
.map(date => ({ date, closeTs: utcMs(date, 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 store = createPassThroughStore({
|
||||
bars,
|
||||
eventsTable: {
|
||||
columns: [...EVENTS_COLUMNS],
|
||||
rows: [...baseEvents, ...intradayCutoffEvents],
|
||||
},
|
||||
});
|
||||
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: dates[0]!,
|
||||
to: dates[21]!,
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 2,
|
||||
postDays: 2,
|
||||
benchmark: 'none',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
|
||||
expect(res.payload?.status).toBe('ok');
|
||||
expect(res.payload?.vaultExcludedEvents).toBe(2);
|
||||
expect(res.payload?.eventCount).toBe(6);
|
||||
expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true);
|
||||
|
||||
// Request starting on the intraday cutoff day before vaultCutoffTs:
|
||||
// returns insufficient_data cleanly without calling calendar resolver with inverted dates.
|
||||
calendarCalls.length = 0;
|
||||
const ledger2 = createFakeLedger();
|
||||
const server2 = createMcpServer({
|
||||
name: 'research-mcp',
|
||||
version: '1.0.0',
|
||||
tools: [
|
||||
createEventStudyTool({
|
||||
store,
|
||||
ledger: ledger2.executor,
|
||||
vaultContext: { vaultCutoffTs },
|
||||
principalId: AGENT_PRINCIPAL,
|
||||
resolveExchangeCalendars,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const startOnCutoffRes = await invoke(server2, {
|
||||
listingIds,
|
||||
from: `${cutoffDate}T01:00:00.000Z`,
|
||||
to: `${cutoffDate}T11:00:00.000Z`,
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 1,
|
||||
postDays: 1,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
|
||||
expect(startOnCutoffRes.isError).toBeUndefined();
|
||||
expect(startOnCutoffRes.payload?.status).toBe('insufficient_data');
|
||||
expect(calendarCalls).toHaveLength(0);
|
||||
expect(ledger2.insertCalls).toBe(0);
|
||||
});
|
||||
|
||||
test('exact boundary timestamps (fromMs, toMs, asOfMs) and malformed ts rejection', async () => {
|
||||
const dates = makeBusinessDates('2023-07-03', 20);
|
||||
const vaultCutoffDate = dates[19]!;
|
||||
const vaultCutoffTs = utcMs(vaultCutoffDate, 0);
|
||||
const listingIds = [301, 302, 303, 304, 305, 306];
|
||||
|
||||
const bars: BarRecord[] = [];
|
||||
for (const id of listingIds) {
|
||||
let price = 30;
|
||||
for (let t = 0; t < 19; t += 1) {
|
||||
price = Number((price * (1 + (t % 2 === 0 ? 0.015 : -0.005))).toFixed(6));
|
||||
const ts = utcMs(dates[t]!, 21);
|
||||
bars.push({
|
||||
listingId: id,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1_000,
|
||||
knownAt: ts,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const fromIso = `${dates[2]}T00:00:00.000Z`;
|
||||
const toIso = `${dates[15]}T23:59:59.999Z`;
|
||||
const asOfIso = `${dates[14]}T21:00:00.000Z`;
|
||||
const fromMs = Date.parse(fromIso);
|
||||
const toMs = Date.parse(toIso);
|
||||
const asOfMs = Date.parse(asOfIso);
|
||||
|
||||
const rows: TableRow[] = [
|
||||
// Exact fromMs -> included
|
||||
{
|
||||
listing_id: listingIds[0]!,
|
||||
ts: fromMs,
|
||||
known_at: fromMs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// fromMs - 1 -> excluded
|
||||
{
|
||||
listing_id: listingIds[1]!,
|
||||
ts: fromMs - 1,
|
||||
known_at: fromMs - 1,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// Exact asOfMs -> included
|
||||
{
|
||||
listing_id: listingIds[2]!,
|
||||
ts: utcMs(dates[10]!, 14),
|
||||
known_at: asOfMs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// asOfMs + 1 -> excluded
|
||||
{
|
||||
listing_id: listingIds[3]!,
|
||||
ts: utcMs(dates[10]!, 14),
|
||||
known_at: asOfMs + 1,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
// toMs + 1 -> excluded
|
||||
{
|
||||
listing_id: listingIds[4]!,
|
||||
ts: toMs + 1,
|
||||
known_at: asOfMs,
|
||||
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, 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 store = createPassThroughStore({
|
||||
bars,
|
||||
eventsTable: { columns: [...EVENTS_COLUMNS], 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: fromIso,
|
||||
to: toIso,
|
||||
asOf: asOfIso,
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 1,
|
||||
postDays: 1,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
|
||||
// Only 2 events survived the exact boundaries (fromMs and asOfMs) -> insufficient_data (< 5)
|
||||
expect(res.payload?.status).toBe('insufficient_data');
|
||||
expect(res.payload?.eventCount).toBe(2);
|
||||
expect(ledger.insertCalls).toBe(0);
|
||||
|
||||
// Malformed `ts` on an otherwise eligible event row must fail with sanitized EventPanelError
|
||||
const malformedStore = createPassThroughStore({
|
||||
bars,
|
||||
eventsTable: {
|
||||
columns: [...EVENTS_COLUMNS],
|
||||
rows: [
|
||||
{
|
||||
listing_id: listingIds[0]!,
|
||||
ts: 'not-a-timestamp' as unknown as number,
|
||||
known_at: fromMs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '8-K',
|
||||
payload_json: '{}',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const malformedLedger = createFakeLedger();
|
||||
const malformedServer = createMcpServer({
|
||||
name: 'research-mcp',
|
||||
version: '1.0.0',
|
||||
tools: [
|
||||
createEventStudyTool({
|
||||
store: malformedStore,
|
||||
ledger: malformedLedger.executor,
|
||||
vaultContext: { vaultCutoffTs },
|
||||
principalId: AGENT_PRINCIPAL,
|
||||
resolveExchangeCalendars,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const badRes = await invoke(malformedServer, {
|
||||
listingIds,
|
||||
from: fromIso,
|
||||
to: toIso,
|
||||
asOf: asOfIso,
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 1,
|
||||
postDays: 1,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
|
||||
expect(badRes.isError).toBe(true);
|
||||
expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.');
|
||||
expect(malformedLedger.insertCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
1419
libs/research/test/mcp-event-study.test.ts
Normal file
1419
libs/research/test/mcp-event-study.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue