JSON Schema 验证 —— 给 MCP 工具穿上"数据校验盔甲",防止垃圾进垃圾出
MCP JSON Schema Validation(JSON Schema 验证)是 MCP 协议中用于定义和验证工具输入输出数据格式的机制。它使用 JSON Schema 标准来描述数据的结构、类型和约束,确保工具调用时传入的参数和返回的结果都符合预期格式。
就像餐厅的菜单:告诉你"这道菜需要什么配料"(输入格式),以及"这道菜长什么样"(输出格式)。
// MCP 工具的 JSON Schema 定义
{
"name": "web_search",
"description": "搜索网页",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索关键词",
"minLength": 1,
"maxLength": 200
},
"count": {
"type": "number",
"description": "返回结果数量",
"minimum": 1,
"maximum": 10,
"default": 5
}
},
"required": ["query"]
}
}
| 规则 | 说明 | 示例 |
|---|---|---|
| type | 数据类型 | string, number, boolean, object, array |
| required | 必填字段 | ["query", "count"] |
| minimum/maximum | 数值范围 | minimum: 1, maximum: 100 |
| minLength/maxLength | 字符串长度 | minLength: 1, maxLength: 200 |
| enum | 枚举值 | ["asc", "desc"] |
| pattern | 正则匹配 | "^[a-zA-Z]+$" |
OpenClaw 自动对所有工具调用进行 Schema 验证,确保数据格式正确。
// SKILL.md 中定义工具 Schema
---
name: my-tool
tools:
- name: create_post
description: "创建博客文章"
input:
type: object
properties:
title:
type: string
minLength: 1
maxLength: 100
description: "文章标题"
content:
type: string
minLength: 100
description: "文章内容"
tags:
type: array
items:
type: string
minItems: 1
maxItems: 10
description: "文章标签"
required: [title, content]
---
// Schema 验证失败示例
工具调用: web_search({ query: "", count: 100 })
验证结果:
{
"valid": false,
"errors": [
{
"field": "query",
"message": "String is too short (0 chars), minimum 1"
},
{
"field": "count",
"message": "Number is too large (100), maximum 10"
}
]
}
最后更新:2026-06-25 | 作者:妙趣AI
有问题?联系我们