toMedia
Agent SDK

工具系统

Agent SDK 的内置工具与自定义工具 — 文件操作、命令执行、代码搜索

内置工具

Agent SDK 继承了 Claude Code 的所有内置工具:

工具功能说明
Read读取文件支持文本、图片、PDF
Write创建文件覆盖写入
Edit编辑文件精确字符串替换
Bash执行命令Shell 命令执行
Glob文件搜索按模式匹配文件名
Grep内容搜索正则表达式搜索文件内容
Agent子 Agent启动子 Agent 处理子任务

权限控制

允许特定工具

const claude = new ClaudeCode({
  allowedTools: [
    "Read",           // 允许所有读取
    "Glob",           // 允许文件搜索
    "Grep",           // 允许内容搜索
    "Bash(npm test)", // 仅允许 npm test
    "Bash(git *)",    // 允许所有 git 命令
  ],
});

拒绝特定工具

const claude = new ClaudeCode({
  deniedTools: [
    "Bash(rm *)",     // 禁止删除
    "Bash(sudo *)",   // 禁止 sudo
    "Write",          // 禁止创建文件
  ],
});

自定义工具

定义工具

import { ClaudeCode, Tool } from "@anthropic-ai/claude-code-sdk";

const searchDocsToolTool: Tool = {
  name: "search_docs",
  description: "搜索项目文档库",
  inputSchema: {
    type: "object",
    properties: {
      query: {
        type: "string",
        description: "搜索关键词",
      },
      limit: {
        type: "number",
        description: "返回结果数量",
        default: 5,
      },
    },
    required: ["query"],
  },
  async execute(input: { query: string; limit?: number }) {
    // 实现搜索逻辑
    const results = await searchDocs(input.query, input.limit || 5);
    return JSON.stringify(results);
  },
};

注册工具

const claude = new ClaudeCode({
  customTools: [searchDocsTool],
});

// Claude 现在可以使用 search_docs 工具
const stream = await claude.sendMessage(
  "搜索文档中关于认证的内容"
);

工具输入输出 Schema

const databaseQueryTool: Tool = {
  name: "query_database",
  description: "执行数据库查询",
  inputSchema: {
    type: "object",
    properties: {
      sql: {
        type: "string",
        description: "SQL 查询语句(只读)",
      },
      database: {
        type: "string",
        enum: ["users", "orders", "products"],
        description: "目标数据库",
      },
    },
    required: ["sql", "database"],
  },
  outputSchema: {
    type: "object",
    properties: {
      rows: {
        type: "array",
        description: "查询结果行",
      },
      rowCount: {
        type: "number",
        description: "结果数量",
      },
    },
  },
  async execute(input) {
    const result = await db.query(input.sql);
    return JSON.stringify({
      rows: result.rows,
      rowCount: result.rowCount,
    });
  },
};

工具调用事件

监听工具调用过程:

const stream = await claude.sendMessage("分析项目结构");

for await (const event of stream) {
  switch (event.type) {
    case "tool_use":
      console.log(`调用工具: ${event.name}`);
      console.log(`参数: ${JSON.stringify(event.input)}`);
      break;
    case "tool_result":
      console.log(`工具结果: ${event.content.substring(0, 100)}...`);
      break;
    case "text":
      process.stdout.write(event.text);
      break;
  }
}

子 Agent

使用 Agent 工具启动子 Agent 并行处理:

const claude = new ClaudeCode({
  allowedTools: ["Read", "Glob", "Grep", "Agent"],
});

// Claude 可以自动启动子 Agent
const stream = await claude.sendMessage(
  "并行分析 src/ 和 tests/ 目录的代码质量"
);
// Claude 会启动两个子 Agent 分别处理

最佳实践

  1. 最小权限:只允许必要的工具
  2. 工具描述:description 越详细,Claude 调用越准确
  3. 错误返回:工具执行失败时返回有意义的错误信息
  4. 超时控制:长时间运行的工具设置超时
  5. 输入验证:在 execute 函数中验证输入

On this page