跳转到主要内容

@ag-kit/tools API 参考

@ag-kit/tools 包的完整应用程序接口文档。本参考涵盖所有可用工具、其接口、方法签名以及包含 MultiEditTool、事务支持和增强工具包等最新功能的实用示例。

API 概览

安装方式

npm install @ag-kit/tools

核心接口

BaseTool 接口

所有工具都继承自具备高级泛型支持和生命周期管理的抽象 BaseTool 类:
abstract class BaseTool<
  TSchema extends z.ZodTypeAny = z.ZodTypeAny,
  TState = Record<string, unknown>,
  TOutput = any,
> {
  public name: string;
  public description?: string;
  public requiresApproval?: boolean;
  public readonly schema?: TSchema;

  constructor(options: IBaseToolOptions<TSchema>);

  // 带验证和错误处理的公共调用方法
  async invoke<TInput extends TBaseToolInvokeInput<TSchema>>(
    input: TInput,
    context?: ToolExecutionContext<TState>
  ): Promise<ToolResult<TOutput>>;

  // 抽象方法:必须由子类实现
  protected abstract _invoke<TInput extends TBaseToolInvokeInput<TSchema>>(
    input: TInput,
    context?: ToolExecutionContext<TState>
  ): Promise<TOutput | ToolResult<TOutput>>;

  // 实用方法
  getDisplay(params: { name: string; input: any }): string;
  getMetadata(): { name: string; description?: string; schema: any };
  protected validateInput(input: any): ToolResult;
}
核心特性:
  • 泛型类型安全:完整的 TypeScript 泛型支持(模式、状态和输出类型)
  • 自动验证:基于 Zod 模式的输入验证
  • 上下文支持:包含会话、用户和状态追踪的执行上下文
  • 审批流程:敏感操作的可选审批要求
  • 错误处理:全面的错误分类和时间指标
  • 元数据访问:工具自省和显示定制

ToolResult 接口

标准化结果格式,包含全面的错误分类:
class ToolResult<TOutput = any> {
  public success: boolean;
  public data?: TOutput;
  public error?: string;
  public executionTime?: number;
  public error_type?:
    | "validation"
    | "security"
    | "file_not_found"
    | "permission"
    | "execution"
    | "unknown";

  constructor({
    success,
    data,
    error,
    error_type,
    executionTime,
  }: {
    success: boolean;
    data?: TOutput;
    error?: string;
    error_type?: ToolResult["error_type"];
    executionTime?: number;
  });
}
属性说明:
  • success:表示操作成功/失败的布尔值
  • data:工具输出数据(成功时)——基于工具的强类型数据
  • error:详细错误信息(失败时)
  • error_type:可编程处理的分类错误类型
  • executionTime:执行耗时(毫秒),用于性能监控
错误类型:
  • validation:输入验证失败
  • security:安全违规(路径遍历、未授权访问)
  • file_not_found:文件或目录缺失
  • permission:访问被拒或权限不足
  • execution:运行时执行错误
  • unknown:未分类错误

BaseToolkit 接口

用于组织和管相关工具集的综合工具包类:
class BaseToolkit<TState extends Record<string, unknown> = Record<string, unknown>> {
  public readonly name: string;
  public readonly description?: string;
  public context?: ToolExecutionContext<TState>;

  constructor(options: IToolkitOptions<TState>);

  // 生命周期管理
  async initialize(): Promise<void>;
  async destroy(): Promise<void>;
  protected async onInitialize(): Promise<void>;  // 子类可重写
  protected async onDestroy(): Promise<void>;     // 子类可重写

  // 工具管理
  addTool(tool: BaseTool): this;
  addTools(tools: BaseTool[]): this;
  removeTool(toolName: string): boolean;
  getTool(name: string): BaseTool | undefined;
  getTools(): BaseTool[];
  getToolNames(): string[];
  hasTool(name: string): boolean;
  searchTools(query: string): BaseTool[];

  // 执行管理
  async invokeTool(toolName: string, input: any, context?: ToolExecutionContext<TState>): Promise<ToolResult>;
  async invokeTools(invocations: Array<{toolName: string; input: any; context?: ToolExecutionContext<TState>}>): Promise<ToolResult[]>;

  // 上下文管理
  setContext(context: ToolExecutionContext<TState>): this;
  getContext(): ToolExecutionContext<TState> | undefined;

  // 事件系统
  addEventListener(listener: ToolkitEventListener): this;
  removeEventListener(listener: ToolkitEventListener): boolean;

