欢迎光临
我们一直在努力

06-Claude-Code工具与插件

06 – Claude Code 工具与插件

📚 免费专栏全套教程: Claude Code 从入门到精通 ✦ 开篇总览|最新目录: Claude Code 从入门到精通 —带你玩转Claude Code!!

Claude Code 的强大之处在于其丰富的工具生态系统,让 AI 能够真正"动手"完成任务。

目录

  • MCP(Model Context Protocol)工具
  • 内置工具列表
  • 自定义工具开发
  • 插件安装与管理
  • 工具最佳实践

  • 1. MCP(Model Context Protocol)工具

    1.1 什么是 MCP?

    Model Context Protocol (MCP) 是 Anthropic 推出的开放协议,用于连接 AI 模型与外部工具、数据源和服务。它提供了一种标准化的方式,让 Claude 能够:

    • 🔌 连接外部 API 和服务
    • 📁 访问本地和远程文件系统
    • 🗄️ 查询数据库
    • 🌐 与 Web 服务交互
    • 🔐 安全地处理认证

    1.2 MCP 架构

    ┌─────────────────────────────────────────────────────┐
    │ Claude Code │
    │ (MCP Client) │
    └─────────────────────┬───────────────────────────────┘

    │ MCP Protocol (JSON-RPC)

    ┌─────────────────┼─────────────────┐
    │ │ │
    ▼ ▼ ▼
    ┌────────┐ ┌────────┐ ┌────────┐
    │ 文件 │ │ 数据库 │ │ Web │
    │ 服务器 │ │ 服务器 │ │ 服务 │
    └────────┘ └────────┘ └────────┘

    1.3 配置 MCP 服务器

    配置文件位置:

    • macOS/Linux: ~/.config/claude-code/mcp.json
    • Windows: %APPDATA%\\claude-code\\mcp.json

    基础配置示例:

    {
    "mcpServers": {
    "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"],
    "env": {}
    },
    "postgres": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-postgres"],
    "env": {
    "POSTGRES_CONNECTION_STRING": "postgresql://user:pass@localhost/db"
    }
    },
    "github": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-github"],
    "env": {
    "GITHUB_TOKEN": "${GITHUB_TOKEN}"
    }
    }
    }
    }

    1.4 常用 MCP 服务器

    服务器名称功能安装命令
    server-filesystem 文件系统访问 npx -y @modelcontextprotocol/server-filesystem
    server-github GitHub API 集成 npx -y @modelcontextprotocol/server-github
    server-postgres PostgreSQL 数据库 npx -y @modelcontextprotocol/server-postgres
    server-sqlite SQLite 数据库 npx -y @modelcontextprotocol/server-sqlite
    server-fetch Web 请求 npx -y @modelcontextprotocol/server-fetch
    server-puppeteer 浏览器自动化 npx -y @modelcontextprotocol/server-puppeteer
    server-slack Slack 集成 npx -y @modelcontextprotocol/server-slack

    1.5 使用 MCP 工具示例

    # 列出可用的 MCP 工具
    claude tools list

    # 使用文件系统 MCP 工具
    # Claude 会自动检测并使用已配置的 MCP 服务器

    在对话中使用:

    用户: 帮我读取 /projects/myapp/package.json 文件
    Claude: [使用 filesystem MCP 服务器读取文件]

    用户: 查询数据库中最近 7 天的用户注册数
    Claude: [使用 postgres MCP 服务器执行 SQL 查询]

    用户: 创建一个新的 GitHub issue
    Claude: [使用 github MCP 服务器创建 issue]

    1.6 MCP 安全配置

    {
    "mcpServers": {
    "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem"],
    "env": {},
    "security": {
    "allowedPaths": ["/home/user/projects"],
    "readOnly": false,
    "maxFileSize": "10MB"
    }
    }
    }
    }


    2. 内置工具列表

    2.1 文件操作工具

    read – 读取文件

    // 功能:读取文件内容,支持文本和图片
    // 参数:
    // – file_path: 文件路径(必需)
    // – offset: 起始行号(可选,默认 1)
    // – limit: 最大行数(可选,默认 2000 行)

    // 使用示例
    <read>
    <file_path>/home/user/project/src/index.ts</file_path>
    </read>

    // 读取大文件分段
    <read>
    <file_path>/var/log/app.log</file_path>
    <offset>1000</offset>
    <limit>500</limit>
    </read>

    write – 写入文件

    // 功能:创建或覆盖文件
    // 参数:
    // – file_path: 文件路径(必需)
    // – content: 文件内容(必需)

    // 使用示例
    <write>
    <file_path>/home/user/project/README.md</file_path>
    <content>
    # My Project

    这是一个示例项目。

    ## 安装

    \\`\\`\\`bash
    npm install
    \\`\\`\\`
    </content>
    </write>

    edit – 精确编辑文件

    // 功能:精确替换文件中的文本
    // 参数:
    // – file_path: 文件路径(必需)
    // – oldText: 要替换的文本(必需,必须精确匹配)
    // – newText: 新文本(必需)

    // 使用示例
    <edit>
    <file_path>/home/user/project/package.json</file_path>
    <oldText>"version": "1.0.0"</oldText>
    <newText>"version": "1.1.0"</newText>
    </edit>

    2.2 命令执行工具

    exec – 执行 Shell 命令

    // 功能:执行 Shell 命令
    // 参数:
    // – command: 要执行的命令(必需)
    // – workdir: 工作目录(可选)
    // – timeout: 超时时间秒数(可选)
    // – env: 环境变量(可选)
    // – pty: 是否使用伪终端(可选)
    // – background: 后台运行(可选)

    // 基础示例
    <exec>
    <command>npm test</command>
    <workdir>/home/user/project</workdir>
    </exec>

    // 带环境变量
    <exec>
    <command>node server.js</command>
    <env>
    <NODE_ENV>production</NODE_ENV>
    <PORT>3000</PORT>
    </env>
    <background>true</background>
    </exec>

    // 交互式命令(需要 pty)
    <exec>
    <command>vim config.txt</command>
    <pty>true</pty>
    </exec>

    process – 管理后台进程

    // 功能:管理正在运行的 exec 会话
    // 参数:
    // – action: 操作类型(list | poll | log | write | send-keys | kill)
    // – sessionId: 会话 ID
    // – data: 写入数据(write 操作)
    // – keys: 发送按键(send-keys 操作)

    // 列出所有进程
    <process>
    <action>list</action>
    </process>

    // 查看进程输出
    <process>
    <action>log</action>
    <sessionId>abc123</sessionId>
    </process>

    // 终止进程
    <process>
    <action>kill</action>
    <sessionId>abc123</sessionId>
    </process>

    2.3 网络工具

    web_search – Web 搜索

    // 功能:使用 Brave Search API 搜索网页
    // 参数:
    // – query: 搜索关键词(必需)
    // – count: 结果数量(可选,1-10,默认 10)
    // – country: 国家代码(可选,如 'US', 'CN')
    // – freshness: 时间过滤(可选,如 'pd', 'pw', 'pm')

    // 使用示例
    <web_search>
    <query>Claude Code MCP tutorial 2024</query>
    <count>5</count>
    <freshness>pm</freshness>
    </web_search>

    web_fetch – 获取网页内容

    // 功能:获取并提取网页内容
    // 参数:
    // – url: 网页 URL(必需)
    // – extractMode: 提取模式('markdown' | 'text')
    // – maxChars: 最大字符数(可选)

    // 使用示例
    <web_fetch>
    <url>https://docs.anthropic.com/claude/docs</url>
    <extractMode>markdown</extractMode>
    <maxChars>5000</maxChars>
    </web_fetch>

    2.4 浏览器工具

    browser – 浏览器自动化

    // 功能:控制浏览器进行自动化操作
    // 参数:
    // – action: 操作类型(status | start | stop | tabs | open | navigate | snapshot | screenshot | act | close)
    // – profile: 浏览器配置('chrome' | 'openclaw')
    // – targetUrl: 目标 URL
    // – request: 操作请求对象

    // 启动浏览器
    <browser>
    <action>start</action>
    <profile>chrome</profile>
    </browser>

    // 打开网页
    <browser>
    <action>open</action>
    <targetUrl>https://github.com</targetUrl>
    </browser>

    // 获取页面快照
    <browser>
    <action>snapshot</action>
    <refs>aria</refs>
    </browser>

    // 执行点击操作
    <browser>
    <action>act</action>
    <request>
    <kind>click</kind>
    <ref>e42</ref>
    </request>
    </browser>

    // 输入文本
    <browser>
    <action>act</action>
    <request>
    <kind>type</kind>
    <ref>e15</ref>
    <text>Hello World</text>
    </request>
    </browser>

    // 截图
    <browser>
    <action>screenshot</action>
    <type>png</type>
    </browser>

    2.5 消息工具

    message – 发送消息

    // 功能:通过渠道插件发送消息
    // 参数:
    // – action: 操作类型('send')
    // – target: 目标频道/用户
    // – message: 消息内容
    // – media: 媒体文件 URL 或路径

    // 发送文本消息
    <message>
    <action>send</action>
    <target>#general</target>
    <message>Hello from Claude!</message>
    </message>

    // 发送带图片的消息
    <message>
    <action>send</action>
    <target>@user123</target>
    <message>这是截图</message>
    <media>/path/to/image.png</media>
    </message>

    2.6 TTS 语音工具

    tts – 文本转语音

    // 功能:将文本转换为语音
    // 参数:
    // – text: 要转换的文本(必需)
    // – channel: 输出格式(可选)

    // 使用示例
    <tts>
    <text>你好,我是 Claude,很高兴为你服务!</text>
    </tts>

    2.7 工具汇总表

    工具名称分类功能描述
    read 文件 读取文件内容
    write 文件 创建/覆盖文件
    edit 文件 精确编辑文件
    exec 命令 执行 Shell 命令
    process 命令 管理后台进程
    web_search 网络 搜索网页
    web_fetch 网络 获取网页内容
    browser 浏览器 浏览器自动化
    canvas UI Canvas 展示与控制
    nodes 设备 管理配对设备
    message 通信 发送消息
    tts 语音 文本转语音
    subagents 子代理 子代理管理
    feishu_* 协作 飞书集成工具

    3. 自定义工具开发

    3.1 工具开发基础

    Claude Code 支持通过 MCP 协议开发自定义工具。一个基本的 MCP 工具包含:

    // mcp-server-template/index.ts
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

    // 定义工具
    const TOOLS = [
    {
    name: "hello_world",
    description: "一个简单的示例工具",
    inputSchema: {
    type: "object",
    properties: {
    name: {
    type: "string",
    description: "要问候的名字"
    }
    },
    required: ["name"]
    }
    }
    ];

    // 创建服务器
    const server = new Server(
    { name: "example-server", version: "1.0.0" },
    { capabilities: { tools: {} } }
    );

    // 处理工具列表请求
    server.setRequestHandler(ListToolsRequestSchema, async () => {
    return { tools: TOOLS };
    });

    // 处理工具调用请求
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (name === "hello_world") {
    return {
    content: [{
    type: "text",
    text: `你好,${args.name}!欢迎使用自定义工具。`
    }]
    };
    }

    throw new Error(`未知工具: ${name}`);
    });

    // 启动服务器
    const transport = new StdioServerTransport();
    await server.connect(transport);

    3.2 实用自定义工具示例

    示例 1:天气查询工具

    // weather-tool/index.ts
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    import {
    ListToolsRequestSchema,
    CallToolRequestSchema
    } from "@modelcontextprotocol/sdk/types.js";

    const server = new Server(
    { name: "weather-server", version: "1.0.0" },
    { capabilities: { tools: {} } }
    );

    // 工具定义
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools: [{
    name: "get_weather",
    description: "获取指定城市的天气信息",
    inputSchema: {
    type: "object",
    properties: {
    city: {
    type: "string",
    description: "城市名称(中文或英文)"
    },
    unit: {
    type: "string",
    enum: ["celsius", "fahrenheit"],
    description: "温度单位",
    default: "celsius"
    }
    },
    required: ["city"]
    }
    }]
    }));

    // 工具实现
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (name === "get_weather") {
    try {
    // 调用天气 API(示例使用 wttr.in)
    const response = await fetch(
    `https://wttr.in/${encodeURIComponent(args.city)}?format=j1`
    );
    const data = await response.json();

    const current = data.current_condition[0];
    const temp = args.unit === "fahrenheit"
    ? current.temp_F
    : current.temp_C;

    return {
    content: [{
    type: "text",
    text: JSON.stringify({
    city: args.city,
    temperature: `${temp}°${args.unit === "fahrenheit" ? "F" : "C"}`,
    condition: current.weatherDesc[0].value,
    humidity: `${current.humidity}%`,
    wind: `${current.windspeedKmph} km/h`
    }, null, 2)
    }]
    };
    } catch (error) {
    return {
    content: [{
    type: "text",
    text: `获取天气失败: ${error.message}`
    }],
    isError: true
    };
    }
    }

    throw new Error(`未知工具: ${name}`);
    });

    // 启动
    const transport = new StdioServerTransport();
    await server.connect(transport);

    示例 2:数据库查询工具

    // db-tool/index.ts
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    import pg from "pg";

    const { Pool } = pg;
    const pool = new Pool({
    connectionString: process.env.DATABASE_URL
    });

    const server = new Server(
    { name: "postgres-server", version: "1.0.0" },
    { capabilities: { tools: {} } }
    );

    server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools: [
    {
    name: "query",
    description: "执行 SQL 查询(只读)",
    inputSchema: {
    type: "object",
    properties: {
    sql: {
    type: "string",
    description: "SELECT 查询语句"
    }
    },
    required: ["sql"]
    }
    },
    {
    name: "list_tables",
    description: "列出数据库中的所有表",
    inputSchema: {
    type: "object",
    properties: {}
    }
    },
    {
    name: "describe_table",
    description: "显示表结构",
    inputSchema: {
    type: "object",
    properties: {
    table_name: {
    type: "string",
    description: "表名"
    }
    },
    required: ["table_name"]
    }
    }
    ]
    }));

    server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    try {
    switch (name) {
    case "query": {
    // 安全检查:只允许 SELECT
    if (!args.sql.trim().toUpperCase().startsWith("SELECT")) {
    throw new Error("只允许执行 SELECT 查询");
    }
    const result = await pool.query(args.sql);
    return {
    content: [{
    type: "text",
    text: JSON.stringify(result.rows, null, 2)
    }]
    };
    }

    case "list_tables": {
    const result = await pool.query(`
    SELECT table_name
    FROM information_schema.tables
    WHERE table_schema = 'public'
    `
    );
    return {
    content: [{
    type: "text",
    text: JSON.stringify(result.rows, null, 2)
    }]
    };
    }

    case "describe_table": {
    const result = await pool.query(`
    SELECT column_name, data_type, is_nullable, column_default
    FROM information_schema.columns
    WHERE table_name = $1
    ORDER BY ordinal_position
    `
    , [args.table_name]);
    return {
    content: [{
    type: "text",
    text: JSON.stringify(result.rows, null, 2)
    }]
    };
    }

    default:
    throw new Error(`未知工具: ${name}`);
    }
    } catch (error) {
    return {
    content: [{
    type: "text",
    text: `错误: ${error.message}`
    }],
    isError: true
    };
    }
    });

    const transport = new StdioServerTransport();
    await server.connect(transport);

    示例 3:API 集成工具

    // api-tool/index.ts
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

    const server = new Server(
    { name: "api-server", version: "1.0.0" },
    { capabilities: { tools: {} } }
    );

    // 通用的 API 调用工具
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
    tools: [{
    name: "http_request",
    description: "发送 HTTP 请求",
    inputSchema: {
    type: "object",
    properties: {
    method: {
    type: "string",
    enum: ["GET", "POST", "PUT", "DELETE", "PATCH"],
    description: "HTTP 方法"
    },
    url: {
    type: "string",
    description: "请求 URL"
    },
    headers: {
    type: "object",
    description: "请求头",
    additionalProperties: { type: "string" }
    },
    body: {
    type: "object",
    description: "请求体(JSON)"
    }
    },
    required: ["method", "url"]
    }
    }]
    }));

    server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (name === "http_request") {
    const options = {
    method: args.method,
    headers: {
    "Content-Type": "application/json",
    args.headers
    }
    };

    if (args.body && ["POST", "PUT", "PATCH"].includes(args.method)) {
    options.body = JSON.stringify(args.body);
    }

    const response = await fetch(args.url, options);
    const text = await response.text();

    let result;
    try {
    result = JSON.parse(text);
    } catch {
    result = text;
    }

    return {
    content: [{
    type: "text",
    text: JSON.stringify({
    status: response.status,
    statusText: response.statusText,
    headers: Object.fromEntries(response.headers),
    body: result
    }, null, 2)
    }]
    };
    }

    throw new Error(`未知工具: ${name}`);
    });

    const transport = new StdioServerTransport();
    await server.connect(transport);

    3.3 工具开发最佳实践

    // ✅ 好的实践:清晰的错误处理
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
    try {
    const { name, arguments: args } = request.params;

    // 验证输入
    if (!args.required_param) {
    return {
    content: [{
    type: "text",
    text: "错误:缺少必需参数 required_param"
    }],
    isError: true
    };
    }

    // 执行操作
    const result = await doSomething(args);

    return {
    content: [{
    type: "text",
    text: JSON.stringify(result, null, 2)
    }]
    };
    } catch (error) {
    return {
    content: [{
    type: "text",
    text: `操作失败: ${error.message}`
    }],
    isError: true
    };
    }
    });

    // ✅ 好的实践:详细的工具描述
    {
    name: "search_code",
    description: `在代码库中搜索指定模式。

    返回匹配的文件列表和上下文。

    示例用法:
    – 搜索函数定义:search_code("function hello")
    – 搜索 TODO 注释:search_code("TODO:")
    – 使用正则:search_code("/import.*from/")`,
    inputSchema: {
    // …
    }
    }

    // ✅ 好的实践:安全的默认设置
    {
    name: "read_file",
    inputSchema: {
    type: "object",
    properties: {
    path: { type: "string" },
    max_size: {
    type: "number",
    default: 1000000, // 默认限制 1MB
    description: "最大文件大小(字节)"
    }
    }
    }
    }

    3.4 发布自定义工具

    # 创建项目
    mkdir my-mcp-tool && cd my-mcp-tool

    # 初始化 npm
    npm init -y

    # 安装依赖
    npm install @modelcontextprotocol/sdk

    # 创建入口文件
    cat > index.ts << 'EOF'
    // 你的工具代码
    EOF

    # 配置 package.json
    {
    "name": "@your-org/mcp-server-xxx",
    "version": "1.0.0",
    "type": "module",
    "bin": {
    "mcp-server-xxx": "./dist/index.js"
    },
    "scripts": {
    "build": "tsc",
    "prepare": "npm run build"
    }
    }

    # 发布到 npm
    npm publish –access public


    4. 插件安装与管理

    4.1 安装插件

    方法 1:通过配置文件

    // ~/.config/claude-code/mcp.json
    {
    "mcpServers": {
    "my-plugin": {
    "command": "npx",
    "args": ["-y", "@my-org/mcp-server-plugin"],
    "env": {
    "API_KEY": "your-api-key"
    }
    }
    }
    }

    方法 2:通过 CLI 安装

    # 使用 npx(推荐)
    npx -y @modelcontextprotocol/create-server my-tool

    # 全局安装
    npm install -g @my-org/mcp-server-plugin

    # 然后在配置中使用
    {
    "mcpServers": {
    "my-plugin": {
    "command": "mcp-server-plugin"
    }
    }
    }

    方法 3:从源码安装

    # 克隆仓库
    git clone https://github.com/user/mcp-server-awesome.git
    cd mcp-server-awesome

    # 安装依赖并构建
    npm install
    npm run build

    # 在配置中指定路径
    {
    "mcpServers": {
    "awesome": {
    "command": "node",
    "args": ["/path/to/mcp-server-awesome/dist/index.js"]
    }
    }
    }

    4.2 配置管理

    环境变量配置

    {
    "mcpServers": {
    "github": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-github"],
    "env": {
    "GITHUB_TOKEN": "${GITHUB_TOKEN}",
    "GITHUB_ORG": "my-org"
    }
    },
    "slack": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-slack"],
    "env": {
    "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}"
    }
    }
    }
    }

    多环境配置

    # 项目级配置
    # 项目根目录/.claude/mcp.json

    # 用户级配置
    # ~/.config/claude-code/mcp.json

    # 环境变量
    export GITHUB_TOKEN="ghp_xxx"
    export SLACK_BOT_TOKEN="xoxb-xxx"

    4.3 插件验证与调试

    # 验证配置
    claude mcp validate

    # 列出已安装的工具
    claude tools list

    # 测试特定工具
    claude tools test <tool-name>

    # 查看服务器日志
    claude mcp logs <server-name>

    4.4 插件更新与卸载

    # 更新 npm 包
    npm update -g @modelcontextprotocol/server-filesystem

    # 更新到特定版本
    npm install -g @modelcontextprotocol/server-filesystem@2.0.0

    # 卸载
    npm uninstall -g @modelcontextprotocol/server-filesystem

    # 从配置中移除
    # 编辑 mcp.json,删除对应的服务器配置

    4.5 推荐插件集合

    {
    "mcpServers": {
    "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "${HOME}/projects"]
    },
    "github": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-github"],
    "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
    },
    "postgres": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-postgres"],
    "env": { "POSTGRES_CONNECTION_STRING": "${DATABASE_URL}" }
    },
    "fetch": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-fetch"]
    },
    "memory": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-memory"]
    }
    }
    }


    5. 工具最佳实践

    5.1 工具选择指南

    任务类型 推荐工具
    ─────────────────────────────────────
    文件读取 read
    文件创建/覆盖 write
    文件修改 edit
    命令执行 exec
    后台任务 exec + background + process
    网页搜索 web_search
    网页抓取 web_fetch
    浏览器自动化 browser
    消息发送 message
    语音输出 tts
    数据库操作 MCP postgres/sqlite
    API 调用 MCP fetch 或自定义工具

    5.2 性能优化

    批量操作

    // ❌ 避免:多次小操作
    for (const file of files) {
    await read({ file_path: file });
    }

    // ✅ 推荐:批量处理
    const results = await Promise.all(
    files.map(f => read({ file_path: f }))
    );

    使用后台进程

    # ❌ 避免:阻塞式执行
    <exec>
    <command>npm run build</command>
    </exec>

    # ✅ 推荐:后台执行
    <exec>
    <command>npm run build</command>
    <background>true</background>
    </exec>

    # 然后轮询状态
    <process>
    <action>poll</action>
    <sessionId>build-123</sessionId>
    </process>

    5.3 错误处理

    // ✅ 好的实践:清晰的错误反馈
    <read>
    <file_path>/path/to/file</file_path>
    </read>

    // 如果文件不存在,Claude 会收到明确的错误信息
    // 然后可以尝试其他路径或询问用户

    // ✅ 使用 try-catch 模式
    <exec>
    <command>test f config.json && cat config.json || echo "File not found"</command>
    </exec>

    5.4 安全考虑

    // ❌ 避免:直接使用用户输入
    <exec>
    <command>rm rf ${user_input}</command> // 危险!
    </exec>

    // ✅ 推荐:验证和转义
    <exec>
    <command>find . name "*.log" type f</command>
    </exec>

    // ✅ 限制文件访问范围
    // 在 MCP 配置中:
    {
    "mcpServers": {
    "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/safe/directory"]
    }
    }
    }

    5.5 工具链式调用

    用户: 帮我分析这个项目的依赖,并检查是否有安全漏洞

    Claude 的思考过程:
    1. [read] 读取 package.json
    2. [exec] 运行 npm audit
    3. [web_search] 搜索已知漏洞
    4. [write] 生成报告文件

    执行顺序:

    <!– 步骤 1 –>
    <read>
    <file_path>/project/package.json</file_path>
    </read>

    <!– 步骤 2 –>
    <exec>
    <command>npm audit –json</command>
    <workdir>/project</workdir>
    </exec>

    <!– 步骤 3:如有需要 –>
    <web_search>
    <query>npm vulnerability CVE-2024-xxxx</query>
    </web_search>

    <!– 步骤 4 –>
    <write>
    <file_path>/project/security-report.md</file_path>
    <content>
    # 安全审计报告

    </content>
    </write>

    5.6 调试技巧

    # 1. 启用详细日志
    export CLAUDE_DEBUG=1

    # 2. 检查 MCP 服务器状态
    claude mcp status

    # 3. 测试单个工具
    claude tools test read –file-path test.txt

    # 4. 查看工具调用历史
    claude history –tools

    # 5. 模拟工具调用
    claude simulate –tool read –args '{"file_path": "test.txt"}'

    5.7 常见问题解决

    问题 1:工具调用超时

    # 解决方案:增加超时时间
    <exec>
    <command>long-running-command</command>
    <timeout>300</timeout> <!5 分钟 —>
    </exec>

    问题 2:文件路径问题

    # 使用绝对路径
    <read>
    <file_path>/home/user/project/file.txt</file_path>
    </read>

    # 或相对于工作目录
    <read>
    <file_path>./src/index.ts</file_path>
    </read>

    问题 3:环境变量未加载

    // 在 mcp.json 中明确设置
    {
    "mcpServers": {
    "my-server": {
    "command": "node",
    "args": ["server.js"],
    "env": {
    "NODE_ENV": "production",
    "API_KEY": "actual-key-here"
    }
    }
    }
    }

    5.8 工具组合模式

    模式 1:搜索-读取-分析

    用户: 找到所有 TypeScript 文件中使用了 async/await 的函数

    执行:
    1. [exec] grep -r "async\\|await" –include="*.ts" .
    2. [read] 读取相关文件
    3. [edit] 可选:修改代码

    模式 2:浏览器自动化流程

    用户: 帮我登录网站并截图

    执行:
    1. [browser] action=start
    2. [browser] action=open targetUrl=https://example.com
    3. [browser] action=snapshot
    4. [browser] action=act request={"kind": "type", "ref": "username", "text": "user"}
    5. [browser] action=act request={"kind": "type", "ref": "password", "text": "pass"}
    6. [browser] action=act request={"kind": "click", "ref": "submit"}
    7. [browser] action=screenshot

    模式 3:数据处理管道

    用户: 获取 API 数据,处理并保存

    执行:
    1. [exec] curl -s https://api.example.com/data
    2. [exec] 处理数据的脚本
    3. [write] 保存结果


    总结

    Claude Code 的工具系统通过 MCP 协议实现了强大的扩展性:

    能力说明
    内置工具 文件、命令、网络、浏览器等核心能力
    MCP 工具 标准化的第三方工具集成
    自定义工具 完全可控的工具开发能力
    安全控制 权限、范围、环境隔离

    掌握工具系统,让 Claude Code 成为真正的开发助手!


    参考资源

    • MCP 官方文档
    • Anthropic Claude Code 文档
    • MCP 服务器仓库
    • Awesome MCP Tools
    赞(0)
    未经允许不得转载:171主机测评 » 06-Claude-Code工具与插件
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址