MCP 深度实战指南

举报
yd_47669746 发表于 2026/11/07 23:03:16 2026/11/07
【摘要】 一、理解 MCP 的本质 为什么需要 MCPClaude Code 本身能做的事情:读写文件、执行命令、搜索代码。Claude Code 不能做的事情:连接数据库查询调用第三方 API操作浏览器访问 Slack/Jira/Confluence执行特定平台的命令MCP 就是解决这个问题的:让 Claude 能使用任何外部工具。 MCP 的架构Claude Code (Client) │...

一、理解 MCP 的本质

为什么需要 MCP

Claude Code 本身能做的事情:读写文件、执行命令、搜索代码。

Claude Code 不能做的事情:

  • 连接数据库查询
  • 调用第三方 API
  • 操作浏览器
  • 访问 Slack/Jira/Confluence
  • 执行特定平台的命令

MCP 就是解决这个问题的:让 Claude 能使用任何外部工具。

MCP 的架构

Claude Code (Client)
    │
    │ JSON-RPC over stdio/SSE
    │
    ▼
MCP Server (你配置的工具服务)
    │
    │ 实际操作
    │
    ▼
外部资源(数据库、API、文件系统、浏览器...)

MCP 的三种能力

Tools(工具)    — 让 Claude 能执行操作(查询、写入、调用)
Resources(资源)— 让 Claude 能读取数据(文件、数据库、配置)
Prompts(模板)  — 预定义的 Prompt 模板

二、MCP Server 配置详解

配置文件位置

项目级:.claude/settings.json    — 只对当前项目生效
用户级:~/.claude/settings.json  — 对所有项目生效

stdio 模式(本地工具)

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:password@localhost:5432/mydb"
      ]
    }
  }
}

工作原理:

  1. Claude Code 启动 MCP Server 子进程
  2. 通过 stdin/stdout 通信
  3. JSON-RPC 协议

SSE 模式(远程服务)

{
  "mcpServers": {
    "remote-tools": {
      "url": "https://mcp.example.com/sse"
    }
  }
}

带环境变量的配置

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

安全提示:不要把 token 提交到 Git,用环境变量引用:

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

三、常用 MCP Server 深度使用

1. PostgreSQL — 数据库操作

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:pass@localhost:5432/mydb"
      ]
    }
  }
}

实际使用场景:

# 场景 1:理解数据结构
"查看 users 表的结构,有哪些字段和索引"

# 场景 2:数据驱动开发
"根据 orders 表的结构,帮我写 Prisma schema"

# 场景 3:调试数据问题
"查询最近 10 条失败的支付记录,看看是什么原因"

# 场景 4:性能分析
"运行 EXPLAIN ANALYZE 分析这个查询的性能:
SELECT * FROM orders WHERE user_id = 123 AND status = 'pending'"

# 场景 5:数据迁移验证
"迁移完成后,检查 users 表中是否还有空的 email 字段"

技巧:先让 Claude 了解表结构,再写代码,比让它猜字段名准确得多。

2. GitHub — 完整 Git 工作流

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

实际使用场景:

# 场景 1:Issue 驱动开发
"查看 issue #42 的内容,理解需求,然后实现它"

# 场景 2:PR 管理
"审查 PR #38 的代码评论,看看 reviewer 提了什么问题,
然后修复这些问题"

# 场景 3:批量操作
"找到所有 label 为 'bug' 且状态为 open 的 issue,
按创建时间排序,列出前 10 个"

# 场景 4:Release 管理
"查看自上次 release 以来的所有 merged PR,
生成 release notes"

3. Puppeteer — 浏览器自动化

{
  "mcpServers": {
    "puppeteer": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
    }
  }
}

实际使用场景:

# 场景 1:视觉验证
"打开 http://localhost:3000,截图看看首页的样式"

# 场景 2:交互测试
"打开登录页,输入用户名 admin 和密码 123456,
点击登录按钮,看看会发生什么"

# 场景 3:响应式检查
"打开首页,分别在 375px、768px、1440px 宽度下截图"

# 场景 4:性能检查
"打开首页,用 Performance API 测量页面加载时间"

# 场景 5:抓取数据
"打开 https://example.com/products,
抓取所有商品的名称和价格,保存为 JSON"

4. Brave Search — 联网搜索

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

实际使用场景:

# 场景 1:技术调研
"搜索 PostgreSQL 16 的新特性,和我们的项目有什么关系"

# 场景 2:错误排查
"搜索这个错误信息:TypeError: Cannot read properties of undefined,
看看社区是怎么解决的"

# 场景 3:竞品分析
"搜索 'headless CMS' 的最新对比文章,
列出前 5 个方案的优劣"

# 场景 4:依赖调研
"搜索 'zod vs yup vs joi 2026',看看现在社区推荐用哪个"

5. Sentry — 错误监控

