74 / 90

Day 74:工具 Schema、验证与协议边界

把工具定义为 JSON Schema 契约,将验证失败按层分类,定位 MCP 的 host/client/server 角色——不从玩具装置声称协议合规。

Agent(智能体) 480 分钟有效研习(8 小时)
01 120 分钟

作为契约的工具 Schema:tool_use、tool_calls 与 JSON Schema

Agent 辅助工程检查

前置要求

Day 73 的控制循环;Python 区块中的基础 JSON 与函数签名。

学习目标

说明生产级模型 API 如何声明工具(name、description、JSON Schema 的 parameters)、tool_use / tool_calls 块如何携带名称与参数、MCP 如何把同一契约推广为 host/client/server 角色——同时明确有界装置未实现的范围。

操作指引

1. 工具 Schema 是一份契约:唯一的 name、自然语言的 description,以及列出 properties、类型、required 字段与 additionalProperties 策略的 JSON Schema parameters 对象。模型只能提案它见过 Schema 的调用。
2. Anthropic 方式:模型返回 tool_use 内容块 {id, name, input};客户端执行后以 tool_result 块回复。OpenAI 方式:模型返回 tool_calls[{id, function:{name, arguments(JSON 字符串)}}];客户端以 role:"tool" 消息回复。两者都把模型的请求与工具的执行分离——与本装置在 next_action 与 _tool_call 之间划的接缝相同。
3. MCP 一段话:host 进程内嵌 client;每个 client 与一个 server 维持一条连接,server 通过 JSON-RPC 2.0 暴露 tools、resources 与 prompts,并在 initialize 时做能力协商;传输层为 stdio 或 streamable HTTP。
4. 合规边界:projects.agent_learning 用手写参数检查硬编码了三个工具。它只演示分发与验证的形态——没有 JSON-RPC 帧、没有 initialize 握手、没有工具发现、没有 Schema 协商。把它当作循环形态来学,不要当成协议实现。
5. Schema 为什么重要:它是验证器强制的表面;畸形调用在工具运行前就会失败在 Schema 层。

自主演练与记录

把三个项目工具(list_notes、read_note、write_report)写成 Anthropic 风格的工具定义,每个含 name、description 与 input_schema 的 JSON Schema。

独立掌握标准

为三个工具全部产出有效工具定义,并说出玩具装置缺失的至少两项协议特性(JSON-RPC 帧、能力协商、发现机制、流式传输)。

权威源资源与权利证明

linking Anthropic PBC copyright (no open license stated) / linked reference Linking only; no documentation text is copied

Anthropic Tool Use (Function Calling) Implementation Guide

作者 / 机构: Anthropic PBC | 原始出处链接 ↗

对应章节 / 时间戳: Tool Use Overview, Schema Definitions, and Stop Reasons

验证版本与日期: Claude API Specification (Verified: 2026-10-30)

入选理由:

Detailed production reference for client-side tool definitions, tool_use content blocks, stop reason tool_use, and tool_result response formatting.

来源前置条件:

REST API concepts, JSON schema specification, and basic Python client programming.

安全回退方案(离线弹性):

Offline mock request/response cycles and tool payload schemas are provided in the repo.

对比候选资源与选型分析 (2)
Google Gemini Function Calling Documentation ↗ compared_alternative [Creative Commons Attribution 4.0]

Protobuf and REST function declaration schema; Anthropic documentation provides explicit structured message block mechanics (tool_use / tool_result).

Cohere Tool Use and Multi-Step Agents Guide ↗ compared_alternative [Open Documentation]

Multi-step tool calling parameter definitions; Anthropic specification demonstrates clear separated content blocks essential for inspectable event traces.

linking OpenAI copyright (no open license stated) / linked reference Linking only; no documentation text is copied

OpenAI Function Calling and Structured Outputs Guide

作者 / 机构: OpenAI | 原始出处链接 ↗

对应章节 / 时间戳: Function Calling Architecture and Strict Outputs

验证版本与日期: OpenAI API Reference (Verified: 2026-10-30)

入选理由:

Widely adopted specification establishing tool choice parameters, JSON schema function descriptions, tool_calls arrays, and role: "tool" responses.

来源前置条件:

