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:
Studio 2026-11-30 15:34:20 -05:00
parent 0bea9a6f1d
commit 73ac978bb3
10 changed files with 2266 additions and 0 deletions

View file

@ -0,0 +1,4 @@
export * from './protocol';
export * from './server';
export * from './stdio';
export * from './tools/query-data';

View file

@ -0,0 +1,245 @@
import { z } from 'zod';
/** Supported Model Context Protocol revision. */
export const MCP_PROTOCOL_VERSION = '2025-03-26';
/** Standard JSON-RPC 2.0 error codes. */
export const JSON_RPC_ERROR_CODES = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
INTERNAL_ERROR: -32603,
} as const;
export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES];
/** Valid JSON-RPC 2.0 request identifier (string or finite number). */
export const jsonRpcIdSchema = z.union([z.string(), z.number().finite()]);
export type JsonRpcId = z.infer<typeof jsonRpcIdSchema>;
/** Strict JSON-RPC 2.0 request envelope (must carry a valid `id`). */
export const jsonRpcRequestSchema = z
.object({
jsonrpc: z.literal('2.0'),
id: jsonRpcIdSchema,
method: z.string().min(1),
params: z.unknown().optional(),
})
.strict();
export type JsonRpcRequest = z.infer<typeof jsonRpcRequestSchema>;
/** Strict JSON-RPC 2.0 notification envelope (must NOT carry an `id`). */
export const jsonRpcNotificationSchema = z
.object({
jsonrpc: z.literal('2.0'),
method: z.string().min(1),
params: z.unknown().optional(),
})
.strict();
export type JsonRpcNotification = z.infer<typeof jsonRpcNotificationSchema>;
export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification;
export interface JsonRpcSuccessResponse {
readonly jsonrpc: '2.0';
readonly id: JsonRpcId;
readonly result: unknown;
}
export interface JsonRpcErrorObject {
readonly code: number;
readonly message: string;
readonly data?: unknown;
}
export interface JsonRpcErrorResponse {
readonly jsonrpc: '2.0';
readonly id: JsonRpcId | null;
readonly error: JsonRpcErrorObject;
}
export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
/** MCP text content block returned inside `tools/call` results. */
export interface McpTextContent {
readonly type: 'text';
readonly text: string;
}
/** MCP `tools/call` result envelope. */
export interface McpToolCallResult {
readonly content: readonly McpTextContent[];
readonly isError?: boolean;
}
/** Minimal JSON Schema Draft 7/2020-12 property definition for MCP tool inputs. */
export interface JsonSchemaProperty {
readonly type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
readonly description?: string;
readonly enum?: readonly (string | number | boolean | null)[];
readonly const?: string | number | boolean | null;
readonly minimum?: number;
readonly maximum?: number;
readonly exclusiveMinimum?: number;
readonly exclusiveMaximum?: number;
readonly minLength?: number;
readonly maxLength?: number;
readonly minItems?: number;
readonly maxItems?: number;
readonly items?: JsonSchemaProperty;
readonly properties?: Readonly<Record<string, JsonSchemaProperty>>;
readonly required?: readonly string[];
readonly additionalProperties?: boolean;
readonly anyOf?: readonly JsonSchemaProperty[];
readonly default?: unknown;
}
/** Strict top-level JSON Schema object emitted by `tools/list`. */
export interface JsonSchemaObject {
readonly type: 'object';
readonly properties: Readonly<Record<string, JsonSchemaProperty>>;
readonly required?: readonly string[];
readonly additionalProperties: false;
readonly description?: string;
}
/** Tool metadata returned in `tools/list`. */
export interface McpToolDescriptor {
readonly name: string;
readonly description: string;
readonly inputSchema: JsonSchemaObject;
}
/** Strict MCP `initialize` params schema. */
export const mcpInitializeParamsSchema = z
.object({
protocolVersion: z.string().min(1).optional(),
capabilities: z.record(z.unknown()).optional(),
clientInfo: z
.object({
name: z.string().min(1),
version: z.string().min(1),
})
.strict()
.optional(),
})
.strict();
/** Strict MCP `notifications/initialized` params schema. */
export const mcpInitializedNotificationParamsSchema = z.object({}).strict();
/** Strict MCP `ping` params schema. */
export const mcpPingParamsSchema = z.object({}).strict();
/** Strict MCP `tools/list` params schema. */
export const mcpToolsListParamsSchema = z
.object({
cursor: z.string().min(1).optional(),
})
.strict();
/** Strict MCP `tools/call` params schema. */
export const mcpToolsCallParamsSchema = z
.object({
name: z.string().min(1),
arguments: z.record(z.unknown()).optional(),
})
.strict();
export type ParsedJsonRpcMessage =
| { readonly ok: true; readonly kind: 'request'; readonly message: JsonRpcRequest }
| { readonly ok: true; readonly kind: 'notification'; readonly message: JsonRpcNotification }
| {
readonly ok: false;
readonly errorCode: JsonRpcErrorCode;
readonly message: string;
};
/**
* Parses a raw JSON-RPC 2.0 message string.
*
* - Malformed JSON returns `PARSE_ERROR` (-32700).
* - Non-object payloads or invalid envelopes (including an explicit invalid `id`
* such as `id: null` or `id: true`) return `INVALID_REQUEST` (-32600).
* - Objects without an `id` property are parsed as notifications.
*/
export function parseJsonRpcMessage(raw: string): ParsedJsonRpcMessage {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.PARSE_ERROR,
message: 'Parse error: invalid JSON.',
};
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: expected a JSON-RPC 2.0 object.',
};
}
const hasId = Object.prototype.hasOwnProperty.call(parsed, 'id');
if (hasId) {
const requestResult = jsonRpcRequestSchema.safeParse(parsed);
if (!requestResult.success) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: malformed JSON-RPC 2.0 request envelope.',
};
}
return {
ok: true,
kind: 'request',
message: requestResult.data,
};
}
const notificationResult = jsonRpcNotificationSchema.safeParse(parsed);
if (!notificationResult.success) {
return {
ok: false,
errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
message: 'Invalid Request: malformed JSON-RPC 2.0 notification envelope.',
};
}
return {
ok: true,
kind: 'notification',
message: notificationResult.data,
};
}
/** Builds a JSON-RPC 2.0 success response object. */
export function jsonRpcSuccess(id: JsonRpcId, result: unknown): JsonRpcSuccessResponse {
return {
jsonrpc: '2.0',
id,
result,
};
}
/** Builds a JSON-RPC 2.0 error response object. */
export function jsonRpcError(
id: JsonRpcId | null,
code: number,
message: string,
data?: unknown
): JsonRpcErrorResponse {
const error: JsonRpcErrorObject =
data !== undefined ? { code, message, data } : { code, message };
return {
jsonrpc: '2.0',
id,
error,
};
}

