MCP (Model Context Protocol) 学习笔记

377 阅读6分钟

目录


1. 概述

MCP的意义

MCP (Model Context Protocol) 是一套标准协议,它规定了AI应用程序与外部工具之间如何通信。

核心价值:

  • 标准化:统一的协议规范,降低集成成本
  • 安全性:明确的权限边界和验证机制
  • 可扩展性:灵活的工具和资源定义
  • 高效性:基于stdio的本地通信优化

主要应用

  1. 效能工具
    • AISC (AI Source Control) - 智能代码版本控制
    • AIUT (AI Unit Testing) - AI单元测试
    • AICR (AI Code Review) - AI代码检查

2. 前置知识

2.1 JSON-RPC协议

JSON-RPC是一种无状态、轻量级的远程过程调用(RPC)协议,补充了进程功能的不足。

基本格式

请求格式

{
  "jsonrpc": "2.0",
  "method": "sum",
  "params": [1, 2, 4],
  "id": "1"
}

响应格式

{
  "jsonrpc": "2.0",
  "result": 7,
  "id": "1"
}

实现示例

// utils.js
import fs from 'fs';

export default {
  sum({ a, b }) {
    return a + b;
  },
  createFile({ filename, content }) {
    try {
      fs.writeFileSync(filename, content);
      return true;
    } catch {
      return false;
    }
  }
}

2.2 Transports传输层

stdio (标准输入输出)

特点

  • 简洁高效,适用于本地进程间通信
  • 进程间相互隔离,通过stdio接口进行通信
  • 父进程监听子进程输出,实现消息传递

基本原理

  1. 进程有两个接口:标准输出接口和标准输入接口
  2. 进程与进程间相互隔离,需要通信机制
  3. stdio提供了高效的本地进程间通信方式

代码示例

输出示例

// Node.js环境中
process.stdout.write('hello world\n');
// console.log 内部就是调用 process.stdout.write

服务端示例

// server.js
process.stdin.on('data', data => {
  const resp = `回复: ${data}\n`;
  process.stdout.write(resp);
});

客户端示例

// client.js
import { spawn } from 'child_process';

const serverProcess = spawn('node', ['server.js']);

serverProcess.stdout.on('data', data => {
  console.log(`${data}`);
});

const messages = ['声明有意义吗?', '宇宙有尽头吗?', '再见!'];

messages.forEach((msg, index) => {
  setTimeout(() => {
    console.log(`--> ${msg}`);
    serverProcess.stdin.write(`${msg}\n`);
  }, index * 1000);
});

3. MCP核心概念

3.1 基本架构

┌─────────────────┐       ┌─────────────────┐
│                 │       │                 │
│   MCP Client    │◄─────►│   MCP Server    │
│   (AI应用)      │  JSON-RPC │   (工具提供者)   │
│                 │  over  │                 │
│                 │  stdio │                 │
└─────────────────┘       └─────────────────┘
        │                         │
        ▼                         ▼
   ┌─────────┐               ┌─────────┐
   │用户接口  │               │实际工具  │
   │Claude等 │               │文件系统  │
   │        │               │数据库等  │
   └─────────┘               └─────────┘

3.2 核心组件

  • Client (客户端):AI应用程序,如Claude,负责发起请求
  • Server (服务端):工具提供者,暴露具体功能给客户端使用
  • Transport (传输层):通信方式,支持stdio和HTTP
  • Protocol (协议层):基于JSON-RPC的消息格式规范

3.3 关键概念

  • Tools (工具):服务端提供的功能接口
  • Resources (资源):服务端管理的数据或文件
  • Prompts (提示):预定义的AI提示模板
  • Sampling (采样):AI模型的采样配置

4. MCP协议规范

4.1 初始化流程

客户端发起初始化请求

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "roots": {
        "listChanged": true
      },
      "sampling": {},
      "elicitation": {}
    },
    "clientInfo": {
      "name": "ExampleClient",
      "title": "Example Client Display Name",
      "version": "1.0.0"
    }
  }
}

服务端响应初始化

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "logging": {},
      "prompts": { "listChanged": true }
    }
  },
  "serverInfo": {
    "name": "ExampleServer",
    "title": "Example Server Display Name",
    "version": "1.0.0"
  },
  "instructions": "Optional instructions to display to the user."
}

4.2 工具发现

客户端请求工具列表

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list"
}

服务端响应工具列表

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "inputSchema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City name or location"
            }
          },
          "required": ["location"]
        }
      },
      {
        "name": "create_file",
        "description": "Create a new file with content",
        "inputSchema": {
          "type": "object",
          "properties": {
            "filename": {
              "type": "string",
              "description": "Name of the file to create"
            },
            "content": {
              "type": "string",
              "description": "Content of the file"
            }
          },
          "required": ["filename", "content"]
        }
      }
    ]
  }
}

4.3 工具调用

客户端调用工具

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "location": "北京"
    }
  }
}

服务端响应工具执行结果

{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "北京当前天气:晴,气温15°C,湿度45%"
      }
    ]
  }
}

5. 实际应用场景

5.1 开发效率工具

AISC (AI Source Control)

  • 智能代码提交消息生成
  • 自动代码冲突解决
  • 智能分支管理

AIUT (AI Unit Testing)

  • 自动生成测试用例
  • 测试覆盖率分析
  • 回归测试自动化

AICR (AI Code Review)

  • 代码质量检查
  • 安全漏洞检测
  • 代码风格统一

5.2 系统集成场景

graph TD
    A[Claude/GPT等AI] --> B[MCP Client]
    B --> C[文件系统Server]
    B --> D[数据库Server]
    B --> E[API集成Server]
    B --> F[云服务Server]
    
    C --> G[本地文件操作]
    D --> H[SQL查询执行]
    E --> I[第三方API调用]
    F --> J[AWS/Azure操作]

5.3 具体应用示例

文件管理助手

AI通过MCP可以:

  1. 读取项目文件结构
  2. 创建/修改代码文件
  3. 执行构建命令
  4. 运行测试套件

数据分析助手

AI通过MCP可以:

  1. 连接数据库查询数据
  2. 生成可视化图表
  3. 创建分析报告
  4. 自动化数据处理流程

6. MCP开发指南

6.1 创建MCP Server

项目结构

my-mcp-server/
├── package.json
├── src/
│   ├── index.js          # 主入口
│   ├── tools/            # 工具实现
│   │   ├── fileTools.js
│   │   └── weatherTools.js
│   └── utils/
│       └── validation.js
└── README.md

基础Server实现

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

class MyMCPServer {
  constructor() {
    this.server = new Server(
      {
        name: 'my-mcp-server',
        version: '1.0.0',
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );
    
    this.setupHandlers();
  }

  setupHandlers() {
    // 工具列表处理
    this.server.setRequestHandler('tools/list', async () => {
      return {
        tools: [
          {
            name: 'read_file',
            description: '读取文件内容',
            inputSchema: {
              type: 'object',
              properties: {
                path: {
                  type: 'string',
                  description: '文件路径'
                }
              },
              required: ['path']
            }
          }
        ]
      };
    });

    // 工具调用处理
    this.server.setRequestHandler('tools/call', async (request) => {
      const { name, arguments: args } = request.params;
      
      switch (name) {
        case 'read_file':
          return await this.readFile(args.path);
        default:
          throw new Error(`Unknown tool: ${name}`);
      }
    });
  }

  async readFile(path) {
    try {
      const fs = await import('fs/promises');
      const content = await fs.readFile(path, 'utf-8');
      return {
        content: [
          {
            type: 'text',
            text: content
          }
        ]
      };
    } catch (error) {
      throw new Error(`Failed to read file: ${error.message}`);
    }
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
  }
}

// 启动服务器
const server = new MyMCPServer();
server.run().catch(console.error);

6.2 配置Claude使用MCP

Claude Desktop配置

配置文件路径:~/Library/Application Support/Claude/claude_desktop_config.json

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

6.3 开发最佳实践

错误处理

this.server.setRequestHandler('tools/call', async (request) => {
  try {
    // 工具逻辑
    return result;
  } catch (error) {
    return {
      error: {
        code: -32000,
        message: error.message,
        data: {
          type: error.constructor.name
        }
      }
    };
  }
});

参数验证

function validateArgs(args, schema) {
  // 使用joi或ajv进行参数验证
  const { error } = schema.validate(args);
  if (error) {
    throw new Error(`Invalid arguments: ${error.message}`);
  }
}

日志记录

import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'mcp-server.log' })
  ]
});

7. MCP项目生态

7.1 官方项目

7.2 社区项目

常用MCP Servers

  • mcp-server-filesystem:文件系统操作
  • mcp-server-git:Git操作
  • mcp-server-postgres:PostgreSQL数据库
  • mcp-server-sqlite:SQLite数据库
  • mcp-server-brave-search:网络搜索
  • mcp-server-github:GitHub API集成

安装示例

# 安装文件系统服务器
npm install -g @modelcontextprotocol/server-filesystem

# 配置到Claude Desktop
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/directory"
      ]
    }
  }
}

7.3 开发资源

文档和工具

调试工具

# MCP Inspector - 调试工具
npm install -g @modelcontextprotocol/inspector

# 启动调试器
mcp-inspector path/to/your/server.js

8. 总结

MCP (Model Context Protocol) 是连接AI模型与外部工具的桥梁协议,通过标准化的JSON-RPC通信格式,实现了AI应用与各种系统服务的无缝集成。

核心价值

  1. 标准化:统一的协议规范,降低集成成本
  2. 安全性:明确的权限边界和验证机制
  3. 可扩展性:灵活的工具和资源定义
  4. 高效性:基于stdio的本地通信优化