stock-bot/libs/research/src/mcp/protocol.ts
2026-11-30 23:29:51 -05:00

274 lines
7.9 KiB
TypeScript

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;
}
/** Valid MCP progress token (`string | finite number`). */
export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]);
export type McpProgressToken = z.infer<typeof mcpProgressTokenSchema>;
/** Standard optional MCP `_meta` request/notification metadata bag. */
export const mcpRequestMetaSchema = z
.object({
progressToken: mcpProgressTokenSchema.optional(),
})
.passthrough();
export type McpRequestMeta = z.infer<typeof mcpRequestMetaSchema>;
const jsonObjectSchema = z.custom<Record<string, unknown>>(
(value): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value),
{ message: 'Expected a JSON object.' }
);
/** 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(),
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `notifications/initialized` params schema. */
export const mcpInitializedNotificationParamsSchema = z
.object({
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `ping` params schema. */
export const mcpPingParamsSchema = z
.object({
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `tools/list` params schema. */
export const mcpToolsListParamsSchema = z
.object({
cursor: z.string().min(1).optional(),
_meta: mcpRequestMetaSchema.optional(),
})
.strict();
/** Strict MCP `tools/call` params schema (preserves own keys on `arguments`). */
export const mcpToolsCallParamsSchema = z
.object({
name: z.string().min(1),
arguments: jsonObjectSchema.optional(),
_meta: mcpRequestMetaSchema.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,
};
}