{
  "mcpServers": {
    "sentry": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-sentry"],
      "env": {
        "SENTRY_AUTH_TOKEN": "sntrys_xxx",
        "SENTRY_ORG": "my-org",
        "SENTRY_PROJECT": "my-project"
      }
    }
  }
}

实际使用场景:

# 场景 1:错误排查
"查看最近 1 小时的错误,按频率排序"

# 场景 2:根因分析
"查看这个错误的详细堆栈:Error: Connection timeout,
是哪个函数抛出的,最近什么时候开始出现的"

# 场景 3:趋势分析
"这个月的错误率和上个月对比怎么样"

# 场景 4:修复验证
"我刚修复了 issue #123 对应的 bug,
看看 Sentry 上这个错误是否还在出现"

四、MCP 组合使用

场景一:端到端 Bug 修复

# 1. 从 Sentry 获取错误信息
"查看 Sentry 最近的高频错误"

# 2. 定位问题
"根据堆栈信息,在代码中找到问题"

# 3. 查看相关数据
"查询数据库中相关数据的状态"

# 4. 修复代码
"修复这个问题"

# 5. 验证
"运行测试,确保修复正确"

# 6. 创建 PR
"创建 PR,描述中引用 Sentry 错误链接"

# 全程不需要离开 Claude Code

场景二:数据驱动开发

# 1. 了解现有数据
"查看数据库中 users 表的结构和数据样本"

# 2. 设计接口
"根据数据结构设计用户管理 API"

# 3. 实现代码
"实现接口"

# 4. 测试
"用实际数据测试接口"

# 5. 验证
"查询数据库确认数据写入正确"

场景三:Issue 到 PR 的完整流程

# 1. 读取 Issue
"查看 GitHub issue #42 的内容和评论"

# 2. 分析需求
"理解这个 issue 要求什么"

# 3. 实现
"实现功能"

# 4. 测试
"运行测试"

# 5. 创建 PR
"创建 PR,关联 issue #42,
描述中写清楚怎么测试"

五、自定义 MCP Server 开发

什么时候需要自定义

已有 MCP Server 不满足需求
需要连接内部系统
需要封装复杂的业务逻辑

基本结构(TypeScript)

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "my-internal-tools",
  version: "1.0.0",
});

// 工具 1:查询内部用户系统
server.tool(
  "find_user",
  "根据邮箱或手机号查找用户",
  {
    email: z.string().email().optional(),
    phone: z.string().optional(),
  },
  async ({ email, phone }) => {
    // 连接内部用户服务
    const user = await internalUserService.find({ email, phone });
    return {
      content: [{ type: "text", text: JSON.stringify(user, null, 2) }],
    };
  }
);

// 工具 2:发送通知
server.tool(
  "send_notification",
  "给用户发送通知",
  {
    user_id: z.string(),
    message: z.string(),
    channel: z.enum(["email", "sms", "push"]),
  },
  async ({ user_id, message, channel }) => {
    const result = await notificationService.send({
      user_id,
      message,
      channel,
    });
    return {
      content: [{ type: "text", text: `通知已发送: ${result.id}` }],
    };
  }
);

// 资源:暴露内部文档
server.resource(
  "internal-docs",
  "docs://api/authentication",
  async (uri) => {
    const doc = await fetchInternalDoc("authentication");
    return {
      contents: [{ uri: uri.href, text: doc }],
    };
  }
);

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

注册到 Claude Code

{
  "mcpServers": {
    "internal": {
      "command": "node",
      "args": ["./mcp-servers/internal/dist/index.js"],
      "env": {
        "INTERNAL_API_KEY": "xxx"
      }
    }
  }
}

实战:连接内部 API

// 连接公司内部的工单系统
server.tool(
  "create_ticket",
  "在工单系统中创建工单",
  {
    title: z.string(),
    description: z.string(),
    priority: z.enum(["low", "medium", "high", "critical"]),
    assignee: z.string().optional(),
  },
  async ({ title, description, priority, assignee }) => {
    const response = await fetch("https://tickets.internal/api/tickets", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.TICKET_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ title, description, priority, assignee }),
    });

    const ticket = await response.json();
    return {
      content: [
        {
          type: "text",
          text: `工单已创建: ${ticket.id}\n链接: ${ticket.url}`,
        },
      ],
    };
  }
);

六、MCP 调试与排错

查看 MCP 状态

# 在 Claude Code 中
/mcp

# 显示所有已连接的 Server 和可用工具

常见问题

Server 启动失败

# 症状:/mcp 显示 server 状态为 disconnected

# 排查:
# 1. 检查命令是否可用
npx -y @modelcontextprotocol/server-postgres --help

# 2. 检查参数是否正确
# 3. 检查环境变量是否设置

# 4. 查看日志
ls ~/.claude/logs/
tail -f ~/.claude/logs/mcp.log

工具调用超时

# 症状:调用工具后长时间无响应

# 原因:
# - Server 处理太慢
# - 网络问题(远程 Server)
# - 数据库查询太慢

