MCP 协议详解:从概念到实战

1. 什么是 MCP

MCP(Model Context Protocol,模型上下文协议)是一种开放协议,用于标准化 AI 模型与外部数据源、工具之间的交互方式。它由 Anthropic 于 2024 年底提出并开源,旨在解决 AI 应用开发中「每个模型对接每个数据源都需要单独定制」的碎片化问题。

可以把 MCP 理解为 AI 世界的「USB-C 接口」:过去,不同的外设需要不同的接口和驱动;现在,只要设备支持统一标准,插上就能用。MCP 让 AI 应用与数据源、工具之间通过统一协议连接,一次接入、处处可用。

2. 为什么需要 MCP

在 MCP 出现之前,AI 应用接入外部能力通常面临以下痛点:

  • 集成成本高:每个数据源(数据库、文件系统、第三方 API)都需要单独编写适配代码。
  • 重复造轮子:不同项目之间难以复用已有的集成逻辑。
  • 安全边界模糊:模型直接接触原始数据,权限控制难以统一管理。
  • 生态割裂:各家模型厂商的插件体系互不兼容。

MCP 通过「客户端---服务器」架构将这些问题标准化,让开发者只需实现一次协议,即可对接任意支持 MCP 的 AI 应用。

3. MCP 的核心架构

MCP 采用经典的客户端---服务器架构,包含三个核心角色:

  • MCP Host:运行 AI 模型的宿主程序,如 Claude Desktop、IDE 插件等。它负责发起请求并消费工具返回的结果。
  • MCP Client:在 Host 内部与 MCP Server 建立一对一连接的组件。
  • MCP Server:暴露数据源或工具能力的服务端程序,通过标准协议向 Client 提供能力。

三者关系如下图所示:
#mermaid-svg-yrRxq7dZAsJ11Awl{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-yrRxq7dZAsJ11Awl .error-icon{fill:#552222;}#mermaid-svg-yrRxq7dZAsJ11Awl .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-yrRxq7dZAsJ11Awl .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-yrRxq7dZAsJ11Awl .marker{fill:#333333;stroke:#333333;}#mermaid-svg-yrRxq7dZAsJ11Awl .marker.cross{stroke:#333333;}#mermaid-svg-yrRxq7dZAsJ11Awl svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-yrRxq7dZAsJ11Awl p{margin:0;}#mermaid-svg-yrRxq7dZAsJ11Awl .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster-label text{fill:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster-label span{color:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster-label span p{background-color:transparent;}#mermaid-svg-yrRxq7dZAsJ11Awl .label text,#mermaid-svg-yrRxq7dZAsJ11Awl span{fill:#333;color:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl .node rect,#mermaid-svg-yrRxq7dZAsJ11Awl .node circle,#mermaid-svg-yrRxq7dZAsJ11Awl .node ellipse,#mermaid-svg-yrRxq7dZAsJ11Awl .node polygon,#mermaid-svg-yrRxq7dZAsJ11Awl .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-yrRxq7dZAsJ11Awl .rough-node .label text,#mermaid-svg-yrRxq7dZAsJ11Awl .node .label text,#mermaid-svg-yrRxq7dZAsJ11Awl .image-shape .label,#mermaid-svg-yrRxq7dZAsJ11Awl .icon-shape .label{text-anchor:middle;}#mermaid-svg-yrRxq7dZAsJ11Awl .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-yrRxq7dZAsJ11Awl .rough-node .label,#mermaid-svg-yrRxq7dZAsJ11Awl .node .label,#mermaid-svg-yrRxq7dZAsJ11Awl .image-shape .label,#mermaid-svg-yrRxq7dZAsJ11Awl .icon-shape .label{text-align:center;}#mermaid-svg-yrRxq7dZAsJ11Awl .node.clickable{cursor:pointer;}#mermaid-svg-yrRxq7dZAsJ11Awl .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-yrRxq7dZAsJ11Awl .arrowheadPath{fill:#333333;}#mermaid-svg-yrRxq7dZAsJ11Awl .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-yrRxq7dZAsJ11Awl .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-yrRxq7dZAsJ11Awl .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-yrRxq7dZAsJ11Awl .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-yrRxq7dZAsJ11Awl .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-yrRxq7dZAsJ11Awl .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster text{fill:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl .cluster span{color:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-yrRxq7dZAsJ11Awl .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-yrRxq7dZAsJ11Awl rect.text{fill:none;stroke-width:0;}#mermaid-svg-yrRxq7dZAsJ11Awl .icon-shape,#mermaid-svg-yrRxq7dZAsJ11Awl .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-yrRxq7dZAsJ11Awl .icon-shape p,#mermaid-svg-yrRxq7dZAsJ11Awl .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-yrRxq7dZAsJ11Awl .icon-shape .label rect,#mermaid-svg-yrRxq7dZAsJ11Awl .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-yrRxq7dZAsJ11Awl .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-yrRxq7dZAsJ11Awl .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-yrRxq7dZAsJ11Awl :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} MCP Host(AI 应用)
JSON-RPC 2.0
AI 模型
MCP Client
MCP Server
本地数据源
远程 API
数据库

