import {z} from 'zod' export type McpJsonRpcRequest = {jsonrpc: '2.0', id?: (string | null | number) | undefined, method: string, params?: {[key: string]: unknown} | undefined}; export type CreateApiMcpArgs = {Accept: string, 'MCP-Protocol-Version'?: string | undefined, Origin?: string | undefined, body: McpJsonRpcRequest}; export type CreateApiMcpOptions = {baseUrl?: string | undefined, McpOAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const mcpJsonRpcResponse = z.object({jsonrpc: z.literal("2.0"), id: z.union([z.string().nullable(), z.number()]).optional(), result: z.record(z.string(), z.unknown()).optional(), error: z.record(z.string(), z.unknown()).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Streamable HTTP JSON-RPC endpoint for remote MCP clients. * * POST /mcp */ export const createApiMcp = async (args: CreateApiMcpArgs, options?: CreateApiMcpOptions) => { const {baseUrl = "https://api.traxy.ai/api/v1", fetch: fetchFn = fetch, McpOAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Accept != null) headers.set("Accept", String(args.Accept)) if (args['MCP-Protocol-Version'] != null) headers.set("MCP-Protocol-Version", String(args['MCP-Protocol-Version'])) if (args.Origin != null) headers.set("Origin", String(args.Origin)) if (McpOAuth !== undefined) headers.set('authorization', `Bearer ${McpOAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/mcp${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(mcpJsonRpcResponse, await res.json()) };