  // 实用方法
  getMetadata(): { name: string; description?: string; toolCount: number; tools: any[]; initialized: boolean };
  validate(): { valid: boolean; errors: string[] };
  clone(newName?: string): BaseToolkit;
}
核心特性:
  • 泛型状态支持:类型安全的状态管理
  • 生命周期钩子:可重写的 onInitialize()onDestroy() 方法
  • 批量操作:通过 invokeTools() 执行多个工具
  • 工具发现:按名称或描述搜索和筛选工具
  • 事件系统:监听工具包和工具生命周期事件
  • 上下文共享:跨工具共享执行上下文
  • 验证机制:内置完整性检查和错误报告
  • 克隆功能:创建不同配置的工具包副本

DynamicTool 类

动态工具实现,无需子类化即可从函数创建工具:
class DynamicTool<
  TSchema extends z.ZodTypeAny = z.ZodTypeAny,
  TState = Record<string, unknown>,
  TOutput = any,
> extends BaseTool<TSchema, TState, TOutput> {
  constructor(options: IDynamicToolOptions<TSchema, TState, TOutput>);
  protected async _invoke(input, context?): Promise<TOutput | ToolResult<TOutput>>;
}

interface IDynamicToolOptions<TSchema, TState, TOutput> extends IBaseToolOptions {
  schema: TSchema;
  func: (input: TInput, context?: ToolExecutionContext<TState>) => Promise<TOutput | ToolResult<TOutput>>;
}
使用示例:
const dynamicTool = new DynamicTool({
  name: 'calculate',
  description: '执行数学计算',
  schema: z.object({
    expression: z.string(),
    precision: z.number().optional()
  }),
  func: async (input, context) => {
    const result = eval(input.expression); // 生产环境请勿使用eval!
    return {
      result,
      precision: input.precision || 2,
      timestamp: new Date().toISOString()
    };
  }
});

tool() 辅助函数