MCP 的通信基于 JSON-RPC 2.0 协议,支持两种传输方式:

  • stdio:通过标准输入输出进行本地进程间通信,适合本地开发。
  • HTTP/SSE:通过 HTTP 或 Server-Sent Events 进行远程通信,适合分布式部署。

4. MCP 的核心概念

4.1 工具(Tools)

工具是 MCP Server 暴露给模型的可调用能力,例如查询天气、读写文件、调用搜索 API 等。每个工具包含名称、描述和参数 Schema,模型根据描述决定何时调用。

4.2 资源(Resources)

资源是 Server 提供给模型读取的数据,例如文档内容、数据库查询结果。资源可以是静态的,也可以是动态生成的。

4.3 提示词(Prompts)

提示词是 Server 预定义的可复用提示模板,帮助模型以特定方式处理任务。例如,一个「代码审查」提示词可以规范模型审查代码的步骤和输出格式。

4.4 采样(Sampling)

采样允许 Server 反向请求模型生成内容,实现 Server 与模型的双向交互。这在需要 Server 主动调用模型能力的场景中非常有用。

5. MCP 的工作流程

一次典型的 MCP 交互流程如下:

  1. 初始化:Client 与 Server 建立连接,交换协议版本和能力信息。
  2. 能力发现:Client 获取 Server 暴露的工具、资源和提示词列表。
  3. 模型决策:AI 模型根据用户请求和工具描述,决定是否调用某个工具。
  4. 工具调用:Client 向 Server 发送工具调用请求,携带参数。
  5. 结果返回:Server 执行工具并返回结果,Client 将结果交给模型继续处理。

MCP Server MCP Client AI 模型 用户 MCP Server MCP Client AI 模型 用户 #mermaid-svg-G5rPtnDaBH2TVXcx{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-G5rPtnDaBH2TVXcx .error-icon{fill:#552222;}#mermaid-svg-G5rPtnDaBH2TVXcx .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-G5rPtnDaBH2TVXcx .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-G5rPtnDaBH2TVXcx .marker{fill:#333333;stroke:#333333;}#mermaid-svg-G5rPtnDaBH2TVXcx .marker.cross{stroke:#333333;}#mermaid-svg-G5rPtnDaBH2TVXcx svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-G5rPtnDaBH2TVXcx p{margin:0;}#mermaid-svg-G5rPtnDaBH2TVXcx .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-G5rPtnDaBH2TVXcx text.actor>tspan{fill:black;stroke:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .actor-line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-G5rPtnDaBH2TVXcx .innerArc{stroke-width:1.5;stroke-dasharray:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-G5rPtnDaBH2TVXcx .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-G5rPtnDaBH2TVXcx #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-G5rPtnDaBH2TVXcx .sequenceNumber{fill:white;}#mermaid-svg-G5rPtnDaBH2TVXcx #sequencenumber{fill:#333;}#mermaid-svg-G5rPtnDaBH2TVXcx #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-G5rPtnDaBH2TVXcx .messageText{fill:#333;stroke:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-G5rPtnDaBH2TVXcx .labelText,#mermaid-svg-G5rPtnDaBH2TVXcx .labelText>tspan{fill:black;stroke:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .loopText,#mermaid-svg-G5rPtnDaBH2TVXcx .loopText>tspan{fill:black;stroke:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-G5rPtnDaBH2TVXcx .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-G5rPtnDaBH2TVXcx .noteText,#mermaid-svg-G5rPtnDaBH2TVXcx .noteText>tspan{fill:black;stroke:none;}#mermaid-svg-G5rPtnDaBH2TVXcx .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-G5rPtnDaBH2TVXcx .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-G5rPtnDaBH2TVXcx .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-G5rPtnDaBH2TVXcx .actorPopupMenu{position:absolute;}#mermaid-svg-G5rPtnDaBH2TVXcx .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-G5rPtnDaBH2TVXcx .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-G5rPtnDaBH2TVXcx .actor-man circle,#mermaid-svg-G5rPtnDaBH2TVXcx line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-G5rPtnDaBH2TVXcx :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 提问 需要调用工具 初始化连接 返回工具列表 调用工具(携带参数) 返回执行结果 传递结果 生成最终回答

