MCP(Model Context Protocol)技术详解

整理自AI对话 | 2025年12月19日

一、MCP概述

1.1 基本定义

MCP(Model Context Protocol)是由Anthropic主导开发的开放协议,用于让AI助手安全、可控地访问外部工具、数据和系统。

1.2 核心特性

  • 标准化接口:统一了AI与工具的交互方式
  • 安全隔离:AI只能通过定义好的"工具"与外界交互,无法直接执行任意代码
  • 跨模型兼容:支持不同AI模型使用相同的工具集
  • 协议化通信:基于结构化消息传递的通信机制

二、MCP与AI编程工具的协作机制

2.1 架构层级

AI编程工具(Cursor、Windsurf、Claude Desktop等)
        ↓
    MCP协议层(安全中介)
        ↓
外部系统(文件系统、Git、数据库、API等)

2.2 协作场景

2.2.1 代码开发场景

  • 项目结构分析:读取项目文件树和依赖关系
  • 版本控制集成:与Git交互,查看提交历史、分支状态
  • 代码搜索:在代码库中进行语义搜索

2.2.2 数据操作场景

  • 数据库查询:连接开发数据库,执行查询操作
  • API测试:调用REST/GraphQL接口进行调试
  • 文件操作:安全地读写配置文件、日志文件

2.2.3 系统管理场景

  • 日志监控:查看应用日志和系统状态
  • 服务管理:检查服务运行状态
  • 环境配置:管理开发环境变量和配置

三、MCP配置详解

3.1 配置文件结构

3.1.1 Claude Desktop配置示例

{
  "mcpServers": {
    "file-system": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-filesystem", "/path/to/project"],
      "env": {
        "READ_ONLY": "true"
      }
    },
    "git-repo": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-git", "/path/to/repo"]
    }
  }
}

3.1.2 Cursor配置示例

// 位置:.cursor/mcp.json
{
  "mcpServers": {
    "codebase-search": {
      "command": "node",
      "args": ["./local-search-server.js"],
      "env": {
        "INDEX_PATH": "./code-index",
        "MAX_RESULTS": "50"
      }
    }
  }
}

3.2 配置步骤流程

步骤1:确定配置文件位置

# macOS
~/Library/Application Support/Claude/claude_desktop_config.json

# Windows
%APPDATA%\Claude\claude_desktop_config.json

# Linux
~/.config/Claude/claude_desktop_config.json

步骤2:添加MCP服务器配置

{
  "mcpServers": {
    "postgres-dev": {
      "command": "npx",
      "args": [
        "@modelcontextprotocol/server-postgres",
        "--connectionString",
        "postgresql://user:pass@localhost:5432/dev_db"
      ],
      "timeout": 30000
    }
  }
}

步骤3:验证配置

  1. 重启AI工具应用
  2. 检查MCP服务器连接状态
  3. 测试工具调用功能

3.3 常用MCP服务器参考

服务器类型 安装命令 主要功能 安全建议
文件系统 npx @modelcontextprotocol/server-filesystem 文件读写、目录遍历 设置只读模式,限制目录范围
Git集成 npx @modelcontextprotocol/server-git 版本控制操作 只读访问,禁用危险操作
SQLite数据库 npx @modelcontextprotocol/server-sqlite 数据库查询 限制连接字符串,使用只读模式
PostgreSQL npx @modelcontextprotocol/server-postgres 数据库操作 使用只读账号,限制查询复杂度
HTTP客户端 npx @modelcontextprotocol/server-http API调用 限制目标域名,设置超时
系统信息 npx @modelcontextprotocol/server-sysinfo 系统状态监控 限制敏感信息访问

四、自定义MCP服务器开发

4.1 基本服务器结构

// custom-server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

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