创建 DynamicTool 实例的便捷工厂函数:
function tool<TSchema extends z.ZodTypeAny, TState, TOutput>(
  func: (input: TInput, context?: ToolExecutionContext<TState>) => Promise<TOutput | ToolResult<TOutput>>,
  options: {
    name: string;
    description?: string;
    schema: TSchema;
```typescript
      console.log(`工具包已初始化: ${event.toolkit.name}`);
      break;
  }
});

// 工具和操作会触发事件
toolkit.addTool(weatherTool);
await toolkit.initialize();
await toolkit.invokeTool('get_weather', { city: 'Tokyo' });

应用程序接口使用模式

工具创建

使用工厂函数、tool()辅助工具或继承BaseTool来创建工具:
import {
  createReadTool,
  createMultieditTool,
  tool,
  BaseTool,
  DynamicTool,
  LocalFileOperator
} from '@ag-kit/tools';
import { z } from 'zod';

// 方法1:使用内置工厂函数(推荐用于内置工具)
const context = {
  workingDirectory: process.cwd(),
  fsOperator: new LocalFileOperator()
};

const readTool = createReadTool(context);
const multieditTool = createMultieditTool(context);

// 方法2:使用tool()辅助工具创建自定义工具(推荐用于简单工具)
const customTool = tool(
  async ({ input, options }) => {
    const result = `已处理: ${input}`;
    return {
      result: options?.format === 'json' ? { processed: input } : result,
      timestamp: new Date().toISOString()
    };
  },
  {
    name: 'example_tool',
    description: '示例工具用于演示',
    schema: z.object({
      input: z.string(),
      options: z.object({
        format: z.enum(['json', 'text']).default('text')
      }).optional()
    })
  }
);

// 方法3:直接使用DynamicTool类(需要更多控制时)
const dynamicTool = new DynamicTool({
  name: 'advanced_tool',
  description: '具有自定义行为的高级工具',
  requiresApproval: true,
  schema: z.object({
    operation: z.enum(['create', 'update', 'delete']),
    data: z.any()
  }),
  func: async (input, context) => {
    // 访问上下文获取用户信息、状态等
    const userId = context?.userId;
    const timestamp = context?.timestamp || new Date();

    // 执行操作
    const result = await performOperation(input.operation, input.data, userId);

    return new ToolResult({
      success: true,
      data: { result, userId, timestamp }
    });
  }
});

// 方法4:继承BaseTool类(用于具有自定义逻辑的复杂工具)
class CustomBaseTool extends BaseTool<typeof customSchema, { counter: number }, CustomOutput> {
  constructor() {
    super({
      name: 'custom_base_tool',
      description: '继承BaseTool的自定义工具',
      schema: customSchema,
      requiresApproval: false
    });
  }

  protected async _invoke(input: CustomInput, context?: ToolExecutionContext<{ counter: number }>) {
    // 自定义验证
    if (!this.validateCustomInput(input)) {
      return new ToolResult({
        success: false,
        error: '自定义验证失败',
        error_type: 'validation'
      });
    }

    // 访问和修改状态
    const state = context?.state || { counter: 0 };
    state.counter++;

    // 执行操作
    const result = await this.performCustomOperation(input);

    return {
      output: result,
      counter: state.counter,
      processed_at: new Date().toISOString()
    };
  }

  private validateCustomInput(input: any): boolean {
    // 自定义验证逻辑
    return true;
  }

  private async performCustomOperation(input: CustomInput): Promise<any> {
    // 自定义操作逻辑
    return { success: true };
  }
}

工具调用

所有工具都遵循相同的异步调用模式,并提供全面的错误处理:
// 基本调用
const result = await readTool.invoke({ file_path: 'package.json' });

if (result.success) {
  console.log('文件内容:', result.data.content);
  console.log('文件大小:', result.data.size);
} else {
  console.error('错误:', result.error);
  console.error('类型:', result.error_type);
}

// MultiEditTool示例,包含详细结果
const editResult = await multieditTool.invoke({
  file_path: 'config.ts',
  edits: [
    { old_string: 'debug: false', new_string: 'debug: true' },
    { old_string: 'port: 3000', new_string: 'port: 8080' }
  ]
});

if (editResult.success) {
  console.log(`应用了 ${editResult.data.edits_successful}/${editResult.data.edits_total} 处编辑`);
  console.log(`总替换次数: ${editResult.data.total_replacements}`);
  editResult.data.edit_results.forEach((edit, i) => {
    console.log(`编辑 ${i + 1}: ${edit.success ? '成功' : '失败'} (${edit.occurrences} 次替换)`);
  });
}

错误处理

针对不同类型的错误采取特定的恢复策略:
const result = await tool.invoke(input);

if (!result.success) {
  switch (result.error_type) {
    case 'validation':
      // 处理输入验证错误 - 检查模式要求
      console.error('无效输入:', result.error);
      break;
    case 'permission':
      // 处理权限/访问错误 - 检查文件权限
      console.error('访问被拒绝:', result.error);
      break;
    case 'file_not_found':
      // 处理缺失文件 - 创建或检查路径
      console.error('文件未找到:', result.error);
      break;
    case 'security':
      // 处理安全违规 - 路径遍历等
      console.error('安全违规:', result.error);
      break;
    case 'execution':
      // 处理运行时执行错误 - 工具特定问题
      console.error('执行失败:', result.error);
      break;
    case 'network':
      // 处理网络/连接错误 - E2B, MCP连接
      console.error('网络错误:', result.error);
      break;
    default:
      console.error('未知错误:', result.error);
  }
}

// 基于事务的错误恢复
import { withTransaction } from '@ag-kit/tools/fs/transaction';

try {
  await withTransaction(fsOperator, async (transactionOp) => {
    // 必须一起成功的多个操作
    await transactionOp.writeFile('config.json', newConfig);
    await transactionOp.writeFile('backup.json', oldConfig);
    // 如果任何操作失败,所有更改都将回滚
  });
} catch (error) {
  console.error('事务失败,所有更改已回滚:', error);
}

应用程序接口特性

类型安全

  • 完整的TypeScript支持:所有工具输入和输出的编译时类型检查
  • 运行时验证:带有详细错误信息的Zod模式验证
  • 强类型结果:具有IntelliSense支持的工具特定返回类型
  • 通用接口:灵活的类型系统用于自定义工具开发

异步操作

  • 基于Promise的API:所有操作返回promise以支持async/await
  • 超时控制:可配置长时间运行操作的超时
  • 资源管理:自动清理和资源释放
  • 取消支持:集成AbortController以支持操作取消

错误处理

  • 结构化错误类型:分类错误以便程序化处理
  • 详细上下文:包含堆栈跟踪和元数据的丰富错误信息
  • 一致格式:所有工具统一的错误结构
  • 性能监控:执行时间跟踪和性能指标

高级特性

  • 事务支持:具有回滚能力的原子操作
  • 多后端支持:本地、内存中和沙箱执行环境
  • 批量操作:MultiEditTool用于高效批量操作
  • 工具包管理:具有生命周期管理的组织化工具集合
  • 事件系统:用于监控的工具和工具包生命周期事件
  • 安全特性:路径验证、沙箱化和权限控制

工具类别

文件系统工具

支持多后端的文件和目录操作API,包括:
  • 独立工具:读取、写入、编辑、多编辑、全局搜索、Grep、列表操作
  • 事务支持:具有回滚能力的原子操作
  • 多后端:本地、内存中和沙箱文件操作器
  • 增强工具包:可配置模式适应不同用例
查看API参考 →

代码执行工具

具有沙箱隔离的安全多语言代码执行: 执行器:
  • BuiltInCodeExecutor:具有完全隔离的E2B沙箱执行
  • UnsafeLocalCodeExecutor:用于可信环境的本地执行
支持语言:
  • Python、JavaScript/Node.js、TypeScript、Bash、R、Java、Go、C++等
特性:
  • 超时控制、资源限制、文件系统集成
  • 实时输出流和错误处理
查看API参考 →

命令行工具

具有安全验证和多命令支持的Shell命令执行: 工具:
  • BashTool:具有环境控制的单命令执行
  • MultiCommandTool:具有状态持久化的顺序命令执行
安全特性:
  • 命令验证、路径限制、环境隔离
  • 常见操作的内置命令构建器
查看API参考 →

浏览器自动化工具

与Playwright和E2B沙箱集成的Web自动化: 特性:
  • 在隔离环境中的安全浏览器自动化
  • 截图捕获、元素交互、
  带安全验证和多命令支持的Shell命令执行
  </Card>
  <Card title="浏览器应用程序接口" icon="globe" href="/reference/tools/browser">
    通过Playwright和E2B沙箱集成实现网页自动化
  </Card>
  <Card title="MCP协议应用程序接口" icon="plug" href="/reference/tools/mcp">
    面向外部工具生态的模型上下文协议集成
  </Card>
</CardGroup>

## 最新功能与示例

### 本版本新增功能

#### 多编辑工具
通过原子操作对单个文件执行多次连续编辑:

```typescript
import { createMultieditTool } from '@ag-kit/tools';

const multieditTool = createMultieditTool(context);

const result = await multieditTool.invoke({
  file_path: 'config.ts',
  edits: [
    { old_string: 'debug: false', new_string: 'debug: true' },
    { old_string: 'port: 3000', new_string: 'port: 8080' },
    { old_string: 'env: "dev"', new_string: 'env: "prod"' }
  ]
});

// 每个编辑的详细结果
result.data.edit_results.forEach((edit, i) => {
  console.log(`编辑 ${i + 1}: ${edit.success ? '成功' : '失败'}`);
  console.log(`替换次数: ${edit.occurrences}`);
});

事务支持

对多个文件操作进行分组,失败时自动回滚:
import { withTransaction } from '@ag-kit/tools/fs/transaction';

await withTransaction(fsOperator, async (transactionOp) => {
  // 所有操作要么全部成功,要么全部回滚
  await transactionOp.writeFile('config.json', newConfig);
  await transactionOp.writeFile('backup.json', oldConfig);
  await transactionOp.rename('old-file.txt', 'archived-file.txt');
});

增强版文件系统工具包

为您的使用场景选择最优工具配置:
import { FilesystemToolkit } from '@ag-kit/tools';

// 增强模式:原子工具+多编辑
const toolkit = new FilesystemToolkit({
  context,
  config: { mode: "enhanced" }
});

// 按类别获取工具
const fileOps = toolkit.getFileOperationTools(); // 读取、写入、编辑、多编辑
const utilities = toolkit.getUtilityTools();     // 通配符搜索、文本搜索、目录列表

// 动态切换模式
toolkit.switchMode("integrated"); // 使用字符串替换编辑器
toolkit.switchMode("enhanced");   // 返回增强模式

工具包管理

组织和管理多个工具包:
import { toolkitManager } from '@ag-kit/tools';

// 注册工具包
toolkitManager.register(filesystemToolkit);
toolkitManager.register(mcpToolkit);

// 初始化所有工具包
await toolkitManager.initializeAll();

// 获取所有工具包中的工具
const allTools = toolkitManager.getAllTools();

// 查找特定工具
const readTools = toolkitManager.findTool('read');

// 清理资源
await toolkitManager.destroyAll();

相关文档