UNPKG

autosnippet

Version:

Extract code patterns into a knowledge base for AI coding assistants

33 lines (32 loc) 1.51 kB
/** * MCP 工具统一错误处理 * * 提供 wrapHandler() 包装函数,将所有 handler 的异常统一转换为 * envelope 格式的错误响应,确保: * 1. Zod schema 校验 → 结构化 VALIDATION_ERROR (外部输入防御) * 2. 已知业务错误 → 结构化 errorCode + message * 3. 未知异常 → 通用 INTERNAL_ERROR + 原始 message * 4. 一致的 meta.tool + meta.responseTimeMs * * @module external/mcp/errorHandler */ import { z } from 'zod'; /** Handler function signature for MCP tools */ type McpHandlerFn = (ctx: Record<string, unknown>, args: Record<string, unknown>) => Promise<unknown>; /** * 包装 MCP handler 函数,提供 Zod 输入校验 + 统一错误处理 * * 如果 TOOL_SCHEMAS 中存在 toolName 对应的 Zod schema, * 则在 handler 执行前自动校验并 parse(应用 defaults + coercion), * 校验失败返回结构化 VALIDATION_ERROR,不会到达 handler。 * * @param toolName 工具名(用于 meta.tool + schema 查找) * @param handlerFn 原始 handler: (ctx, args) => Promise<unknown> * @param [schema] 可选的显式 schema 覆盖(优先于 TOOL_SCHEMAS 自动查找) * @returns 包装后的 handler,保证 *不会* throw */ export declare function wrapHandler(toolName: string, handlerFn: McpHandlerFn, schema?: z.ZodType): (ctx: Record<string, unknown>, rawArgs: Record<string, unknown>) => Promise<unknown>; declare const _default: { wrapHandler: typeof wrapHandler; }; export default _default;