好的 Schema = AI 一看就会用,差的 Schema = AI 一直调用失败
Schema 是 AI 和工具之间的"契约"。好的 Schema 设计让 AI 准确理解什么时候用、怎么传参、期待什么返回。本文总结 10 条 Schema 设计黄金法则。
MCP Server 通过 Zod Schema 告诉 AI 每个工具需要什么参数。Schema 写不好,AI 就会: - 传错参数类型(应该是数字给了字符串) - 漏必填参数 - 永远不敢调用(参数描述太模糊) Schema 设计的核心原则:**站在 AI 的角度思考,而不是站在开发者的角度**。
❌ 坏:queryUser、get_user_by_id、search-user ✅ 好:search-contacts、find-colleague、query-employee-directory 工具名就是 AI 看到的"可用动作"。用 kebab-case 或 snake_case,避免缩写,让名字一眼就知道干啥的。
每一个参数都要写清楚: - 数据类型和格式要求 - 示例值 - 边界条件 - 和其他参数的互斥 / 依赖关系 // ✅ 好示例 start_date: z.string().describe("ISO 8601 日期,如 2024-01-01。必填。"), end_date: z.string().optional().describe("ISO 8601 日期,如 2024-01-31。不填默认等于今天。"),
❌ 坏:一个 tool 叫 process-order,参数有 20 种操作类型 ✅ 好:拆成 create-order / cancel-order / query-order / list-orders AI 喜欢小而明确的工具。10 个精准工具胜过 1 个万能工具。
返回值不要只给纯文本。尽量返回结构化的 JSON,让上层 AI 好理解、好展示: // ✅ 好 return { content: [{ type: "text", text: JSON.stringify({ city: "北京", temp: 25, condition: "晴", humidity: 60 }) }] }; // 然后 text 里可以附带人类可读的摘要 return { content: [{ type: "text", text: "北京:晴 25°C,湿度 60%" }] };
工具执行失败时,返回带人类可读错误信息的响应,而不是让进程崩掉: try { const result = await doSomething(); return { content: [{ type: "text", text: JSON.stringify(result) }] }; } catch (err) { return { isError: true, content: [{ type: "text", text: `❌ 操作失败:${err.message}` }] }; } AI 会根据 isError 决定要不要重试或换个方式。