T-129: M2.1a — MCP copilot core: dependency-free JSON-RPC/MCP stdio server + tool registry + vault-fenced query_data in libs/research/src/mcp/
This commit is contained in:
parent
c48781811c
commit
8d706b1039
3 changed files with 607 additions and 37 deletions
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from '../../market-data-store';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type AdjFactorsSnapshotErrorCode,
|
||||
MarketDataStoreNotImplementedError,
|
||||
} from '../../market-data-store-duckdb';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
|
|
@ -18,6 +19,9 @@ 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})$/;
|
||||
|
||||
/** Default maximum number of bar rows returned by `query_data`. */
|
||||
export const QUERY_DATA_DEFAULT_LIMIT = 500;
|
||||
|
|
@ -109,39 +113,163 @@ 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 formatUtcIsoMs(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString();
|
||||
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 formatDomainError(err: Error): McpToolCallResult {
|
||||
const firstLine = err.message
|
||||
.split(/\r?\n/, 1)[0]
|
||||
?.replace(/\s+at\s+\S.*$/u, '')
|
||||
.trim();
|
||||
const detail = firstLine !== undefined && firstLine.length > 0 ? firstLine : 'Query failed.';
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `${err.name}: ${detail}`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number {
|
||||
if (clampedTo || DATE_ONLY_RE.test(rawTo)) {
|
||||
return 999;
|
||||
}
|
||||
return extractExplicitSubMsMicros(rawTo);
|
||||
}
|
||||
|
||||
function isMappedStoreError(err: unknown): err is Error {
|
||||
return (
|
||||
err instanceof VaultHoldoutFenceError ||
|
||||
err instanceof VaultScopeNotAuthorizedError ||
|
||||
err instanceof MarketDataStoreValidationError ||
|
||||
err instanceof MarketDataStoreNotImplementedError ||
|
||||
err instanceof AdjFactorsSnapshotError
|
||||
);
|
||||
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 {
|
||||
|
|
@ -206,12 +334,20 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry
|
|||
);
|
||||
|
||||
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.asOfMs,
|
||||
asOfSubMs
|
||||
);
|
||||
const resolved = await store.universe({
|
||||
ref: input.universe,
|
||||
date: utcDateOf(fenced.toMs),
|
||||
date: universeDate,
|
||||
});
|
||||
if (resolved.length === 0) {
|
||||
const emptyPayload: QueryDataResultPayload = {
|
||||
|
|
@ -238,10 +374,12 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry
|
|||
listingIds = [...(input.listingIds ?? [])];
|
||||
}
|
||||
|
||||
const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoMs(fenced.toMs) : input.to;
|
||||
const effectiveFencedTo = fenced.clampedTo
|
||||
? formatUtcIsoWithMicros(fenced.toMs, 999)
|
||||
: input.to;
|
||||
const effectiveFencedAsOf =
|
||||
fenced.clampedAsOf || input.asOf === undefined
|
||||
? formatUtcIsoMs(fenced.asOfMs)
|
||||
? formatUtcIsoWithMicros(fenced.asOfMs, 999)
|
||||
: input.asOf;
|
||||
|
||||
const stream = store.bars({
|
||||
|
|
@ -297,8 +435,9 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry
|
|||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
if (isMappedStoreError(err)) {
|
||||
return formatDomainError(err);
|
||||
const mapped = formatMappedStoreError(err);
|
||||
if (mapped !== null) {
|
||||
return mapped;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue