
Cline SDK 工具系统详解createTool 自定义工具、工具策略与 ClineCore 内置工具实战【免费下载链接】clineAutonomous coding agent as an SDK, IDE extension, or CLI assistant.项目地址: https://gitcode.com/GitHub_Trending/cl/cline本文基于 Cline SDK 官方技能文档 Tools Reference系统讲解 Cline SDK 的工具Tools体系如何用createTool()定义自定义工具、JSON Schema 与 Zod 两种入参校验方式、工具配置项与默认值、工具策略toolPolicies、中止信号、流式输出与测试方法。读完本文你可以独立编写、注册并治理一个 Agent 的完整工具集并理解各参数在 createTool 源码 中的实际行为。工具是 Agent 与世界交互的方式Cline SDK 的 Agent 通过工具与世界交互。工具分两类内置工具Built-in Tools由ClineCore提供开启enableTools: true后自动可用覆盖 Shell 执行、文件编辑、读取、补丁、搜索、网页抓取等高频能力自定义工具Custom Tools你自己用createTool()定义封装业务逻辑如查询 Issue、触发部署、调用内部 API与内置工具同等地暴露给模型。使用 createTool 创建自定义工具createTool()从cline/sdk或cline/shared导出接收一个配置对象返回一个AgentTool实例。基础示例原始 JSON Schemaimport { createTool } from cline/sdk const myTool createTool({ name: search_issues, description: Search GitHub issues by query. Returns up to 10 results., inputSchema: { type: object, properties: { query: { type: string, description: Search query }, state: { type: string, enum: [open, closed, all] }, }, required: [query], }, execute: async (input) { const issues await github.searchIssues(input.query, input.state) return { issues, count: issues.length } }, })Zod Schema 方式如果偏好类型推导inputSchema可以直接传 Zod schemaexecute的入参类型会被推导为z.inferTSchemaimport { createTool } from cline/sdk import { z } from zod const deployTool createTool({ name: deploy, description: Deploy the app to the specified environment., inputSchema: z.object({ environment: z.enum([staging, production]).describe(Target environment), version: z.string().optional().describe(Version tag, defaults to latest), }), execute: async (input) { const result await deploy(input.environment, input.version) return { url: result.url, status: deployed } }, })源码深读createTool 对 inputSchema 做了什么从 sdk/packages/shared/src/tools/create.ts 的实现看createTool有三个重载签名JSON Schema 对象、Zod schema、二者的联合内部流程是Zod 转换若传入的是z.ZodType实例先经过zodToJsonSchema转换为 JSON Schema见 agent.ts 中的类型定义。schema 规范化normalizeToolInputSchema剥离 Zod v4toJSONSchema()输出的$schema元键避免它出现在发给模型的 tool 定义中若 schema 没有显式type但包含properties/required/additionalProperties自动补上顶层type: object处理allOf/anyOf/oneOf要求顶层必须是对象形状。allOf只要有一个分支显式type: object即可而anyOf/oneOf的所有分支都必须声明type: object否则在注册期就抛出错误——混合类型的 union如object | string不能直接作为inputSchema应把严格对象 schema 传给inputSchema把 union/强制转换逻辑留在execute()内部。回填执行策略默认值并原样返回工具对象。这些行为在 create.test.ts 中有完整测试覆盖例如顶层 anyOf 含非对象分支时抛错和Zod union schema 直接作为 inputSchema 时抛错两个回归用例正是针对union schema 静默下发给 LLM provider 导致推理期报错这一类缺陷。工具配置项与默认值createTool的完整配置选项及默认值如下默认值以 create.ts 源码 与测试断言为准createTool({ name: string, // snake_case单个 agent 内唯一 description: string, // 工具做什么模型据此决策 inputSchema: JSONSchema | ZodSchema, // 入参校验 execute: async (input, context, onChange?) output, timeoutMs?: number, // 默认: 30000 retryable?: boolean, // 默认: true maxRetries?: number, // 默认: 3 lifecycle?: { completesRun?: boolean // true 成功后结束 agent 循环 }, })选项默认值说明timeoutMs3000030 秒单次执行超时时间retryabletrue失败后是否允许重试maxRetries3最大重试次数lifecycle.completesRunundefined为true时工具成功执行即结束当前 run测试用例 create.test.ts 明确断言了上述默认值不传策略字段时timeoutMs 30_000、retryable true、maxRetries 3显式传入timeoutMs: 1_000, retryable: false, maxRetries: 0时原样保留。AgentToolContextexecute 的第二参数execute的第二个参数提供运行时上下文。官方文档给出的核心字段interface AgentToolContext { agentId: string conversationId: string iteration: number abortSignal?: AbortSignal metadata?: Recordstring, unknown }对照当前仓库 sdk/packages/shared/src/agent.ts 中的AgentToolContext接口它还提供了sessionId、runId、toolCallId、signalAbortSignal、snapshot当前运行时状态快照含消息、usage、待处理 tool call 等以及emitUpdate向宿主推送增量更新等字段。也就是说除文档列出的核心信息外工具实现内还能拿到本轮runId与工具调用toolCallId便于把工具执行关联到具体的会话轮次和事件流中。工具命名规范名称必须使用snake_case如search_issues、deploy_app名称必须在单个 Agent 的工具集内唯一名称要具描述性——模型依赖工具名称与描述共同决定调用哪个工具、如何传参。工具描述description是模型可见的说明书模型读取description来决定何时、如何调用工具。应写清楚工具的能力边界、约束与预期行为// Bad: 含糊 description: Does deployment stuff // Good: 具体且带约束 description: Deploy the application to staging or production. Staging deployments are immediate. Production requires a passing CI build. Returns the deployment URL and status.建议把约束条件、限流规则rate limits、返回值形态都写进描述减少模型误调用。工具中的错误处理返回错误数据而不是抛异常推荐的模式是把错误作为结构化数据返回让 Agent 自行调整策略// Good: 返回错误数据 execute: async (input) { const file await readFile(input.path).catch(() null) if (!file) { return { error: File not found, path: input.path } } return { content: file } }原因在于抛出的异常会计入 Agent 的错误次数mistake limit可能直接让本轮任务失败而返回错误数据时模型能把错误作为工具结果读回进而修正入参或换一种方法继续推进。对幂等查询类操作优先用返回错误结构把throw留给确实无法恢复的故障。完成工具Completion Tools提前结束 Agent 循环把lifecycle.completesRun设为true该工具成功执行后 Agent 循环立即结束。适合提交最终答案确认完成任务这类终结性动作const submitAnswer createTool({ name: submit_answer, description: Submit the final answer and end the task., inputSchema: z.object({ answer: z.string(), confidence: z.number().min(0).max(1), }), lifecycle: { completesRun: true }, execute: async (input) input, })执行完成后模型会看到该工具的结果run 随即结束最终输出可通过result.toolCalls访问。对应地agent.ts 中AgentToolDefinition.lifecycle的注释也说明completesRun表示成功调用该工具即完成当前 run。ClineCore 内置工具使用ClineCore并开启enableTools: true时以下工具自动可用工具名称作用Shellbash在会话工作区执行 shell 命令Editoreditor创建与编辑文件Readread_files读取文件内容Patchapply_patch对文件应用 unified diffSearchsearch搜索文件内容与目录结构Webfetch_web通过 HTTP 抓取网页内容内置工具遵守CoreSessionConfig中的cwd设置即以会话工作目录为根执行文件与命令操作。从源码结构看当前仓库 core 包在 constants.ts 中注册的工具名常量为read_files、search_codebase、run_commands、fetch_web_content、apply_patch、editor、skills、ask_question、submit_and_exit其中搜索、命令执行、网页抓取的具体名称与上表search/bash/fetch_web略有差异——实际开发时应以 definitions.ts 中createTool注册时的name字段与ALL_DEFAULT_TOOL_NAMES常量为准避免在toolPolicies中写错工具名导致策略不生效。工具策略Tool Policies可用性与审批控制工具策略用来控制哪些工具可用、哪些需要审批在两个层面配置// 在 Agent 配置中 const agent new Agent({ tools: [toolA, toolB, toolC], toolPolicies: { tool_a: { autoApprove: true }, // 无需询问直接执行 tool_b: { autoApprove: false }, // 执行前触发审批回调 tool_c: { enabled: false }, // 对模型完全隐藏 }, }) // 在 ClineCore 会话中 await cline.start({ prompt: ..., config: { ... }, toolPolicies: { bash: { autoApprove: true }, editor: { autoApprove: false }, }, })策略选项及其效果策略效果{ autoApprove: true }工具无需审批直接运行{ autoApprove: false }运行前触发审批回调{ enabled: false }工具对模型完全隐藏未设置策略默认可用且自动批准核心包还内置了策略预设机制presets.ts 中的createToolPoliciesWithPreset提供default与yolo两种预设其中yolo会为通配符*以及全部默认工具名生成{ enabled: true, autoApprove: true }策略即全部工具启用并免审批适合无人值守的批处理场景default则返回空策略对象交由逐工具显式配置。长时间工具尊重 Abort Signal对于耗时较长的工具应在循环中检查中止信号提前返回已处理的部分结果execute: async (input, context) { const results [] for (const item of input.items) { if (context.abortSignal?.aborted) { return { results, aborted: true, processed: results.length } } results.push(await processItem(item)) } return { results, processed: results.length } }这样用户取消任务时工具不会一直空转到timeoutMs到期而是及时收尾并报告进度。流式工具输出onChange 回调execute的第三个参数onChange用于流式推送中间进度execute: async (input, context, onChange) { let progress 0 for (const step of steps) { progress onChange?.(Processing step ${progress}/${steps.length}...) await processStep(step) } return { completed: true } }适合多步骤、可展示进度的长任务让调用方TUI、IDE 侧边栏等实时感知工具执行状态。测试工具工具本质是普通 async 函数execute可直接调用测试非常简单import { describe, it, expect } from vitest describe(deploy tool, () { it(deploys to staging, async () { const context { agentId: test, conversationId: test, iteration: 1 } const result await deployTool.execute({ environment: staging }, context) expect(result.status).toBe(deployed) }) })由于createTool的 schema 规范化逻辑是纯函数如上文normalizeToolInputSchema其边界行为同样可以用 vitest 直接断言create.test.ts 就是官方仓库内的范例。MCP 工具集成ClineCore还支持连接 MCPModel Context Protocol服务器获取额外工具。在项目根目录的.cline/mcp-servers.json中声明{ servers: { my-server: { command: node, args: [./mcp-server.js] } } }配置后 MCP 工具会自动与内置工具、自定义工具并列出现对模型统一可见无需在代码中手动注册。延伸阅读Agent Reference —— 在 Agent 中使用工具ClineCore Reference —— 在 ClineCore 中使用工具Plugins Reference —— 把工具打包为插件SDK Tools API 文档 与 创建自定义工具指南 —— 仓库内的配套公开文档源码入口createTool 实现、AgentTool 类型定义、内置工具定义、工具预设【免费下载链接】clineAutonomous coding agent as an SDK, IDE extension, or CLI assistant.项目地址: https://gitcode.com/GitHub_Trending/cl/cline创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考