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.