概述#
Claude Code 提供了一套强大的插件开发 API,允许开发者扩展和定制系统功能。本章节将详细介绍核心 API 接口、使用方法和最佳实践。
核心 API 接口#
IPlugin 接口#
IPlugin 是所有插件必须实现的核心接口:
typescript/** * 插件接口 */ export interface IPlugin { /** * 插件元数据 */ metadata: PluginMetadata; /** * 插件配置 */ config: PluginConfig; /** * 插件状态 */ status: PluginStatus; /** * 初始化插件 * @param context 插件上下文 */ initialize(context: PluginContext): Promise<void>; /** * 启动插件 */ start(): Promise<void>; /** * 停止插件 */ stop(): Promise<void>; /** * 清理插件 */ cleanup(): Promise<void>; /** * 处理插件消息 * @param message 消息内容 */ handleMessage(message: PluginMessage): Promise<PluginMessageResponse>; /** * 获取插件功能 */ getCapabilities(): PluginCapabilities; }
PluginMetadata 接口#
插件元数据定义了插件的基本信息:
typescript/** * 插件元数据 */ export interface PluginMetadata { /** * 插件唯一标识符 */ id: string; /** * 插件名称 */ name: string; /** * 插件版本 */ version: string; /** * 插件描述 */ description: string; /** * 插件作者 */ author?: string; /** * 插件许可证 */ license?: string; /** * 插件主页 */ homepage?: string; /** * 插件依赖 */ dependencies?: PluginDependency[]; /** * 插件兼容性 */ compatibility?: PluginCompatibility; }
PluginContext 接口#
插件上下文提供了插件与系统交互的能力:
typescript/** * 插件上下文 */ export interface PluginContext { /** * 系统服务提供者 */ services: ServiceProvider; /** * 日志服务 */ logger: Logger; /** * 配置服务 */ configService: ConfigService; /** * 事件总线 */ eventBus: EventBus; /** * 插件管理器 */ pluginManager: PluginManager; /** * 资源管理器 */ resourceManager: ResourceManager; /** * 获取系统信息 */ getSystemInfo(): SystemInfo; /** * 发送系统通知 */ sendNotification(notification: Notification): Promise<void>; /** * 执行系统命令 */ executeCommand(command: Command): Promise<CommandResult>; }
工具 API#
ITool 接口#
ITool 接口用于创建可复用的工具:
typescript/** * 工具接口 */ export interface ITool { /** * 工具元数据 */ metadata: ToolMetadata; /** * 工具配置 */ config: ToolConfig; /** * 执行工具 * @param parameters 工具参数 */ execute(parameters: ToolParameters): Promise<ToolResult>; /** * 验证参数 * @param parameters 工具参数 */ validate(parameters: ToolParameters): ToolValidationResult; /** * 获取工具帮助信息 */ getHelp(): ToolHelp; }
ToolMetadata 接口#
typescript/** * 工具元数据 */ export interface ToolMetadata { /** * 工具唯一标识符 */ id: string; /** * 工具名称 */ name: string; /** * 工具描述 */ description: string; /** * 工具类型 */ type: ToolType; /** * 工具参数 */ parameters: ToolParameter[]; /** * 工具返回结果 */ returns: ToolReturn; /** * 工具示例 */ examples: ToolExample[]; }
命令 API#
ICommand 接口#
ICommand 接口用于实现 CLI 命令:
typescript/** * 命令接口 */ export interface ICommand { /** * 命令元数据 */ metadata: CommandMetadata; /** * 执行命令 * @param args 命令参数 * @param options 命令选项 */ execute(args: string[], options: CommandOptions): Promise<CommandResult>; /** * 验证命令参数 * @param args 命令参数 * @param options 命令选项 */ validate(args: string[], options: CommandOptions): CommandValidationResult; /** * 获取命令帮助信息 */ getHelp(): CommandHelp; }
CommandMetadata 接口#
typescript/** * 命令元数据 */ export interface CommandMetadata { /** * 命令名称 */ name: string; /** * 命令描述 */ description: string; /** * 命令别名 */ aliases?: string[]; /** * 命令参数 */ arguments: CommandArgument[]; /** * 命令选项 */ options: CommandOption[]; /** * 命令示例 */ examples: CommandExample[]; /** * 命令类别 */ category?: string; /** * 命令可见性 */ visible?: boolean; }
钩子 API#
IHook 接口#
IHook 接口用于实现事件驱动功能:
typescript/** * 钩子接口 */ export interface IHook { /** * 钩子元数据 */ metadata: HookMetadata; /** * 执行钩子 * @param context 钩子上下文 */ execute(context: HookContext): Promise<HookResult>; /** * 注册钩子 */ register(): void; /** * 注销钩子 */ unregister(): void; }
HookMetadata 接口#
typescript/** * 钩子元数据 */ export interface HookMetadata { /** * 钩子名称 */ name: string; /** * 钩子描述 */ description: string; /** * 钩子类型 */ type: HookType; /** * 钩子触发点 */ triggerPoint: string; /** * 钩子优先级 */ priority: number; /** * 钩子参数 */ parameters: HookParameter[]; /** * 钩子返回结果 */ returns: HookReturn; }
API 使用示例#
创建简单插件#
typescriptimport { IPlugin, PluginMetadata, PluginContext } from '@claude-code/plugin-sdk'; export class HelloWorldPlugin implements IPlugin { metadata: PluginMetadata = { id: 'hello-world-plugin', name: 'Hello World Plugin', version: '1.0.0', description: 'A simple hello world plugin', author: 'Claude Code Team', license: 'MIT' }; config: any = {}; status: any = {}; async initialize(context: PluginContext): Promise<void> { context.logger.info('Hello World Plugin initialized'); } async start(): Promise<void> { console.log('Hello World Plugin started'); } async stop(): Promise<void> { console.log('Hello World Plugin stopped'); } async cleanup(): Promise<void> { console.log('Hello World Plugin cleaned up'); } async handleMessage(message: any): Promise<any> { return { message: 'Hello from plugin' }; } getCapabilities(): any { return { features: ['hello-world'] }; } }
创建工具#
typescriptimport { ITool, ToolMetadata, ToolParameters } from '@claude-code/plugin-sdk'; export class CalculatorTool implements ITool { metadata: ToolMetadata = { id: 'calculator-tool', name: 'Calculator Tool', description: 'A simple calculator tool', type: 'utility', parameters: [ { name: 'operation', type: 'string', description: 'Operation to perform' }, { name: 'a', type: 'number', description: 'First number' }, { name: 'b', type: 'number', description: 'Second number' } ], returns: { type: 'number', description: 'Calculation result' }, examples: [ { input: { operation: 'add', a: 1, b: 2 }, output: 3 }, { input: { operation: 'multiply', a: 3, b: 4 }, output: 12 } ] }; config: any = {}; async execute(parameters: ToolParameters): Promise<any> { const { operation, a, b } = parameters; switch (operation) { case 'add': return a + b; case 'subtract': return a - b; case 'multiply': return a * b; case 'divide': return a / b; default: throw new Error(`Unknown operation: ${operation}`); } } validate(parameters: ToolParameters): any { if (!parameters.operation) { return { valid: false, error: 'Operation is required' }; } return { valid: true }; } getHelp(): any { return { description: 'A simple calculator tool' }; } }
API 最佳实践#
1. 接口设计原则#
- 单一职责:每个接口只负责一个功能
- 最小依赖:减少接口之间的耦合
- 明确契约:清晰定义输入输出
- 版本管理:使用语义化版本控制
2. 错误处理#
typescript// 推荐的错误处理方式 try { // 执行操作 } catch (error) { context.logger.error('Operation failed', error); throw new PluginError('OPERATION_FAILED', 'Failed to perform operation', error); }
3. 性能优化#
- 异步操作:使用 Promise 和 async/await
- 缓存策略:缓存频繁使用的数据
- 批量处理:减少系统调用次数
- 资源管理:及时释放资源
4. 安全性#
- 输入验证:验证所有外部输入
- 权限控制:检查用户权限
- 数据加密:保护敏感数据
- 审计日志:记录重要操作
常见问题#
Q: 如何处理 API 版本兼容性?#
A: 使用版本号管理 API,提供向后兼容的实现:
typescript// 版本兼容示例 if (context.getSystemInfo().version >= '2.0.0') { // 使用新 API } else { // 使用兼容 API }
Q: 如何扩展现有 API?#
A: 使用装饰器或适配器模式扩展 API:
typescript// 使用装饰器扩展 API @decorate(ITool) export class EnhancedTool extends BaseTool { // 扩展功能 }
Q: 如何调试 API 调用?#
A: 使用日志和调试工具:
typescript// 调试日志 context.logger.debug('API call', { parameters, result });
总结#
Claude Code 插件开发 API 提供了一套完整的扩展机制,允许开发者创建强大的插件和工具。通过遵循最佳实践和设计原则,可以创建出高质量、可维护的插件。
下一章将介绍高级插件开发技术,包括插件通信、数据持久化和性能优化。