MCP

Claude MCP 集成完全攻略:让 Claude 成为全能 AI Agent

详细教程:如何在 Claude Desktop 和 Claude API 中配置和使用 MCP,让 Claude 获得操作文件、数据库、API 等外部服务的能力。

Claude 是目前对 MCP 支持最完善的 LLM。从 Claude Desktop 的桌面应用到 Claude API 的开发者接口,MCP 已经深度集成到 Claude 的每一个使用场景中。这篇文章将带你完整走一遍 Claude MCP 的配置和使用流程。

Claude Desktop 配置 MCP

Claude Desktop 是体验 MCP 最简单的方式。你只需要编辑一个配置文件,就能让 Claude 获得各种新能力。

配置文件位置

  • macOS~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows%APPDATA%\Claude\claude_desktop_config.json

基础配置结构

{
  "mcpServers": {
    "server-name": {
      "command": "命令",
      "args": ["参数1", "参数2"],
      "env": {
        "环境变量": "值"
      }
    }
  }
}

常用 MCP Server 配置示例

文件系统 Server——让 Claude 读写本地文件:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/yourname/Documents"
      ]
    }
  }
}

GitHub Server——让 Claude 操作 GitHub 仓库:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "your-token-here"
      }
    }
  }
}

SQLite Server——让 Claude 查询数据库:

{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": [
        "mcp-server-sqlite",
        "--db-path",
        "/path/to/database.db"
      ]
    }
  }
}

Brave Search Server——让 Claude 搜索网页:

{
  "mcpServers": {
    "brave-search": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "your-api-key"
      }
    }
  }
}

同时配置多个 Server

你可以在同一个配置文件中注册多个 Server,Claude 会自动发现并使用所有可用的工具:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "ghp_xxx" }
    },
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "./data.db"]
    }
  }
}

Claude API 中使用 MCP

对于开发者来说,在 Claude API 中使用 MCP 需要更多的代码工作。你需要自己实现 MCP Client 逻辑,将 MCP 工具转换为 Claude API 的 Function Calling 格式。

完整的 Agent 实现

import Anthropic from '@anthropic-ai/sdk';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

class ClaudeMCPAgent {
  private claude: Anthropic;
  private mcpClients: Client[] = [];
  private tools: any[] = [];

  constructor() {
    this.claude = new Anthropic();
  }

  async addMCPServer(command: string, args: string[]) {
    const client = new Client({ name: 'agent', version: '1.0.0' });
    const transport = new StdioClientTransport({ command, args });
    await client.connect(transport);
    this.mcpClients.push(client);

    // 发现并注册工具
    const { tools } = await client.listTools();
    for (const tool of tools) {
      this.tools.push({
        name: tool.name,
        description: tool.description,
        input_schema: tool.inputSchema,
      });
    }
  }

  async chat(message: string): Promise<string> {
    const messages: Anthropic.MessageParam[] = [
      { role: 'user', content: message }
    ];

    while (true) {
      const response = await this.claude.messages.create({
        model: 'claude-sonnet-4-20250514',
        max_tokens: 4096,
        tools: this.tools,
        messages,
      });

      // 如果 Claude 决定使用工具
      if (response.stop_reason === 'tool_use') {
        const toolResults: Anthropic.ToolResultBlockParam[] = [];

        for (const block of response.content) {
          if (block.type === 'tool_use') {
            const result = await this.executeTool(block.name, block.input);
            toolResults.push({
              type: 'tool_result',
              tool_use_id: block.id,
              content: result,
            });
          }
        }

        messages.push({ role: 'assistant', content: response.content });
        messages.push({ role: 'user', content: toolResults });
        continue;
      }

      // 返回最终回答
      return response.content
        .filter((b): b is Anthropic.TextBlock => b.type === 'text')
        .map(b => b.text)
        .join('');
    }
  }