# 解决:
# - 检查 Server 实现的性能
# - 增加超时配置
# - 优化查询

工具返回错误

# 症状:工具调用返回错误信息

# 排查:
# - 检查输入参数是否正确
# - 检查 Server 端的错误日志
# - 手动测试 Server 的功能

日志位置

~/.claude/logs/
  ├── claude.log       # Claude Code 主日志
  ├── mcp.log          # MCP 相关日志
  └── tools.log        # 工具调用日志

实战:MCP Server 连接断开后恢复

症状:用着用着 MCP 工具突然不可用了

常见原因:
1. 数据库连接超时(长时间没查询)
2. 网络波动导致 SSE 连接断开
3. Server 进程被系统 kill 了(内存不足)
# 排查:
# 1. 在 Claude Code 中检查状态
/mcp

# 2. 如果显示 disconnected,重启 Claude Code
# 退出后重新运行
claude

# 3. 如果是数据库类 Server,检查数据库是否可达
# 用 Bash 工具测试连接
pg_isready -h localhost -p 5432

# 4. 如果是远程 SSE Server,检查 URL
curl -I https://mcp.example.com/sse

实战:GitHub Token 过期

症状:GitHub MCP Server 报 401 Unauthorized

原因:Personal Access Token 过期或权限不够
# 解决:
# 1. 生成新 Token
# GitHub → Settings → Developer settings → Personal access tokens
# 勾选:repo, read:org, read:user

# 2. 更新配置
# 项目级:.claude/settings.json
# 用户级:~/.claude/settings.json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_新token"
      }
    }
  }
}

# 3. 重启 Claude Code

# 建议:用 Fine-grained Token,权限更细,过期时间可设

实战:Windows 上 npx 启动 MCP Server 超时

症状:npx 执行 MCP Server 时超时或卡住

原因:Windows 上 npx 首次运行需要下载包,可能很慢
# 解决:
# 方案一:预先全局安装
npm install -g @modelcontextprotocol/server-postgres
npm install -g @modelcontextprotocol/server-github
npm install -g @modelcontextprotocol/server-puppeteer
npm install -g @modelcontextprotocol/server-brave-search

# 然后在配置中用 node 直接运行
{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": [
        "C:/Users/你的用户名/AppData/Roaming/npm/node_modules/@modelcontextprotocol/server-postgres/dist/index.js",
        "postgresql://..."
      ]
    }
  }
}

# 方案二:用 npx 但加超时
# 在 .claude/settings.json 中
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "--timeout", "60000", "@modelcontextprotocol/server-postgres", "postgresql://..."]
    }
  }
}

实战:多个 MCP Server 互相冲突

症状:配置了多个 Server 后,有些工具不显示或调用错误

原因:
1. Server 名称冲突
2. 同一个工具名被多个 Server 注册
3. 资源竞争(如两个 Server 都连同一个数据库)
# 解决:
# 1. 给每个 Server 取唯一的名称
{
  "mcpServers": {
    "prod-db": { ... },
    "staging-db": { ... },
    "github-main": { ... }
  }
}

# 2. 如果工具冲突,用 /mcp 查看哪个 Server 注册了什么工具
/mcp

# 3. 禁用冲突的工具
# 在配置中排除
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "xxx" },
      "disabledTools": ["search_repositories"]
    }
  }
}

实战:MCP Server 占用太多内存

症状:Claude Code 运行越来越慢,系统内存不足

原因:某些 MCP Server(如 Puppeteer)会启动浏览器,占用大量内存
# 解决:
# 1. 不需要时禁用 Server
# 把配置注释掉或删掉,重启 Claude Code

# 2. 对于 Puppeteer,配置为 headless 模式
{
  "mcpServers": {
    "puppeteer": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"],
      "env": {
        "PUPPETEER_LAUNCH_OPTIONS": "{\"headless\": true, \"args\": [\"--no-sandbox\", \"--disable-dev-shm-usage\"]}"
      }
    }
  }
}

# 3. 不要同时开太多 Server
# 日常开发:postgres + github 就够了
# 需要时再加 puppeteer、brave-search

七、MCP 安全注意事项

不要泄露敏感信息

// 差:token 硬编码
{
  "env": {
    "GITHUB_TOKEN": "ghp_xxxxxxxxxxxxx"
  }
}

// 好:用环境变量
{
  "env": {
    "GITHUB_TOKEN": "${GITHUB_TOKEN}"
  }
}

最小权限原则

// 差:给完整的数据库权限
"postgresql://admin:password@localhost:5432/production"

// 好:只读权限
"postgresql://readonly:password@localhost:5432/production"

限制文件系统访问

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/projects"  // 只允许访问特定目录
      ]
    }
  }
}

审计工具调用

// 使用 Hook 记录所有 MCP 工具调用
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "mcp_*",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$(date): MCP tool call: $CLAUDE_TOOL_NAME\" >> ~/.claude/mcp-audit.log"
          }
        ]
      }
    ]
  }
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。