来源:Claude Code Cookbook · Part 34 · 原文标题:Part 34 — Building Custom Agents
面向 🔴 Advanced → Agent Engineer 读者。本章通过 Agent SDK 实现一个完整、可运行的 Agent 应用项目
agent-app/:包含 CLI、Session、自定义工具、Structured Output、MCP、Subagent、日志、错误处理、审批、测试与 README。
官方参考:Agent SDK overview、Quickstart、Custom tools、Structured outputs、Python reference
34.0 项目目标
构建一个 Code Review Agent:它读取一个 git diff,调用自定义工具获取提交元数据,让模型输出结构化的审查结论(问题清单 + 严重度),并把结果写成 JSON 文件。
语言选 Python(claude-agent-sdk)。TypeScript 对应 API 见 Part 33 与注释。
34.1 项目目录
1 | agent-app/ |
34.2 依赖
requirements.txt:
1 | claude-agent-sdk |
安装:
1 | python3 -m venv .venv && source .venv/bin/activate |
34.3 自定义工具(tools.py)
tools.py 定义一个读取 git diff 的自定义工具,通过 SDK 内置的 in-process MCP server 暴露:
1 | from claude_agent_sdk import tool, create_sdk_mcp_server |
34.4 主程序(agent.py)
1 | import asyncio, json |
34.5 MCP / Subagent / 审批 / 日志(扩展点)
- MCP 外部 server:
ClaudeAgentOptions(mcp_servers={"github": {"type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"]}})。 - Subagent:
options传agents={"reviewer": {"description": "...", "prompt": "...", "tools": ["Read"]}},并在 allowedTools 加Agent。 - 审批:
permission_mode="acceptEdits"自动批准写入;或用can_use_tool回调自定义决策。 - 日志:
env开启 OTel(见 Part 43)或把 stdout 转 JSON 事件。 - 错误处理:检查
msg.type == "result"的subtype(error_max_turns、error_max_budget_usd等)与errors列表。
34.6 运行与验证
1 | source .venv/bin/activate |
验证:review.json 存在且符合 SCHEMA。
34.7 测试(tests/test_agent.py)
1 | def test_schema_valid(): |
34.8 清理与安全
- 删除练习产生的
review.json:rm review.json。 - Agent 需要 API key:
export ANTHROPIC_API_KEY=...(或受支持的 Provider 环境变量)。 - 不要让 Agent 接触真实秘密;
can_use_tool或disallowed_tools限制危险工具。