// 工具定义
server.setRequestHandler(ToolsListRequestSchema, async () => ({
  tools: [
    {
      name: "query-metrics",
      description: "查询系统指标数据",
      inputSchema: {
        type: "object",
        properties: {
          metricName: { type: "string" },
          timeRange: { type: "string" }
        },
        required: ["metricName"]
      }
    }
  ]
}));

// 工具执行处理
server.setRequestHandler(ToolCallRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  switch (name) {
    case "query-metrics":
      // 处理指标查询逻辑
      return {
        content: [{
          type: "text",
          text: `查询指标 ${args.metricName} 的结果...`
        }]
      };
    default:
      throw new Error(`未知工具: ${name}`);
  }
});

// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("MCP服务器已启动");

4.2 服务器配置文件

// package.json片段
{
  "name": "mcp-server-custom",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "mcp-server-custom": "./server.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.0.0"
  }
}

五、安全配置最佳实践

5.1 权限控制原则

  1. 最小权限原则:只授予必要的访问权限
  2. 沙盒环境:在生产环境中使用隔离的沙盒
  3. 审计日志:记录所有MCP工具调用

5.2 环境隔离配置

{
  "mcpServers": {
    "dev-database": {
      "command": "npx",
      "args": [
        "@modelcontextprotocol/server-postgres",
        "--connectionString",
        "${DEV_DB_URL}"
      ],
      "env": {
        "READ_ONLY": "true",
        "QUERY_TIMEOUT": "5000"
      }
    },
    "prod-database": {
      "command": "npx",
      "args": [
        "@modelcontextprotocol/server-postgres",
        "--connectionString",
        "${PROD_DB_URL}"
      ],
      "env": {
        "READ_ONLY": "true",
        "QUERY_TIMEOUT": "3000",
        "MAX_ROWS": "100"
      },
      "enabled": false  // 默认禁用,需要时手动开启
    }
  }
}

5.3 监控与日志

// 监控配置示例
const mcpMonitoring = {
  enabled: true,
  logLevel: "info",
  audit: {
    logAllCalls: true,
    alertOn: ["sensitive_operation", "high_volume"]
  },
  rateLimiting: {
    maxRequestsPerMinute: 100,
    maxConcurrentRequests: 5
  }
};

六、故障排除

6.1 常见问题

  1. 连接失败
  2. 检查MCP服务器命令路径
  3. 验证环境变量配置
  4. 检查端口和权限设置

  5. 性能问题

  6. 优化查询复杂度
  7. 配置适当的超时时间
  8. 启用缓存机制

  9. 安全问题

  10. 定期更新MCP服务器
  11. 审查工具权限设置
  12. 监控异常调用模式

6.2 调试方法

# 1. 检查MCP服务器日志
tail -f ~/.cache/mcp-server.log

# 2. 测试MCP服务器直接运行
npx @modelcontextprotocol/server-filesystem --help

# 3. 验证配置语法
node -c config-file.json

七、未来发展方向

7.1 生态扩展

  • 更多官方和社区MCP服务器
  • 标准化工具描述格式
  • 跨平台兼容性增强

7.2 功能演进

  • 实时数据流支持
  • 双向通信机制
  • 分布式MCP服务器网络

7.3 安全增强

  • 细粒度权限控制
  • 加密通信通道
  • 自动化安全审计

附录:配置快速参考

文件位置速查

工具/平台 配置文件路径
Claude Desktop ~/Library/Application Support/Claude/claude_desktop_config.json
Cursor 项目目录:.cursor/mcp.json
Windsurf ~/.config/windsurf/mcp.json

常用命令速查

# 安装文件系统服务器
npx @modelcontextprotocol/server-filesystem@latest

# 安装Git服务器
npx @modelcontextprotocol/server-git@latest

# 测试MCP连接
curl -X POST http://localhost:8080/mcp/list-tools

# 查看已安装的MCP服务器
npm list -g | grep mcp-server

文档版本:1.0 | 最后更新:2025年12月19日
本文档基于实际AI对话整理,内容可能随技术发展而变化