MCP (Model Context Protocol) 学习笔记

目录

  • [1. 概述](#1. 概述 "#1-%E6%A6%82%E8%BF%B0")
  • [2. 前置知识](#2. 前置知识 "#2-%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86")
    • [2.1 JSON-RPC协议](#2.1 JSON-RPC协议 "#21-json-rpc%E5%8D%8F%E8%AE%AE")
    • [2.2 Transports传输层](#2.2 Transports传输层 "#22-transports%E4%BC%A0%E8%BE%93%E5%B1%82")
  • [3. MCP核心概念](#3. MCP核心概念 "#3-mcp%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5")
    • [3.1 基本架构](#3.1 基本架构 "#31-%E5%9F%BA%E6%9C%AC%E6%9E%B6%E6%9E%84")
    • [3.2 核心组件](#3.2 核心组件 "#32-%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6")
    • [3.3 关键概念](#3.3 关键概念 "#33-%E5%85%B3%E9%94%AE%E6%A6%82%E5%BF%B5")
  • [4. MCP协议规范](#4. MCP协议规范 "#4-mcp%E5%8D%8F%E8%AE%AE%E8%A7%84%E8%8C%83")
    • [4.1 初始化流程](#4.1 初始化流程 "#41-%E5%88%9D%E5%A7%8B%E5%8C%96%E6%B5%81%E7%A8%8B")
    • [4.2 工具发现](#4.2 工具发现 "#42-%E5%B7%A5%E5%85%B7%E5%8F%91%E7%8E%B0")
    • [4.3 工具调用](#4.3 工具调用 "#43-%E5%B7%A5%E5%85%B7%E8%B0%83%E7%94%A8")
  • [5. 实际应用场景](#5. 实际应用场景 "#5-%E5%AE%9E%E9%99%85%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF")
    • [5.1 开发效率工具](#5.1 开发效率工具 "#51-%E5%BC%80%E5%8F%91%E6%95%88%E7%8E%87%E5%B7%A5%E5%85%B7")
    • [5.2 系统集成场景](#5.2 系统集成场景 "#52-%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E5%9C%BA%E6%99%AF")
    • [5.3 具体应用示例](#5.3 具体应用示例 "#53-%E5%85%B7%E4%BD%93%E5%BA%94%E7%94%A8%E7%A4%BA%E4%BE%8B")
  • [6. MCP开发指南](#6. MCP开发指南 "#6-mcp%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97")
    • [6.1 创建MCP Server](#6.1 创建MCP Server "#61-%E5%88%9B%E5%BB%BAmcp-server")
    • [6.2 配置Claude使用MCP](#6.2 配置Claude使用MCP "#62-%E9%85%8D%E7%BD%AEclaude%E4%BD%BF%E7%94%A8mcp")
    • [6.3 开发最佳实践](#6.3 开发最佳实践 "#63-%E5%BC%80%E5%8F%91%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5")
  • [7. MCP项目生态](#7. MCP项目生态 "#7-mcp%E9%A1%B9%E7%9B%AE%E7%94%9F%E6%80%81")
    • [7.1 官方项目](#7.1 官方项目 "#71-%E5%AE%98%E6%96%B9%E9%A1%B9%E7%9B%AE")
    • [7.2 社区项目](#7.2 社区项目 "#72-%E7%A4%BE%E5%8C%BA%E9%A1%B9%E7%9B%AE")
    • [7.3 开发资源](#7.3 开发资源 "#73-%E5%BC%80%E5%8F%91%E8%B5%84%E6%BA%90")
  • [8. 总结](#8. 总结 "#8-%E6%80%BB%E7%BB%93")

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)协议,补充了进程功能的不足。

基本格式

请求格式

json 复制代码
{
  "jsonrpc": "2.0",
  "method": "sum",
  "params": [1, 2, 4],
  "id": "1"
}

响应格式

json 复制代码
{
  "jsonrpc": "2.0",
  "result": 7,
  "id": "1"
}

实现示例

js 复制代码
// 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提供了高效的本地进程间通信方式

代码示例

输出示例

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

服务端示例

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

客户端示例

js 复制代码
// 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 基本架构

arduino 复制代码
┌─────────────────┐       ┌─────────────────┐
│                 │       │                 │
│   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 初始化流程

客户端发起初始化请求

json 复制代码
{
  "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"
    }
  }
}

服务端响应初始化

json 复制代码
{
  "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 工具发现

客户端请求工具列表

json 复制代码
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list"
}

服务端响应工具列表

json 复制代码
{
  "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 工具调用

客户端调用工具

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

服务端响应工具执行结果

json 复制代码
{
  "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

项目结构

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

基础Server实现

js 复制代码
// 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

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

6.3 开发最佳实践

错误处理

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

参数验证

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

日志记录

js 复制代码
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集成

安装示例

bash 复制代码
# 安装文件系统服务器
npm install -g @modelcontextprotocol/server-filesystem

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

7.3 开发资源

文档和工具

调试工具

bash 复制代码
# 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的本地通信优化
相关推荐
Sokach3865 分钟前
vue3引入tailwindcss 4.1
前端·css
云水边16 分钟前
vue模版中.gitignore和.prettierrc功能区分
前端
尝尝你的优乐美18 分钟前
封装那些Vue3.0中好用的指令
前端·javascript·vue.js
敲代码的彭于晏21 分钟前
localStorage 不够用?试试 IndexedDB !
前端·javascript·浏览器
chxii24 分钟前
5.4 4pnpm 使用介绍
前端·javascript·vue.js
好好好明天会更好32 分钟前
Vue 中 slot 的常用场景有哪些
前端·vue.js
奔赴_向往1 小时前
【qiankun 踩坑】路由切换回来,子应用 Vuex Store 数据居然还在
前端
sorryhc1 小时前
【AI解读源码系列】ant design mobile——Image图片
前端·javascript·react.js
老猴_stephanie1 小时前
Sentry On-Premise 21.7 问题排查与处理总结
前端
sorryhc1 小时前
【AI解读源码系列】ant design mobile——Button按钮
前端·javascript·react.js