JSON data structures, chat completion roles, and schema validation.

安全回退方案(离线弹性):

Standard schema dictionaries and simulated tool call responses are bundled in the repository.

对比候选资源与选型分析 (2)
Mistral AI Function Calling Guide ↗ compared_alternative [Open Documentation]

Follows OpenAI-compatible schema convention; OpenAI documentation serves as the primary originating reference for tools and tool_calls schemas.

Ollama Tools and Function Calling Documentation ↗ compared_alternative [MIT / Open Documentation]

Local model runtime implementation of function calling; OpenAI docs document the standard schema contract and strict output validation.

02 120 分钟

为 read_note 参数编写并应用 JSON Schema

独立掌握检查(无 AI 辅助)

前置要求

Day 74 活动 1:工具 Schema 的结构与契约思想。

学习目标

独立为 read_note 参数编写 JSON Schema(draft 2020-12)object 结构,并用它分类四个候选参数负载,包括仅靠 Schema 验证不足够的情形。

操作指引

1. 编写结构:type 为 object;properties.filename 为 string;required 为 [filename];additionalProperties 为 false;可选地加 pattern 限制路径分隔符。
2. 用你的结构与装置规则 Path(filename).name == filename 双重判定四个负载:
a) {"filename": "alpha.txt"} ——Schema 通过,装置接受。
b) {"filename": "../outside.txt"} ——宽松 Schema 下字符串可以通过,但装置的 basename 检查拦截路径穿越,判 invalid_arguments。要点:Schema 验证是必要而非充分条件,策略检查位于更深一层。
c) {"file": "alpha.txt"} ——required 不满足(缺 filename)且违反 additionalProperties —— invalid_arguments。
d) {"filename": 42} ——类型不符 —— invalid_arguments。
3. 按 负载 / Schema 判定 / 装置判定 / 错误码 四列记录到表格。
4. 适配器的第一条故障路径之所以发出 ../outside.txt 正是为此:修复依赖诚实的错误观察,而不是 Schema 静默地改写输入。

自主演练与记录

编写 read_note.schema.json,并对负载 a-d 填一张四行判定表(Schema 判定 / 装置判定 / 错误码)。

独立掌握标准

独立写出含 required 与 additionalProperties 的结构;四个判定全对,包括“Schema 通过但装置拒绝”的穿越情形。

权威源资源与权利证明

linking IETF Trust License / Open Standard

JSON Schema: A Media Type for Describing JSON Documents (Draft 2020-12)

作者 / 机构: Austin Wright, Henry Andrews, Ben Hutton, Greg Dennis | 原始出处链接 ↗

对应章节 / 时间戳: Section 4 & 5 (Schema Objects and Keywords)

验证版本与日期: IETF Internet-Draft 2020-12 (Verified: 2026-10-30)

入选理由:

The normative standard governing parameter schemas, type validation, required constraints, additionalProperties restrictions, and descriptive metadata in tool definitions.

来源前置条件:

JSON data interchange formats, data typing, and structural validation concepts.

安全回退方案(离线弹性):

Compact schema validator examples and standard validation rules are embedded in local project code.

对比候选资源与选型分析 (2)
OpenAPI Specification 3.1.0 (OAI) ↗ compared_alternative [Apache-2.0]

Comprehensive REST API specification format; JSON Schema Draft 2020-12 is the exact underlying core used by modern agent tool definition protocols.

JSON Schema Draft-07 Specification ↗ compared_alternative [IETF Open Standard]

Legacy JSON schema dialect; modern tool protocols standardise on 2020-12 with strict keyword support.

linking IETF Trust License / Open Standard

RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format

作者 / 机构: Tim Bray (Ed.) | 原始出处链接 ↗

对应章节 / 时间戳: Section 1-4 (JSON Syntax and Grammar)

验证版本与日期: IETF Standards Track RFC 8259 (Verified: 2026-10-30)

入选理由:

Foundational Internet standard defining strict JSON grammar, token parsing, and whitespace rules underpinning model tool calling serialization.

来源前置条件:

Text encoding, UTF-8 parsing, and serialized data exchange.

安全回退方案(离线弹性):

JSON grammar parsing rules and error recovery guidelines are documented in curriculum notes.

对比候选资源与选型分析 (2)
RFC 7049: Concise Binary Object Representation (CBOR) ↗ compared_alternative [IETF Open Standard]

Binary serialization standard; text-based LLMs operate primarily on human-readable UTF-8 JSON interchange formats.

YAML 1.2 Specification (OASIS / yaml.org) ↗ compared_alternative [Open Standard]

Indentation-sensitive text format; JSON has universally standardized parsing across language runtimes and tool schemas.

03 120 分钟

故障词汇:unknown_tool、invalid_arguments、not_found、size_limit

Agent 辅助工程检查

前置要求

Day 74 活动 2:Schema 验证与装置策略检查。

学习目标

把装置发出的每个结构化错误映射到产生它的验证层(存在性、参数形状、资源状态、负载大小),并把扁平的 {ok:false,error} 形态与协议级错误面关联起来。

操作指引

1. 阅读 projects/agent_learning/agent.py 的 _tool_call 并列表:
- name 不在 ALLOWED_TOOLS -> unknown_tool(分发层)。
- arguments 非 Mapping,或键多/少 -> invalid_arguments(Schema 层)。
- read_note 的 filename 违反 basename 规则 -> invalid_arguments(Schema 层内的策略子层)。
- 磁盘上无此笔记 -> not_found(工具运行时层)。
- write_report 的 content 超 4096 字节 -> size_limit(资源限制层)。
2. 在 tempfile 工作区里的 Python REPL 中逐一触发这些错误(先 create_fixture),记录观察对象。
3. 畸形结果:真实协议中工具必须返回可序列化的结果;若工具输出非 JSON,协议层自身会抛错(带 code 与 message 的 JSON-RPC 错误对象)。本装置的扁平错误字符串是对该面的教学化简。
4. 结构化错误为何重要:适配器的修复步骤依据观察重新规划;含糊的失败只会让循环瞎猜。

自主演练与记录

在 REPL 中调用 _tool_call 传入 {"name": "delete_all", "arguments": {}},以及 content 为 5000 字符的 write_report;记录两个观察并补入错误分层表。

独立掌握标准

以正确的层归属复现全部四个错误码,并能用一段协议术语解释畸形结果的风险。

权威源资源与权利证明

linking Apache-2.0 (specification; unrelicensed legacy contributions remain MIT) / Open Specification

Model Context Protocol (MCP) Specification

作者 / 机构: Anthropic PBC & Open Source Contributors | 原始出处链接 ↗

对应章节 / 时间戳: Architecture Overview, Transports, Tools, and Resources

验证版本与日期: MCP Specification 2024-11-05 (Verified: 2026-10-30)

入选理由:

Normative open architecture specification defining Host, Client, and Server separation, resource subscriptions, tool listing/invoking primitives, and JSON-RPC 2.0 message framing.

来源前置条件:

Client-server architecture, JSON-RPC 2.0 protocol, and standard IO communication.

安全回退方案(离线弹性):

Architectural comparison tables, loop invariants, and message frame examples are self-contained in curriculum materials.

对比候选资源与选型分析 (2)

Precursor JSON-RPC architecture for code intelligence in IDEs; MCP adapts similar client-server decoupling specifically for LLM context, tools, and prompts.

OpenAI Responses API Built-in Tools ↗ compared_alternative [Proprietary Documentation]

Hosted, vendor-managed built-in tool execution (successor to the Assistants API tools); MCP provides an open, decoupled local/remote client-server standard.

linking Anthropic PBC copyright (no open license stated) / linked reference Linking only; no documentation text is copied

Anthropic Tool Use (Function Calling) Implementation Guide

作者 / 机构: Anthropic PBC | 原始出处链接 ↗

对应章节 / 时间戳: Tool Use Overview, Schema Definitions, and Stop Reasons

验证版本与日期: Claude API Specification (Verified: 2026-10-30)

入选理由:

Detailed production reference for client-side tool definitions, tool_use content blocks, stop reason tool_use, and tool_result response formatting.

来源前置条件:

REST API concepts, JSON schema specification, and basic Python client programming.

安全回退方案(离线弹性):

Offline mock request/response cycles and tool payload schemas are provided in the repo.

