T-131: M2.1b — MCP copilot analyze_signal tool: vault-fenced short-interest signal study (bars + shortsAsOf → forward-return panel → analyzeSignal + trial ledger) in libs/research/src/mcp/tools/
This commit is contained in:
parent
5df349e82c
commit
e7bd019bb6
5 changed files with 2420 additions and 225 deletions
|
|
@ -1,4 +1,5 @@
|
|||
export * from './protocol';
|
||||
export * from './server';
|
||||
export * from './stdio';
|
||||
export * from './tools/analyze-signal';
|
||||
export * from './tools/query-data';
|
||||
|
|
|
|||
744
libs/research/src/mcp/tools/analyze-signal.ts
Normal file
744
libs/research/src/mcp/tools/analyze-signal.ts
Normal file
|
|
@ -0,0 +1,744 @@
|
|||
import {
|
||||
type IcSummary,
|
||||
type RecencySplitResult,
|
||||
type SignalPanelAnalysis,
|
||||
type SignalPanelDiagnostics as CalcSignalPanelDiagnostics,
|
||||
analyzeSignalPanel,
|
||||
} from '@stock-bot/calculations';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
type TableRow,
|
||||
type VaultFenceContext,
|
||||
} from '../../market-data-store';
|
||||
import {
|
||||
SHORTS_SIGNAL_FIELDS,
|
||||
type ShortsSignalField,
|
||||
type SignalPanelDiagnostics,
|
||||
SignalPanelError,
|
||||
type SignalPanelErrorCode,
|
||||
buildForwardReturnPanel,
|
||||
collectBars,
|
||||
shortsTableToSignalRows,
|
||||
} from '../../signal-panel';
|
||||
import {
|
||||
type AnalyzeSignalInsufficientDataReason,
|
||||
type SignalLedgerSeries,
|
||||
SignalStudyError,
|
||||
type SignalStudyErrorCode,
|
||||
type SignalStudyExpression,
|
||||
type StudyTrialSummary,
|
||||
analyzeSignal,
|
||||
} 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,
|
||||
MCP_MAX_LISTING_IDS,
|
||||
createListingIdsFieldSchema,
|
||||
createUniverseFieldSchema,
|
||||
fenceVaultQueryBounds,
|
||||
formatMappedStoreError,
|
||||
hasExclusiveListingSelector,
|
||||
isValidUtcBoundString,
|
||||
resolvePreStartUniverseDate,
|
||||
utcDateOf,
|
||||
validateVaultCutoffTs,
|
||||
} from './vault-fenced-input';
|
||||
|
||||
/** Hard maximum number of explicit `listingIds` accepted by `analyze_signal`. */
|
||||
export const ANALYZE_SIGNAL_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
|
||||
|
||||
/** Hard maximum forward-return horizon in trading sessions. */
|
||||
export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252;
|
||||
|
||||
/** Maximum number of latest dated observations exposed in the tool response preview. */
|
||||
export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100;
|
||||
|
||||
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 utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE);
|
||||
|
||||
const shortsSignalSpecSchema = z
|
||||
.object({
|
||||
source: z.literal('shorts').describe('Signal data source (currently "shorts").'),
|
||||
field: z
|
||||
.enum(SHORTS_SIGNAL_FIELDS)
|
||||
.describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'),
|
||||
})
|
||||
.strict()
|
||||
.describe('Discriminated signal source and field specification.');
|
||||
|
||||
/**
|
||||
* Strict Zod input schema for the `analyze_signal` 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 analyzeSignalInputSchema = 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.'
|
||||
),
|
||||
signal: shortsSignalSpecSchema,
|
||||
horizonSessions: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS)
|
||||
.describe(
|
||||
`Forward-return horizon in trading sessions (1–${ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS}).`
|
||||
),
|
||||
maxSignalAgeSessions: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.optional()
|
||||
.describe('Optional maximum signal age in trading sessions before a signal is treated as stale.'),
|
||||
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.'),
|
||||
ledgerSeries: z
|
||||
.enum(['rank_ic', 'quantile_spread'])
|
||||
.default('rank_ic')
|
||||
.describe('Daily series recorded to trial_ledger and evaluated for DSR (default rank_ic).'),
|
||||
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.'),
|
||||
adjustment: z
|
||||
.enum(['raw', 'split', 'total'])
|
||||
.default('raw')
|
||||
.describe('Bar price adjustment mode (default raw).'),
|
||||
})
|
||||
.strict()
|
||||
.refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE);
|
||||
|
||||
export type AnalyzeSignalInput = z.infer<typeof analyzeSignalInputSchema>;
|
||||
|
||||
/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */
|
||||
export interface AnalyzeSignalToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
readonly ledger: TrialLedgerExecutor;
|
||||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||||
readonly principalId: string;
|
||||
}
|
||||
|
||||
/** Single dated observation in the bounded series preview. */
|
||||
export interface AnalyzeSignalSeriesPoint {
|
||||
readonly date: string;
|
||||
readonly value: number;
|
||||
}
|
||||
|
||||
/** Bounded preview of the selected ledger series (latest 100 observations). */
|
||||
export interface AnalyzeSignalSeriesPreview {
|
||||
readonly series: SignalLedgerSeries;
|
||||
readonly totalCount: number;
|
||||
readonly truncated: boolean;
|
||||
readonly points: readonly AnalyzeSignalSeriesPoint[];
|
||||
}
|
||||
|
||||
/** Projected quantile-spread summary without raw per-bucket typed arrays. */
|
||||
export interface AnalyzeSignalQuantilesSummary {
|
||||
readonly quantiles: number;
|
||||
readonly validDates: number;
|
||||
readonly skippedDates: number;
|
||||
readonly bucketMeanReturns: readonly (number | null)[];
|
||||
readonly spreadSummary: IcSummary;
|
||||
}
|
||||
|
||||
/** Projected top/bottom quantile membership turnover summary. */
|
||||
export interface AnalyzeSignalTurnoverSummary {
|
||||
readonly count: number;
|
||||
readonly meanTopTurnover: number | null;
|
||||
readonly meanBottomTurnover: number | null;
|
||||
}
|
||||
|
||||
/** Bounded summary projection of {@link SignalPanelAnalysis}. */
|
||||
export interface AnalyzeSignalAnalysisSummary {
|
||||
readonly pearsonIc: IcSummary;
|
||||
readonly rankIc: IcSummary;
|
||||
readonly quantiles: AnalyzeSignalQuantilesSummary;
|
||||
readonly turnover: AnalyzeSignalTurnoverSummary;
|
||||
readonly recency: RecencySplitResult;
|
||||
readonly diagnostics: CalcSignalPanelDiagnostics;
|
||||
readonly ledgerSeries: AnalyzeSignalSeriesPreview;
|
||||
}
|
||||
|
||||
interface AnalyzeSignalResultBase {
|
||||
readonly scope: 'vault_fenced';
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly signal: {
|
||||
readonly source: 'shorts';
|
||||
readonly field: ShortsSignalField;
|
||||
};
|
||||
readonly horizonSessions: number;
|
||||
readonly adjustment: 'raw' | 'split' | 'total';
|
||||
readonly universeMarket: UniverseMarket;
|
||||
readonly horizonBucket: HorizonBucket;
|
||||
readonly fromMs: number;
|
||||
readonly toMs: number;
|
||||
readonly asOfMs: number;
|
||||
readonly clampedTo: boolean;
|
||||
readonly clampedAsOf: boolean;
|
||||
readonly listingCount: number;
|
||||
readonly panelDiagnostics: SignalPanelDiagnostics;
|
||||
readonly analysis: AnalyzeSignalAnalysisSummary;
|
||||
}
|
||||
|
||||
/** Structured JSON payload serialized into the `analyze_signal` MCP text result. */
|
||||
export type AnalyzeSignalResultPayload =
|
||||
| (AnalyzeSignalResultBase & {
|
||||
readonly status: 'ok';
|
||||
readonly trial: StudyTrialSummary;
|
||||
readonly deflatedSharpe: ClusterDeflatedSharpeResult;
|
||||
})
|
||||
| (AnalyzeSignalResultBase & {
|
||||
readonly status: 'insufficient_data';
|
||||
readonly reason: AnalyzeSignalInsufficientDataReason;
|
||||
});
|
||||
|
||||
const ZERO_PANEL_DIAGNOSTICS: SignalPanelDiagnostics = {
|
||||
vaultExcludedDates: 0,
|
||||
droppedNoSignal: 0,
|
||||
droppedStaleSignal: 0,
|
||||
droppedMissingForwardBar: 0,
|
||||
droppedNonPositiveClose: 0,
|
||||
duplicateBars: 0,
|
||||
};
|
||||
|
||||
const SIGNAL_PANEL_ERROR_MESSAGES: Readonly<Record<SignalPanelErrorCode, string>> = {
|
||||
invalid_input: 'Invalid signal panel input.',
|
||||
invalid_horizon: 'Invalid forward-return horizon.',
|
||||
invalid_option: 'Invalid signal panel option.',
|
||||
invalid_date: 'Invalid signal panel date.',
|
||||
invalid_bar: 'Market bar data failed panel validation.',
|
||||
invalid_signal: 'Signal table data failed panel validation.',
|
||||
duplicate_bar: 'Conflicting duplicate daily bars detected.',
|
||||
};
|
||||
|
||||
const SIGNAL_STUDY_ERROR_MESSAGES: Readonly<Record<SignalStudyErrorCode, string>> = {
|
||||
invalid_request: 'Invalid signal study request.',
|
||||
empty_panel: 'Signal panel is empty.',
|
||||
invalid_date: 'Invalid signal study date.',
|
||||
unsorted_dates: 'Signal panel dates are not strictly ascending.',
|
||||
duplicate_date: 'Duplicate date detected in signal panel.',
|
||||
invalid_panel: 'Signal panel failed validation.',
|
||||
invalid_option: 'Invalid signal 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 projectAnalysisSummary(
|
||||
analysis: SignalPanelAnalysis,
|
||||
selectedSeries: SignalLedgerSeries
|
||||
): AnalyzeSignalAnalysisSummary {
|
||||
const rawDates = selectedSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates;
|
||||
const rawValues =
|
||||
selectedSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries;
|
||||
const totalCount = Math.min(rawDates.length, rawValues.length);
|
||||
const truncated = totalCount > ANALYZE_SIGNAL_MAX_SERIES_POINTS;
|
||||
const startIdx = truncated ? totalCount - ANALYZE_SIGNAL_MAX_SERIES_POINTS : 0;
|
||||
const points: AnalyzeSignalSeriesPoint[] = [];
|
||||
|
||||
for (let i = startIdx; i < totalCount; i += 1) {
|
||||
points.push({
|
||||
date: rawDates[i] as string,
|
||||
value: rawValues[i] as number,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
pearsonIc: analysis.pearsonIc,
|
||||
rankIc: analysis.rankIc,
|
||||
quantiles: {
|
||||
quantiles: analysis.quantiles.quantiles,
|
||||
validDates: analysis.quantiles.validDates,
|
||||
skippedDates: analysis.quantiles.skippedDates,
|
||||
bucketMeanReturns: [...analysis.quantiles.bucketMeanReturns],
|
||||
spreadSummary: analysis.quantiles.spreadSummary,
|
||||
},
|
||||
turnover: {
|
||||
count: analysis.turnover.count,
|
||||
meanTopTurnover: analysis.turnover.meanTopTurnover,
|
||||
meanBottomTurnover: analysis.turnover.meanBottomTurnover,
|
||||
},
|
||||
recency: analysis.recency,
|
||||
diagnostics: analysis.diagnostics,
|
||||
ledgerSeries: {
|
||||
series: selectedSeries,
|
||||
totalCount,
|
||||
truncated,
|
||||
points,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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 (typeof row.ts === 'number' && Number.isFinite(row.ts)) {
|
||||
if (
|
||||
row.ts < fromMs ||
|
||||
row.ts > toMs ||
|
||||
row.ts >= vaultCutoffTs ||
|
||||
utcDateOf(row.ts) >= vaultCutoffDate
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (typeof row.knownAt === 'number' && Number.isFinite(row.knownAt)) {
|
||||
if (row.knownAt > asOfMs || row.knownAt >= vaultCutoffTs) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) {
|
||||
continue;
|
||||
}
|
||||
eligible.push(row);
|
||||
}
|
||||
return eligible;
|
||||
}
|
||||
|
||||
function filterEligibleShortsTable(
|
||||
table: Table,
|
||||
listingIdSet: ReadonlySet<number>,
|
||||
fromUtcDate: string,
|
||||
toUtcDate: string,
|
||||
asOfMs: number,
|
||||
vaultCutoffTs: number,
|
||||
vaultCutoffDate: string
|
||||
): Table {
|
||||
if (
|
||||
typeof table !== 'object' ||
|
||||
table === null ||
|
||||
!Array.isArray(table.columns) ||
|
||||
!Array.isArray(table.rows)
|
||||
) {
|
||||
return table;
|
||||
}
|
||||
|
||||
const eligibleRows: TableRow[] = [];
|
||||
for (let i = 0; i < table.rows.length; i += 1) {
|
||||
const row = table.rows[i];
|
||||
if (typeof row !== 'object' || row === null) {
|
||||
eligibleRows.push(row as TableRow);
|
||||
continue;
|
||||
}
|
||||
const knownAt = row.known_at;
|
||||
if (typeof knownAt === 'number' && Number.isFinite(knownAt)) {
|
||||
if (knownAt > asOfMs || knownAt >= vaultCutoffTs) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const reportDate = row.report_date;
|
||||
if (typeof reportDate === 'string') {
|
||||
if (reportDate < fromUtcDate || reportDate > toUtcDate || reportDate >= vaultCutoffDate) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const listingId = row.listing_id;
|
||||
if (typeof listingId === 'number' && !listingIdSet.has(listingId)) {
|
||||
continue;
|
||||
}
|
||||
eligibleRows.push(row);
|
||||
}
|
||||
|
||||
return {
|
||||
columns: table.columns,
|
||||
rows: eligibleRows,
|
||||
};
|
||||
}
|
||||
|
||||
function buildCanonicalStudyExpression(params: {
|
||||
readonly input: AnalyzeSignalInput;
|
||||
readonly listingIds: readonly number[];
|
||||
readonly universeSnapshotDate: string | null;
|
||||
readonly fromMs: number;
|
||||
readonly toMs: number;
|
||||
readonly asOfMs: number;
|
||||
}): SignalStudyExpression {
|
||||
const { input, listingIds, universeSnapshotDate, fromMs, toMs, asOfMs } = params;
|
||||
return {
|
||||
expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`,
|
||||
params: {
|
||||
version: 1,
|
||||
signalSource: input.signal.source,
|
||||
signalField: input.signal.field,
|
||||
horizonSessions: input.horizonSessions,
|
||||
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
||||
adjustment: input.adjustment,
|
||||
ledgerSeries: input.ledgerSeries,
|
||||
fromMs,
|
||||
toMs,
|
||||
asOfMs,
|
||||
},
|
||||
universe:
|
||||
input.universe !== undefined
|
||||
? {
|
||||
kind: 'universe',
|
||||
ref: input.universe,
|
||||
snapshotDate: universeSnapshotDate,
|
||||
listingIds,
|
||||
}
|
||||
: {
|
||||
kind: 'listingIds',
|
||||
listingIds,
|
||||
},
|
||||
horizon: `${input.horizonSessions}d`,
|
||||
};
|
||||
}
|
||||
|
||||
function formatMappedAnalyzeSignalError(err: unknown): McpToolCallResult {
|
||||
const storeMapped = formatMappedStoreError(err);
|
||||
if (storeMapped !== null) {
|
||||
return storeMapped;
|
||||
}
|
||||
|
||||
if (err instanceof SignalPanelError) {
|
||||
const detail = Object.prototype.hasOwnProperty.call(SIGNAL_PANEL_ERROR_MESSAGES, err.code)
|
||||
? SIGNAL_PANEL_ERROR_MESSAGES[err.code]
|
||||
: 'Signal panel construction failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `SignalPanelError: ${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]
|
||||
: 'Signal 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: AnalyzeSignalToolOptions): number {
|
||||
if (
|
||||
typeof options.store !== 'object' ||
|
||||
options.store === null ||
|
||||
typeof options.store.bars !== 'function' ||
|
||||
typeof options.store.shortsAsOf !== 'function' ||
|
||||
typeof options.store.universe !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, 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.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 `analyze_signal` MCP tool backed by an injected
|
||||
* {@link MarketDataStore} and {@link TrialLedgerExecutor}.
|
||||
*
|
||||
* Enforces `scope: 'vault_fenced'`, fences bounds before any store call,
|
||||
* resolves named universes strictly prior to the study start date, filters
|
||||
* bars and shorts defensively against the effective window and Vault cutoff,
|
||||
* builds the forward-return panel, runs `analyzeSignal` with the injected
|
||||
* research principal, and returns a bounded summary payload.
|
||||
*/
|
||||
export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpToolEntry {
|
||||
const vaultCutoffTs = validateFactoryOptions(options);
|
||||
const { store, ledger, principalId } = options;
|
||||
|
||||
return defineMcpTool({
|
||||
name: 'analyze_signal',
|
||||
description:
|
||||
'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.',
|
||||
inputSchema: analyzeSignalInputSchema,
|
||||
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = fenceVaultQueryBounds(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
},
|
||||
vaultCutoffTs
|
||||
);
|
||||
|
||||
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 basePayloadFields = {
|
||||
scope: 'vault_fenced' as const,
|
||||
vaultCutoffTs,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
signal: {
|
||||
source: input.signal.source,
|
||||
field: input.signal.field,
|
||||
},
|
||||
horizonSessions: input.horizonSessions,
|
||||
adjustment: input.adjustment,
|
||||
universeMarket: input.universeMarket,
|
||||
horizonBucket: input.horizonBucket,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
clampedTo: fenced.clampedTo,
|
||||
clampedAsOf: fenced.clampedAsOf,
|
||||
listingCount: listingIds.length,
|
||||
};
|
||||
|
||||
if (listingIds.length === 0) {
|
||||
const emptyAnalysis = analyzeSignalPanel([], {
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
});
|
||||
const payload: AnalyzeSignalResultPayload = {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: 'too_few_observations',
|
||||
panelDiagnostics: ZERO_PANEL_DIAGNOSTICS,
|
||||
analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries),
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
const rawBars = await collectBars(
|
||||
store.bars({
|
||||
listingIds,
|
||||
timeframe: '1d',
|
||||
from: input.from,
|
||||
to: fenced.effectiveFencedTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: fenced.effectiveFencedAsOf,
|
||||
scope: 'vault_fenced',
|
||||
})
|
||||
);
|
||||
|
||||
const rawShortsTable = await store.shortsAsOf({
|
||||
listingIds,
|
||||
from: input.from,
|
||||
to: fenced.effectiveFencedTo,
|
||||
asOf: fenced.effectiveFencedAsOf,
|
||||
});
|
||||
|
||||
const listingIdSet = new Set<number>(listingIds);
|
||||
const eligibleBars = filterEligibleBars(
|
||||
rawBars,
|
||||
listingIdSet,
|
||||
fenced.fromMs,
|
||||
fenced.toMs,
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
|
||||
const eligibleShortsTable = filterEligibleShortsTable(
|
||||
rawShortsTable,
|
||||
listingIdSet,
|
||||
utcDateOf(fenced.fromMs),
|
||||
utcDateOf(fenced.toMs),
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
|
||||
const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
||||
const built = buildForwardReturnPanel({
|
||||
bars: eligibleBars,
|
||||
signals,
|
||||
horizonSessions: input.horizonSessions,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
...(input.maxSignalAgeSessions !== undefined
|
||||
? { maxSignalAgeSessions: input.maxSignalAgeSessions }
|
||||
: {}),
|
||||
});
|
||||
|
||||
if (built.panel.length === 0) {
|
||||
const emptyAnalysis = analyzeSignalPanel([], {
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
});
|
||||
const payload: AnalyzeSignalResultPayload = {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: 'too_few_observations',
|
||||
panelDiagnostics: built.diagnostics,
|
||||
analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries),
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
}
|
||||
|
||||
const expression = buildCanonicalStudyExpression({
|
||||
input,
|
||||
listingIds,
|
||||
universeSnapshotDate,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
});
|
||||
|
||||
const studyResult = await analyzeSignal(ledger, {
|
||||
principalId,
|
||||
...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}),
|
||||
...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}),
|
||||
universeMarket: input.universeMarket,
|
||||
horizonBucket: input.horizonBucket,
|
||||
expression,
|
||||
panel: built.panel,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
ledgerSeries: input.ledgerSeries,
|
||||
});
|
||||
|
||||
const analysisSummary = projectAnalysisSummary(studyResult.analysis, input.ledgerSeries);
|
||||
|
||||
const payload: AnalyzeSignalResultPayload =
|
||||
studyResult.status === 'ok'
|
||||
? {
|
||||
...basePayloadFields,
|
||||
status: 'ok',
|
||||
panelDiagnostics: built.diagnostics,
|
||||
analysis: analysisSummary,
|
||||
trial: studyResult.trial,
|
||||
deflatedSharpe: studyResult.deflatedSharpe,
|
||||
}
|
||||
: {
|
||||
...basePayloadFields,
|
||||
status: 'insufficient_data',
|
||||
reason: studyResult.reason,
|
||||
panelDiagnostics: built.diagnostics,
|
||||
analysis: analysisSummary,
|
||||
};
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
return formatMappedAnalyzeSignalError(err);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -4,24 +4,20 @@ import {
|
|||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type VaultFenceContext,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
applyVaultFence,
|
||||
} from '../../market-data-store';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type AdjFactorsSnapshotErrorCode,
|
||||
MarketDataStoreNotImplementedError,
|
||||
} from '../../market-data-store-duckdb';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
import { type McpToolEntry, defineMcpTool } from '../server';
|
||||
|
||||
const INT32_MIN = -2_147_483_648;
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/;
|
||||
import {
|
||||
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||||
MCP_MAX_LISTING_IDS,
|
||||
createListingIdsFieldSchema,
|
||||
createUniverseFieldSchema,
|
||||
fenceVaultQueryBounds,
|
||||
formatMappedStoreError,
|
||||
hasExclusiveListingSelector,
|
||||
resolveUniverseDate,
|
||||
validateVaultCutoffTs,
|
||||
} from './vault-fenced-input';
|
||||
|
||||
/** Default maximum number of bar rows returned by `query_data`. */
|
||||
export const QUERY_DATA_DEFAULT_LIMIT = 500;
|
||||
|
|
@ -30,7 +26,7 @@ export const QUERY_DATA_DEFAULT_LIMIT = 500;
|
|||
export const QUERY_DATA_MAX_LIMIT = 5_000;
|
||||
|
||||
/** Hard maximum number of explicit `listingIds` accepted by `query_data`. */
|
||||
export const QUERY_DATA_MAX_LISTING_IDS = 500;
|
||||
export const QUERY_DATA_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS;
|
||||
|
||||
/**
|
||||
* Strict Zod input schema for the `query_data` MCP tool.
|
||||
|
|
@ -40,17 +36,12 @@ export const QUERY_DATA_MAX_LISTING_IDS = 500;
|
|||
*/
|
||||
export const queryDataInputSchema = z
|
||||
.object({
|
||||
listingIds: z
|
||||
.array(z.number().int().min(INT32_MIN).max(INT32_MAX))
|
||||
.min(1)
|
||||
.max(QUERY_DATA_MAX_LISTING_IDS)
|
||||
.optional()
|
||||
.describe('Explicit INT32 listing IDs to query (mutually exclusive with universe).'),
|
||||
universe: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'),
|
||||
listingIds: createListingIdsFieldSchema(
|
||||
'Explicit INT32 listing IDs to query (mutually exclusive with universe).'
|
||||
),
|
||||
universe: createUniverseFieldSchema(
|
||||
'Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'
|
||||
),
|
||||
from: z
|
||||
.string()
|
||||
.min(1)
|
||||
|
|
@ -83,10 +74,7 @@ export const queryDataInputSchema = z
|
|||
),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
data => (data.listingIds !== undefined) !== (data.universe !== undefined),
|
||||
'Exactly one of "listingIds" or "universe" must be provided.'
|
||||
);
|
||||
.refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE);
|
||||
|
||||
export type QueryDataInput = z.infer<typeof queryDataInputSchema>;
|
||||
|
||||
|
|
@ -113,166 +101,7 @@ export interface QueryDataResultPayload {
|
|||
readonly rows: readonly BarRecord[];
|
||||
}
|
||||
|
||||
const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
||||
'from',
|
||||
'to',
|
||||
'asOf',
|
||||
'date',
|
||||
'ref',
|
||||
'listingIds',
|
||||
'timeframe',
|
||||
'adjustment',
|
||||
'scope',
|
||||
'limit',
|
||||
]);
|
||||
|
||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||
'bars',
|
||||
'crossSection',
|
||||
'fundamentalsAsOf',
|
||||
'events',
|
||||
'shortsAsOf',
|
||||
'macroAsOf',
|
||||
'fx',
|
||||
'universe',
|
||||
]);
|
||||
|
||||
const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly<Record<AdjFactorsSnapshotErrorCode, string>> = {
|
||||
missing_snapshot:
|
||||
'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.',
|
||||
missing_metadata: 'Required adj_factors snapshot metadata is missing.',
|
||||
invalid_metadata: 'adj_factors snapshot metadata is invalid.',
|
||||
unsupported_version: 'adj_factors snapshot metadata version is unsupported.',
|
||||
retrospective_rejected:
|
||||
'Retrospective adj_factors snapshots are rejected for point-in-time queries.',
|
||||
incompatible_fence:
|
||||
'adj_factors snapshot fence does not match the query asOf or Vault cutoff.',
|
||||
path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.',
|
||||
unpinned_mutable_path:
|
||||
'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.',
|
||||
};
|
||||
|
||||
function utcDateOf(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function extractExplicitSubMsMicros(raw: string): number {
|
||||
const match = ISO_FRACTIONAL_RE.exec(raw);
|
||||
if (match === null) {
|
||||
return 0;
|
||||
}
|
||||
const frac = match[1] ?? '';
|
||||
if (frac.length <= 3) {
|
||||
return 0;
|
||||
}
|
||||
const microDigits = frac.slice(3, 6).padEnd(3, '0');
|
||||
return Number(microDigits);
|
||||
}
|
||||
|
||||
function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number {
|
||||
if (clampedTo || DATE_ONLY_RE.test(rawTo)) {
|
||||
return 999;
|
||||
}
|
||||
return extractExplicitSubMsMicros(rawTo);
|
||||
}
|
||||
|
||||
function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number {
|
||||
if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) {
|
||||
return 999;
|
||||
}
|
||||
return extractExplicitSubMsMicros(rawAsOf);
|
||||
}
|
||||
|
||||
function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string {
|
||||
const isoMs = new Date(epochMs).toISOString();
|
||||
if (subMsMicros === 0) {
|
||||
return isoMs;
|
||||
}
|
||||
const extra = String(subMsMicros).padStart(3, '0');
|
||||
return `${isoMs.slice(0, -1)}${extra}Z`;
|
||||
}
|
||||
|
||||
function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string {
|
||||
const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY;
|
||||
const dayEndMs = dayStartMs + MS_PER_DAY - 1;
|
||||
if (epochMs === dayEndMs && subMsMicros === 999) {
|
||||
return utcDateOf(dayStartMs);
|
||||
}
|
||||
return utcDateOf(dayStartMs - MS_PER_DAY);
|
||||
}
|
||||
|
||||
function resolveUniverseDate(
|
||||
toMs: number,
|
||||
toSubMs: number,
|
||||
asOfMs: number,
|
||||
asOfSubMs: number
|
||||
): string {
|
||||
if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) {
|
||||
return resolveCompletedUtcDate(asOfMs, asOfSubMs);
|
||||
}
|
||||
return resolveCompletedUtcDate(toMs, toSubMs);
|
||||
}
|
||||
|
||||
function formatMappedStoreError(err: unknown): McpToolCallResult | null {
|
||||
if (err instanceof VaultHoldoutFenceError) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.',
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof VaultScopeNotAuthorizedError) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof MarketDataStoreValidationError) {
|
||||
const text =
|
||||
err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field)
|
||||
? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".`
|
||||
: 'MarketDataStoreValidationError: Query parameters failed store validation.';
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof MarketDataStoreNotImplementedError) {
|
||||
const text = SAFE_STORE_METHODS.has(err.method)
|
||||
? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.`
|
||||
: 'MarketDataStoreNotImplementedError: Requested store operation is not supported.';
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof AdjFactorsSnapshotError) {
|
||||
const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code)
|
||||
? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code]
|
||||
: 'Adjusted bars snapshot verification failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: QueryDataToolOptions): void {
|
||||
function validateFactoryOptions(options: QueryDataToolOptions): number {
|
||||
if (
|
||||
typeof options.store !== 'object' ||
|
||||
options.store === null ||
|
||||
|
|
@ -285,18 +114,7 @@ function validateFactoryOptions(options: QueryDataToolOptions): void {
|
|||
);
|
||||
}
|
||||
|
||||
const cutoffTs = options.vaultContext?.vaultCutoffTs;
|
||||
if (
|
||||
typeof cutoffTs !== 'number' ||
|
||||
!Number.isFinite(cutoffTs) ||
|
||||
!Number.isSafeInteger(cutoffTs) ||
|
||||
Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`,
|
||||
'vaultCutoffTs'
|
||||
);
|
||||
}
|
||||
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -309,9 +127,8 @@ function validateFactoryOptions(options: QueryDataToolOptions): void {
|
|||
* hard max {@link QUERY_DATA_MAX_LIMIT}).
|
||||
*/
|
||||
export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry {
|
||||
validateFactoryOptions(options);
|
||||
const vaultCutoffTs = validateFactoryOptions(options);
|
||||
const { store } = options;
|
||||
const vaultCutoffTs = options.vaultContext.vaultCutoffTs;
|
||||
|
||||
return defineMcpTool({
|
||||
name: 'query_data',
|
||||
|
|
@ -320,30 +137,24 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry
|
|||
inputSchema: queryDataInputSchema,
|
||||
async handler(input: QueryDataInput): Promise<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
const fenced = fenceVaultQueryBounds(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
}
|
||||
vaultCutoffTs
|
||||
);
|
||||
|
||||
const effectiveLimit = input.limit;
|
||||
const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo);
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf);
|
||||
let listingIds: number[];
|
||||
|
||||
if (input.universe !== undefined) {
|
||||
const universeDate = resolveUniverseDate(
|
||||
fenced.toMs,
|
||||
toSubMs,
|
||||
fenced.toSubMs,
|
||||
fenced.asOfMs,
|
||||
asOfSubMs
|
||||
fenced.asOfSubMs
|
||||
);
|
||||
const resolved = await store.universe({
|
||||
ref: input.universe,
|
||||
|
|
@ -374,21 +185,13 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry
|
|||
listingIds = [...(input.listingIds ?? [])];
|
||||
}
|
||||
|
||||
const effectiveFencedTo = fenced.clampedTo
|
||||
? formatUtcIsoWithMicros(fenced.toMs, 999)
|
||||
: input.to;
|
||||
const effectiveFencedAsOf =
|
||||
fenced.clampedAsOf || input.asOf === undefined
|
||||
? formatUtcIsoWithMicros(fenced.asOfMs, 999)
|
||||
: input.asOf;
|
||||
|
||||
const stream = store.bars({
|
||||
listingIds,
|
||||
timeframe: input.timeframe,
|
||||
from: input.from,
|
||||
to: effectiveFencedTo,
|
||||
to: fenced.effectiveFencedTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: effectiveFencedAsOf,
|
||||
asOf: fenced.effectiveFencedAsOf,
|
||||
scope: 'vault_fenced',
|
||||
});
|
||||
|
||||
|
|
|
|||
322
libs/research/src/mcp/tools/vault-fenced-input.ts
Normal file
322
libs/research/src/mcp/tools/vault-fenced-input.ts
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
type FencedTimeRange,
|
||||
MarketDataStoreValidationError,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
applyVaultFence,
|
||||
} from '../../market-data-store';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type AdjFactorsSnapshotErrorCode,
|
||||
MarketDataStoreNotImplementedError,
|
||||
} from '../../market-data-store-duckdb';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
|
||||
export const INT32_MIN = -2_147_483_648;
|
||||
export const INT32_MAX = 2_147_483_647;
|
||||
export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
export const MS_PER_DAY = 86_400_000;
|
||||
|
||||
/** Hard maximum number of explicit `listingIds` accepted by Vault-fenced MCP tools. */
|
||||
export const MCP_MAX_LISTING_IDS = 500;
|
||||
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/;
|
||||
|
||||
export const EXCLUSIVE_LISTING_SELECTOR_MESSAGE =
|
||||
'Exactly one of "listingIds" or "universe" must be provided.';
|
||||
|
||||
/** Returns true when exactly one of `listingIds` or `universe` is supplied. */
|
||||
export function hasExclusiveListingSelector(data: {
|
||||
readonly listingIds?: readonly number[];
|
||||
readonly universe?: string;
|
||||
}): boolean {
|
||||
return (data.listingIds !== undefined) !== (data.universe !== undefined);
|
||||
}
|
||||
|
||||
/** Shared Zod field schema for explicit INT32 `listingIds` (1–500). */
|
||||
export function createListingIdsFieldSchema(description: string) {
|
||||
return z
|
||||
.array(z.number().int().min(INT32_MIN).max(INT32_MAX))
|
||||
.min(1)
|
||||
.max(MCP_MAX_LISTING_IDS)
|
||||
.optional()
|
||||
.describe(description);
|
||||
}
|
||||
|
||||
/** Shared Zod field schema for a named `universe` reference. */
|
||||
export function createUniverseFieldSchema(description: string) {
|
||||
return z.string().min(1).optional().describe(description);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a raw string is a valid calendar date (`YYYY-MM-DD`) or
|
||||
* UTC ISO-8601 timestamp with an explicit timezone offset (`Z` or `±HH:MM`).
|
||||
*/
|
||||
export function isValidUtcBoundString(raw: string): boolean {
|
||||
try {
|
||||
applyVaultFence(
|
||||
{ from: raw, to: raw, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates an injected server-side `vaultCutoffTs` epoch-ms boundary. */
|
||||
export function validateVaultCutoffTs(cutoffTs: unknown): number {
|
||||
if (
|
||||
typeof cutoffTs !== 'number' ||
|
||||
!Number.isFinite(cutoffTs) ||
|
||||
!Number.isSafeInteger(cutoffTs) ||
|
||||
Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`,
|
||||
'vaultCutoffTs'
|
||||
);
|
||||
}
|
||||
return cutoffTs;
|
||||
}
|
||||
|
||||
/** Returns the UTC calendar date (`YYYY-MM-DD`) for an epoch-ms timestamp. */
|
||||
export function utcDateOf(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function extractExplicitSubMsMicros(raw: string): number {
|
||||
const match = ISO_FRACTIONAL_RE.exec(raw);
|
||||
if (match === null) {
|
||||
return 0;
|
||||
}
|
||||
const frac = match[1] ?? '';
|
||||
if (frac.length <= 3) {
|
||||
return 0;
|
||||
}
|
||||
const microDigits = frac.slice(3, 6).padEnd(3, '0');
|
||||
return Number(microDigits);
|
||||
}
|
||||
|
||||
export function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number {
|
||||
if (clampedTo || DATE_ONLY_RE.test(rawTo)) {
|
||||
return 999;
|
||||
}
|
||||
return extractExplicitSubMsMicros(rawTo);
|
||||
}
|
||||
|
||||
export function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number {
|
||||
if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) {
|
||||
return 999;
|
||||
}
|
||||
return extractExplicitSubMsMicros(rawAsOf);
|
||||
}
|
||||
|
||||
export function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string {
|
||||
const isoMs = new Date(epochMs).toISOString();
|
||||
if (subMsMicros === 0) {
|
||||
return isoMs;
|
||||
}
|
||||
const extra = String(subMsMicros).padStart(3, '0');
|
||||
return `${isoMs.slice(0, -1)}${extra}Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the latest completed UTC calendar date at or before `(epochMs, subMsMicros)`.
|
||||
* A full day is completed only at `23:59:59.999999Z`; any earlier instant resolves
|
||||
* to the preceding UTC calendar date.
|
||||
*/
|
||||
export function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string {
|
||||
const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY;
|
||||
const dayEndMs = dayStartMs + MS_PER_DAY - 1;
|
||||
if (epochMs === dayEndMs && subMsMicros === 999) {
|
||||
return utcDateOf(dayStartMs);
|
||||
}
|
||||
return utcDateOf(dayStartMs - MS_PER_DAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the completed UTC date at `min(effectiveTo, effectiveAsOf)` for point-in-time
|
||||
* universe resolution in `query_data`.
|
||||
*/
|
||||
export function resolveUniverseDate(
|
||||
toMs: number,
|
||||
toSubMs: number,
|
||||
asOfMs: number,
|
||||
asOfSubMs: number
|
||||
): string {
|
||||
if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) {
|
||||
return resolveCompletedUtcDate(asOfMs, asOfSubMs);
|
||||
}
|
||||
return resolveCompletedUtcDate(toMs, toSubMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a fixed pre-study cohort date: the latest completed UTC date strictly
|
||||
* before the study start (`fromMs`) and no later than effective `asOf`.
|
||||
*/
|
||||
export function resolvePreStartUniverseDate(
|
||||
fromMs: number,
|
||||
asOfMs: number,
|
||||
asOfSubMs: number
|
||||
): string {
|
||||
const fromDayStartMs = Math.floor(fromMs / MS_PER_DAY) * MS_PER_DAY;
|
||||
const preStartDate = utcDateOf(fromDayStartMs - MS_PER_DAY);
|
||||
const asOfCompletedDate = resolveCompletedUtcDate(asOfMs, asOfSubMs);
|
||||
return asOfCompletedDate < preStartDate ? asOfCompletedDate : preStartDate;
|
||||
}
|
||||
|
||||
/** Result of fencing MCP query bounds against the server-injected Vault cutoff. */
|
||||
export interface VaultFencedBounds extends FencedTimeRange {
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly toSubMs: number;
|
||||
readonly asOfSubMs: number;
|
||||
readonly effectiveFencedTo: string;
|
||||
readonly effectiveFencedAsOf: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@link applyVaultFence} under `scope: 'vault_fenced'` with
|
||||
* `vaultOperatorAuthorized: false` and computes microsecond-preserving effective
|
||||
* `to` / `asOf` query strings.
|
||||
*/
|
||||
export function fenceVaultQueryBounds(
|
||||
input: { readonly from: string; readonly to: string; readonly asOf?: string },
|
||||
vaultCutoffTs: number
|
||||
): VaultFencedBounds {
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
}
|
||||
);
|
||||
|
||||
const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo);
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf);
|
||||
const effectiveFencedTo = fenced.clampedTo
|
||||
? formatUtcIsoWithMicros(fenced.toMs, 999)
|
||||
: input.to;
|
||||
const effectiveFencedAsOf =
|
||||
fenced.clampedAsOf || input.asOf === undefined
|
||||
? formatUtcIsoWithMicros(fenced.asOfMs, 999)
|
||||
: input.asOf;
|
||||
|
||||
return {
|
||||
...fenced,
|
||||
vaultCutoffDate: utcDateOf(vaultCutoffTs),
|
||||
toSubMs,
|
||||
asOfSubMs,
|
||||
effectiveFencedTo,
|
||||
effectiveFencedAsOf,
|
||||
};
|
||||
}
|
||||
|
||||
const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
||||
'from',
|
||||
'to',
|
||||
'asOf',
|
||||
'date',
|
||||
'ref',
|
||||
'listingIds',
|
||||
'timeframe',
|
||||
'adjustment',
|
||||
'scope',
|
||||
'limit',
|
||||
]);
|
||||
|
||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||
'bars',
|
||||
'crossSection',
|
||||
'fundamentalsAsOf',
|
||||
'events',
|
||||
'shortsAsOf',
|
||||
'macroAsOf',
|
||||
'fx',
|
||||
'universe',
|
||||
]);
|
||||
|
||||
const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly<Record<AdjFactorsSnapshotErrorCode, string>> = {
|
||||
missing_snapshot:
|
||||
'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.',
|
||||
missing_metadata: 'Required adj_factors snapshot metadata is missing.',
|
||||
invalid_metadata: 'adj_factors snapshot metadata is invalid.',
|
||||
unsupported_version: 'adj_factors snapshot metadata version is unsupported.',
|
||||
retrospective_rejected:
|
||||
'Retrospective adj_factors snapshots are rejected for point-in-time queries.',
|
||||
incompatible_fence:
|
||||
'adj_factors snapshot fence does not match the query asOf or Vault cutoff.',
|
||||
path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.',
|
||||
unpinned_mutable_path:
|
||||
'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.',
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps known `MarketDataStore` / Vault domain errors to fixed, sanitized
|
||||
* `isError: true` MCP tool results without leaking SQL, file paths, or URIs.
|
||||
*/
|
||||
export function formatMappedStoreError(err: unknown): McpToolCallResult | null {
|
||||
if (err instanceof VaultHoldoutFenceError) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.',
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof VaultScopeNotAuthorizedError) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.",
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof MarketDataStoreValidationError) {
|
||||
const text =
|
||||
err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field)
|
||||
? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".`
|
||||
: 'MarketDataStoreValidationError: Query parameters failed store validation.';
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof MarketDataStoreNotImplementedError) {
|
||||
const text = SAFE_STORE_METHODS.has(err.method)
|
||||
? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.`
|
||||
: 'MarketDataStoreNotImplementedError: Requested store operation is not supported.';
|
||||
return {
|
||||
content: [{ type: 'text', text }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (err instanceof AdjFactorsSnapshotError) {
|
||||
const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code)
|
||||
? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code]
|
||||
: 'Adjusted bars snapshot verification failed.';
|
||||
return {
|
||||
content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
1325
libs/research/test/mcp-analyze-signal.test.ts
Normal file
1325
libs/research/test/mcp-analyze-signal.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