6. 快速上手:构建第一个 MCP Server

下面以 Python 为例,演示如何构建一个最简单的 MCP Server。首先安装官方 SDK:

bash 复制代码
pip install mcp

创建一个简单的天气查询工具:

python 复制代码
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent

app = Server("weather-server")

@app.list_tools()
async def list_tools():
    return [
        Tool(
            name="get_weather",
            description="查询指定城市的天气",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称"}
                },
                "required": ["city"]
            }
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "get_weather":
        city = arguments["city"]
        # 这里替换为真实的天气 API 调用
        return [TextContent(type="text", text=f"{city} 今天晴,25°C")]
    raise ValueError(f"未知工具: {name}")

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await app.run(read_stream, write_stream)

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

运行上述代码后,一个基于 stdio 传输的 MCP Server 就启动了。接下来在任意支持 MCP 的客户端(如 Claude Desktop)中配置该 Server 的启动命令,即可让模型调用 get_weather 工具。

7. MCP 的典型应用场景

  • 代码助手:让模型直接读写本地文件、执行命令、调用构建工具。
  • 数据分析:模型通过 MCP 连接数据库,执行查询并分析结果。
  • 自动化办公:模型调用邮件、日历、文档等办公工具完成自动化流程。
  • 智能客服:模型通过 MCP 查询订单、库存等业务数据,提供精准回答。
  • 个人知识库:模型通过 MCP 检索本地笔记、文档,实现个人 RAG。

8. 生态与现状

MCP 发布后迅速获得广泛支持:

  • Anthropic:Claude Desktop 原生支持 MCP。
  • OpenAI:已宣布在 Agents SDK 中支持 MCP。
  • Google:Gemini 相关工具链逐步接入 MCP。
  • 社区生态:官方仓库已收录数百个社区贡献的 MCP Server,覆盖数据库、浏览器、设计工具、云服务等。

MCP 正在成为 AI 应用连接外部世界的通用标准,其「一次实现、处处复用」的理念正在重塑 AI 工具链的开发方式。

9. 总结

MCP 通过标准化的客户端---服务器架构,解决了 AI 应用接入外部数据源和工具时的碎片化问题。它定义了工具、资源、提示词、采样四大核心概念,基于 JSON-RPC 2.0 通信,支持本地和远程两种部署方式。

对于开发者而言,掌握 MCP 意味着可以用一套标准接口,让 AI 模型接入任意外部能力。随着各大厂商的陆续支持,MCP 有望成为 AI 时代的基础设施协议。

相关推荐
xrlfreedom7 小时前
大厂 MCP 面试实录:本地 stdio MCP Server 远程化改造方案
tools·mcp·stdio 传输
deepseek231 天前
从 MCP 工具定义自动生成 Agent 评测集:把可靠性验证接入 CI
持续集成·ai agent·mcp·llm 评测
Blockbuater_drug1 天前
MCP Server 接入实战: 9种平台配置差异与凭证安全
claude·cursor·mcp·openclaw·hermes agent·dsh·agent 配置
Geek-Chow1 天前
MCP 模型上下文协议:八、深入传输层 · stdio 与 Streamable HTTP
人工智能·mcp
asaotomo2 天前
从抓包插件到浏览器安全 Agent:Hx0 鹰眼 v1.0.6,正式接入 MCP
安全·渗透测试·agent·浏览器插件·ai工具·mcp
guwentian2 天前
手撕 MCP:用 TypeScript 从零写一个能跑的最小客户端(附可运行 demo)
开发语言·nodejs·mcp
deepseek232 天前
Anthropic开源Commerce Agents:购物与商户智能体如何把审批写进工具链
人工智能·ai agent·mcp
xrlfreedom2 天前
大厂 MCP 面试实录:基于 Streamable HTTP 的 OAuth 2.1 服务集成测试设计
resources·mcp·oauth 2.1·streamable http 传输
zfelix3 天前
别在 MCP、Skills、Subagent 里挑一个——它们根本不是同一层的东西
mcp