对比候选资源与选型分析 (2)
Google Gemini Function Calling Documentation ↗ compared_alternative [Creative Commons Attribution 4.0]

Protobuf and REST function declaration schema; Anthropic documentation provides explicit structured message block mechanics (tool_use / tool_result).

Cohere Tool Use and Multi-Step Agents Guide ↗ compared_alternative [Open Documentation]

Multi-step tool calling parameter definitions; Anthropic specification demonstrates clear separated content blocks essential for inspectable event traces.

04 120 分钟

评估:验证层与协议合规边界

独立掌握检查(无 AI 辅助)

前置要求

完成 Day 74 活动 1-3。

学习目标

独立把八个验证场景按层分类,并写出评分标准要求的合规边界声明。

操作指引

1. 把每个场景归入且仅归入一层——序列化、Schema、分发、工具运行时或资源限制——并给出可观察错误:(a) arguments 文本不是合法 JSON;(b) 缺必需键;(c) 注册表中没有的工具名;(d) 磁盘上无该笔记;(e) 报告内容超 4096 字节;(f) filename 含 ../;(g) arguments 是列表而非对象;(h) 真实协议中工具结果无法序列化为 JSON。
2. 写三句合规边界声明:本装置教授循环与验证形态;它不是 MCP 客户端;它不证明任何协议合规。指出至少两项缺失的协议特性。
3. 独立评分标准:八项至少对七项,边界声明完整,无协助。
4. 协助评分标准:可以让 Agent 起草表格,但每一行必须由你亲自对照 _tool_call 源码核实。

自主演练与记录

不打开 agent.py 完成八行分类表与三句边界声明,随后对照源码核对。

独立掌握标准

独立掌握检查:八行至少对七行,且无协助地说出含两项缺失协议特性的边界声明。

权威源资源与权利证明

linking Apache-2.0 (specification; unrelicensed legacy contributions remain MIT) / Open Specification

Model Context Protocol (MCP) Specification

作者 / 机构: Anthropic PBC & Open Source Contributors | 原始出处链接 ↗

对应章节 / 时间戳: Architecture Overview, Transports, Tools, and Resources

验证版本与日期: MCP Specification 2024-11-05 (Verified: 2026-10-30)

入选理由:

Normative open architecture specification defining Host, Client, and Server separation, resource subscriptions, tool listing/invoking primitives, and JSON-RPC 2.0 message framing.

来源前置条件:

Client-server architecture, JSON-RPC 2.0 protocol, and standard IO communication.

安全回退方案(离线弹性):

Architectural comparison tables, loop invariants, and message frame examples are self-contained in curriculum materials.

对比候选资源与选型分析 (2)

Precursor JSON-RPC architecture for code intelligence in IDEs; MCP adapts similar client-server decoupling specifically for LLM context, tools, and prompts.

OpenAI Responses API Built-in Tools ↗ compared_alternative [Proprietary Documentation]

Hosted, vendor-managed built-in tool execution (successor to the Assistants API tools); MCP provides an open, decoupled local/remote client-server standard.

linking IETF Trust License / Open Standard

JSON Schema: A Media Type for Describing JSON Documents (Draft 2020-12)

作者 / 机构: Austin Wright, Henry Andrews, Ben Hutton, Greg Dennis | 原始出处链接 ↗

对应章节 / 时间戳: Section 4 & 5 (Schema Objects and Keywords)

验证版本与日期: IETF Internet-Draft 2020-12 (Verified: 2026-10-30)

入选理由:

The normative standard governing parameter schemas, type validation, required constraints, additionalProperties restrictions, and descriptive metadata in tool definitions.

来源前置条件:

JSON data interchange formats, data typing, and structural validation concepts.

安全回退方案(离线弹性):

Compact schema validator examples and standard validation rules are embedded in local project code.

对比候选资源与选型分析 (2)
OpenAPI Specification 3.1.0 (OAI) ↗ compared_alternative [Apache-2.0]

Comprehensive REST API specification format; JSON Schema Draft 2020-12 is the exact underlying core used by modern agent tool definition protocols.

JSON Schema Draft-07 Specification ↗ compared_alternative [IETF Open Standard]

Legacy JSON schema dialect; modern tool protocols standardise on 2020-12 with strict keyword support.