  private async executeTool(name: string, args: any): Promise<string> {
    for (const client of this.mcpClients) {
      try {
        const result = await client.callTool({ name, arguments: args });
        return result.content.map((c: any) => c.text || '').join('\n');
      } catch {
        continue;
      }
    }
    throw new Error(`工具 ${name} 未找到`);
  }

  async cleanup() {
    for (const client of this.mcpClients) {
      await client.close();
    }
  }
}

// 使用示例
const agent = new ClaudeMCPAgent();
await agent.addMCPServer('npx', ['-y', '@modelcontextprotocol/server-filesystem', '/home']);
await agent.addMCPServer('npx', ['-y', '@modelcontextprotocol/server-github']);

const response = await agent.chat('帮我看看当前目录有哪些文件');
console.log(response);

await agent.cleanup();

Claude MCP 的工作原理

当你在 Claude Desktop 中使用 MCP 时,背后的流程是这样的:

  1. 启动阶段——Claude Desktop 启动配置文件中定义的所有 MCP Server 子进程
  2. 能力发现——每个 Server 通过 tools/listresources/list 声明自己的能力
  3. 对话阶段——当你发送消息时,Claude 会看到所有可用的工具,并决定是否需要调用
  4. 工具执行——如果 Claude 决定使用工具,Claude Desktop 将调用请求发送给对应的 Server
  5. 结果返回——Server 执行工具并将结果返回给 Claude
  6. 继续推理——Claude 基于工具返回的结果继续生成回答

整个过程对用户是透明的——你只需要正常对话,Claude 会自动判断何时需要使用工具。

实际应用场景演示

场景一:代码审查助手

配置 GitHub Server 后,你可以让 Claude 审查 Pull Request:

用户:帮我审查一下 PR #42 的代码变更

Claude:我来查看这个 PR 的内容。
[调用 github:get_pull_request 工具]
[调用 github:get_pull_request_diff 工具]

这个 PR 主要做了以下改动:
1. 修改了用户认证逻辑...
2. 建议改进的地方...

场景二:数据分析助手

配置 SQLite Server 后,Claude 可以直接查询数据库:

用户:上个月的用户增长情况如何?

Claude:让我查询一下相关数据。
[调用 sqlite:query 工具,执行 SQL 查询]

根据查询结果,上个月新增用户 1,234 人...

场景三:文档管理助手

配置文件系统 Server 后,Claude 可以帮你管理本地文件:

用户:帮我整理一下 Downloads 文件夹里的 PDF 文件

Claude:我先看看 Downloads 目录里有哪些文件。
[调用 filesystem:list_directory 工具]
[调用 filesystem:read_file 工具]

我找到了 5 个 PDF 文件,建议按以下方式整理...

常见问题(FAQ)

Claude Desktop 支持多少个 MCP Server?

理论上没有限制,但建议不超过 10 个。过多的 Server 会增加启动时间和内存消耗,也可能让 Claude 在选择工具时产生困惑。

MCP Server 崩溃会影响 Claude Desktop 吗?

会。如果 MCP Server 进程崩溃,对应的工具将不可用,但 Claude Desktop 本身不会受到影响。重启 Claude Desktop 会重新启动所有 Server。

如何查看 MCP Server 的日志?

Claude Desktop 将 MCP Server 的日志输出到 ~/Library/Logs/Claude/ 目录(macOS)。你可以在那里查看 Server 的运行状态和错误信息。

可以在移动设备上使用 MCP 吗?

目前 Claude 的移动应用不支持 MCP。MCP 功能仅在 Claude Desktop(桌面应用)和 Claude API 中可用。

总结

Claude 与 MCP 的深度集成使其成为目前最强大的 AI Agent 平台之一。通过合理配置 MCP Server,你可以让 Claude 访问文件系统、数据库、代码仓库、搜索引擎等各种外部服务,将其从一个对话助手升级为一个全能的智能代理。

关键在于选择合适的 MCP Server 组合,根据你的实际需求定制 Claude 的能力边界。