AI模型通信协议

MCP是一个开放标准协议,用于实现AI模型与外部工具、数据源和服务之间的实时通信,提供标准化的上下文访问和外部操作能力。

  • by rdntech14
  • 本地部署
  • 更新于
在 GitHub 查看 rdntech14/mcp

使用说明

模型上下文协议(MCP)

🌟 Introduction

模型上下文协议(MCP)是一种 开放标准 这使得人工智能模型(智能层)与外部工具、数据源和服务之间能够进行无缝、实时的通信。它为AI应用程序提供了一种标准化的访问方式 实时上下文 并执行 外部行动,使人工智能系统更强大、更先进、更具情境感知能力。


🎯 Understanding the MCP Acronym

快速定义:

  • Mmodel=智能
  • C上下文=信息
  • P协议=标准

在深入了解MCP的工作之前,让我们分解一下每个单词的含义:

模型

在MCP的背景下,a 模型 指的是人工智能模型(如GPT、Claude等大型语言模型或其他机器学习模型)。这些模型是生成响应、做出决策并为应用程序提供价值的智能层。模型基于历史数据进行训练,在没有外部集成的情况下访问实时信息存在局限性。

上下文

上下文 指做出明智决策或生成准确响应所需的相关信息、数据和知识。这包括:

  • 来自数据库和API的实时数据
  • 组织特定信息
  • 用户特定的详细信息和历史记录
  • 外部系统状态和配置

如果没有适当的上下文,人工智能模型可能会提供过时、不准确或通用的响应。MCP使模型能够从多个来源访问丰富的动态上下文。

协议

A. 协议 是用于不同系统之间通信的一组标准化规则和规范。它定义了:

  • 消息的格式
  • 请求和响应的结构
  • 如何处理错误
  • 系统如何建立和维护连接

通过建立标准协议,不同的人工智能工具和外部服务可以无缝通信,而不需要为每种组合定制集成代码。


❓ What is MCP?

MCP是一种协议,允许:

  • AI模型 从外部来源请求信息
  • 外部服务 为人工智能模型提供数据和功能
  • 双向通信 通过标准化接口
  • 可扩展性 通过连接多种工具和服务

它在客户端-服务器架构上运行,具有明确的关注点分离,实现了模块化和可扩展的AI应用程序。


💡 The Problem MCP Solves

传统的人工智能模型有很大的局限性:

  1. 训练数据的稳定性: 人工智能模型基于历史数据进行训练,无法访问实时信息
  2. 有限背景: 模型无法访问特定于组织的数据、数据库和内部系统
  3. 无外部操作: 模型无法触发工作流、发送通知或与外部服务交互
  4. 集成挑战: 每个AI工具都需要与每个外部服务进行自定义集成,从而导致代码冗余
  5. 缺乏标准化: 没有标准协议,集成是不一致的,难以维护

✅ The MCP Solution: Key Benefits

MCP通过提供以下服务来应对这些挑战:

1.实时上下文访问

  • AI模型可以查询实时数据库、API和外部服务
  • 获取最新信息可以做出更好、更准确的回应
  • 示例:人工智能助手可以获取当前股票价格、天气数据或客户信息

2.可扩展性和模块化

  • 可以添加新的工具和服务,而无需修改核心AI模型
  • 多个服务器可以连接到单个客户端
  • 示例:独立添加新的数据库服务器、CRM系统或电子邮件服务

3.标准化整合

  • 一种协议适用于所有集成,而不是定制解决方案
  • 减少开发时间和维护开销
  • 语言无关的通信确保了不同技术栈之间的兼容性

4.人工智能自主性

  • 模型可以执行简单文本生成之外的操作
  • 执行数据库查询、触发自动化、发送通信
  • 示例:人工智能可以安排会议、创建门票或实时更新记录

5.企业准备就绪

  • 内置安全和身份验证挂钩
  • 企业部署的可扩展架构
  • 明确的关注点分离有助于更好的治理和控制

MCP至关重要的现实场景

场景 传统方法 使用MCP
客户支持AI 人工数据录入查看客户历史 AI直接实时查询客户数据库
DevOps自动化 每个工具的硬编码脚本 MCP连接到监控、日志记录和基础设施服务器
数据分析 从各种来源手动导出数据 AI通过MCP服务器查询多个数据源
代码助手 需要不断更新新工具 通过MCP插入IDE、版本控制和构建系统
多工具工作流 每个组合的自定义集成 单个MCP客户端连接到多个专用服务器

🏛️ Core Components

1.MCP主机

这 MCP主机 是运行AI模型或应用程序的机器或环境。它启动通信并协调客户端和服务器之间的交互。

责任:

  • 管理MCP连接的生命周期
  • 在客户端和服务器之间路由请求
  • 处理身份验证和安全
  • 协调资源分配

2.MCP客户端

这 MCP客户端 是MCP架构内服务的消费者。通常,这是一个AI应用程序、IDE插件或任何需要访问外部资源的软件。

责任:

  • 向MCP服务器发送请求
  • 处理响应
  • 处理错误和重试
  • 保持连接状态

3.MCP服务器

这 MCP服务器 是通过MCP协议公开工具、资源或数据的服务提供商。

MCP服务器的类型:

  • 工具服务器: 提供可调用的函数或操作
  • 资源服务器: 公开数据和信息
  • 提示服务器: 提供预先构建的提示或模板
  • 复合服务器: 结合多种功能

责任:

  • 监听传入请求
  • 执行操作或获取数据
  • 以标准格式返回结果
  • 处理连接管理

🏗️ MCP Architecture

MCP核心结构

┌─────────────┐
│   MCP Host  │
│  (contains) │
└──────┬──────┘
       │
       ├─────────────────────────┐
       │                         │
   ┌───▼────┐            ┌──────▼──┐
   │ Client │◄───────────┤ Server  │
   │        │  JSON-RPC  │         │
   │        ├───────────►│         │
   └────────┘            └─────────┘
       ▲                       ▲
       │   Message Exchange    │
       └───────────────────────┘

使用MCP的AI应用程序

┌────────────────────────────────────────────────────────────────┐
│                  MCP Host (AI Application)                     │
│                                                                │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │                    Application Layer                     │  │
│  │  • User Interface                                        │  │
│  │  • Request Routing                                       │  │
│  │  • Response Handling                                     │  │
│  └────────────────┬─────────────────────────────────────────┘  │
│                   │                                            │
│  ┌────────────────▼─────────────────┐  ┌──────────────────┐    │
│  │         MCP Client               │  │   LLM Provider   │    │
│  │                                  │  │  (Claude, GPT,   │    │
│  │  • Connection Management         │◄─┤   Gemini, etc.)  │    │
│  │  • Tool Discovery                │  │                  │    │
│  │  • Request/Response Handling     │  │  • Tool Calling  │    │
│  │  • Protocol Implementation       │  │  • Reasoning     │    │
│  └────────────────┬─────────────────┘  └──────────────────┘    │
│                   │                                            │
└───────────────────┼────────────────────────────────────────────┘
                    │
                    │ MCP Protocol (JSON-RPC 2.0)
                    │ • tools/list
                    │ • tools/call
                    │ • resources/list
                    │ • prompts/list
                    │
┌───────────────────▼────────────────────────────────────────────┐
│                      MCP Server                                │
│                                                                │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │                   Server Implementation                  │  │
│  │  • Tool Definitions                                      │  │
│  │  • Request Handling                                      │  │
│  │  • Business Logic                                        │  │
│  └────────────────┬─────────────────────────────────────────┘  │
│                   │                                            │
│  ┌────────────────▼─────────────────────────────────────────┐  │
│  │                    Data Sources                           │ │
│  │                                                           │ │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐    │ │
│  │  │ Database │  │  Files   │  │   APIs   │  │ Other   │    │ │
│  │  └──────────┘  └──────────┘  └──────────┘  └─────────┘    │ │
│  │                                                           │ │
│  └───────────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────────┘

📊 MCP Sequence Flow

第一阶段:启动和发现

阶段2:查询时间执行

MCP工具定义-格式

原始MCP服务器响应

当MCP客户端请求时 tools/list,服务器以JSON格式响应:

{
  "tools": [
    {
      "name": "read_file",
      "description": "Read the complete contents of a file from the file system. Handles various text encodings and provides detailed error messages if the file cannot be read.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "path": {
            "type": "string",
            "description": "The absolute or relative path to the file to read"
          }
        },
        "required": ["path"]
      }
    },
    {
      "name": "search_database",
      "description": "Search the customer database using natural language queries. Returns matching records with relevance scores.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {
            "type": "string",
            "description": "The search query in natural language"
          },
          "limit": {
            "type": "integer",
            "description": "Maximum number of results to return",
            "default": 10,
            "minimum": 1,
            "maximum": 100
          },
          "filters": {
            "type": "object",
            "description": "Optional filters to narrow results",
            "properties": {
              "status": {
                "type": "string",
                "enum": ["active", "inactive", "pending"]
              },
              "created_after": {
                "type": "string",
                "format": "date"
              }
            }
          }
        },
        "required": ["query"]
      }
    },
    {
      "name": "execute_sql",
      "description": "Execute a SQL query against the connected database. Supports SELECT, INSERT, UPDATE, and DELETE operations with transaction support.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {
            "type": "string",
            "description": "The SQL query to execute"
          },
          "params": {
            "type": "array",
            "description": "Query parameters for prepared statements",
            "items": {
              "type": ["string", "number", "boolean", "null"]
            }
          },
          "timeout": {
            "type": "integer",
            "description": "Query timeout in seconds",
            "default": 30
          }
        },
        "required": ["query"]
      }
    }
  ]
}

如何向LLM展示工具

MCP客户端将工具定义转换为适合LLM系统提示的格式。确切的格式取决于所使用的LLM提供程序。

示例1:拟人克劳德格式
You are an AI assistant with access to tools via the Model Context Protocol.

You can invoke tools by writing a function_calls block like this:
<function_calls>
<invoke>
<tool_name>tool_name_here</tool_name>
<parameters>
<param_name>value</param_name>
</parameters>
</invoke>
</function_calls>

Available tools:

<tools>
<tool>
<name>read_file</name>
<description>
Read the complete contents of a file from the file system. Handles various text 
encodings and provides detailed error messages if the file cannot be read.
</description>
<parameters>
  <parameter>
    <name>path</name>
    <type>string</type>
    <required>true</required>
    <description>The absolute or relative path to the file to read</description>
  </parameter>
</parameters>
</tool>

<tool>
<name>search_database</name>
<description>
Search the customer database using natural language queries. Returns matching 
records with relevance scores.
</description>
<parameters>
  <parameter>
    <name>query</name>
    <type>string</type>
    <required>true</required>
    <description>The search query in natural language</description>
  </parameter>
  <parameter>
    <name>limit</name>
    <type>integer</type>
    <required>false</required>
    <description>Maximum number of results to return (default: 10, min: 1, max: 100)</description>
  </parameter>
  <parameter>
    <name>filters</name>
    <type>object</type>
    <required>false</required>
    <description>Optional filters: status (active|inactive|pending), created_after (date)</description>
  </parameter>
</parameters>
</tool>

<tool>
<name>execute_sql</name>
<description>
Execute a SQL query against the connected database. Supports SELECT, INSERT, 
UPDATE, and DELETE operations with transaction support.
</description>
<parameters>
  <parameter>
    <name>query</name>
    <type>string</type>
    <required>true</required>
    <description>The SQL query to execute</description>
  </parameter>
  <parameter>
    <name>params</name>
    <type>array</type>
    <required>false</required>
    <description>Query parameters for prepared statements</description>
  </parameter>
  <parameter>
    <name>timeout</name>
    <type>integer</type>
    <required>false</required>
    <description>Query timeout in seconds (default: 30)</description>
  </parameter>
</parameters>
</tool>
</tools>
示例2:OpenAI函数调用格式
{
  "model": "gpt-4",
  "messages": [
    {
      "role": "system",
      "content": "You are an AI assistant with access to tools via MCP."
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "Read the complete contents of a file from the file system. Handles various text encodings and provides detailed error messages if the file cannot be read.",
        "parameters": {
          "type": "object",
          "properties": {
            "path": {
              "type": "string",
              "description": "The absolute or relative path to the file to read"
            }
          },
          "required": ["path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "search_database",
        "description": "Search the customer database using natural language queries. Returns matching records with relevance scores.",
        "parameters": {
          "type": "object",
          "properties": {
            "query": {
              "type": "string",
              "description": "The search query in natural language"
            },
            "limit": {
              "type": "integer",
              "description": "Maximum number of results to return",
              "default": 10,
              "minimum": 1,
              "maximum": 100
            },
            "filters": {
              "type": "object",
              "description": "Optional filters to narrow results",
              "properties": {
                "status": {
                  "type": "string",
                  "enum": ["active", "inactive", "pending"]
                },
                "created_after": {
                  "type": "string",
                  "format": "date"
                }
              }
            }
          },
          "required": ["query"]
        }
      }
    }
  ]
}
示例3:简化自然语言格式

一些实现使用更易读的格式:

SYSTEM PROMPT:

You are an AI assistant with access to the following MCP tools:

1. **read_file**
   Purpose: Read the complete contents of a file from the file system
   Parameters:
   - path (required): The absolute or relative path to the file to read
   Example: read_file("/home/user/document.txt")

2. **search_database**
   Purpose: Search the customer database using natural language queries
   Parameters:
   - query (required): The search query in natural language
   - limit (optional): Maximum results to return (1-100, default: 10)
   - filters (optional): Object with status and/or created_after filters
   Example: search_database("customers in California", limit=20)

3. **execute_sql**
   Purpose: Execute SQL queries with transaction support
   Parameters:
   - query (required): The SQL query to execute
   - params (optional): Array of parameters for prepared statements
   - timeout (optional): Query timeout in seconds (default: 30)
   Example: execute_sql("SELECT * FROM users WHERE id = ?", params=[123])

When you need to use a tool, clearly indicate which tool and what parameters.

📡 MCP Protocols

MCP支持多种传输协议以实现灵活性:

1. 标准输入/输出

  • 使用工艺管道进行通信
  • 非常适合本地单机部署
  • 低开销
  • 无网络延迟
  • 直接流程间沟通

用例: 本地AI应用程序与同一台机器上的MCP服务器通信

2. 超文本传输协议

  • HTTP/HTTPS上的传统请求-响应模型
  • 无状态通信
  • 更易于调试和监控
  • 更适合网络上的分布式系统
  • 标准端口80(HTTP)或443(HTTPS)

用例: 基于云的部署,可通过互联网访问的远程MCP服务器

3. SSE(服务器发送事件)

  • 服务器向客户端发送连续的数据流
  • 基于HTTP构建
  • 单向通信(服务器→ 客户)
  • 用于实时通知和更新
  • 持久HTTP连接

用例: 来自MCP服务器的流式响应和实时更新

协议选择指南

协议 最佳用途 限制
标准 本地开发,单机 不适合网络通信
超文本传输协议 基于互联网的远程服务器 无状态,每次请求的开销更高
上海证券交易所 实时流媒体更新 仅单向通信
📊 Click to expand: Detailed Protocol Comparison Table

协议对照表

功能 SSE HTTP stdio
单向流媒体 ✅ 本地 ❌ 不理想 ✅ 是的
实时更新 ✅ 是 ⚠️ 需要投票 ✅ 是的
设置复杂性 ✅ 简单 ✅ 简单 ✅ 简单
网络使用 ✅ 高效 ❌ 更高的开销 ✅ 效率很高
浏览器支持 ✅ 现代浏览器 ✅ 所有浏览器 不适用
在MCP中使用 ✅ 最适合流媒体播放 ✅ 请求响应 ✅ 对于本地

🔄 HTTP (Polling) vs. SSE (Pushing)

HTTP架构(请求-响应)

Application Layer (MCP Host):
┌─────────────────────────────────────────────┐
│         MCP Host (Your AI Application)      │
├─────────────────────────────────────────────┤
│                                             │
│  ┌────────────────────────────────────┐    │
│  │      MCP Client Component          │    │
│  │  (Established by your app)         │    │
│  │  - Sends request to MCP Server     │    │
│  │  - Waits for response              │    │
│  │  - Processes data                  │    │
│  │  - Polls repeatedly                │    │
│  └────────────────────────────────────┘    │
│                     │                       │
│      Request 1      │ Request 2      Request 3
│      (Poll every    │ (Poll every    (Poll every
│       2 seconds)    │  2 seconds)     2 seconds)
│        ▼            │   ▼              ▼
└─────────────────────┼──────────────────────┘
                      │
          ┌──────────────────────────┐
          │   MCP Server             │
          │  (Stock Feed Service)    │
          │  - Waits for requests    │
          │  - Returns current data  │
          │  - Closes connection     │
          └──────────────────────────┘

📈 Click to expand: HTTP Communication Flow Example

HTTP通信流

Time 0s:
┌──────────────┐                           ┌─────────────┐
│  MCP Client  │                           │ MCP Server  │
│  (AI App)    │                           │ (Stock Feed)│
└──────┬───────┘                           └──────▲──────┘
       │                                          │
       │ 1. CLIENT INITIATES REQUEST              │
       ├─────────────────────────────────────────►│
       │ GET /mcp/stock-prices                    │
       │                                          │
       │ 2. SERVER RESPONDS                       │
       │◄─────────────────────────────────────────┤
       │ 200 OK                                   │
       │ {"stocks": AAPL=$150.25, GOOGL=$140}    │
       │                                          │
       │ 3. CONNECTION CLOSES                     │
       │ (Client has current data only)           │
       │
       ├─► AI Model receives context             │
       │   (Analyzes stock data)                  │
       │

... 2 seconds pass ...

Time 2s: Client asks again (Polling)
       │ 4. CLIENT INITIATES NEW REQUEST          │
       ├─────────────────────────────────────────►│
       │ GET /mcp/stock-prices                    │
       │ (Client must ask repeatedly)             │
       │                                          │
       │ 5. SERVER RESPONDS                       │
       │◄─────────────────────────────────────────┤
       │ 200 OK                                   │
       │ {"stocks": AAPL=$150.50, GOOGL=$139.80} │
       │                                          │
       │ 6. CONNECTION CLOSES                     │
       │
       ├─► AI Model receives context             │
       │   (Analyzes updated data)                │
       │

... 2 seconds pass ...

Time 4s: Client asks again (Polling continues)
       │ 7. CLIENT INITIATES ANOTHER REQUEST      │
       ├─────────────────────────────────────────►│
       │ GET /mcp/stock-prices                    │
       │                                          │
       │ 8. SERVER RESPONDS                       │
       │◄─────────────────────────────────────────┤
       │ 200 OK                                   │
       │ {"stocks": AAPL=$151.00, GOOGL=$139.50} │
       │                                          │
       │ 9. CONNECTION CLOSES                     │

[This polling pattern repeats every 2 seconds]
[Multiple connections opened and closed]

要点:

  • ❌ 已建立和关闭多个连接
  • ❌ 客户端通过发出请求来提取数据
  • ✅ 客户端控制轮询间隔
  • ⚠️ 民意调查之间缺少更新的风险
  • ⚠️ 如果数据没有改变,则请求被浪费

HTTP理解(请求-响应)

特性 详细信息
连接模型 每个请求的新连接
数据流 客户端通过请求获取数据
客户端行为 请求数据,然后等待
数据更改时 客户在下次投票前不知道
轮询 必填(客户反复询问)
实时 伪实时(取决于轮询间隔)
延迟 较高(等待轮询间隔)
网络效率 效率较低(许多连接)
最适合 偶尔的查询,简单的请求
示例用例 天气查询、一次性查找

工作原理:

1. Client: "Give me current stock prices"
2. Client sends request to Server
3. Server responds with data
4. Connection closes
5. Client waits (2 seconds)
6. Client: "Give me current stock prices" (again)
7. Server responds with (possibly) updated data
8. Connection closes
9. (Repeat steps 5-8)

SSE架构和通信流程

服务器发送事件(SSE)是一种允许服务器通过单个持久HTTP连接向客户端推送实时更新的技术。与客户端始终请求数据的传统HTTP不同,SSE允许服务器在发生任何事情时向客户端发送数据。

SSE消息格式

SSE消息遵循简单的文本格式:

data: message content
id: unique-message-id
event: event-type

关键字段:

  • data:实际消息/有效载荷
  • id:消息的可选唯一标识符
  • event:可选事件类型名称

MCP的真实SSE示例

脚本: 客户希望从MCP服务器获取实时股票价格

客户端连接:

GET /mcp/stock-prices HTTP/1.1
Host: server.example.com
Accept: text/event-stream

服务器发送:

event: stock_update
data: {"symbol":"AAPL","price":150.25,"change":"+2.50"}
id: stock-001

event: stock_update
data: {"symbol":"GOOGL","price":140.50,"change":"-1.25"}
id: stock-002

event: stock_update
data: {"symbol":"MSFT","price":380.75,"change":"+3.00"}
id: stock-003

客户收到更新(随着价格的变化而不断更新):

Stock prices updated:
- AAPL: $150.25 ↑
- GOOGL: $140.50 ↓
- MSFT: $380.75 ↑

此示例演示了:

  • ✅ 客户端建立一个持久的SSE连接
  • ✅ 每当股价发生变化时,服务器都会推送更新
  • ✅ 无需客户端进行轮询
  • ✅ 实时数据流
  • ✅ 连接无限期保持打开状态

SSE架构(持久连接)

Application Layer (MCP Host):
┌─────────────────────────────────────────────┐
│         MCP Host (Your AI Application)      │
├─────────────────────────────────────────────┤
│                                             │
│  ┌────────────────────────────────────┐    │
│  │      MCP Client Component          │    │
│  │  (Established by your app)         │    │
│  │  - Connects to Stock MCP Server    │    │
│  │  - Receives price updates          │    │
│  │  - Passes context to AI Model      │    │
│  └────────────────────────────────────┘    │
│                     │                       │
│                     │ Uses SSE Connection   │
│                     │ (Persistent)          │
│                     │                       │
└─────────────────────┼───────────────────────┘
                      │
                      │ HTTP + SSE
                      │ GET /stock-prices
                      │ Accept: text/event-stream
                      ▼
          ┌──────────────────────────┐
          │   MCP Server             │
          │  (Stock Feed Service)    │
          │  - Runs stock feed logic │
          │  - Pushes updates via SSE│
          │  - Updates continuously  │
          └──────────────────────────┘

🔄 Click to expand: SSE Communication Flow Example

SSE通信流程

┌──────────────┐                           ┌─────────────┐
│  MCP Client  │                           │ MCP Server  │
│  (AI App)    │                           │ (Stock Feed)│
└──────┬───────┘                           └──────▲──────┘
       │                                          │
       │ 1. ESTABLISH CONNECTION                  │
       ├─────────────────────────────────────────►│
       │ GET /mcp/stock-prices                    │
       │ Accept: text/event-stream                │
       │                                          │
       │ 2. CONNECTION OPEN (Persistent)          │
       │                                          │
       │◄─────────────────────────────────────────┤
       │ 200 OK                                   │
       │ Content-Type: text/event-stream          │
       │ (Connection stays open)                  │
       │

Time 1s: Server sends first update
       │◄─ event: stock_update ─────────────────┤
       │   data: AAPL=$150.25                     │
       │
       ├─► AI Model receives context             │
       │   (Analyzes stock data)                  │
       │

Time 2s: Server sends second update
       │◄─ event: stock_update ─────────────────┤
       │   data: AAPL=$150.50                     │
       │
       ├─► AI Model receives context             │
       │   (Analyzes new data)                    │
       │

Time 3s: Server sends third update
       │◄─ event: stock_update ─────────────────┤
       │   data: AAPL=$151.00                     │
       │
       ├─► AI Model receives context             │
       │   (Analyzes updated data)                │
       │

[Connection remains open indefinitely]
[Server pushes data whenever it changes]

要点:

  • ✅ 已建立一个持久连接
  • ✅ 每当数据发生变化时,服务器都会推送更新
  • ✅ 无需客户端进行轮询
  • ✅ 即时实时更新
  • ✅ 客户永远不需要再问

SSE理解(持久连接)

特性 详细信息
连接模型 一个持久连接保持打开状态
数据流 服务器向客户端推送更新
客户端行为 倾听更新,从不询问
数据更改时 服务器立即发送新数据
轮询 无需投票
实时 真正的实时(即时更新)
延迟 最小值(亚秒)
网络效率 高效(一个连接)
最适合 持续流媒体,实时更新
示例用例 股票价格、实时通知、监控

工作原理:

1. Client: "Give me live stock prices"
2. Client establishes SSE connection to Server
3. Connection stays open
4. Server: "Stock price changed to $150"
5. Client receives immediately
6. Server: "Stock price changed to $151"
7. Client receives immediately
8. (Repeat steps 6-7 as long as connection is open)

何时使用每个

在以下情况下使用SSE:

  • ✅ 服务器需要发送连续的更新流
  • ✅ 实时通知至关重要
  • ✅ 单向沟通就足够了
  • ✅ 你想保持轻量级的连接

在以下情况下使用HTTP:

  • ✅ 偶尔需要查询
  • ✅ 简单的请求-响应模式
  • ✅ 无状态操作
  • ✅ 遗留系统兼容性

🔌 JSON-RPC Format

MCP使用 JSON-RPC 2.0 消息格式规范。这确保了标准化的、与语言无关的沟通。

JSON-RPC结构

请求格式:

{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "method": "method_name",
  "params": {
    "param1": "value1",
    "param2": "value2"
  }
}

响应格式(成功):

{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "result": {
    "status": "success",
    "data": "response-data"
  }
}

响应格式(错误):

{
  "jsonrpc": "2.0",
  "id": "unique-request-id",
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": "Additional error information"
  }
}

JSON-RPC组件:

组件 描述
jsonrpc 协议版本(始终为“2.0”)
method 要调用的程序的名称
params 方法的参数(数组或对象)
id 用于关联请求响应的唯一标识符
result 成功响应数据
error 失败时的错误对象
⚠️ Click to expand: Common Error Codes Reference

常见错误代码:

  • -32700:分析错误
  • -32600:无效请求
  • -32601:未找到方法
  • -32602:无效参数
  • -32603:内部错误
  • -32000 to -32099:服务器错误(保留用于实现定义的错误)

MCP Workflow Example

场景:AI助手查询数据库

1. Client Request:
{
  "jsonrpc": "2.0",
  "id": "req-001",
  "method": "query_database",
  "params": {
    "query": "SELECT * FROM users WHERE status='active'"
  }
}

2. Server Processing:
   - Authenticates request
   - Validates query syntax
   - Executes database query
   - Formats results

3. Server Response:
{
  "jsonrpc": "2.0",
  "id": "req-001",
  "result": {
    "status": "success",
    "rows": [
      {"id": 1, "name": "John", "status": "active"},
      {"id": 2, "name": "Jane", "status": "active"}
    ]
  }
}

4. Client Processing:
   - Receives response
   - Extracts data
   - Passes context to AI model
   - Generates informed response

⭐ Key Benefits of MCP

✅ 标准化: 跨集成的一致协议
✅ 可扩展性: 易于添加新服务器和客户端
✅ 模块化: 解耦架构允许独立更新
✅ 实时数据: AI模型访问当前信息
✅ 语言无关: 基于JSON的通信跨技术工作
✅ 安全: 内置错误处理和身份验证挂钩


🚀 Use Cases
  • IDE集成: 可访问项目文件的AI编码助手
  • 数据分析: AI分析实时数据源
  • 自动化: AI触发外部工作流程
  • 客户支持: AI访问客户数据库以获取上下文
  • DevOps: 人工智能监控和管理基础设施

📋 Conclusion

模型上下文协议提供了一个强大的、标准化的框架,用于将人工智能模型与外部服务连接起来。通过在灵活的传输协议上利用JSON-RPC,MCP实现了安全、可扩展和可维护的集成,增强了人工智能功能,并为人工智能应用程序带来了上下文感知。