Skip to content

MCP 服务器

什么是 MCP?

MCP (Model Context Protocol) 是 Anthropic 开发的标准协议,用于连接 AI 模型与外部数据源和服务。

核心概念:

  • 📡 统一接口:标准化的数据访问方式
  • 🔌 可扩展:轻松添加新的数据源
  • 🔒 安全:细粒度的权限控制
  • ⚡ 高效:实时数据访问

MCP 能做什么?

  • 连接数据库(PostgreSQL, MySQL, MongoDB等)
  • 访问云服务(AWS, Google Cloud, Azure)
  • 集成开发工具(GitHub, Jira, Slack)
  • 读取本地文件系统
  • 调用外部 API

配置 MCP 服务器

配置文件位置

~/.config/claude-code/mcp-servers.json

基本配置结构

json
{
  "mcpServers": {
    "server-name": {
      "command": "node",
      "args": ["/path/to/server.js"],
      "env": {
        "API_KEY": "your-key"
      }
    }
  }
}

示例:文件系统服务器

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/projects"
      ]
    }
  }
}

常用 MCP 服务器

1. 文件系统服务器

安装:

bash
npm install -g @modelcontextprotocol/server-filesystem

配置:

json
{
  "mcpServers": {
    "filesystem": {
      "command": "mcp-server-filesystem",
      "args": ["/home/user/documents"]
    }
  }
}

使用:

bash
You: 读取 /documents/report.pdf 的内容

Claude: [Using MCP filesystem server]
Reading report.pdf...
[Content summary]

2. GitHub 服务器

配置:

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

使用:

bash
You: 获取我的 GitHub 仓库列表

Claude: [Using MCP GitHub server]
Found 25 repositories:
1. user/project-a (⭐ 123)
2. user/project-b (⭐ 45)
...

3. PostgreSQL 服务器

配置:

json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres"
      ],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/db"
      }
    }
  }
}

使用:

bash
You: 查询数据库中的用户总数

Claude: [Using MCP Postgres server]
SELECT COUNT(*) FROM users;
Result: 1,234 users

自定义 MCP 服务器

创建简单的 MCP 服务器

javascript
// my-mcp-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');

const server = new Server({
  name: 'my-custom-server',
  version: '1.0.0',
}, {
  capabilities: {
    tools: {},
  },
});

// 定义工具
server.setRequestHandler('tools/list', async () => {
  return {
    tools: [{
      name: 'get_weather',
      description: 'Get weather for a city',
      inputSchema: {
        type: 'object',
        properties: {
          city: {
            type: 'string',
            description: 'City name',
          },
        },
        required: ['city'],
      },
    }],
  };
});

// 处理工具调用
server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'get_weather') {
    const { city } = request.params.arguments;
    // 实现天气查询逻辑
    return {
      content: [{
        type: 'text',
        text: `Weather in ${city}: Sunny, 25°C`,
      }],
    };
  }
});

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

配置自定义服务器

json
{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/path/to/my-mcp-server.js"]
    }
  }
}

MCP 实战案例

案例 1:数据库查询助手

bash
You: 查询销售额最高的前10个产品

Claude: [Using MCP Postgres]
SELECT name, SUM(revenue) as total
FROM products p
JOIN sales s ON p.id = s.product_id
GROUP BY p.id, p.name
ORDER BY total DESC
LIMIT 10;

Top 10 Products:
1. Product A - $125,000
2. Product B - $98,500
...

案例 2:GitHub 自动化

bash
You: 创建一个新的 issue 报告登录bug

Claude: [Using MCP GitHub]
Creating issue in user/repo...

 Issue created: #156
Title: "Bug: Login功能异常"
Labels: bug, priority:high
Assignee: user

案例 3:文档生成

bash
You: 从数据库生成 API 文档

Claude: [Using MCP Postgres + filesystem]
1. Querying database schema...
2. Analyzing table relationships...
3. Generating documentation...
 Created api-docs.md

小结

在本章中,我们学习了:

  • ✅ MCP 协议的概念和用途
  • ✅ 如何配置 MCP 服务器
  • ✅ 常用 MCP 服务器(文件系统、GitHub、数据库)
  • ✅ 创建自定义 MCP 服务器
  • ✅ MCP 实战案例

关键要点:

  • MCP 扩展了 Claude Code 的能力边界
  • 支持多种数据源和服务
  • 可以自定义开发 MCP 服务器
  • 安全配置很重要