From 73ac978bb3a8a7a5a38c361b432693973eeae5a2 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:34:20 -0500 Subject: [PATCH] =?UTF-8?q?T-129:=20M2.1a=20=E2=80=94=20MCP=20copilot=20co?= =?UTF-8?q?re:=20dependency-free=20JSON-RPC/MCP=20stdio=20server=20+=20too?= =?UTF-8?q?l=20registry=20+=20vault-fenced=20`query=5Fdata`=20in=20`libs/r?= =?UTF-8?q?esearch/src/mcp/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 21 + libs/research/package.json | 1 + libs/research/src/mcp/index.ts | 4 + libs/research/src/mcp/protocol.ts | 245 ++++++++++ libs/research/src/mcp/server.ts | 540 ++++++++++++++++++++++ libs/research/src/mcp/stdio.ts | 147 ++++++ libs/research/src/mcp/tools/query-data.ts | 307 ++++++++++++ libs/research/test/mcp-protocol.test.ts | 324 +++++++++++++ libs/research/test/mcp-query-data.test.ts | 482 +++++++++++++++++++ libs/research/test/mcp-stdio.test.ts | 195 ++++++++ 10 files changed, 2266 insertions(+) create mode 100644 libs/research/src/mcp/index.ts create mode 100644 libs/research/src/mcp/protocol.ts create mode 100644 libs/research/src/mcp/server.ts create mode 100644 libs/research/src/mcp/stdio.ts create mode 100644 libs/research/src/mcp/tools/query-data.ts create mode 100644 libs/research/test/mcp-protocol.test.ts create mode 100644 libs/research/test/mcp-query-data.test.ts create mode 100644 libs/research/test/mcp-stdio.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 919c2b6d..fd8e76ad 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -196,3 +196,24 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3 - **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts` - **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`) + +## MCP Copilot Core + +Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the `@stock-bot/research/mcp` subpath (`libs/research/src/mcp/index.ts`). It is intentionally **not** re-exported from the browser-safe `@stock-bot/research` default entrypoint. + +### Registering Tools & Running Stdio Framing + +- **`defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })`** — Registers a strict Zod-validated tool, converts `inputSchema` into a strict JSON Schema (`additionalProperties: false`, or uses an explicit `jsonSchema` override), returns `isError: true` on invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak. +- **`createMcpServer({ name, version, tools })`** — Transport-agnostic JSON-RPC 2.0 dispatcher implementing `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` via `handleMessage(raw: string): Promise`. Rejects duplicate tool names at creation time. +- **`runStdioServer(server, { input?, output?, maxLineBytes? })`** — Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting to `process.stdin` / `process.stdout`), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order, `maxLineBytes` frame-size protection (default `4 MiB`), and zero non-protocol bytes on `output`. + +### `query_data` Tool (Vault-Fenced) + +- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). +- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. + +### Remaining M2 MCP Items (Later Tasks) + +- Additional research tools: `search_symbols`, `analyze_signal`, `event_study`, `file_finding`, and `read_knowledge`. +- SSE/HTTP transport wrapper in `apps/stock/web-api`. +- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/package.json b/libs/research/package.json index 89c29140..fb865726 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -13,6 +13,7 @@ "./event-panel": "./src/event-panel.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", + "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", "./signal-study": "./src/signal-study.ts", diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts new file mode 100644 index 00000000..8b021dbe --- /dev/null +++ b/libs/research/src/mcp/index.ts @@ -0,0 +1,4 @@ +export * from './protocol'; +export * from './server'; +export * from './stdio'; +export * from './tools/query-data'; diff --git a/libs/research/src/mcp/protocol.ts b/libs/research/src/mcp/protocol.ts new file mode 100644 index 00000000..f3d66d8c --- /dev/null +++ b/libs/research/src/mcp/protocol.ts @@ -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; + +/** 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; + +/** 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; + +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>; + 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>; + 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, + }; +} diff --git a/libs/research/src/mcp/server.ts b/libs/research/src/mcp/server.ts new file mode 100644 index 00000000..08a80b73 --- /dev/null +++ b/libs/research/src/mcp/server.ts @@ -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 { + readonly name: string; + readonly description: string; + readonly inputSchema: z.ZodType; + readonly jsonSchema?: JsonSchemaObject; + readonly handler: (input: TInput) => Promise | 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) => Promise; +} + +/** 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; +} + +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, + outerDescription: string | undefined +): JsonSchemaObject { + const shape = schema.shape; + const properties: Record = {}; + 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; + 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(definition: McpToolDefinition): 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): Promise { + 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(); + 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 { + 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}".` + ) + ); + } + } + }, + }; +} diff --git a/libs/research/src/mcp/stdio.ts b/libs/research/src/mcp/stdio.ts new file mode 100644 index 00000000..580c3b6e --- /dev/null +++ b/libs/research/src/mcp/stdio.ts @@ -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; + +/** 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 { + const ok = output.write(`${line}\n`); + if (!ok && typeof output.once === 'function') { + await new Promise(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 { + 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 => { + 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 => { + 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 => { + 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); + } + } +} diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts new file mode 100644 index 00000000..a336985e --- /dev/null +++ b/libs/research/src/mcp/tools/query-data.ts @@ -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; + +/** Configuration for {@link createQueryDataTool}. */ +export interface QueryDataToolOptions { + readonly store: MarketDataStore; + readonly vaultContext: Pick; +} + +/** 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 { + 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; + } + }, + }); +} diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts new file mode 100644 index 00000000..eb312d45 --- /dev/null +++ b/libs/research/test/mcp-protocol.test.ts @@ -0,0 +1,324 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import * as rootResearchExports from '../src/index'; +import { + JSON_RPC_ERROR_CODES, + MCP_PROTOCOL_VERSION, + createMcpServer, + defineMcpTool, + zodObjectToJsonSchema, +} from '../src/mcp/index'; + +interface JsonRpcParsedResponse { + jsonrpc: string; + id: string | number | null; + result?: Record; + error?: { + code: number; + message: string; + data?: unknown; + }; +} + +function parseResponse(raw: string | null): JsonRpcParsedResponse { + expect(raw).not.toBeNull(); + return JSON.parse(raw as string) as JsonRpcParsedResponse; +} + +describe('MCP protocol & server core', () => { + test('initialize returns protocolVersion, serverInfo, and capabilities.tools', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' }, + }, + }) + ); + + const response = parseResponse(raw); + expect(response.jsonrpc).toBe('2.0'); + expect(response.id).toBe(1); + expect(response.error).toBeUndefined(); + expect(response.result).toEqual({ + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: { tools: {} }, + serverInfo: { + name: 'stock-bot-research', + version: '0.1.0', + }, + }); + }); + + test('notifications/initialized returns null (no response)', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }) + ); + + expect(raw).toBeNull(); + }); + + test('ping returns empty object result', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'ping-1', + method: 'ping', + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe('ping-1'); + expect(response.result).toEqual({}); + }); + + test('echoes string and numeric request ids verbatim (including 0 and negative integers)', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const ids: readonly (string | number)[] = ['req-abc', '', 0, -42, 9007199254740991]; + for (const id of ids) { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'ping', + }) + ); + const response = parseResponse(raw); + expect(response.id).toBe(id); + } + }); + + test('malformed JSON returns -32700 with id: null', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage('{not valid json'); + const response = parseResponse(raw); + expect(response.id).toBeNull(); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('non-JSON-RPC objects and explicit invalid id return -32600', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const badPayloads = [ + '42', + '"hello"', + 'null', + '[]', + JSON.stringify({ foo: 'bar' }), + JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: true, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: { nested: 1 }, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', extra: true }), + ]; + + for (const payload of badPayloads) { + const raw = await server.handleMessage(payload); + const response = parseResponse(raw); + expect(response.id).toBeNull(); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_REQUEST); + } + }); + + test('unknown method returns -32601 echoing request id', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'unknown-1', + method: 'resources/list', + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe('unknown-1'); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND); + }); + + test('tools/call rejects unknown tool name and malformed params with -32602', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [], + }); + + const unknownToolRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 10, + method: 'tools/call', + params: { name: 'does_not_exist', arguments: {} }, + }) + ); + const unknownToolResp = parseResponse(unknownToolRaw); + expect(unknownToolResp.id).toBe(10); + expect(unknownToolResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + + const badParamsRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 11, + method: 'tools/call', + params: { name: 123, arguments: 'not-an-object' }, + }) + ); + const badParamsResp = parseResponse(badParamsRaw); + expect(badParamsResp.id).toBe(11); + expect(badParamsResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('invalid tool arguments return isError: true with readable message and zero handler calls', async () => { + let handlerCalls = 0; + const echoTool = defineMcpTool({ + name: 'echo_count', + description: 'Echoes a positive integer count.', + inputSchema: z.object({ count: z.number().int().min(1) }).strict(), + handler(input) { + handlerCalls += 1; + return { + content: [{ type: 'text', text: String(input.count) }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 20, + method: 'tools/call', + params: { + name: 'echo_count', + arguments: { count: 0, unexpected: true }, + }, + }) + ); + + expect(handlerCalls).toBe(0); + const response = parseResponse(raw); + expect(response.id).toBe(20); + expect(response.error).toBeUndefined(); + const result = response.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(result.isError).toBe(true); + expect(result.content[0]?.type).toBe('text'); + expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); + }); + + test('throwing tool handler returns isError: true with sanitized error and zero stack trace', async () => { + const boomTool = defineMcpTool({ + name: 'explode', + description: 'Always throws an error.', + inputSchema: z.object({}).strict(), + handler() { + const err = new Error('Simulated backend failure\n at secretInternal (/srv/app/secret.ts:42:9)'); + err.name = 'BackendFailureError'; + throw err; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [boomTool], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 30, + method: 'tools/call', + params: { name: 'explode', arguments: {} }, + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe(30); + expect(response.error).toBeUndefined(); + const result = response.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(result.isError).toBe(true); + const text = result.content[0]?.text ?? ''; + expect(text).toBe('BackendFailureError: Simulated backend failure'); + expect(text).not.toContain('at '); + expect(text).not.toContain('/srv/app/secret.ts'); + expect(text).not.toContain('\n'); + }); + + test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => { + const makeTool = () => + defineMcpTool({ + name: 'dup_tool', + description: 'Duplicate tool test.', + inputSchema: z.object({ x: z.string() }).strict(), + handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), + }); + + expect(() => + createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [makeTool(), makeTool()], + }) + ).toThrow(/Duplicate MCP tool name/i); + + expect(() => + zodObjectToJsonSchema(z.object({ bad: z.date() }).strict()) + ).toThrow(/Unsupported Zod schema type/i); + }); + + test('browser-safe root entrypoint does not re-export MCP symbols', () => { + const exportedKeys = Object.keys(rootResearchExports); + expect(exportedKeys).not.toContain('createMcpServer'); + expect(exportedKeys).not.toContain('defineMcpTool'); + expect(exportedKeys).not.toContain('runStdioServer'); + expect(exportedKeys).not.toContain('createQueryDataTool'); + }); +}); diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts new file mode 100644 index 00000000..03722117 --- /dev/null +++ b/libs/research/test/mcp-query-data.test.ts @@ -0,0 +1,482 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + VaultScopeNotAuthorizedError, +} from '../src/market-data-store'; +import { + AdjFactorsSnapshotError, + type BarsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + QUERY_DATA_DEFAULT_LIMIT, + QUERY_DATA_MAX_LIMIT, + type QueryDataResultPayload, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close - 1, + high: close + 1, + low: close - 2, + close, + volume: 1_000, + vwap: close, + knownAt, + }; +} + +interface FakeStoreState { + readonly barsCalls: BarsQuery[]; + readonly universeCalls: UniverseQuery[]; + readonly store: MarketDataStore; +} + +function createFakeStore(options?: { + batches?: readonly BarBatch[]; + universeIds?: readonly number[]; + barsError?: Error; + universeError?: Error; +}): FakeStoreState { + const barsCalls: BarsQuery[] = []; + const universeCalls: UniverseQuery[] = []; + + const batches = options?.batches ?? []; + const universeIds = options?.universeIds ?? []; + + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + if (options?.barsError !== undefined) { + const err = options.barsError; + return { + [Symbol.asyncIterator]() { + return { + next() { + return Promise.reject(err); + }, + }; + }, + }; + } + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options?.universeError !== undefined) { + throw options.universeError; + } + return [...universeIds]; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + + return { barsCalls, universeCalls, store }; +} + +async function callQueryData( + fake: FakeStoreState, + args: Record +): Promise<{ + rawResponse: string; + isError: boolean; + text: string; +}> { + const tool = createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [tool], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'q1', + method: 'tools/call', + params: { + name: 'query_data', + arguments: args, + }, + }) + ); + + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse as string) as { + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + return { + rawResponse: rawResponse as string, + isError: parsed.result.isError === true, + text: parsed.result.content[0]?.text ?? '', + }; +} + +describe('MCP query_data tool', () => { + test('tools/list exposes query_data with strict inputSchema and omits scope / vault_evaluation_only', async () => { + const fake = createFakeStore(); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/list', + }) + ); + + const parsed = JSON.parse(raw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(parsed.result.tools).toHaveLength(1); + const tool = parsed.result.tools[0]; + expect(tool?.name).toBe('query_data'); + expect(tool?.inputSchema.type).toBe('object'); + expect(tool?.inputSchema.additionalProperties).toBe(false); + expect(tool?.inputSchema.required).toEqual(['from', 'to']); + + const propKeys = Object.keys(tool?.inputSchema.properties ?? {}); + expect(propKeys).toContain('listingIds'); + expect(propKeys).toContain('universe'); + expect(propKeys).toContain('from'); + expect(propKeys).toContain('to'); + expect(propKeys).toContain('limit'); + expect(propKeys).not.toContain('scope'); + expect(propKeys).not.toContain('vault_evaluation_only'); + expect(tool?.inputSchema.required).not.toContain('scope'); + expect(tool?.inputSchema.required).not.toContain('vault_evaluation_only'); + }); + + test('returns pre-cutoff rows and records scope === vault_fenced on every bars() call', async () => { + const bar1 = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.5); + const bar2 = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 152.0); + const fake = createFakeStore({ + batches: [{ rows: [bar1, bar2] }], + }); + + const { isError, text } = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + + expect(isError).toBe(false); + expect(fake.barsCalls).toHaveLength(1); + expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); + + const payload = JSON.parse(text) as QueryDataResultPayload; + expect(payload.scope).toBe('vault_fenced'); + expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); + expect(payload.clampedTo).toBe(false); + expect(payload.rowCount).toBe(2); + expect(payload.truncated).toBe(false); + expect(payload.rows).toEqual([bar1, bar2]); + }); + + test('enforces default limit, explicit limit, max limit, and rejects out-of-bounds limits with zero store calls', async () => { + const totalRows = QUERY_DATA_MAX_LIMIT + 5; + const allRows: BarRecord[] = []; + for (let i = 0; i < totalRows; i += 1) { + allRows.push(makeBar(101, Date.UTC(2024, 0, 1, 0, 0, 0) + i * 60_000, 100 + i * 0.01)); + } + + // Omitted limit -> caps at QUERY_DATA_DEFAULT_LIMIT with truncated: true + const defaultFake = createFakeStore({ batches: [{ rows: allRows }] }); + const defaultRes = await callQueryData(defaultFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + }); + expect(defaultRes.isError).toBe(false); + const defaultPayload = JSON.parse(defaultRes.text) as QueryDataResultPayload; + expect(defaultPayload.limit).toBe(QUERY_DATA_DEFAULT_LIMIT); + expect(defaultPayload.rowCount).toBe(QUERY_DATA_DEFAULT_LIMIT); + expect(defaultPayload.truncated).toBe(true); + + // Explicit limit -> caps at requested value + const explicitFake = createFakeStore({ batches: [{ rows: allRows }] }); + const explicitRes = await callQueryData(explicitFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: 3, + }); + expect(explicitRes.isError).toBe(false); + const explicitPayload = JSON.parse(explicitRes.text) as QueryDataResultPayload; + expect(explicitPayload.limit).toBe(3); + expect(explicitPayload.rowCount).toBe(3); + expect(explicitPayload.truncated).toBe(true); + + // Exact QUERY_DATA_MAX_LIMIT -> succeeds + const maxFake = createFakeStore({ batches: [{ rows: allRows }] }); + const maxRes = await callQueryData(maxFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: QUERY_DATA_MAX_LIMIT, + }); + expect(maxRes.isError).toBe(false); + const maxPayload = JSON.parse(maxRes.text) as QueryDataResultPayload; + expect(maxPayload.rowCount).toBe(QUERY_DATA_MAX_LIMIT); + expect(maxPayload.truncated).toBe(true); + + // limit > QUERY_DATA_MAX_LIMIT or <= 0 -> isError: true with zero store calls + for (const badLimit of [QUERY_DATA_MAX_LIMIT + 1, 0, -5]) { + const badFake = createFakeStore({ batches: [{ rows: allRows }] }); + const badRes = await callQueryData(badFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: badLimit, + }); + expect(badRes.isError).toBe(true); + expect(badFake.barsCalls).toHaveLength(0); + expect(badFake.universeCalls).toHaveLength(0); + } + }); + + test('rejects scope, vault_evaluation_only, or unknown keys with isError: true and zero store calls', async () => { + const injectedPayloads: Record[] = [ + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + scope: 'vault_evaluation_only', + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + scope: 'vault_fenced', + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + vault_evaluation_only: true, + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + unknownFlag: 'x', + }, + ]; + + for (const args of injectedPayloads) { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], + }); + const res = await callQueryData(fake, args); + expect(res.isError).toBe(true); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); + } + }); + + test('range starting at or after vaultCutoffTs returns isError: true naming VaultHoldoutFenceError with zero store calls', async () => { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 3, 5, 20, 0, 0), 200)] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-31', + to: '2025-04-15', + }); + + expect(res.isError).toBe(true); + expect(res.text).toContain('VaultHoldoutFenceError'); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); + }); + + test('range straddling vaultCutoffTs clamps to/asOf strictly below cutoff', async () => { + const preBar = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 150); + const fake = createFakeStore({ + batches: [{ rows: [preBar] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-30', + asOf: '2025-05-01', + }); + + expect(res.isError).toBe(false); + expect(fake.barsCalls).toHaveLength(1); + expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); + expect(Date.parse(fake.barsCalls[0]?.to ?? '')).toBe(VAULT_CUTOFF_TS - 1); + expect(Date.parse(fake.barsCalls[0]?.asOf ?? '')).toBe(VAULT_CUTOFF_TS - 1); + + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.toMs).toBe(VAULT_CUTOFF_TS - 1); + expect(payload.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(payload.rows).toEqual([preBar]); + }); + + test('defense-in-depth drops post-cutoff rows (ts >= cutoff or knownAt >= cutoff) from a leaky store', async () => { + const preBar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150); + const leakyTsBar = makeBar(101, VAULT_CUTOFF_TS, 999); + const leakyFutureTsBar = makeBar(101, Date.UTC(2025, 3, 2, 20, 0, 0), 1000); + const leakyKnownAtBar = makeBar( + 101, + Date.UTC(2025, 2, 25, 20, 0, 0), + 148, + VAULT_CUTOFF_TS + ); + + const fake = createFakeStore({ + batches: [{ rows: [preBar, leakyTsBar, leakyFutureTsBar, leakyKnownAtBar] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-15', + }); + + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.rows).toEqual([preBar]); + }); + + test('universe path resolves strictly pre-cutoff date and handles empty universe cleanly', async () => { + const preBar = makeBar(202, Date.UTC(2025, 2, 28, 20, 0, 0), 50); + const populatedFake = createFakeStore({ + universeIds: [202], + batches: [{ rows: [preBar] }], + }); + + const res = await callQueryData(populatedFake, { + universe: 'US_EQ', + from: '2025-03-01', + to: '2025-04-30', + }); + + expect(res.isError).toBe(false); + expect(populatedFake.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); + expect(populatedFake.barsCalls).toHaveLength(1); + expect(populatedFake.barsCalls[0]?.listingIds).toEqual([202]); + expect(populatedFake.barsCalls[0]?.scope).toBe('vault_fenced'); + + // Empty universe -> zero bars() calls + const emptyFake = createFakeStore({ universeIds: [] }); + const emptyRes = await callQueryData(emptyFake, { + universe: 'CA_EQ', + from: '2025-03-01', + to: '2025-03-30', + }); + expect(emptyRes.isError).toBe(false); + expect(emptyFake.universeCalls).toHaveLength(1); + expect(emptyFake.barsCalls).toHaveLength(0); + const emptyPayload = JSON.parse(emptyRes.text) as QueryDataResultPayload; + expect(emptyPayload.rowCount).toBe(0); + expect(emptyPayload.rows).toEqual([]); + }); + + test('maps store domain errors to isError: true naming the exact error class without stack traces', async () => { + const domainErrors: readonly [Error, string][] = [ + [new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'], + [new MarketDataStoreValidationError('Bad timeframe bound', 'from'), 'MarketDataStoreValidationError'], + [new MarketDataStoreNotImplementedError('bars', '1m not supported'), 'MarketDataStoreNotImplementedError'], + [new AdjFactorsSnapshotError('retrospective_rejected', 'Retrospective snapshot rejected'), 'AdjFactorsSnapshotError'], + ]; + + for (const [err, expectedName] of domainErrors) { + const fake = createFakeStore({ barsError: err }); + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + expect(res.isError).toBe(true); + expect(res.text).toContain(expectedName); + expect(res.text).not.toContain('\n'); + expect(res.text).not.toContain('at '); + } + }); + + test('repeated identical calls produce byte-identical JSON output', async () => { + const bar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.25); + const fake1 = createFakeStore({ batches: [{ rows: [bar] }] }); + const fake2 = createFakeStore({ batches: [{ rows: [bar] }] }); + + const args = { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + timeframe: '1d', + adjustment: 'raw', + limit: 10, + }; + + const res1 = await callQueryData(fake1, args); + const res2 = await callQueryData(fake2, args); + expect(res1.rawResponse).toBe(res2.rawResponse); + }); +}); diff --git a/libs/research/test/mcp-stdio.test.ts b/libs/research/test/mcp-stdio.test.ts new file mode 100644 index 00000000..08d38bd5 --- /dev/null +++ b/libs/research/test/mcp-stdio.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import { + JSON_RPC_ERROR_CODES, + type StdioOutput, + createMcpServer, + defineMcpTool, + runStdioServer, +} from '../src/mcp/index'; + +function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } { + const chunks: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }; + return { + output, + chunks, + text: () => chunks.join(''), + }; +} + +async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator { + for (const chunk of chunks) { + yield chunk; + } +} + +describe('MCP stdio transport', () => { + test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => { + const echoTool = defineMcpTool({ + name: 'echo_label', + description: 'Echoes a UTF-8 label.', + inputSchema: z.object({ label: z.string() }).strict(), + handler(input) { + return { + content: [{ type: 'text', text: input.label }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const encoder = new TextEncoder(); + const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; + const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`; + const msg3Bytes = encoder.encode( + `${JSON.stringify({ + jsonrpc: '2.0', + id: 'utf8-2', + method: 'tools/call', + params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } }, + })}\n` + ); + + // Split right in the middle of the multi-byte UTF-8 emoji sequence. + const rocketStart = msg3Bytes.indexOf(0xf0); + expect(rocketStart).toBeGreaterThan(0); + const splitPoint = rocketStart + 2; + + const input = yieldChunks([ + encoder.encode(msg1), + encoder.encode(msg2), + msg3Bytes.slice(0, splitPoint), + msg3Bytes.slice(splitPoint), + ]); + + const sink = createMemoryOutput(); + await runStdioServer(server, { input, output: sink.output }); + + const rawOut = sink.text(); + expect(rawOut.endsWith('\n')).toBe(true); + const lines = rawOut.slice(0, -1).split('\n'); + expect(lines).toHaveLength(2); + + const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record }; + const resp2 = JSON.parse(lines[1] ?? '') as { + id: string; + result: { content: { type: string; text: string }[] }; + }; + + expect(resp1.id).toBe(1); + expect(resp1.result).toEqual({}); + expect(resp2.id).toBe('utf8-2'); + expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ'); + }); + + test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => { + const delayedTool = defineMcpTool({ + name: 'delayed', + description: 'Resolves after deterministic microtask/timer delay.', + inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(), + async handler(input) { + await new Promise(resolve => { + setTimeout(resolve, input.delayMs); + }); + return { + content: [{ type: 'text', text: input.tag }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [delayedTool], + }); + + const payload = [ + JSON.stringify({ + jsonrpc: '2.0', + id: 'first-slow', + method: 'tools/call', + params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } }, + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 'second-fast', + method: 'tools/call', + params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } }, + }), + ].join('\n'); + + const sink = createMemoryOutput(); + await runStdioServer(server, { + input: yieldChunks([`${payload}\n`]), + output: sink.output, + }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const first = JSON.parse(lines[0] ?? '') as { id: string }; + const second = JSON.parse(lines[1] ?? '') as { id: string }; + expect(first.id).toBe('first-slow'); + expect(second.id).toBe('second-fast'); + }); + + test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const input = yieldChunks([ + '\n \r\n', + `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`, + '\n', + JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }), + ]); + + const sink = createMemoryOutput(); + await runStdioServer(server, { input, output: sink.output }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1); + expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2); + }); + + test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`; + const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`; + + const sink = createMemoryOutput(); + await runStdioServer(server, { + input: yieldChunks([hugeLine, nextLine]), + output: sink.output, + maxLineBytes: 128, + }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const errResp = JSON.parse(lines[0] ?? '') as { + id: null; + error: { code: number }; + }; + const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record }; + expect(errResp.id).toBeNull(); + expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + expect(okResp.id).toBe(2); + expect(okResp.result).toEqual({}); + }); +});