ClaudeAgentSDK工具集成Skill claude-agent-sdk-tool-integration

这个技能用于通过Claude Agent SDK集成工具、权限和MCP服务器,使AI智能体能够执行文件读写、数据库查询等操作。关键词包括:Claude Agent SDK, 工具集成, MCP服务器, AI智能体, 权限管理, 自定义工具。

AI智能体 0 次安装 0 次浏览 更新于 3/25/2026

名称:claude-agent-sdk-tool-integration 描述:在使用Agent SDK时,用于将工具、权限和MCP服务器集成到Claude AI智能体中。 允许的工具:

  • 读取
  • 写入
  • 编辑
  • Bash
  • Grep
  • Glob

Claude Agent SDK - 工具集成

在Claude Agent SDK中处理工具、权限和MCP(模型上下文协议)服务器。

工具权限

允许特定工具

import { Agent } from '@anthropic-ai/claude-agent-sdk';

const agent = new Agent({
  allowedTools: [
    'read_file',
    'write_file',
    'list_files',
    'grep',
    'bash',
  ],
});

阻止工具

const agent = new Agent({
  disallowedTools: ['bash', 'web_search'],
});

权限模式

// 严格模式 - 需要显式用户批准
const agent = new Agent({
  permissionMode: 'strict',
});

// 宽松模式 - 自动批准已知的安全操作
const agent = new Agent({
  permissionMode: 'permissive',
});

自定义工具

定义自定义工具

import { Agent, Tool } from '@anthropic-ai/claude-agent-sdk';

const customTool: Tool = {
  name: 'get_weather',
  description: '获取当前位置的天气',
  input_schema: {
    type: 'object',
    properties: {
      location: {
        type: 'string',
        description: '城市名称',
      },
    },
    required: ['location'],
  },
  execute: async (input) => {
    const { location } = input;
    // 调用天气API
    return {
      location,
      temperature: 72,
      conditions: '晴朗',
    };
  },
};

const agent = new Agent({
  tools: [customTool],
});

工具执行上下文

const customTool: Tool = {
  name: 'read_database',
  description: '查询数据库',
  input_schema: {
    type: 'object',
    properties: {
      query: { type: 'string' },
    },
    required: ['query'],
  },
  execute: async (input, context) => {
    // 上下文提供代理状态和实用工具
    console.log('代理模型:', context.model);

    const result = await runQuery(input.query);
    return result;
  },
};

MCP服务器集成

添加MCP服务器

const agent = new Agent({
  mcpServers: {
    filesystem: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/allowed'],
    },
    git: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-git'],
    },
  },
});

使用MCP资源

// 代理自动拥有访问MCP服务器资源的权限
const agent = new Agent({
  mcpServers: {
    filesystem: {
      command: 'npx',
      args: ['-y', '@modelcontextprotocol/server-filesystem', './data'],
    },
  },
});

// 代理现在可以通过MCP读取文件
await agent.chat('读取 data/config.json 的内容');

MCP服务器配置

const agent = new Agent({
  mcpServers: {
    database: {
      command: 'node',
      args: ['./mcp-servers/database.js'],
      env: {
        DATABASE_URL: process.env.DATABASE_URL,
      },
    },
  },
});

工具响应处理

流式工具响应

const response = await agent.chat('列出 src/ 中的所有文件');

for await (const chunk of response) {
  if (chunk.type === 'tool_use') {
    console.log('调用的工具:', chunk.name);
  }
  if (chunk.type === 'tool_result') {
    console.log('工具结果:', chunk.content);
  }
}

错误处理

const customTool: Tool = {
  name: 'risky_operation',
  description: '执行风险操作',
  input_schema: {
    type: 'object',
    properties: {
      action: { type: 'string' },
    },
    required: ['action'],
  },
  execute: async (input) => {
    try {
      const result = await performOperation(input.action);
      return { success: true, result };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误',
      };
    }
  },
};

最佳实践

最少权限原则

// 好:只允许必要的工具
const agent = new Agent({
  allowedTools: ['read_file', 'list_files'],
});

// 避免:不必要地允许所有工具
const agent = new Agent({
  allowedTools: ['*'],
});

工具输入验证

const customTool: Tool = {
  name: 'delete_file',
  description: '删除文件',
  input_schema: {
    type: 'object',
    properties: {
      path: { type: 'string' },
    },
    required: ['path'],
  },
  execute: async (input) => {
    // 验证输入
    if (!input.path || input.path.includes('..')) {
      throw new Error('无效的文件路径');
    }

    // 防止删除关键文件
    if (input.path.startsWith('/etc') || input.path.startsWith('/sys')) {
      throw new Error('无法删除系统文件');
    }

    await deleteFile(input.path);
    return { deleted: input.path };
  },
};

MCP服务器沙盒化

// 好:将文件系统访问限制到特定目录
const agent = new Agent({
  mcpServers: {
    filesystem: {
      command: 'npx',
      args: [
        '-y',
        '@modelcontextprotocol/server-filesystem',
        './workspace', // 仅沙盒到工作空间
      ],
    },
  },
});

反模式

不要允许无限制的Bash访问

// 坏:无限制的bash访问
const agent = new Agent({
  allowedTools: ['bash'],
});

// 更好:使用特定工具替代
const agent = new Agent({
  allowedTools: ['read_file', 'write_file', 'list_files'],
});

不要忽略工具错误

// 坏:静默失败
const customTool: Tool = {
  execute: async (input) => {
    try {
      return await riskyOperation(input);
    } catch {
      return null; // 静默失败
    }
  },
};

// 好:显式错误处理
const customTool: Tool = {
  execute: async (input) => {
    try {
      return await riskyOperation(input);
    } catch (error) {
      return {
        error: true,
        message: error instanceof Error ? error.message : '操作失败',
      };
    }
  },
};

相关技能

  • agent-creation: 代理初始化和配置
  • context-management: 管理代理上下文和内存