View file

@ -0,0 +1,540 @@
import { z } from 'zod';
import {
JSON_RPC_ERROR_CODES,
type JsonSchemaObject,
type JsonSchemaProperty,
MCP_PROTOCOL_VERSION,
type McpToolCallResult,
type McpToolDescriptor,
jsonRpcError,
jsonRpcSuccess,
mcpInitializeParamsSchema,
mcpPingParamsSchema,
mcpToolsCallParamsSchema,
mcpToolsListParamsSchema,
parseJsonRpcMessage,
} from './protocol';
/** Configuration for defining a strongly typed MCP tool. */
export interface McpToolDefinition<TInput> {
readonly name: string;
readonly description: string;
readonly inputSchema: z.ZodType<TInput, z.ZodTypeDef, unknown>;
readonly jsonSchema?: JsonSchemaObject;
readonly handler: (input: TInput) => Promise<McpToolCallResult> | McpToolCallResult;
}
/** Type-erased tool entry registered on an {@link McpServer}. */
export interface McpToolEntry {
readonly name: string;
readonly description: string;
readonly inputSchema: JsonSchemaObject;
readonly execute: (rawArguments: Record<string, unknown>) => Promise<McpToolCallResult>;
}
/** Options for {@link createMcpServer}. */
export interface McpServerOptions {
readonly name: string;
readonly version: string;
readonly tools?: readonly McpToolEntry[];
}
/** Transport-agnostic MCP JSON-RPC 2.0 server interface. */
export interface McpServer {
readonly name: string;
readonly version: string;
listTools(): readonly McpToolDescriptor[];
handleMessage(raw: string): Promise<string | null>;
}
function isOptionalSchema(schema: z.ZodTypeAny): boolean {
if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) {
return true;
}
if (schema instanceof z.ZodEffects) {
return isOptionalSchema(schema._def.schema);
}
return false;
}
function withDescription(
prop: JsonSchemaProperty,
description: string | undefined
): JsonSchemaProperty {
if (description !== undefined && prop.description === undefined) {
return { ...prop, description };
}
return prop;
}
function convertZodType(schema: z.ZodTypeAny): JsonSchemaProperty {
const outerDescription = schema.description;
if (schema instanceof z.ZodEffects) {
return withDescription(convertZodType(schema._def.schema), outerDescription);
}
if (schema instanceof z.ZodOptional) {
return withDescription(convertZodType(schema.unwrap()), outerDescription);
}
if (schema instanceof z.ZodDefault) {
const inner = convertZodType(schema._def.innerType);
const defaultValue: unknown = schema._def.defaultValue();
return withDescription({ ...inner, default: defaultValue }, outerDescription);
}
if (schema instanceof z.ZodNullable) {
const inner = convertZodType(schema.unwrap());
return withDescription({ anyOf: [inner, { type: 'null' }] }, outerDescription);
}
if (schema instanceof z.ZodString) {
let minLength: number | undefined;
let maxLength: number | undefined;
for (const check of schema._def.checks) {
if (check.kind === 'min') {
minLength = check.value;
} else if (check.kind === 'max') {
maxLength = check.value;
} else if (check.kind === 'length') {
minLength = check.value;
maxLength = check.value;
}
}
const result: {
type: 'string';
description?: string;
minLength?: number;
maxLength?: number;
} = { type: 'string' };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (minLength !== undefined) {
result.minLength = minLength;
}
if (maxLength !== undefined) {
result.maxLength = maxLength;
}
return result;
}
if (schema instanceof z.ZodNumber) {
let isInt = false;
let minimum: number | undefined;
let maximum: number | undefined;
let exclusiveMinimum: number | undefined;
let exclusiveMaximum: number | undefined;
for (const check of schema._def.checks) {
if (check.kind === 'int') {
isInt = true;
} else if (check.kind === 'min') {
if (check.inclusive) {
minimum = check.value;
} else {
exclusiveMinimum = check.value;
}
} else if (check.kind === 'max') {
if (check.inclusive) {
maximum = check.value;
} else {
exclusiveMaximum = check.value;
}
}
}
const result: {
type: 'integer' | 'number';
description?: string;
minimum?: number;
maximum?: number;
exclusiveMinimum?: number;
exclusiveMaximum?: number;
} = { type: isInt ? 'integer' : 'number' };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (minimum !== undefined) {
result.minimum = minimum;
}
if (maximum !== undefined) {
result.maximum = maximum;
}
if (exclusiveMinimum !== undefined) {
result.exclusiveMinimum = exclusiveMinimum;
}
if (exclusiveMaximum !== undefined) {
result.exclusiveMaximum = exclusiveMaximum;
}
return result;
}
if (schema instanceof z.ZodBoolean) {
return outerDescription !== undefined
? { type: 'boolean', description: outerDescription }
: { type: 'boolean' };
}
if (schema instanceof z.ZodEnum) {
const values = [...schema._def.values] as readonly string[];
return outerDescription !== undefined
? { type: 'string', enum: values, description: outerDescription }
: { type: 'string', enum: values };
}
if (schema instanceof z.ZodLiteral) {
const literalValue: unknown = schema._def.value;
if (
typeof literalValue === 'string' ||
typeof literalValue === 'number' ||
typeof literalValue === 'boolean' ||
literalValue === null
) {
const literalType: JsonSchemaProperty['type'] =
literalValue === null
? 'null'
: typeof literalValue === 'string'
? 'string'
: typeof literalValue === 'number'
? 'number'
: 'boolean';
return outerDescription !== undefined
? { type: literalType, const: literalValue, description: outerDescription }
: { type: literalType, const: literalValue };
}
throw new Error('Unsupported ZodLiteral value type in MCP tool input schema.');
}
if (schema instanceof z.ZodArray) {
const items = convertZodType(schema._def.type);
const result: {
type: 'array';
items: JsonSchemaProperty;
description?: string;
minItems?: number;
maxItems?: number;
} = { type: 'array', items };
if (outerDescription !== undefined) {
result.description = outerDescription;
}
if (schema._def.minLength !== null) {
result.minItems = schema._def.minLength.value;
}
if (schema._def.maxLength !== null) {
result.maxItems = schema._def.maxLength.value;
}
if (schema._def.exactLength !== null) {
result.minItems = schema._def.exactLength.value;
result.maxItems = schema._def.exactLength.value;
}
return result;
}
if (schema instanceof z.ZodUnion) {
const options = (schema._def.options as readonly z.ZodTypeAny[]).map(option =>
convertZodType(option)
);
return outerDescription !== undefined
? { anyOf: options, description: outerDescription }
: { anyOf: options };
}
if (schema instanceof z.ZodObject) {
return convertZodObject(schema, outerDescription);
}
const typeName =
typeof (schema._def as { typeName?: unknown }).typeName === 'string'
? (schema._def as { typeName: string }).typeName
: 'unknown';
throw new Error(`Unsupported Zod schema type "${typeName}" in MCP tool input schema.`);
}
function convertZodObject(
schema: z.ZodObject<z.ZodRawShape>,
outerDescription: string | undefined
): JsonSchemaObject {
const shape = schema.shape;
const properties: Record<string, JsonSchemaProperty> = {};
const required: string[] = [];
for (const [key, fieldSchema] of Object.entries(shape)) {
properties[key] = convertZodType(fieldSchema);
if (!isOptionalSchema(fieldSchema)) {
required.push(key);
}
}
const description = outerDescription ?? schema.description;
const result: {
type: 'object';
properties: Record<string, JsonSchemaProperty>;
required?: string[];
additionalProperties: false;
description?: string;
} = {
type: 'object',
properties,
additionalProperties: false,
};
if (required.length > 0) {
result.required = required;
}
if (description !== undefined) {
result.description = description;
}
return result;
}
/**
* Converts a Zod v3 object schema (including `.refine()` / `.superRefine()`
* `ZodEffects` wrappers) into a strict {@link JsonSchemaObject}.
*
* Fails fast on unsupported Zod schema types so misconfigured tools are caught
* at registration time rather than at `tools/list` time.
*/
export function zodObjectToJsonSchema(schema: z.ZodTypeAny): JsonSchemaObject {
let current: z.ZodTypeAny = schema;
let description = schema.description;
while (current instanceof z.ZodEffects) {
current = current._def.schema;
if (description === undefined && current.description !== undefined) {
description = current.description;
}
}
if (!(current instanceof z.ZodObject)) {
throw new Error('MCP tool inputSchema must be a ZodObject (optionally wrapped in ZodEffects).');
}
return convertZodObject(current, description);
}
function formatZodIssues(error: z.ZodError): string {
const parts = error.issues.map(issue => {
const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : '';
return `${path}${issue.message}`;
});
return parts.join('; ');
}
function sanitizeToolError(err: unknown): string {
if (err instanceof Error) {
const rawName = typeof err.name === 'string' && err.name.trim().length > 0 ? err.name.trim() : 'Error';
const firstLine = (typeof err.message === 'string' ? err.message : '')
.split(/\r?\n/, 1)[0]
?.replace(/\s+at\s+\S.*$/u, '')
.trim();
if (firstLine !== undefined && firstLine.length > 0) {
return `${rawName}: ${firstLine}`;
}
return `${rawName}: Tool execution failed.`;
}
return 'Error: Tool execution failed.';
}
/**
* Defines a type-erased MCP tool entry with eager JSON Schema generation,
* strict argument validation, and sanitized error handling.
*/
export function defineMcpTool<TInput>(definition: McpToolDefinition<TInput>): McpToolEntry {
if (typeof definition.name !== 'string' || definition.name.trim().length === 0) {
throw new Error('MCP tool name must be a non-empty string.');
}
if (typeof definition.description !== 'string' || definition.description.trim().length === 0) {
throw new Error(`MCP tool "${definition.name}" description must be a non-empty string.`);
}
const resolvedSchema: JsonSchemaObject =
definition.jsonSchema ?? zodObjectToJsonSchema(definition.inputSchema);
return {
name: definition.name,
description: definition.description,
inputSchema: resolvedSchema,
async execute(rawArguments: Record<string, unknown>): Promise<McpToolCallResult> {
const parsed = definition.inputSchema.safeParse(rawArguments);
if (!parsed.success) {
return {
content: [
{
type: 'text',
text: `Invalid arguments for tool "${definition.name}": ${formatZodIssues(parsed.error)}`,
},
],
isError: true,
};
}
try {
return await definition.handler(parsed.data);
} catch (err: unknown) {
return {
content: [
{
type: 'text',
text: sanitizeToolError(err),
},
],
isError: true,
};
}
},
};
}
/**
* Creates a transport-agnostic MCP JSON-RPC 2.0 server with a validated tool
* registry.
*/
export function createMcpServer(options: McpServerOptions): McpServer {
if (typeof options.name !== 'string' || options.name.trim().length === 0) {
throw new Error('MCP server name must be a non-empty string.');
}
if (typeof options.version !== 'string' || options.version.trim().length === 0) {
throw new Error('MCP server version must be a non-empty string.');
}
const toolMap = new Map<string, McpToolEntry>();
const toolDescriptors: McpToolDescriptor[] = [];
for (const tool of options.tools ?? []) {
if (toolMap.has(tool.name)) {
throw new Error(`Duplicate MCP tool name: "${tool.name}".`);
}
toolMap.set(tool.name, tool);
toolDescriptors.push({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
});
}
const frozenDescriptors: readonly McpToolDescriptor[] = Object.freeze([...toolDescriptors]);
return {
name: options.name,
version: options.version,
listTools(): readonly McpToolDescriptor[] {
return frozenDescriptors;
},
async handleMessage(raw: string): Promise<string | null> {
const parsed = parseJsonRpcMessage(raw);
if (!parsed.ok) {
return JSON.stringify(jsonRpcError(null, parsed.errorCode, parsed.message));
}
if (parsed.kind === 'notification') {
return null;
}
const { id, method, params } = parsed.message;
switch (method) {
case 'initialize': {
if (params !== undefined) {
const initParams = mcpInitializeParamsSchema.safeParse(params);
if (!initParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for initialize: ${formatZodIssues(initParams.error)}`
)
);
}
}
return JSON.stringify(
jsonRpcSuccess(id, {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {
tools: {},
},
serverInfo: {
name: options.name,
version: options.version,
},
})
);
}
case 'ping': {
if (params !== undefined) {
const pingParams = mcpPingParamsSchema.safeParse(params);
if (!pingParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for ping: ${formatZodIssues(pingParams.error)}`
)
);
}
}
return JSON.stringify(jsonRpcSuccess(id, {}));
}
case 'tools/list': {
if (params !== undefined) {
const listParams = mcpToolsListParamsSchema.safeParse(params);
if (!listParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for tools/list: ${formatZodIssues(listParams.error)}`
)
);
}
}
return JSON.stringify(
jsonRpcSuccess(id, {
tools: frozenDescriptors,
})
);
}
case 'tools/call': {
const callParams = mcpToolsCallParamsSchema.safeParse(params);
if (!callParams.success) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Invalid params for tools/call: ${formatZodIssues(callParams.error)}`
)
);
}
const tool = toolMap.get(callParams.data.name);
if (tool === undefined) {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.INVALID_PARAMS,
`Unknown tool: "${callParams.data.name}".`
)
);
}
const result = await tool.execute(callParams.data.arguments ?? {});
return JSON.stringify(jsonRpcSuccess(id, result));
}
default: {
return JSON.stringify(
jsonRpcError(
id,
JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND,
`Method not found: "${method}".`
)
);
}
}
},
};
}

View file

@ -0,0 +1,147 @@
import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol';
import type { McpServer } from './server';
/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */
export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024;
/** Readable byte/string stream accepted by {@link runStdioServer}. */
export type StdioInput = AsyncIterable<Uint8Array | string>;
/** Minimal writable stream interface accepted by {@link runStdioServer}. */
export interface StdioOutput {
write(chunk: string): boolean;
once?(event: 'drain', listener: () => void): unknown;
}
/** Options for {@link runStdioServer}. */
export interface StdioServerOptions {
readonly input?: StdioInput;
readonly output?: StdioOutput;
readonly maxLineBytes?: number;
}
async function writeLine(output: StdioOutput, line: string): Promise<void> {
const ok = output.write(`${line}\n`);
if (!ok && typeof output.once === 'function') {
await new Promise<void>(resolve => {
output.once?.('drain', () => {
resolve();
});
});
}
}
/**
* Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an
* {@link McpServer}.
*
* - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte
* characters split across chunk boundaries are never corrupted.
* - Dispatches lines strictly sequentially in arrival order.
* - Writes only compact newline-terminated JSON-RPC responses to `output`
* (skipping `null` notification results and blank lines).
* - Guards against oversized unterminated frames via `maxLineBytes`.
*/
export async function runStdioServer(
server: McpServer,
options?: StdioServerOptions
): Promise<void> {
const input: StdioInput = options?.input ?? process.stdin;
const output: StdioOutput = options?.output ?? process.stdout;
const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES;
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`);
}
const decoder = new TextDecoder('utf-8');
const encoder = new TextEncoder();
let buffer = '';
let droppingOversizedLine = false;
const processLine = async (rawLine: string): Promise<void> => {
const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
if (trimmed.trim().length === 0) {
return;
}
const response = await server.handleMessage(trimmed);
if (response !== null) {
await writeLine(output, response);
}
};
const emitOversizedError = async (): Promise<void> => {
const errorPayload = JSON.stringify(
jsonRpcError(
null,
JSON_RPC_ERROR_CODES.PARSE_ERROR,
`Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.`
)
);
await writeLine(output, errorPayload);
};
const drainBuffer = async (): Promise<void> => {
while (true) {
const newlineIdx = buffer.indexOf('\n');
if (newlineIdx === -1) {
if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) {
droppingOversizedLine = true;
buffer = '';
await emitOversizedError();
}
return;
}
const rawLine = buffer.slice(0, newlineIdx);
buffer = buffer.slice(newlineIdx + 1);
if (droppingOversizedLine) {
droppingOversizedLine = false;
continue;
}
if (encoder.encode(rawLine).byteLength > maxLineBytes) {
await emitOversizedError();
continue;
}
await processLine(rawLine);
}
};
for await (const chunk of input) {
const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
if (text.length === 0) {
continue;
}
if (droppingOversizedLine) {
const newlineIdx = text.indexOf('\n');
if (newlineIdx === -1) {
continue;
}
droppingOversizedLine = false;
buffer = text.slice(newlineIdx + 1);
} else {
buffer += text;
}
await drainBuffer();
}
const tail = decoder.decode();
if (tail.length > 0 && !droppingOversizedLine) {
buffer += tail;
}
await drainBuffer();
if (!droppingOversizedLine && buffer.length > 0) {
if (encoder.encode(buffer).byteLength > maxLineBytes) {
await emitOversizedError();
} else {
await processLine(buffer);
}
}
}

View 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;
}
},
});
}