T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps)
This commit is contained in:
parent
60f972bd53
commit
b49bbd59b4
3 changed files with 1554 additions and 87 deletions
|
|
@ -14,10 +14,14 @@ import {
|
|||
type TableRow,
|
||||
type VaultFenceContext,
|
||||
} from '../../market-data-store';
|
||||
import { UNIVERSE_REFS } from '../../market-data-store-duckdb';
|
||||
import {
|
||||
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
||||
type FundamentalsPitValueField,
|
||||
UNIVERSE_REFS,
|
||||
} from '../../market-data-store-duckdb';
|
||||
import {
|
||||
SHORTS_SIGNAL_FIELDS,
|
||||
type ShortsSignalField,
|
||||
type SignalObservation,
|
||||
type SignalPanelDiagnostics,
|
||||
SignalPanelError,
|
||||
type SignalPanelErrorCode,
|
||||
|
|
@ -44,8 +48,8 @@ import {
|
|||
UNIVERSE_MARKETS,
|
||||
type UniverseMarket,
|
||||
} from '../../trial-ledger';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
import { type McpToolEntry, defineMcpTool } from '../server';
|
||||
import type { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol';
|
||||
import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server';
|
||||
import {
|
||||
EXCLUSIVE_LISTING_SELECTOR_MESSAGE,
|
||||
MCP_MAX_LISTING_IDS,
|
||||
|
|
@ -53,6 +57,7 @@ import {
|
|||
createUniverseFieldSchema,
|
||||
fenceVaultQueryBounds,
|
||||
formatMappedStoreError,
|
||||
formatUtcIsoWithMicros,
|
||||
hasExclusiveListingSelector,
|
||||
isValidUtcBoundString,
|
||||
resolvePreStartUniverseDate,
|
||||
|
|
@ -69,6 +74,9 @@ 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;
|
||||
|
||||
/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */
|
||||
export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120;
|
||||
|
||||
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}$/;
|
||||
|
|
@ -84,22 +92,37 @@ const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC
|
|||
|
||||
const shortsSignalSpecSchema = z
|
||||
.object({
|
||||
source: z.literal('shorts').describe('Signal data source (currently "shorts").'),
|
||||
source: z.literal('shorts').describe('Signal data source ("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.');
|
||||
.describe('Short-interest signal 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
|
||||
const fundamentalsSignalSpecSchema = z
|
||||
.object({
|
||||
source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'),
|
||||
field: z
|
||||
.enum(FUNDAMENTALS_PIT_VALUE_FIELDS)
|
||||
.describe(
|
||||
'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).'
|
||||
),
|
||||
allowEstimatedLag: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe(
|
||||
'Whether to include fundamentals snapshots with estimated publication lag (default false).'
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.describe('Point-in-time fundamentals signal specification.');
|
||||
|
||||
const signalSpecSchema = z
|
||||
.discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema])
|
||||
.describe('Discriminated signal source and field specification ("shorts" or "fundamentals").');
|
||||
|
||||
const analyzeSignalSharedFieldsSchema = z
|
||||
.object({
|
||||
listingIds: createListingIdsFieldSchema(
|
||||
'Explicit INT32 listing IDs to study (mutually exclusive with universe).'
|
||||
|
|
@ -118,7 +141,6 @@ export const analyzeSignalInputSchema = z
|
|||
.describe(
|
||||
'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'
|
||||
),
|
||||
signal: shortsSignalSpecSchema,
|
||||
horizonSessions: z
|
||||
.number()
|
||||
.int()
|
||||
|
|
@ -159,6 +181,19 @@ export const analyzeSignalInputSchema = z
|
|||
.default('raw')
|
||||
.describe('Bar price adjustment mode (default raw).'),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/**
|
||||
* 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 = analyzeSignalSharedFieldsSchema
|
||||
.extend({
|
||||
signal: signalSpecSchema,
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, ctx) => {
|
||||
if (!hasExclusiveListingSelector(data)) {
|
||||
|
|
@ -185,18 +220,62 @@ export const analyzeSignalInputSchema = z
|
|||
message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`,
|
||||
});
|
||||
}
|
||||
} else if (data.signal.source === 'shorts' && data.universeMarket === 'FX') {
|
||||
} else if (data.universeMarket === 'FX') {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['universeMarket'],
|
||||
message:
|
||||
'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).',
|
||||
data.signal.source === 'shorts'
|
||||
? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).'
|
||||
: 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type AnalyzeSignalInput = z.infer<typeof analyzeSignalInputSchema>;
|
||||
|
||||
function buildAnalyzeSignalJsonSchema(): JsonSchemaObject {
|
||||
const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema);
|
||||
const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema);
|
||||
const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema);
|
||||
const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? {
|
||||
type: 'boolean' as const,
|
||||
default: false,
|
||||
};
|
||||
const signalProperty: JsonSchemaProperty = {
|
||||
type: 'object',
|
||||
description: signalSpecSchema.description,
|
||||
properties: {
|
||||
source: {
|
||||
type: 'string',
|
||||
enum: ['shorts', 'fundamentals'],
|
||||
description: 'Signal data source ("shorts" or "fundamentals").',
|
||||
},
|
||||
field: {
|
||||
type: 'string',
|
||||
enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS],
|
||||
description: 'Signal field name valid for the chosen source.',
|
||||
},
|
||||
allowEstimatedLag: allowEstimatedLagProp,
|
||||
},
|
||||
required: ['source', 'field'],
|
||||
additionalProperties: false,
|
||||
anyOf: [shortsBranch, fundamentalsBranch],
|
||||
};
|
||||
|
||||
return {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...sharedSchema.properties,
|
||||
signal: signalProperty,
|
||||
},
|
||||
required: [...(sharedSchema.required ?? []), 'signal'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
}
|
||||
|
||||
const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema();
|
||||
|
||||
/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */
|
||||
export interface AnalyzeSignalToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
|
|
@ -250,10 +329,7 @@ interface AnalyzeSignalResultBase {
|
|||
readonly scope: 'vault_fenced';
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly signal: {
|
||||
readonly source: 'shorts';
|
||||
readonly field: ShortsSignalField;
|
||||
};
|
||||
readonly signal: AnalyzeSignalInput['signal'];
|
||||
readonly horizonSessions: number;
|
||||
readonly adjustment: 'raw' | 'split' | 'total';
|
||||
readonly universeMarket: UniverseMarket;
|
||||
|
|
@ -463,6 +539,127 @@ function filterEligibleShortsTable(
|
|||
};
|
||||
}
|
||||
|
||||
function deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] {
|
||||
const latestByMonth = new Map<string, string>();
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const bar = bars[i];
|
||||
if (
|
||||
typeof bar !== 'object' ||
|
||||
bar === null ||
|
||||
typeof bar.ts !== 'number' ||
|
||||
!Number.isFinite(bar.ts)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const sessionDate = utcDateOf(bar.ts);
|
||||
const monthKey = sessionDate.slice(0, 7);
|
||||
const prev = latestByMonth.get(monthKey);
|
||||
if (prev === undefined || sessionDate > prev) {
|
||||
latestByMonth.set(monthKey, sessionDate);
|
||||
}
|
||||
}
|
||||
return [...latestByMonth.values()].sort();
|
||||
}
|
||||
|
||||
function resolveSnapshotAsOf(
|
||||
snapshotDate: string,
|
||||
fencedAsOfMs: number,
|
||||
canonicalAsOf: string
|
||||
): { readonly asOf: string; readonly asOfMs: number } {
|
||||
const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`);
|
||||
if (fencedAsOfMs <= snapshotDayEndMs) {
|
||||
return {
|
||||
asOf: canonicalAsOf,
|
||||
asOfMs: fencedAsOfMs,
|
||||
};
|
||||
}
|
||||
return {
|
||||
asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999),
|
||||
asOfMs: snapshotDayEndMs,
|
||||
};
|
||||
}
|
||||
|
||||
function appendEligibleFundamentalsObservations(params: {
|
||||
readonly table: Table;
|
||||
readonly field: FundamentalsPitValueField;
|
||||
readonly listingIdSet: ReadonlySet<number>;
|
||||
readonly snapshotAsOfMs: number;
|
||||
readonly fencedAsOfMs: number;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly seenKeys: Set<string>;
|
||||
readonly out: SignalObservation[];
|
||||
}): void {
|
||||
const {
|
||||
table,
|
||||
field,
|
||||
listingIdSet,
|
||||
snapshotAsOfMs,
|
||||
fencedAsOfMs,
|
||||
vaultCutoffTs,
|
||||
seenKeys,
|
||||
out,
|
||||
} = params;
|
||||
|
||||
if (
|
||||
typeof table !== 'object' ||
|
||||
table === null ||
|
||||
!Array.isArray(table.columns) ||
|
||||
!Array.isArray(table.rows)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected a fundamentals Table object with array columns and rows.'
|
||||
);
|
||||
}
|
||||
|
||||
for (let i = 0; i < table.rows.length; i += 1) {
|
||||
const row = table.rows[i];
|
||||
if (typeof row !== 'object' || row === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const listingId = row.listing_id;
|
||||
if (
|
||||
typeof listingId !== 'number' ||
|
||||
!Number.isSafeInteger(listingId) ||
|
||||
!listingIdSet.has(listingId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const knownAt = row.effective_known_at;
|
||||
if (
|
||||
typeof knownAt !== 'number' ||
|
||||
!Number.isFinite(knownAt) ||
|
||||
!Number.isSafeInteger(knownAt)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rawValue = row[field];
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedListingId = listingId === 0 ? 0 : listingId;
|
||||
const normalizedKnownAt = knownAt === 0 ? 0 : knownAt;
|
||||
const normalizedValue = rawValue === 0 ? 0 : rawValue;
|
||||
const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`;
|
||||
if (seenKeys.has(dedupeKey)) {
|
||||
continue;
|
||||
}
|
||||
seenKeys.add(dedupeKey);
|
||||
out.push({
|
||||
listingId: normalizedListingId,
|
||||
knownAt: normalizedKnownAt,
|
||||
value: normalizedValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function buildCanonicalStudyExpression(params: {
|
||||
readonly input: AnalyzeSignalInput;
|
||||
readonly listingIds: readonly number[];
|
||||
|
|
@ -479,6 +676,9 @@ function buildCanonicalStudyExpression(params: {
|
|||
version: 1,
|
||||
signalSource: input.signal.source,
|
||||
signalField: input.signal.field,
|
||||
...(input.signal.source === 'fundamentals'
|
||||
? { allowEstimatedLag: input.signal.allowEstimatedLag }
|
||||
: {}),
|
||||
horizonSessions: input.horizonSessions,
|
||||
maxSignalAgeSessions: input.maxSignalAgeSessions ?? null,
|
||||
adjustment: input.adjustment,
|
||||
|
|
@ -553,10 +753,11 @@ function validateFactoryOptions(options: AnalyzeSignalToolOptions): number {
|
|||
options.store === null ||
|
||||
typeof options.store.bars !== 'function' ||
|
||||
typeof options.store.shortsAsOf !== 'function' ||
|
||||
typeof options.store.fundamentalsAsOf !== 'function' ||
|
||||
typeof options.store.universe !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, and `universe`.',
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, and `universe`.',
|
||||
'store'
|
||||
);
|
||||
}
|
||||
|
|
@ -602,8 +803,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
return defineMcpTool({
|
||||
name: 'analyze_signal',
|
||||
description:
|
||||
'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.',
|
||||
'Run a Vault-fenced cross-sectional short-interest or point-in-time fundamentals signal study and record eligible trials to trial_ledger.',
|
||||
inputSchema: analyzeSignalInputSchema,
|
||||
jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA,
|
||||
async handler(input: AnalyzeSignalInput): Promise<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = fenceVaultQueryBounds(
|
||||
|
|
@ -633,14 +835,23 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
listingIds = sortAndDedupeListingIds(input.listingIds ?? []);
|
||||
}
|
||||
|
||||
const signalEcho: AnalyzeSignalInput['signal'] =
|
||||
input.signal.source === 'shorts'
|
||||
? {
|
||||
source: 'shorts',
|
||||
field: input.signal.field,
|
||||
}
|
||||
: {
|
||||
source: 'fundamentals',
|
||||
field: input.signal.field,
|
||||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||||
};
|
||||
|
||||
const basePayloadFields = {
|
||||
scope: 'vault_fenced' as const,
|
||||
vaultCutoffTs,
|
||||
vaultCutoffDate: fenced.vaultCutoffDate,
|
||||
signal: {
|
||||
source: input.signal.source,
|
||||
field: input.signal.field,
|
||||
},
|
||||
signal: signalEcho,
|
||||
horizonSessions: input.horizonSessions,
|
||||
adjustment: input.adjustment,
|
||||
universeMarket: input.universeMarket,
|
||||
|
|
@ -684,13 +895,6 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
})
|
||||
);
|
||||
|
||||
const rawShortsTable = await store.shortsAsOf({
|
||||
listingIds,
|
||||
from: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
});
|
||||
|
||||
const listingIdSet = new Set<number>(listingIds);
|
||||
const eligibleBars = filterEligibleBars(
|
||||
rawBars,
|
||||
|
|
@ -702,17 +906,65 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
|
|||
fenced.vaultCutoffDate
|
||||
);
|
||||
|
||||
const eligibleShortsTable = filterEligibleShortsTable(
|
||||
rawShortsTable,
|
||||
listingIdSet,
|
||||
utcDateOf(fenced.fromMs),
|
||||
utcDateOf(fenced.toMs),
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
let signals: SignalObservation[];
|
||||
if (input.signal.source === 'shorts') {
|
||||
const rawShortsTable = await store.shortsAsOf({
|
||||
listingIds,
|
||||
from: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
});
|
||||
const eligibleShortsTable = filterEligibleShortsTable(
|
||||
rawShortsTable,
|
||||
listingIdSet,
|
||||
utcDateOf(fenced.fromMs),
|
||||
utcDateOf(fenced.toMs),
|
||||
fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
fenced.vaultCutoffDate
|
||||
);
|
||||
signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
||||
} else {
|
||||
const snapshotDates = deriveMonthlySnapshotDates(eligibleBars);
|
||||
if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
|
||||
signals = [];
|
||||
const seenKeys = new Set<string>();
|
||||
for (const snapshotDate of snapshotDates) {
|
||||
const snapshot = resolveSnapshotAsOf(
|
||||
snapshotDate,
|
||||
fenced.asOfMs,
|
||||
fenced.canonicalAsOf
|
||||
);
|
||||
const rawTable = await store.fundamentalsAsOf({
|
||||
listingIds,
|
||||
fields: [input.signal.field],
|
||||
asOf: snapshot.asOf,
|
||||
allowEstimatedLag: input.signal.allowEstimatedLag,
|
||||
});
|
||||
appendEligibleFundamentalsObservations({
|
||||
table: rawTable,
|
||||
field: input.signal.field,
|
||||
listingIdSet,
|
||||
snapshotAsOfMs: snapshot.asOfMs,
|
||||
fencedAsOfMs: fenced.asOfMs,
|
||||
vaultCutoffTs,
|
||||
seenKeys,
|
||||
out: signals,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field);
|
||||
const built = buildForwardReturnPanel({
|
||||
bars: eligibleBars,
|
||||
signals,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue