如何用 Cline SDK 的 createTool 与 zod 构建读取 git diff 的代码审查机器人?
【免费下载链接】clineAutonomous coding agent as an SDK, IDE extension, or CLI assistant.项目地址: https://gitcode.com/GitHub_Trending/cl/cline
这篇教程解决一个具体任务:用 Cline SDK 的createTool与 zod 构建一个代码审查机器人,它从本地 git 仓库读取 diff,逐条输出带严重级别的审查意见,并在结束时给出总结与 approve/reject 决策。教程基于仓库中的 Building an Agent 文档,配套示例位于 apps/examples/code-review-bot。
完成后的机器人做四件事:
- 从本地仓库读取 git diff
- 按需读取完整文件内容作为上下文
- 产出带严重级别的结构化审查意见
- 以总结和 approve/reject 决策结束本次运行
准备条件
文档给出的前提:
- Node.js 22+
- 一个 Anthropic API key
- 一个至少包含一次提交的 git 仓库
获取示例代码:
git clone https://gitcode.com/GitHub_Trending/cl/cline.git cd cline/apps/examples/code-review-bot bun install也可以不运行示例,直接对照 示例源码 阅读。在自己的项目中使用 SDK 时,按 examples 说明 安装公开包即可:npm add @cline/sdk。
工具的写法参考 Creating Custom Tools 文档。每个工具有四个部分:name(唯一标识,推荐 snake_case)、description(模型据此决定何时调用,是最重要的字段)、inputSchema(zod 或 JSON Schema)、execute(真正干活的函数)。SDK 会自动把 zod schema 转成 JSON Schema,execute里的input是完全类型化的。
用 createTool 与 zod 定义审查意见工具
机器人用createTool加 zod schema 做类型安全的工具定义。审查意见工具的代码如下(来自教程):
import { Agent, createTool } from "@cline/sdk" import { z } from "zod" createTool({ name: "add_review_comment", description: "Add a review comment on a specific file and line.", inputSchema: z.object({ file: z.string().describe("File path"), line: z.number().describe("Line number (approximate is fine)"), severity: z.enum(["critical", "warning", "suggestion"]), comment: z.string().describe("The review comment"), }), async execute(input) { reviews.push(input) return `Comment added (${reviews.length} total)` }, })三个关键点:
z.enum把severity约束在固定取值集合内,文档指出这会提升模型调用的准确性;- 每个字段上的
.describe()告诉模型该提供什么; execute里把结果累积到数组reviews,供运行结束后统一处理。
用完成工具结束 Agent 循环
没有显式的结束信号时,agent 会一直循环到maxIterations。submit_review工具用lifecycle: { completesRun: true }标记为完成工具:调用成功后 agent 循环结束:
createTool({ name: "submit_review", description: "Submit the completed review with a summary.", inputSchema: z.object({ summary: z.string().describe("Brief overall assessment of the changes"), approve: z.boolean().describe("Whether the changes look good to merge"), }), lifecycle: { completesRun: true }, async execute(input) { return JSON.stringify({ summary: input.summary, approve: input.approve }) }, })两个工具通过Agent的tools数组注册(注册写法见 Creating Custom Tools):
const agent = new Agent({ tools: [addReviewComment, submitReview], // ... })系统提示词:固定审查工作流
教程用一段结构化的系统提示词规定审查范围和流程。明确告诉 agent 用哪个工具、何时用,可以保持工作流可预测:
const agent = new Agent({ systemPrompt: `You are a senior code reviewer. Analyze the git diff provided and leave review comments using the add_review_comment tool. Focus on: - Bugs and logic errors (critical) - Security issues (critical) - Performance problems (warning) - Style and readability improvements (suggestion) When you are done reviewing, call submit_review with a brief summary.`, // ... })事件流:运行中即时看到审查意见
通过subscribe订阅事件,可以在 agent 工作时流式输出进度,而不是等整个 run 结束:
agent.subscribe((event) => { switch (event.type) { case "assistant-text-delta": process.stdout.write(event.text ?? "") break case "tool-started": if (event.toolCall.toolName === "add_review_comment") { const input = event.toolCall.input console.log(` [${input.severity}] ${input.file}:${input.line} - ${input.comment}`) } break } })教程的用法是:tool-started事件里按工具名过滤,每产生一条意见就立刻打印出来。
运行与验证
运行阶段把 diff 交给 agent,结束后按严重级别分组汇总。diff变量即本地仓库的 git diff 内容:
const result = await agent.run(`Review this git diff:\n\n\`\`\`diff\n${diff}\n\`\`\``) const critical = reviews.filter((r) => r.severity === "critical") const warnings = reviews.filter((r) => r.severity === "warning") const suggestions = reviews.filter((r) => r.severity === "suggestion")在示例目录中启动(sk-ant-...处替换为你自己的 Anthropic API key):
ANTHROPIC_API_KEY=sk-ant-... bun dev # review last commit ANTHROPIC_API_KEY=sk-ant-... bun dev main # review against main文档描述的预期行为:
- 运行过程中,每条审查意见随
tool-started事件流式打印,格式为[severity] file:line - comment; - 运行结束后,程序把
reviews数组按critical/warning/suggestion分组打印汇总; - agent 调用
submit_review后本次运行干净结束,返回值包含总结与 approve/reject 布尔值。
一个需要留意的差异:仓库当前 code-review-bot 示例 已演进为面向真实 GitHub PR 的审查面板(使用CLINE_API_KEY,bun run build:sdk后bun dev,打开 http://localhost:3457 粘贴 PR URL 运行),它的工具集是get_file_context、add_review_finding、submit_review。上面的ANTHROPIC_API_KEY命令与本地 git diff 流程对应的是教程描述的早期版本。如果你只需要"本地 diff + 两个工具"的最小实现,按本文代码自行搭一个工程即可;两个版本共用的模式是createTool+ zod schema、lifecycle: { completesRun: true }和事件订阅。
可选延伸
教程给出的后续方向,均需要自行实现:
- 加一个工具把审查意见通过 GitHub API 发回 PR;
- 用
continue()对具体发现做追问; - 加一个
checkstyle工具,对改动文件跑 linter; - 接 webhook 实现 PR 自动审查。
工具本身的测试与错误处理细节(如把错误作为结构化数据返回而不是抛异常)见 Creating Custom Tools。
【免费下载链接】clineAutonomous coding agent as an SDK, IDE extension, or CLI assistant.项目地址: https://gitcode.com/GitHub_Trending/cl/cline
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考