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
0bea9a6f1d
commit
73ac978bb3
10 changed files with 2266 additions and 0 deletions
307
libs/research/src/mcp/tools/query-data.ts
Normal file
307
libs/research/src/mcp/tools/query-data.ts
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type VaultFenceContext,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
applyVaultFence,
|
||||
} from '../../market-data-store';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
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;
|
||||
|
||||
/** Default maximum number of bar rows returned by `query_data`. */
|
||||
export const QUERY_DATA_DEFAULT_LIMIT = 500;
|
||||
|
||||
/** Hard maximum number of bar rows returned by `query_data`. */
|
||||
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;
|
||||
|
||||
/**
|
||||
* Strict Zod input schema for the `query_data` MCP tool.
|
||||
*
|
||||
* Intentionally omits `scope` and `vault_evaluation_only`; `.strict()` rejects
|
||||
* any caller attempt to supply them or any other unknown key.
|
||||
*/
|
||||
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).'),
|
||||
from: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe('Inclusive start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'),
|
||||
to: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe('Inclusive end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'),
|
||||
timeframe: z
|
||||
.enum(['1m', '5m', '1h', '1d'])
|
||||
.default('1d')
|
||||
.describe('Bar timeframe (default 1d).'),
|
||||
adjustment: z
|
||||
.enum(['raw', 'split', 'total'])
|
||||
.default('raw')
|
||||
.describe('Price/volume adjustment mode (default raw).'),
|
||||
asOf: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(QUERY_DATA_MAX_LIMIT)
|
||||
.default(QUERY_DATA_DEFAULT_LIMIT)
|
||||
.describe(
|
||||
`Maximum number of bar rows to return (default ${QUERY_DATA_DEFAULT_LIMIT}, max ${QUERY_DATA_MAX_LIMIT}).`
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
data => (data.listingIds !== undefined) !== (data.universe !== undefined),
|
||||
'Exactly one of "listingIds" or "universe" must be provided.'
|
||||
);
|
||||
|
||||
export type QueryDataInput = z.infer<typeof queryDataInputSchema>;
|
||||
|
||||
/** Configuration for {@link createQueryDataTool}. */
|
||||
export interface QueryDataToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||||
}
|
||||
|
||||
/** Structured JSON payload serialized into the `query_data` MCP text result. */
|
||||
export interface QueryDataResultPayload {
|
||||
readonly scope: 'vault_fenced';
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly timeframe: '1m' | '5m' | '1h' | '1d';
|
||||
readonly adjustment: 'raw' | 'split' | 'total';
|
||||
readonly fromMs: number;
|
||||
readonly toMs: number;
|
||||
readonly asOfMs: number;
|
||||
readonly clampedTo: boolean;
|
||||
readonly clampedAsOf: boolean;
|
||||
readonly limit: number;
|
||||
readonly rowCount: number;
|
||||
readonly truncated: boolean;
|
||||
readonly rows: readonly BarRecord[];
|
||||
}
|
||||
|
||||
function utcDateOf(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function formatUtcIsoMs(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString();
|
||||
}
|
||||
|
||||
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 isMappedStoreError(err: unknown): err is Error {
|
||||
return (
|
||||
err instanceof VaultHoldoutFenceError ||
|
||||
err instanceof VaultScopeNotAuthorizedError ||
|
||||
err instanceof MarketDataStoreValidationError ||
|
||||
err instanceof MarketDataStoreNotImplementedError ||
|
||||
err instanceof AdjFactorsSnapshotError
|
||||
);
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: QueryDataToolOptions): void {
|
||||
if (
|
||||
typeof options.store !== 'object' ||
|
||||
options.store === null ||
|
||||
typeof options.store.bars !== 'function' ||
|
||||
typeof options.store.universe !== 'function'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid `store`: expected a MarketDataStore implementing `bars` and `universe`.',
|
||||
'store'
|
||||
);
|
||||
}
|
||||
|
||||
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'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the Vault-fenced `query_data` MCP tool backed by an injected
|
||||
* {@link MarketDataStore}.
|
||||
*
|
||||
* Always enforces `scope: 'vault_fenced'`, runs {@link applyVaultFence} before
|
||||
* any store call, drops any post-cutoff row yielded by a store as defense in
|
||||
* depth, and bounds output rows by `limit` (default {@link QUERY_DATA_DEFAULT_LIMIT},
|
||||
* hard max {@link QUERY_DATA_MAX_LIMIT}).
|
||||
*/
|
||||
export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry {
|
||||
validateFactoryOptions(options);
|
||||
const { store } = options;
|
||||
const vaultCutoffTs = options.vaultContext.vaultCutoffTs;
|
||||
|
||||
return defineMcpTool({
|
||||
name: 'query_data',
|
||||
description:
|
||||
'Query Vault-fenced OHLCV market bars for explicit listing IDs or a survivorship-free universe.',
|
||||
inputSchema: queryDataInputSchema,
|
||||
async handler(input: QueryDataInput): Promise<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
}
|
||||
);
|
||||
|
||||
const effectiveLimit = input.limit;
|
||||
let listingIds: number[];
|
||||
|
||||
if (input.universe !== undefined) {
|
||||
const resolved = await store.universe({
|
||||
ref: input.universe,
|
||||
date: utcDateOf(fenced.toMs),
|
||||
});
|
||||
if (resolved.length === 0) {
|
||||
const emptyPayload: QueryDataResultPayload = {
|
||||
scope: 'vault_fenced',
|
||||
vaultCutoffTs,
|
||||
timeframe: input.timeframe,
|
||||
adjustment: input.adjustment,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
clampedTo: fenced.clampedTo,
|
||||
clampedAsOf: fenced.clampedAsOf,
|
||||
limit: effectiveLimit,
|
||||
rowCount: 0,
|
||||
truncated: false,
|
||||
rows: [],
|
||||
};
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(emptyPayload) }],
|
||||
};
|
||||
}
|
||||
listingIds = [...resolved];
|
||||
} else {
|
||||
listingIds = [...(input.listingIds ?? [])];
|
||||
}
|
||||
|
||||
const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoMs(fenced.toMs) : input.to;
|
||||
const effectiveFencedAsOf =
|
||||
fenced.clampedAsOf || input.asOf === undefined
|
||||
? formatUtcIsoMs(fenced.asOfMs)
|
||||
: input.asOf;
|
||||
|
||||
const stream = store.bars({
|
||||
listingIds,
|
||||
timeframe: input.timeframe,
|
||||
from: input.from,
|
||||
to: effectiveFencedTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: effectiveFencedAsOf,
|
||||
scope: 'vault_fenced',
|
||||
});
|
||||
|
||||
const rows: BarRecord[] = [];
|
||||
let truncated = false;
|
||||
|
||||
outer: for await (const batch of stream) {
|
||||
for (const row of batch.rows) {
|
||||
if (
|
||||
!Number.isFinite(row.ts) ||
|
||||
!Number.isFinite(row.knownAt) ||
|
||||
row.ts >= vaultCutoffTs ||
|
||||
row.knownAt >= vaultCutoffTs
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rows.length >= effectiveLimit) {
|
||||
truncated = true;
|
||||
break outer;
|
||||
}
|
||||
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
const payload: QueryDataResultPayload = {
|
||||
scope: 'vault_fenced',
|
||||
vaultCutoffTs,
|
||||
timeframe: input.timeframe,
|
||||
adjustment: input.adjustment,
|
||||
fromMs: fenced.fromMs,
|
||||
toMs: fenced.toMs,
|
||||
asOfMs: fenced.asOfMs,
|
||||
clampedTo: fenced.clampedTo,
|
||||
clampedAsOf: fenced.clampedAsOf,
|
||||
limit: effectiveLimit,
|
||||
rowCount: rows.length,
|
||||
truncated,
|
||||
rows,
|
||||
};
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
if (isMappedStoreError(err)) {
|
||||
return formatDomainError(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue