上一篇【第05篇】Context Engineering——让AI真正理解你的项目
下一篇【第07篇】Cursor完全上手指南——地表最强AI IDE的正确打开方式


摘要

2024年11月,Anthropic发布了MCP(Model Context Protocol),一个允许AI安全、标准化地连接外部数据源和工具的开源协议。短短一年多,MCP已成为AI编程的事实基础设施——500+官方和社区MCP Server覆盖了文件系统、数据库、GitHub、Slack、飞书等几乎所有的开发工具体系。

本文深入MCP的技术架构:Client-Server模型的设计哲学、Tool/Resource/Prompt三大原语的使用场景、JSON-RPC通信机制的细节,以及手把手教你搭建一个自定义MCP Server。如果你想知道"AI是怎么操控外部工具的",这篇就是答案。


一、MCP的诞生——为什么需要这个协议?

1.1 MCP之前的"巴别塔困境"

在MCP出现之前,每个AI应用要对接外部工具都需要单独开发集成:

【MCP之前的碎片化困境】

         ┌─────┐
         │ AI  │
         └──┬──┘
            │
   ┌────────┼────────┬─────────┬─────────┐
   │        │        │         │         │
┌──┴──┐ ┌──┴──┐ ┌──┴──┐ ┌───┴──┐ ┌───┴──┐
│GitHub│ │文件 │ │数据库│ │Slack │ │Jira  │
│ API  │ │系统 │ │驱动  │ │ API  │ │ API  │
└─────┘ └────┘ └────┘ └─────┘ └─────┘

问题:
1. 每个AI应用都要为每个工具写一套集成代码
2. 没有标准的安全模型(每个工具自己处理权限)
3. 工具开发者不知道为谁开发(Cursor? Claude? Windsurf?)
4. 用户在工具间切换时不能复用已有配置

结果:工具越用越多,集成越来越碎片化。

1.2 MCP的设计目标

Anthropic提出MCP的核心理念很简单:AI应用和工具之间需要一个标准协议,就像USB-C让各种外设都能即插即用

【MCP的设计哲学】

USB-C的类比:                    MCP的对应:

设备(手机/电脑)    →   AI应用(Cursor、Claude、Windsurf)
外设(键盘/显示器)   →   工具/数据源(GitHub、数据库、文件系统)
USB-C协议            →   MCP协议
即插即用             →   一次配置,所有AI应用可用
统一标准             →   所有AI工具使用同一套接口

类比的核心:你不必为每个外设买不同的转接头,
          也不必为每个AI工具写不同的集成代码。

二、MCP架构详解——Client-Server模型

2.1 整体架构

【MCP架构全景图】

┌────────────────────────────────────────────────────┐
│                   MCP 生态系统                       │
│                                                     │
│  ┌─────────────┐    ┌─────────────┐                │
│  │   Cursor    │    │Claude Code  │   ← AI应用      │
│  │  (MCP Host) │    │ (MCP Host)  │     (客户端)    │
│  └──────┬──────┘    └──────┬──────┘                │
│         │                  │                        │
│         └────────┬─────────┘                        │
│                  │                                  │
│           MCP Protocol                              │
│        (JSON-RPC over stdio/HTTP)                   │
│                  │                                  │
│    ┌─────────────┼─────────────┐                    │
│    │             │             │                    │
│ ┌──┴──┐    ┌────┴────┐   ┌───┴───┐                │
│ │文件  │    │ GitHub  │   │数据库 │  ← MCP Server  │
│ │系统  │    │ Server  │   │Server │    (服务端)    │
│ └─────┘    └─────────┘   └───────┘                │
│                                                     │
└────────────────────────────────────────────────────┘

通信方式:
├── stdio(本地进程通信):MCP Server作为子进程运行
└── HTTP/SSE(远程通信):MCP Server作为独立服务运行

2.2 核心角色定义

【MCP核心角色】

MCP Host(主机)
├── 定义:运行AI应用的软件(Cursor、Claude Desktop、Windsurf)
├── 职责:发起连接、管理多个MCP Client、提供UI交互
└── 举例:你打开的Cursor窗口

MCP Client(客户端)
├── 定义:Host内部与一个Server保持1:1连接的组件
├── 职责:发送请求、接收响应、管理会话
└── 举例:Cursor中与GitHub Server通信的连接器

MCP Server(服务端)
├── 定义:暴露特定功能(工具、资源、提示)的服务程序
├── 职责:响应请求、执行操作、返回结果
└── 举例:@anthropic/mcp-server-github

三、MCP三大原语——Tool、Resource、Prompt

MCP定义了三种标准的交互方式,统称为"三大原语":

3.1 Tool(工具)——让AI"做"事情

Tool是最常用的原语,让AI执行有副作用的操作。

【Tool原语的工作方式】

AI应用                          MCP Server
   │                                │
   │ list_tools()                   │
   ├───────────────────────────────>│
   │ ← [                            │
   │   { name: "create_issue",      │
   │     description: "创建GitHub   │
   │       Issue",                  │
   │     parameters: {              │
   │       title: string,           │
   │       body: string,            │
   │       labels: string[]         │
   │     }                          │
   │   },                           │
   │   { name: "search_code", ... } │
   │ ]                              │
   │                                │
   │ call_tool("create_issue", {    │
   │   title: "修复登录Bug",         │
   │   body: "...",                 │
   │   labels: ["bug", "high"]      │
   │ })                             │
   ├───────────────────────────────>│
   │                                │──→ GitHub API
   │ ← {                            │←── Issue created
   │   "url": "https://github.com/  │
   │     org/repo/issues/42"        │
   │ }                              │
【常见Tool示例】

MCP Server           提供的Tool
────────────────────────────────────────────
GitHub               create_issue, create_pr, search_code,
                     list_repos, merge_pr

文件系统              read_file, write_file, list_directory,
                     search_files, get_file_info

数据库               execute_query, list_tables,
                     describe_table, create_migration

Slack/飞书           send_message, list_channels,
                     search_messages, add_reaction

天气                 get_weather, get_forecast,
                     get_alerts

3.2 Resource(资源)——让AI"看"数据

Resource用于暴露只读数据,AI可以像读文件一样读取结构化数据。

【Resource vs Tool的区别】

Tool:执行操作(有副作用)
├── 创建GitHub Issue → 改变了GitHub的状态
├── 发送消息 → 改变了聊天状态
└── 写入文件 → 改变了文件系统状态

Resource:读取数据(无副作用)
├── 读取GitHub仓库的文件树
├── 读取数据库Schema
└── 读取配置文件内容

Resource类型:
├── 文本资源:text/plain, application/json
├── 二进制资源:image/png, application/pdf
└── 动态资源:SQL查询结果、API响应

3.3 Prompt(提示模板)——预定义的交互模式

Prompt让MCP Server可以定义标准化的提示模板,帮助用户更高效地与AI交互。

【Prompt原语示例】

MCP Server定义的Prompt模板:

{
  "name": "code_review",
  "description": "代码审查模板",
  "arguments": [
    { "name": "language", "description": "编程语言", "required": true },
    { "name": "focus", "description": "审查重点" }
  ]
}

使用时:
用户选择 "code_review" 模板 → 填入参数
→ 自动生成结构化的审查提示:
  "请审查以下 {language} 代码,重点关注 {focus}:
   1. 安全性
   2. 性能
   3. 代码风格
   4. 边界情况处理
   [待审查代码]"

四、MCP的通信流程——一次完整的交互拆解

4.1 连接与初始化

【MCP连接生命周期】

阶段1:握手(Handshake)
┌──────────────────────────────────────────┐
│ Client → Server: initialize              │
│ {                                        │
│   "protocolVersion": "2024-11-05",       │
│   "capabilities": {                      │
│     "roots": {...},                      │
│     "sampling": {}                       │
│   },                                     │
│   "clientInfo": {                        │
│     "name": "Cursor",                    │
│     "version": "0.45.0"                  │
│   }                                      │
│ }                                        │
│                                          │
│ Server → Client:                         │
│ {                                        │
│   "protocolVersion": "2024-11-05",       │
│   "capabilities": {                      │
│     "tools": {...},   ← 支持Tool原语     │
│     "resources": {...} ← 支持Resource    │
│   },                                     │
│   "serverInfo": {                        │
│     "name": "GitHub MCP Server",         │
│     "version": "1.2.0"                   │
│   }                                      │
│ }                                        │
└──────────────────────────────────────────┘

阶段2:能力发现(Discovery)
┌──────────────────────────────────────────┐
│ Client → Server: tools/list              │
│ Server → Client:                         │
│ [                                        │
│   {                                      │
│     "name": "create_issue",              │
│     "description": "创建GitHub Issue",    │
│     "inputSchema": {                     │
│       "type": "object",                  │
│       "properties": {                    │
│         "title": {"type": "string"},     │
│         "body": {"type": "string"}       │
│       },                                 │
│       "required": ["title"]              │
│     }                                    │
│   },                                     │
│   ...                                    │
│ ]                                        │
└──────────────────────────────────────────┘

4.2 工具调用详细流程

【一次完整的Tool调用】

用户:"在GitHub上创建一个Issue,标题是'用户登录超时'"

    ↓ Cursor解析用户意图

第1步:AI决定调用哪个Tool
┌──────────────────────────────────────┐
│ AI推理:"用户想创建GitHub Issue,    │
│  应该调用 GitHub MCP Server 的        │
│  create_issue 工具"                   │
└──────────────────────────────────────┘

第2步:构造Tool调用参数
┌──────────────────────────────────────┐
│ {                                    │
│   "name": "create_issue",            │
│   "arguments": {                     │
│     "title": "用户登录超时",           │
│     "body": "## 问题描述\n...",       │
│     "labels": ["bug"],               │
│     "repo": "org/project"            │
│   }                                  │
│ }                                    │
└──────────────────────────────────────┘

第3步:发送JSON-RPC请求
┌──────────────────────────────────────┐
│ {                                    │
│   "jsonrpc": "2.0",                  │
│   "method": "tools/call",            │
│   "params": {                        │
│     "name": "create_issue",          │
│     "arguments": {...}               │
│   },                                 │
│   "id": 1                            │
│ }                                    │
└──────────────────────────────────────┘

第4步:MCP Server执行并返回
┌──────────────────────────────────────┐
│ {                                    │
│   "jsonrpc": "2.0",                  │
│   "result": {                        │
│     "content": [{                    │
│       "type": "text",                │
│       "text": "Issue #42 created:    │
│         https://github.com/org/      │
│         repo/issues/42"              │
│     }]                               │
│   },                                 │
│   "id": 1                            │
│ }                                    │
└──────────────────────────────────────┘

第5步:AI将结果展示给用户
"✅ 已创建 Issue #42:用户登录超时
链接:https://github.com/org/repo/issues/42"

五、搭建一个自定义MCP Server

5.1 最小可运行示例

以下是一个最简单的MCP Server,提供一个"获取当前时间"的工具:

# weather-server.py
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
import mcp.server.stdio
import mcp.types as types
from datetime import datetime, timezone

# 创建Server实例
server = Server("my-first-mcp-server")

@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
    """返回Server提供的工具列表"""
    return [
        types.Tool(
            name="get_current_time",
            description="获取当前的UTC时间",
            inputSchema={
                "type": "object",
                "properties": {},
            },
        )
    ]

@server.call_tool()
async def handle_call_tool(
    name: str, 
    arguments: dict
) -> list[types.TextContent]:
    """处理工具调用"""
    if name == "get_current_time":
        now = datetime.now(timezone.utc)
        return [
            types.TextContent(
                type="text",
                text=f"当前UTC时间:{now.isoformat()}"
            )
        ]
    else:
        raise ValueError(f"未知工具: {name}")

async def run():
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationCapabilities(
                sampling={},
                roots={}
            ),
        )

if __name__ == "__main__":
    import asyncio
    asyncio.run(run())

5.2 配置到Cursor

// 在 .cursor/mcp.json 中添加
{
  "mcpServers": {
    "my-tools": {
      "command": "python",
      "args": ["path/to/weather-server.py"]
    }
  }
}

配置完成后,在Cursor中就可以直接对AI说"告诉我现在几点了",AI会自动调用你的MCP Server获取时间。


六、MCP生态现状与未来

6.1 2026年的MCP生态版图

【MCP生态全景(2026年中)】

官方Server(Anthropic提供):
├── @anthropic/mcp-server-github
├── @anthropic/mcp-server-filesystem
├── @anthropic/mcp-server-postgres
├── @anthropic/mcp-server-slack
└── @anthropic/mcp-server-puppeteer

社区热门Server(部分列举):
├── 飞书/钉钉/企业微信(即时通讯)
├── 腾讯文档/Notion/语雀(文档协作)
├── MySQL/Redis/MongoDB(数据库)
├── AWS/GCP/Azure(云服务)
├── Jira/Linear(项目管理)
├── Playwright(浏览器自动化)
└── Docker/Kubernetes(容器编排)

数据统计(截至2026年6月):
├── MCP Server总数:800+
├── 支持MCP的主流AI工具:Cursor, Claude, Windsurf, Copilot, Continue
├── GitHub MCP仓库Star数:80K+
├── 日均MCP工具调用量:数百万级

6.2 MCP的未来方向

【MCP的演进方向】

短期(2026 H2):
├── MCP 2.0 正式发布
├── 更好的安全模型(OAuth 2.0原生支持)
├── Server热加载(无需重启)
├── 更丰富的原语(Streaming、Filesystem代理)

中期(2027):
├── MCP Server市场/应用商店
├── Server托管服务(云上运行,无需本地部署)
├── 多Agent协作的MCP协调协议
└── MCP成为W3C标准

长期愿景:
"每个软件都提供一个MCP接口,
 AI可以像调用函数一样调用任何软件的能力。"

总结

  1. MCP是AI编程的标准化协议:它定义了AI应用如何发现和调用外部工具、资源和提示模板,解决了碎片化集成的问题。
  2. Client-Server架构清晰:AI应用作为Host和Client,外部能力作为Server,通过JSON-RPC协议通信,支持stdio和HTTP两种传输方式。
  3. 三大原语覆盖所有场景:Tool用于执行操作(有副作用),Resource用于读取数据(无副作用),Prompt用于标准化交互模板。
  4. 自定义MCP Server门槛很低:几十行Python代码就能创建一个功能完整的MCP Server,并配置到Cursor/Claude中使用。
  5. MCP生态正在快速膨胀:800+ Server覆盖了几乎所有开发工具和设备,正朝着"每个软件都有MCP接口"的愿景演进。

上一篇【第05篇】Context Engineering——让AI真正理解你的项目
下一篇【第07篇】Cursor完全上手指南——地表最强AI IDE的正确打开方式


Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