为Claude Code Action开发自定义工具
Claude Code Action 是一款强大的 AI 辅助开发工具,支持自动化代码审查、问题分类和测试分析等功能。通过创建自定义工具,可以扩展其功能以满足特定项目需求。本文将介绍如何为 Claude Code Action 开发自定义工具,涵盖从工具定义到集成使用的完整流程。
核心概念
在开始开发之前,需要了解 Claude Code Action 的工具系统架构。每个工具本质上是一个函数,AI 可以调用它来执行特定任务并返回结果。工具的解析和注册机制位于 src/modes/agent/parse-tools.ts 文件中。
每个工具必须包含以下关键部分:
- 唯一标识符:用于 AI 调用工具。
- 参数定义:明确工具所需的输入参数。
- 执行逻辑:实现具体功能的代码。
- 结果格式:规定工具返回数据的结构。
准备工作
确保你的开发环境已正确配置 Claude Code Action 项目:
git clone https://gitcode.com/GitHub_Trending/cl/claude-code-action
cd claude-code-action
npm install
主要涉及的文件包括:
src/modes/agent/parse-tools.ts:工具解析与注册。src/create-prompt/index.ts:工具提示构建。src/entrypoints/format-turns.ts:工具结果格式化。
定义工具接口
使用 TypeScript 接口定义工具结构。例如,在工具文件中定义如下接口:
interface ToolDefinition {
identifier: string;
description: string;
params: {
type: string;
properties: Record;
required: string[];
};
}
该接口描述了工具的基本信息,包括标识符、描述以及参数规范,便于 AI 理解如何正确调用工具。
实现工具逻辑
创建一个工具类来实现具体功能。以下是一个示例工具,用于统计代码行数:
class LineCounter {
async run(filePath: string): Promise<{ lines: number; errors: string[] }> {
try {
const content = await readFile(filePath, "utf-8");
const lineCount = content.split("\n").length;
return { lines: lineCount, errors: [] };
} catch (error) {
return { lines: 0, errors: [String(error)] };
}
}
}
将此类放置在 src/mcp/ 目录下,并遵循项目的文件组织方式。
注册工具
为了让 AI 能识别新工具,需在工具注册表中添加定义。修改 src/modes/agent/parse-tools.ts 文件:
export function addCustomTools() {
const tools = [
{
identifier: "line_counter",
description: "统计指定文件的代码行数",
params: {
type: "object",
properties: {
filePath: {
type: "string",
description: "要统计的文件路径",
},
},
required: ["filePath"],
},
},
];
return tools;
}
测试工具
在 test/modes/ 目录下创建测试文件:
import { test } from "bun:test";
import { LineCounter } from "../../src/mcp/line-counter";
test("LineCounter should return correct line count", async () => {
const counter = new LineCounter();
const result = await counter.run("src/sample.ts");
expect(result.lines).toBeGreaterThan(0);
});
运行以下命令验证工具功能:
npm test
集成到工作流
修改 action.yml 文件,添加工具配置:
tools:
- identifier: line_counter
description: Count lines in specified files
enabled: true
通过 src/create-prompt/index.ts 中的 generateToolList 函数,确保工具被包含在 AI 提示中。
最佳实践
开发自定义工具时,请遵循以下建议:
- 清晰的描述:提供详细的说明,帮助 AI 判断何时使用该工具。
- 严格的参数校验:在
src/validate-env.ts中添加校验逻辑。 - 完善的错误处理:确保工具失败时能提供有用反馈。
- 性能优化:避免长时间运行的操作,考虑异步处理。
- 安全性检查:遵循
SECURITY.md中的安全指南。
通过这些步骤,你可以创建功能强大的自定义工具,扩展 Claude Code Action 的能力,使其更符合项目需求。