Skip to content

21.3 外掛開發 API

概述

Claude Code 提供了一套強大的外掛開發 API,允許開發者擴充套件和定製系統功能。本章節將詳細介紹核心 API 介面、使用方法和最佳實踐。

核心 API 接口

IPlugin 接口

IPlugin 是所有外掛必須實現的核心介面:

bash
    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 接口

外掛後設資料定義了外掛的基本資訊:

bash
    typescript


    /**
     * 插件元数据
     */
    export interface PluginMetadata {
      /**
       * 插件唯一标识符
       */
      id: string;

      /**
       * 插件名称
       */
      name: string;

      /**
       * 插件版本
       */
      version: string;

      /**
       * 插件描述
       */
      description: string;

      /**
       * 插件作者
       */
      author?: string;

      /**
       * 插件许可证
       */
      license?: string;

      /**
       * 插件主页
       */
      homepage?: string;

      /**
       * 插件依赖
       */
      dependencies?: PluginDependency[];

      /**
       * 插件兼容性
       */
      compatibility?: PluginCompatibility;
    }

### PluginContext 接口

外掛上下文提供了外掛與系統互動的能力:

bash
    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 介面用於建立可複用的工具:

bash
    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 命令:

bash
    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 介面用於實現事件驅動功能:

python
    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 使用示例

### 创建简单插件

    typescript


    import { 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'] };
      }
    }

### 创建工具

    typescript


    import { 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. 安全性

  • 輸入驗證 :驗證所有外部輸入
  • 許可權控制 :檢查使用者許可權
  • 資料加密 :保護敏感資料
  • 審計日誌 :記錄重要操作
python
## 常见问题

### 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 提供了一套完整的擴充套件機制,允許開發者建立強大的外掛和工具。透過遵循最佳實踐和設計原則,可以建立出高質量、可維護的外掛。

下一章將介紹高階外掛開發技術,包括外掛通訊、資料持久化和效能最佳化。

基于 MIT 许可发布 | 永久导航