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
5527cebc21
commit
ee6137c770
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,
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -217,6 +217,7 @@ interface CopilotStudyFixture {
|
|||
readonly postCutoffDate: string;
|
||||
readonly bars: readonly BarRecord[];
|
||||
readonly shortsTable: Table;
|
||||
readonly fundamentalsRows: readonly TableRow[];
|
||||
readonly eventsTable: Table;
|
||||
readonly symbols: readonly SymbolSearchRow[];
|
||||
readonly exchangeCalendars: EventStudyExchangeCalendars;
|
||||
|
|
@ -238,8 +239,42 @@ function buildCopilotStudyFixture(): CopilotStudyFixture {
|
|||
const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i);
|
||||
const bars: BarRecord[] = [];
|
||||
const shortsRows: TableRow[] = [];
|
||||
const fundamentalsRows: TableRow[] = [];
|
||||
const eventRows: TableRow[] = [];
|
||||
|
||||
const fundamentalReleaseIndices = [0, 22, 44, 64];
|
||||
for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) {
|
||||
const t = fundamentalReleaseIndices[rIdx]!;
|
||||
const relDate = allDates[t]!;
|
||||
const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15;
|
||||
const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25;
|
||||
fundamentalsRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
effective_known_at: effectiveKnownAt,
|
||||
known_at_source: 'sec_edgar_filing',
|
||||
has_estimated_lag: false,
|
||||
period_end: relDate,
|
||||
fiscal_period: `Q${(rIdx % 4) + 1}`,
|
||||
currency: 'USD',
|
||||
period_known_at: effectiveKnownAt,
|
||||
revenue,
|
||||
net_income: Number((revenue * 0.14).toFixed(2)),
|
||||
operating_cash_flow: Number((revenue * 0.19).toFixed(2)),
|
||||
total_assets: Number((revenue * 3.8).toFixed(2)),
|
||||
total_equity: Number((revenue * 1.7).toFixed(2)),
|
||||
shares_outstanding: 10_000_000,
|
||||
ttm_revenue: ttmRevenue,
|
||||
ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)),
|
||||
ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)),
|
||||
ttm_period_end: relDate,
|
||||
ttm_currency: 'USD',
|
||||
ttm_has_estimated_lag: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventDayIndices = [12, 20, 28, 38, 48, 58];
|
||||
const eventSet = new Set<string>();
|
||||
for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) {
|
||||
|
|
@ -362,6 +397,7 @@ function buildCopilotStudyFixture(): CopilotStudyFixture {
|
|||
columns: [...SHORTS_COLUMNS],
|
||||
rows: shortsRows,
|
||||
},
|
||||
fundamentalsRows,
|
||||
eventsTable: {
|
||||
columns: [...EVENTS_COLUMNS],
|
||||
rows: eventRows,
|
||||
|
|
@ -378,6 +414,7 @@ interface FakeMarketDataStoreHandle {
|
|||
readonly store: MarketDataStore;
|
||||
readonly getBarsCalls: () => number;
|
||||
readonly getShortsCalls: () => number;
|
||||
readonly getFundamentalsCalls: () => number;
|
||||
readonly getEventsCalls: () => number;
|
||||
readonly getUniverseCalls: () => number;
|
||||
}
|
||||
|
|
@ -391,6 +428,7 @@ function createFakeMarketDataStore(
|
|||
const leaky = options?.leakyVaultRows ?? false;
|
||||
let barsCalls = 0;
|
||||
let shortsCalls = 0;
|
||||
let fundamentalsCalls = 0;
|
||||
let eventsCalls = 0;
|
||||
let universeCalls = 0;
|
||||
|
||||
|
|
@ -537,8 +575,63 @@ function createFakeMarketDataStore(
|
|||
async crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
async fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
async fundamentalsAsOf(q): Promise<Table> {
|
||||
fundamentalsCalls += 1;
|
||||
const idSet = new Set(q.listingIds);
|
||||
const asOfMs = parseBoundMs(q.asOf, true);
|
||||
const allowEstimatedLag = q.allowEstimatedLag ?? false;
|
||||
const latestByListing = new Map<number, TableRow>();
|
||||
|
||||
for (const row of fixture.fundamentalsRows) {
|
||||
const listingId = row.listing_id as number;
|
||||
const knownAt = row.effective_known_at as number;
|
||||
if (!idSet.has(listingId) || knownAt > asOfMs) {
|
||||
continue;
|
||||
}
|
||||
const prev = latestByListing.get(listingId);
|
||||
if (prev === undefined || knownAt > (prev.effective_known_at as number)) {
|
||||
latestByListing.set(listingId, row);
|
||||
}
|
||||
}
|
||||
|
||||
const rows: TableRow[] = [];
|
||||
for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) {
|
||||
const row = latestByListing.get(lid)!;
|
||||
if (!allowEstimatedLag && row.has_estimated_lag === true) {
|
||||
continue;
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
if (leaky) {
|
||||
rows.push({
|
||||
listing_id: fixture.listingIds[0]!,
|
||||
effective_known_at: fixture.vaultCutoffTs,
|
||||
known_at_source: 'sec_edgar_filing',
|
||||
has_estimated_lag: false,
|
||||
period_end: fixture.vaultCutoffDate,
|
||||
fiscal_period: 'Q4',
|
||||
currency: 'USD',
|
||||
period_known_at: fixture.vaultCutoffTs,
|
||||
revenue: 999_999,
|
||||
ttm_revenue: 999_999,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
columns: [
|
||||
'listing_id',
|
||||
'effective_known_at',
|
||||
'known_at_source',
|
||||
'has_estimated_lag',
|
||||
'period_end',
|
||||
'fiscal_period',
|
||||
'currency',
|
||||
'period_known_at',
|
||||
...q.fields,
|
||||
],
|
||||
rows,
|
||||
};
|
||||
},
|
||||
async macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
|
|
@ -552,6 +645,7 @@ function createFakeMarketDataStore(
|
|||
store,
|
||||
getBarsCalls: () => barsCalls,
|
||||
getShortsCalls: () => shortsCalls,
|
||||
getFundamentalsCalls: () => fundamentalsCalls,
|
||||
getEventsCalls: () => eventsCalls,
|
||||
getUniverseCalls: () => universeCalls,
|
||||
};
|
||||
|
|
@ -763,13 +857,14 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal -> event_study -> read_knowledge -> file_finding in one stdio session', async () => {
|
||||
test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => {
|
||||
const fixture = buildCopilotStudyFixture();
|
||||
const { serverOptions, ledger, findings } = buildComposedServerOptions(fixture);
|
||||
const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture);
|
||||
const server = createResearchCopilotMcpServer(serverOptions);
|
||||
const sink = createMemoryOutput();
|
||||
|
||||
let signalTrialRef = '';
|
||||
let shortsTrialRef = '';
|
||||
let fundamentalsTrialRef = '';
|
||||
|
||||
async function* requestStream(): AsyncGenerator<string> {
|
||||
yield `${JSON.stringify({
|
||||
|
|
@ -839,6 +934,25 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
jsonrpc: '2.0',
|
||||
id: 6,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'analyze_signal',
|
||||
arguments: {
|
||||
listingIds: [...fixture.listingIds],
|
||||
from: fixture.firstDate,
|
||||
to: fixture.lastPreCutoffDate,
|
||||
signal: { source: 'fundamentals', field: 'ttm_revenue' },
|
||||
horizonSessions: 5,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
},
|
||||
})}\n`;
|
||||
|
||||
yield `${JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 7,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'event_study',
|
||||
arguments: {
|
||||
|
|
@ -858,7 +972,7 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
|
||||
yield `${JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 7,
|
||||
id: 8,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'read_knowledge',
|
||||
|
|
@ -866,28 +980,36 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
},
|
||||
})}\n`;
|
||||
|
||||
// Decode the earlier analyze_signal response written by runStdioServer before
|
||||
// constructing the file_finding call so the trialRef is dynamically linked.
|
||||
expect(sink.lines.length).toBeGreaterThanOrEqual(5);
|
||||
const signalResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope;
|
||||
const signalPayload = decodeToolJson<AnalyzeSignalResultPayload>(signalResp);
|
||||
expect(signalPayload.status).toBe('ok');
|
||||
if (signalPayload.status !== 'ok') {
|
||||
throw new Error('Expected analyze_signal status to be ok.');
|
||||
// Decode both earlier analyze_signal responses written by runStdioServer before
|
||||
// constructing the file_finding call so both trialRefs are dynamically linked.
|
||||
expect(sink.lines.length).toBeGreaterThanOrEqual(6);
|
||||
const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope;
|
||||
const shortsPayload = decodeToolJson<AnalyzeSignalResultPayload>(shortsResp);
|
||||
expect(shortsPayload.status).toBe('ok');
|
||||
if (shortsPayload.status !== 'ok') {
|
||||
throw new Error('Expected shorts analyze_signal status to be ok.');
|
||||
}
|
||||
signalTrialRef = String(signalPayload.trial.trialId);
|
||||
shortsTrialRef = String(shortsPayload.trial.trialId);
|
||||
|
||||
const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope;
|
||||
const fundamentalsPayload = decodeToolJson<AnalyzeSignalResultPayload>(fundamentalsResp);
|
||||
expect(fundamentalsPayload.status).toBe('ok');
|
||||
if (fundamentalsPayload.status !== 'ok') {
|
||||
throw new Error('Expected fundamentals analyze_signal status to be ok.');
|
||||
}
|
||||
fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId);
|
||||
|
||||
yield `${JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 8,
|
||||
id: 9,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'file_finding',
|
||||
arguments: {
|
||||
kind: 'finding',
|
||||
title: 'Short-interest net_change study on synthetic US_EQ panel',
|
||||
title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel',
|
||||
summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`,
|
||||
trialRefs: [signalTrialRef],
|
||||
trialRefs: [shortsTrialRef, fundamentalsTrialRef],
|
||||
evidenceRefs: [FIXTURE_DATASET_ID],
|
||||
idempotencyKey: 'copilot-e2e-finding-1',
|
||||
},
|
||||
|
|
@ -899,10 +1021,10 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
|
||||
const rawOut = sink.text();
|
||||
expect(rawOut.endsWith('\n')).toBe(true);
|
||||
expect(sink.lines).toHaveLength(8);
|
||||
expect(sink.lines).toHaveLength(9);
|
||||
|
||||
const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope);
|
||||
expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
for (const resp of responses) {
|
||||
expect(resp.error).toBeUndefined();
|
||||
}
|
||||
|
|
@ -933,16 +1055,34 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
expect(queryPayload.truncated).toBe(true);
|
||||
expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true);
|
||||
|
||||
// 5. analyze_signal
|
||||
const signalPayload = decodeToolJson<AnalyzeSignalResultPayload>(responses[4]!);
|
||||
expect(signalPayload.status).toBe('ok');
|
||||
if (signalPayload.status !== 'ok') {
|
||||
throw new Error('Expected analyze_signal status to be ok.');
|
||||
// 5. analyze_signal (shorts)
|
||||
const shortsSignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(responses[4]!);
|
||||
expect(shortsSignalPayload.status).toBe('ok');
|
||||
if (shortsSignalPayload.status !== 'ok') {
|
||||
throw new Error('Expected shorts analyze_signal status to be ok.');
|
||||
}
|
||||
expect(String(signalPayload.trial.trialId)).toBe(signalTrialRef);
|
||||
expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' });
|
||||
expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef);
|
||||
|
||||
// 6. event_study
|
||||
const eventPayload = decodeToolJson<EventStudyResultPayload>(responses[5]!);
|
||||
// 6. analyze_signal (fundamentals)
|
||||
const fundamentalsSignalPayload = decodeToolJson<AnalyzeSignalResultPayload>(responses[5]!);
|
||||
expect(fundamentalsSignalPayload.status).toBe('ok');
|
||||
if (fundamentalsSignalPayload.status !== 'ok') {
|
||||
throw new Error('Expected fundamentals analyze_signal status to be ok.');
|
||||
}
|
||||
expect(fundamentalsSignalPayload.signal).toEqual({
|
||||
source: 'fundamentals',
|
||||
field: 'ttm_revenue',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef);
|
||||
expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe(
|
||||
shortsSignalPayload.trial.expressionHash
|
||||
);
|
||||
expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0);
|
||||
|
||||
// 7. event_study
|
||||
const eventPayload = decodeToolJson<EventStudyResultPayload>(responses[6]!);
|
||||
expect(eventPayload.status).toBe('ok');
|
||||
if (eventPayload.status !== 'ok') {
|
||||
throw new Error('Expected event_study status to be ok.');
|
||||
|
|
@ -950,27 +1090,29 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
expect(eventPayload.benchmark).toBe('equal_weight');
|
||||
expect(eventPayload.study.hasBenchmark).toBe(true);
|
||||
|
||||
// 7. read_knowledge
|
||||
const knowledgePayload = decodeToolJson<ReadKnowledgeResultPayload>(responses[6]!);
|
||||
// 8. read_knowledge
|
||||
const knowledgePayload = decodeToolJson<ReadKnowledgeResultPayload>(responses[7]!);
|
||||
expect(knowledgePayload.rowCount).toBe(1);
|
||||
expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01');
|
||||
|
||||
// 8. file_finding
|
||||
const findingPayload = decodeToolJson<FileFindingResultPayload>(responses[7]!);
|
||||
// 9. file_finding
|
||||
const findingPayload = decodeToolJson<FileFindingResultPayload>(responses[8]!);
|
||||
expect(findingPayload).toEqual({
|
||||
id: FIXED_FINDING_ID,
|
||||
createdAt: FIXED_NOW_ISO,
|
||||
created: true,
|
||||
});
|
||||
|
||||
// Verify trial_ledger recorded both stages under AGENT_PRINCIPAL and matches responses.
|
||||
expect(ledger.rows).toHaveLength(2);
|
||||
expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']);
|
||||
// Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL.
|
||||
expect(ledger.rows).toHaveLength(3);
|
||||
expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']);
|
||||
expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true);
|
||||
expect(ledger.rows[0]?.trial_id).toBe(String(signalPayload.trial.trialId));
|
||||
expect(ledger.rows[1]?.trial_id).toBe(String(eventPayload.trial.trialId));
|
||||
expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId));
|
||||
expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId));
|
||||
expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId));
|
||||
expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash);
|
||||
|
||||
// Verify FindingWritePort recorded exactly one pending_review finding referencing signal trial.
|
||||
// Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials.
|
||||
expect(findings.appendCalls).toHaveLength(1);
|
||||
expect(findings.stored).toHaveLength(1);
|
||||
expect(findings.stored[0]).toMatchObject({
|
||||
|
|
@ -978,7 +1120,7 @@ describe('createResearchCopilotMcpServer', () => {
|
|||
createdAt: findingPayload.createdAt,
|
||||
kind: 'finding',
|
||||
status: 'pending_review',
|
||||
trialRefs: [signalTrialRef],
|
||||
trialRefs: [shortsTrialRef, fundamentalsTrialRef],
|
||||
evidenceRefs: [FIXTURE_DATASET_ID],
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue