烂翻译系列之——MCP中的概念——架构概览
This overview of the Model Context Protocol (MCP) discusses its scope and core concepts, and provides an example demonstrating each core concept.
本篇对模型上下文协议(MCP)的概述介绍了其适用范围和核心概念,并通过示例逐一展示了每个核心概念。
Because MCP SDKs abstract away many concerns, most developers will likely find the data layer protocol section to be the most useful. It discusses how MCP servers can provide context to an AI application.
由于 MCP 软件开发工具包(SDK)已封装了大量底层细节,大多数开发者可能会发现数据层协议部分最为实用。该部分详细说明了 MCP 服务端如何向 AI 应用提供上下文信息。
For specific implementation details, please refer to the documentation for your language-specific SDK.
如需了解具体的实现细节,请参考您所使用编程语言对应的 SDK 文档。
Scope 范围
The Model Context Protocol includes the following projects:
模型上下文协议(MCP)包含以下项目:
- MCP Specification: A specification of MCP that outlines the implementation requirements for clients and servers. MCP 规范:定义 MCP 的技术标准,明确了客户端和服务端的实现要求。
- MCP SDKs: SDKs for different programming languages that implement MCP. MCP SDK:支持多种编程语言的软件开发工具包,用于实现 MCP 协议。
- MCP Development Tools: Tools for developing MCP servers and clients, including the MCP Inspector MCP 开发工具:用于开发 MCP 客户端和服务端的工具,包括 MCP 检查器(MCP Inspector)。
- MCP Reference Server Implementations: Reference implementations of MCP servers. MCP 参考服务端实现:MCP 服务端的参考实现示例,帮助开发者理解和构建自己的服务端。
MCP focuses solely on the protocol for context exchange—it does not dictate how AI applications use LLMs or manage the provided context.
MCP 仅专注于上下文交换的协议,它并不规定 AI 应用如何使用大语言模型(LLM)或如何管理所提供的上下文。
Concepts of MCP MCP 的概念
Participants 参与者
MCP follows a client-server architecture where an MCP host — an AI application like Claude Code or Claude Desktop — establishes connections to one or more MCP servers. The MCP host accomplishes this by creating one MCP client for each MCP server. Each MCP client maintains a dedicated one-to-one connection with its corresponding MCP server.
MCP 采用客户端-服务端架构,其中 MCP 主机 —— 例如 Claude Code 或 Claude Desktop 这类 AI 应用 —— 会与一个或多个 MCP 服务端建立连接。MCP 主机通过为每个 MCP 服务端创建一个 MCP 客户端来实现这一连接。每个 MCP 客户端与其对应的 MCP 服务端保持专用的一对一连接。
The key participants in the MCP architecture are:
MCP 架构中的关键参与者包括:
- MCP Host: The AI application that coordinates and manages one or multiple MCP clients MCP 主机(MCP Host):协调和管理一个或多个 MCP 客户端的 AI 应用。
- MCP Client: A component that maintains a connection to an MCP server and obtains context from an MCP server for the MCP host to use MCP 客户端(MCP Client):负责与 MCP 服务端保持连接,并从服务端获取上下文,供 MCP 主机使用。
- MCP Server: A program that provides context to MCP clients MCP 服务端(MCP Server):向 MCP 客户端提供上下文信息的程序。
For example: Visual Studio Code acts as an MCP host. When Visual Studio Code establishes a connection to an MCP server, such as the Sentry MCP server, the Visual Studio Code runtime instantiates an MCP client object that maintains the connection to the Sentry MCP server. When Visual Studio Code subsequently connects to another MCP server, such as the local filesystem server, the Visual Studio Code runtime instantiates an additional MCP client object to maintain this connection, hence maintaining a one-to-one relationship of MCP clients to MCP servers.
例如:Visual Studio Code 充当 MCP 主机。当 Visual Studio Code 与某个 MCP 服务端(如 Sentry MCP 服务端)建立连接时,其运行时会实例化一个 MCP 客户端对象,用于维护与该 Sentry MCP 服务端的连接。当 Visual Studio Code 随后连接到另一个 MCP 服务端(如本地文件系统服务端)时,运行时会再实例化一个独立的 MCP 客户端对象来维持该连接,从而确保每个 MCP 客户端与每个 MCP 服务端之间保持一对一的关系。
Note that MCP server refers to the program that serves context data, regardless of where it runs. MCP servers can execute locally or remotely. For example, when Claude Desktop launches the filesystem server, the server runs locally on the same machine because it uses the STDIO transport. This is commonly referred to as a “local” MCP server. The official Sentry MCP server runs on the Sentry platform, and uses the Streamable HTTP transport. This is commonly referred to as a “remote” MCP server.
请注意,“MCP 服务端”指的是提供上下文数据的程序,与其运行位置无关。MCP 服务端可以在本地或远程运行。
例如,当 Claude Desktop 启动文件系统服务端时,该服务端在同一台机器上本地运行,因为它使用的是 STDIO 传输方式。这通常被称为“本地”MCP 服务端。而官方的 Sentry MCP 服务端则运行在 Sentry 平台上,并使用可流式 HTTP(Streamable HTTP)传输方式,这通常被称为“远程”MCP 服务端。
Layers 层次结构
MCP consists of two layers: MCP 由两个层次组成:
- Data layer: Defines the JSON-RPC based protocol for client-server communication, including lifecycle management, and core primitives, such as tools, resources, prompts and notifications. 数据层(Data layer):定义基于 JSON-RPC 的客户端与服务端通信协议,包括生命周期管理,以及核心构件,如工具(tools)、资源(resources)、提示词(prompts)和通知(notifications)。
- Transport layer: Defines the communication mechanisms and channels that enable data exchange between clients and servers, including transport-specific connection establishment, message framing, and authorization. 传输层(Transport layer):定义客户端与服务端之间数据交换所使用的通信机制和通道,包括传输方式相关的连接建立、消息分帧和授权机制。
Conceptually the data layer is the inner layer, while the transport layer is the outer layer.
从概念上讲,数据层是内层,而传输层是外层。
Data layer 数据层
The data layer implements a JSON-RPC 2.0 based exchange protocol that defines the message structure and semantics. This layer includes:
数据层实现了一个基于 JSON-RPC 2.0 的交换协议,定义了消息的结构和语义。该层包含以下内容:
- Lifecycle management: Handles connection initialization, capability negotiation, and connection termination between clients and servers 生命周期管理:处理客户端与服务端之间的连接初始化、能力协商以及连接终止。
- Server features: Enables servers to provide core functionality including tools for AI actions, resources for context data, and prompts for interaction templates from and to the client 服务端功能:使服务端能够提供核心功能,包括用于 AI 操作的工具(tools)、用于上下文数据的资源(resources),以及用于与客户端交互的提示词模板(prompts)。
- Client features: Enables servers to ask the client to sample from the host LLM, elicit input from the user, and log messages to the client 客户端功能:允许服务端要求客户端从宿主大语言模型进行采样、向用户获取输入,并将日志消息发送至客户端。
- Utility features: Supports additional capabilities like notifications for real-time updates and progress tracking for long-running operations 辅助功能:支持实时更新通知、长时间运行操作的状态跟踪等扩展能力。
Transport layer 传输层
The transport layer manages communication channels and authentication between clients and servers. It handles connection establishment, message framing, and secure communication between MCP participants.
传输层负责管理客户端与服务端之间的通信通道和身份认证。它处理连接的建立、消息的分帧以及 MCP 参与方之间的安全通信。
MCP supports two transport mechanisms:
MCP 支持两种传输机制:
- Stdio transport: Uses standard input/output streams for direct process communication between local processes on the same machine, providing optimal performance with no network overhead. Stdio 传输:使用标准输入/输出流,在同一台机器上的本地进程之间进行直接通信,性能最优,且无网络开销。
- Streamable HTTP transport: Uses HTTP POST for client-to-server messages with optional Server-Sent Events for streaming capabilities. This transport enables remote server communication and supports standard HTTP authentication methods including bearer tokens, API keys, and custom headers. MCP recommends using OAuth to obtain authentication tokens. 可流式 HTTP 传输(Streamable HTTP transport):使用 HTTP POST 发送客户端到服务端的消息,并可选地使用服务端发送事件(Server-Sent Events, SSE)实现流式传输功能。该机制支持远程服务端通信,并兼容标准的 HTTP 认证方式,包括令牌(bearer tokens)、API 密钥和自定义请求头。MCP 建议使用 OAuth 来获取认证令牌。
The transport layer abstracts communication details from the protocol layer, enabling the same JSON-RPC 2.0 message format across all transport mechanisms.
传输层将通信细节从协议层中抽象出来,使得所有传输机制都能使用相同的 JSON-RPC 2.0 消息格式,从而实现协议的一致性和跨平台的互操作性。
Data Layer Protocol 数据层协议
A core part of MCP is defining the schema and semantics between MCP clients and MCP servers. Developers will likely find the data layer — in particular, the set of primitives — to be the most interesting part of MCP. It is the part of MCP that defines the ways developers can share context from MCP servers to MCP clients.
MCP 的核心在于定义 MCP 客户端与服务端之间的交互模式与语义。开发者可能会发现数据层——尤其是一组构件(primitives)——是 MCP 中最具价值的部分。该层定义了开发者将上下文信息从 MCP 服务端传递至 MCP 客户端的具体方式。
MCP uses JSON-RPC 2.0 as its underlying RPC protocol. Client and servers send requests to each other and respond accordingly. Notifications can be used when no response is required.
MCP 采用 JSON-RPC 2.0 作为底层 RPC 协议。客户端与服务端相互发送请求并接收响应,在无需响应时可通过通知(notifications)实现单向通信。
Lifecycle management 生命周期管理
MCP is a stateful protocol that requires lifecycle management. The purpose of lifecycle management is to negotiate the capabilities that both client and server support. Detailed information can be found in the specification, and the example showcases the initialization sequence.
MCP 是一种有状态协议,需要生命周期管理机制。该管理的目的是协调客户端与服务端双方支持的能力。具体细节可参阅规范文档,示例代码展示了完整的初始化序列。
Primitives 构件
MCP primitives are the most important concept within MCP. They define what clients and servers can offer each other. These primitives specify the types of contextual information that can be shared with AI applications and the range of actions that can be performed.
MCP 构件是协议中最核心的概念,定义了客户端与服务端能相互提供的能力。这些构件明确了可共享给AI应用的上下文信息类型,以及可执行的操作范围。
MCP defines three core primitives that servers can expose:
MCP 定义了服务端可暴露的三类核心构件:
- Tools: Executable functions that AI applications can invoke to perform actions (e.g., file operations, API calls, database queries) 工具:AI 应用可调用的可执行函数,用于执行具体操作(例如:文件操作、API 调用、数据库查询)。
- Resources: Data sources that provide contextual information to AI applications (e.g., file contents, database records, API responses) 资源:为AI应用提供上下文信息的数据源(如文件内容、数据库记录、API响应)
- Prompts: Reusable templates that help structure interactions with language models (e.g., system prompts, few-shot examples) 提示词:可复用的模板,用于帮助结构化与语言模型的交互(例如:系统提示词、少样本示例)。
Each primitive type has associated methods for discovery (*/list
), retrieval (*/get
), and in some cases, execution (tools/call
). MCP clients will use the */list
methods to discover available primitives. For example, a client can first list all available tools (tools/list
) and then execute them. This design allows listings to be dynamic.
每类构件都包含对应的发现(/list)、获取(/get)及执行(tools/call)方法。MCP客户端通过*/list方法动态发现可用构件:例如先列出所有可用工具(tools/list)再执行调用。这种设计使得列表能够动态生成。
As a concrete example, consider an MCP server that provides context about a database. It can expose tools for querying the database, a resource that contains the schema of the database, and a prompt that includes few-shot examples for interacting with the tools.
以数据库查询场景为例:MCP服务端可提供数据库查询工具、包含数据库模式的资源,以及内置工具交互少样本示例的提示模板。更多服务端构件细节请参阅服务端概念。
For more details about server primitives see server concepts.
更多服务端构件细节请参阅服务端概念。
MCP also defines primitives that clients can expose. These primitives allow MCP server authors to build richer interactions.
MCP 同时定义了客户端可暴露的构件,使服务端开发者能构建更丰富的交互:
- Sampling: Allows servers to request language model completions from the client’s AI application. This is useful when servers’ authors want access to a language model, but want to stay model independent and not include a language model SDK in their MCP server. They can use the
sampling/complete
method to request a language model completion from the client’s AI application. 采样(Sampling):允许服务端从客户端的AI应用请求语言模型补全(通过sampling/complete方法)。适用于希望保持模型独立性而不内置SDK的场景 - Elicitation: Allows servers to request additional information from users. This is useful when servers’ authors want to get more information from the user, or ask for confirmation of an action. They can use the
elicitation/request
method to request additional information from the user. 征询(Elicitation):允许服务端向用户请求额外信息(通过elicitation/request方法)。适用于需要确认操作或获取补充信息的场景 - Logging: Enables servers to send log messages to clients for debugging and monitoring purposes. 日志(Logging):支持服务端向客户端发送调试和监控日志
For more details about client primitives see client concepts.
更多客户端构建细节请参阅客户端概念。
Notifications 通知机制
The protocol supports real-time notifications to enable dynamic updates between servers and clients. For example, when a server’s available tools change—such as when new functionality becomes available or existing tools are modified—the server can send tool update notifications to inform connected clients about these changes. Notifications are sent as JSON-RPC 2.0 notification messages (without expecting a response) and enable MCP servers to provide real-time updates to connected clients.
该协议支持实时通知功能,实现服务端与客户端之间的动态更新。例如当服务端可用工具发生变化时(如新增功能或修改现有工具),服务端可主动向已连接的客户端发送工具更新通知。这些通知以 JSON-RPC 2.0 通知消息形式发送(无需等待响应),使 MCP 服务端能够为客户端提供实时状态更新。
Example 示例
Data Layer 数据层
This section provides a step-by-step walkthrough of an MCP client-server interaction, focusing on the data layer protocol. We’ll demonstrate the lifecycle sequence, tool operations, and notifications using JSON-RPC 2.0 messages.
本节通过分步详解方式展示 MCP 客户端-服务端交互过程,重点阐述数据层协议。我们将使用 JSON-RPC 2.0 消息演示生命周期序列、工具操作及通知机制的实际应用。
-
Initialization (Lifecycle Management) 初始化(生命周期管理)
MCP begins with lifecycle management through a capability negotiation handshake. As described in the lifecycle management section, the client sends an initialize request to establish the connection and negotiate supported features.
MCP 通过能力协商握手启动生命周期管理流程。如生命周期管理章节所述,客户端会发送初始化请求以建立连接,并协商双方支持的功能特性。
Initialize Request Initialize Response { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": { "elicitation": {} }, "clientInfo": { "name": "example-client", "version": "1.0.0" } } }
{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": { "listChanged": true }, "resources": {} }, "serverInfo": { "name": "example-server", "version": "1.0.0" } } }
Understanding the Initialization Exchange 理解初始化交流
The initialization process is a key part of MCP’s lifecycle management and serves several critical purposes:
初始化流程是 MCP 生命周期管理的关键环节,主要实现以下核心功能:
- Protocol Version Negotiation: The
protocolVersion
field (e.g., “2025-06-18”) ensures both client and server are using compatible protocol versions. This prevents communication errors that could occur when different versions attempt to interact. If a mutually compatible version is not negotiated, the connection should be terminated. 协议版本协商:protocolVersion
字段(例如 “2025-06-18”)确保客户端和服务端使用兼容的协议版本。这可以防止因版本不一致而导致的通信错误。如果双方无法协商出一个共同支持的兼容版本,应终止连接。 - Capability Discovery: The
capabilities
object allows each party to declare what features they support, including which primitives they can handle (tools, resources, prompts) and whether they support features like notifications. This enables efficient communication by avoiding unsupported operations. 能力发现:capabilities
对象允许双方声明各自支持的功能,包括能够处理的基本构件(如 tools、resources、prompts),以及是否支持通知等功能。通过明确能力,可避免执行对方不支持的操作,从而实现高效通信。 - Identity Exchange: The
clientInfo
andserverInfo
objects provide identification and versioning information for debugging and compatibility purposes. 身份信息交流:clientInfo
和serverInfo
对象提供了客户端与服务端的身份标识及版本信息,便于调试和兼容性检查。
In this example, the capability negotiation demonstrates how MCP primitives are declared:
在以下示例中,能力协商展示了 MCP 基本构件是如何被声明的:
Client Capabilities: 客户端能力:
"elicitation": {}
- The client declares it can work with user interaction requests (can receiveelicitation/create
method calls) 客户端声明其支持用户交互请求(即可以接收elicitation/create
方法调用)
Server Capabilities: 服务端能力:
"tools": {"listChanged": true}
- The server supports the tools primitive AND can sendtools/list_changed
notifications when its tool list changes 服务端支持“工具”构件,并且当工具列表发生变化时,能够发送tools/list_changed
通知"resources": {}
- The server also supports the resources primitive (can handleresources/list
andresources/read
methods) 服务端也支持“资源”构件(可以处理resources/list
和resources/read
方法)
After successful initialization, the client sends a notification to indicate it’s ready:
初始化成功后,客户端会发送一条通知,表明其已准备就绪:
Notification{ "jsonrpc": "2.0", "method": "notifications/initialized" }
How This Works in AI Applications AI 应用中的工作原理
During initialization, the AI application’s MCP client manager establishes connections to configured servers and stores their capabilities for later use. The application uses this information to determine which servers can provide specific types of functionality (tools, resources, prompts) and whether they support real-time updates.
在初始化过程中,AI 应用的 MCP 客户端管理器会与已配置的服务端建立连接,并存储其功能能力以供后续使用。应用利用这些信息来判断哪些服务端能够提供特定类型的功能(如工具、资源、提示词),以及是否支持实时更新。
Pseudo-code for AI application initialization AI 应用初始化的伪代码# Pseudo Code async with stdio_client(server_config) as (read, write): async with ClientSession(read, write) as session: init_response = await session.initialize() if init_response.capabilities.tools: app.register_mcp_server(session, supports_tools=True) app.set_server_ready(session)
- Protocol Version Negotiation: The
-
Tool Discovery (Primitives) 工具发现(基本构件)
Now that the connection is established, the client can discover available tools by sending a
tools/list
request. This request is fundamental to MCP’s tool discovery mechanism — it allows clients to understand what tools are available on the server before attempting to use them.现在连接已建立,客户端可以通过发送
tools/list
请求来发现可用的工具。该请求是 MCP 工具发现机制的核心——它允许客户端在使用工具之前,先了解服务端上有哪些可用工具。Tools List Request Tools List Response { "jsonrpc": "2.0", "id": 2, "method": "tools/list" }
{ "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "calculator_arithmetic", "title": "Calculator", "description": "Perform mathematical calculations including basic arithmetic, trigonometric functions, and algebraic operations", "inputSchema": { "type": "object", "properties": { "expression": { "type": "string", "description": "Mathematical expression to evaluate (e.g., '2 + 3 * 4', 'sin(30)', 'sqrt(16)')" } }, "required": ["expression"] } }, { "name": "weather_current", "title": "Weather Information", "description": "Get current weather information for any location worldwide", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City name, address, or coordinates (latitude,longitude)" }, "units": { "type": "string", "enum": ["metric", "imperial", "kelvin"], "description": "Temperature units to use in response", "default": "metric" } }, "required": ["location"] } } ] } }
Understanding the Tool Discovery Request 理解工具发现请求
The
tools/list
request is simple, containing no parameters.tools/list
请求非常简单,不包含任何参数。Understanding the Tool Discovery Response 理解工具发现响应
The response contains a
tools
array that provides comprehensive metadata about each available tool. This array-based structure allows servers to expose multiple tools simultaneously while maintaining clear boundaries between different functionalities.响应中包含一个
tools
数组,其中提供了每个可用工具的完整元数据。这种基于数组的结构使得服务端能够同时暴露多个工具,同时保持不同功能之间的清晰边界。Each tool object in the response includes several key fields:
响应中的每个工具对象都包含以下几个关键字段:
name
: A unique identifier for the tool within the server’s namespace. This serves as the primary key for tool execution and should follow a clear naming pattern (e.g.,calculator_arithmetic
rather than justcalculate
) 工具在服务端命名空间内的唯一标识符。它作为执行工具的主要键值,应遵循清晰的命名模式(例如使用calculator_arithmetic
而不是简单的calculate
)。title
: A human-readable display name for the tool that clients can show to users 工具的可读显示名称,客户端可将其展示给用户。description
: Detailed explanation of what the tool does and when to use it 对工具功能的详细说明,包括其用途和适用场景。inputSchema
: A JSON Schema that defines the expected input parameters, enabling type validation and providing clear documentation about required and optional parameters 一个 JSON Schema,定义了预期的输入参数,可用于类型验证,并清晰地说明哪些参数是必需的、哪些是可选的。
How This Works in AI Applications AI 应用中的工作原理
The AI application fetches available tools from all connected MCP servers and combines them into a unified tool registry that the language model can access. This allows the LLM to understand what actions it can perform and automatically generates the appropriate tool calls during conversations.
AI 应用会从所有已连接的 MCP 服务端获取可用工具,并将它们整合到一个统一的工具注册表中,供语言模型访问。这使得大语言模型(LLM)能够了解自己可以执行哪些操作,并在对话过程中自动生成相应的工具调用。
Pseudo-code for AI application tool discovery AI 应用工具发现的伪代码# Pseudo-code using MCP Python SDK patterns available_tools = [] for session in app.mcp_server_sessions(): tools_response = await session.list_tools() available_tools.extend(tools_response.tools) conversation.register_available_tools(available_tools)
-
Tool Execution (Primitives) 工具执行(基本构件)
The client can now execute a tool using the
tools/call
method. This demonstrates how MCP primitives are used in practice: after discovering available tools, the client can invoke them with appropriate arguments.客户端现在可以使用
tools/call
方法来执行工具。这展示了 MCP 基本构件在实际中的使用方式:在发现可用工具后,客户端可以使用适当的参数来调用这些工具。Understanding the Tool Execution Request 理解工具执行请求
The
tools/call
request follows a structured format that ensures type safety and clear communication between client and server. Note that we’re using the proper tool name from the discovery response (weather_current
) rather than a simplified name:tools/call
请求遵循一种结构化格式,以确保客户端与服务端之间的类型安全和清晰通信。请注意,我们使用的是在发现响应中获取的准确工具名称(weather_current
),而不是一个简化的名称:Tool Call Request Tool Call Response { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "weather_current", "arguments": { "location": "San Francisco", "units": "imperial" } } }
{ "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "Current weather in San Francisco: 68°F, partly cloudy with light winds from the west at 8 mph. Humidity: 65%" } ] } }
Key Elements of Tool Execution 工具执行的关键要素
The request structure includes several important components:
该请求结构包含以下几个重要组成部分:
name
: Must match exactly the tool name from the discovery response (weather_current
). This ensures the server can correctly identify which tool to execute. 必须与发现响应中的工具名称(weather_current
)完全一致。这确保了服务端能够准确识别需要执行的工具。arguments
: Contains the input parameters as defined by the tool’sinputSchema
. In this example: 包含根据工具的inputSchema
所定义的输入参数。在本示例中:location
: “San Francisco” (required parameter) (必需参数)units
: “imperial” (optional parameter, defaults to “metric” if not specified) (可选参数,若未指定则默认为 “metric”)
- JSON-RPC Structure: Uses standard JSON-RPC 2.0 format with unique
id
for request-response correlation. 采用标准的 JSON-RPC 2.0 格式,并使用唯一的id
来关联请求与响应,确保通信的正确匹配。
Understanding the Tool Execution Response 理解工具执行响应
The response demonstrates MCP’s flexible content system:
该响应展示了 MCP 灵活的内容系统:
content
Array: Tool responses return an array of content objects, allowing for rich, multi-format responses (text, images, resources, etc.) content 数组:工具的响应以content对象数组的形式返回,支持丰富且多格式的响应内容(如文本、图像、资源等)。- Content Types: Each content object has a
type
field. In this example,"type": "text"
indicates plain text content, but MCP supports various content types for different use cases. Content类型:每个content对象都有一个type
字段。在本例中,"type": "text"
表示内容为纯文本,但 MCP 支持多种内容类型,以适应不同的使用场景。 - Structured Output: The response provides actionable information that the AI application can use as context for language model interactions. 结构化输出:响应提供了可操作的信息,AI 应用可将其作为上下文,用于与语言模型的交互。
This execution pattern allows AI applications to dynamically invoke server functionality and receive structured responses that can be integrated into conversations with language models.
这种执行模式使得 AI 应用能够动态调用服务端功能,并接收结构化的响应,进而将这些信息无缝整合到与语言模型的对话中。
How This Works in AI Applications 在 AI 应用中的工作原理
When the language model decides to use a tool during a conversation, the AI application intercepts the tool call, routes it to the appropriate MCP server, executes it, and returns the results back to the LLM as part of the conversation flow. This enables the LLM to access real-time data and perform actions in the external world.
当语言模型在对话过程中决定使用某个工具时,AI 应用会拦截该工具调用,将其路由到相应的 MCP 服务端,执行该操作,并将结果作为对话流程的一部分返回给大语言模型(LLM)。这种机制使 LLM 能够访问实时数据,并在LLM的外部世界中执行实际操作。
# Pseudo-code for AI application tool execution AI 应用工具执行的伪代码 async def handle_tool_call(conversation, tool_name, arguments): session = app.find_mcp_session_for_tool(tool_name) result = await session.call_tool(tool_name, arguments) conversation.add_tool_result(result.content)
-
Real-time Updates (Notifications) 实时更新(通知)
MCP supports real-time notifications that enable servers to inform clients about changes without being explicitly requested. This demonstrates the notification system, a key feature that keeps MCP connections synchronized and responsive.
MCP支持实时通知功能,使得服务器能够在无需显式请求的情况下向客户端推送变更信息。这展示了通知系统的运作机制,该关键特性可确保MCP连接保持同步性和响应能力。
Understanding Tool List Change Notifications 理解工具列表变更通知
When the server’s available tools change—such as when new functionality becomes available, existing tools are modified, or tools become temporarily unavailable—the server can proactively notify connected clients:
当服务端的可用工具发生变化时——例如新增功能、现有工具被修改,或某些工具暂时不可用——服务端可以主动通知所有已连接的客户端:
Request { "jsonrpc": "2.0", "method": "notifications/tools/list_changed" }
Key Features of MCP Notifications MCP 通知的关键特性
- No Response Required: Notice there’s no
id
field in the notification. This follows JSON-RPC 2.0 notification semantics where no response is expected or sent. 无需响应:注意,该通知中没有id
字段。这符合 JSON-RPC 2.0 的通知语义,即不需要也不期望客户端返回响应。 - Capability-Based: This notification is only sent by servers that declared
"listChanged": true
in their tools capability during initialization (as shown in Step 1). 基于能力声明:只有在初始化阶段(如步骤1所示)其工具能力中声明了"listChanged": true
的服务端,才会发送此通知。 - Event-Driven: The server decides when to send notifications based on internal state changes, making MCP connections dynamic and responsive.
- 事件驱动:服务端根据其内部状态的变化来决定何时发送通知,从而使 MCP 连接具有动态性和实时响应能力。
Client Response to Notifications 客户端对通知的响应
Upon receiving this notification, the client typically reacts by requesting the updated tool list. This creates a refresh cycle that keeps the client’s understanding of available tools current:
客户端收到此通知后,通常会立即请求更新后的工具列表。这一机制形成了一种刷新循环,确保客户端始终掌握最新的可用工具信息。
Request { "jsonrpc": "2.0", "id": 4, "method": "tools/list" }
Why Notifications Matter 通知机制的重要性
This notification system is crucial for several reasons:
这一通知系统至关重要,原因如下:
- Dynamic Environments: Tools may come and go based on server state, external dependencies, or user permissions 动态环境支持:工具的可用性可能随服务端状态、外部依赖或用户权限的变化而动态增减。
- Efficiency: Clients don’t need to poll for changes; they’re notified when updates occur 高效性:客户端无需通过轮询方式检查变更,仅在发生更新时接收通知,节省资源。
- Consistency: Ensures clients always have accurate information about available server capabilities 一致性:确保客户端始终掌握服务端可用能力的最新信息,避免使用已失效或过期的功能。
- Real-time Collaboration: Enables responsive AI applications that can adapt to changing contexts 实时协作:使 AI 应用能够快速响应上下文变化,实现更智能、更灵活的交互体验。
This notification pattern extends beyond tools to other MCP primitives, enabling comprehensive real-time synchronization between clients and servers.
这种通知模式不仅适用于工具(tools),还可扩展到 MCP 的其他基本构件(primitives),从而实现客户端与服务端之间全面的实时同步。
How This Works in AI Applications 在 AI 应用中的工作原理
When the AI application receives a notification about changed tools, it immediately refreshes its tool registry and updates the LLM’s available capabilities. This ensures that ongoing conversations always have access to the most current set of tools, and the LLM can dynamically adapt to new functionality as it becomes available.
当 AI 应用收到工具变更的通知时,会立即刷新其工具注册表,并更新大语言模型(LLM)可用的功能列表。这确保了正在进行的对话始终能够访问最新的工具集合,LLM 也能在新功能可用时动态调整并加以利用。
# Pseudo-code for AI application notification handling AI 应用处理通知的伪代码 async def handle_tools_changed_notification(session): tools_response = await session.list_tools() app.update_available_tools(session, tools_response.tools) if app.conversation.is_active(): app.conversation.notify_llm_of_new_capabilities()
- No Response Required: Notice there’s no
