MCP 核心概念:掌握模型上下文协议实现 AI 集成 Model Context Protocol (MCP) 是一个强大且标准化的框架,用于优化大型语言模型(LLM)与外部工具、应用程序和数据源之间的通信。本文将通过 SEO 优化的指南带你深入了解 MCP 的核心概念,确保你理解其客户端-服务器架构、关键组件、通信机制以及最佳实现实践。 概述 本课将探讨构成模型上下文协议(MCP)生态系统的基础架构和组件。你将了解客户端-服务器架构、关键组件以及驱动 MCP 交互的通信机制。 主要学习目标 完成本课后,你将能够: 理解 MCP 的客户端-服务器架构。 识别 Hosts、Clients 和 Servers 的角色与职责。 分析使 MCP 成为灵活集成层的核心特性。
Model Context Protocol (MCP) 是一个强大且标准化的框架,用于优化大型语言模型(LLM)与外部工具、应用程序和数据源之间的通信。本文将通过 SEO 优化的指南带你深入了解 MCP 的核心概念,确保你理解其客户端-服务器架构、关键组件、通信机制以及最佳实现实践。
本课将探讨构成模型上下文协议(MCP)生态系统的基础架构和组件。你将了解客户端-服务器架构、关键组件以及驱动 MCP 交互的通信机制。
完成本课后,你将能够:
MCP 生态系统基于客户端-服务器模型构建。这种模块化结构使 AI 应用能够高效地与工具、数据库、API 及上下文资源交互。下面将把这一架构拆解为核心组件。
MCP 核心采用客户端-服务器架构,主机应用可以连接多个服务器:
MCP 协议是一个不断发展的标准,最新更新可见于 协议规范
在模型上下文协议(MCP)中,Hosts 是用户与协议交互的主要接口,承担关键角色。Hosts 是发起与 MCP 服务器连接以访问数据、工具和提示的应用或环境。Hosts 示例包括集成开发环境(IDE)如 Visual Studio Code,AI 工具如 Claude Desktop,或为特定任务定制的代理程序。
Hosts 是启动连接的 LLM 应用。它们:
Clients 是促进 Hosts 与 MCP 服务器交互的关键组件。Clients 充当中介,使 Hosts 能够访问并利用 MCP 服务器提供的功能。它们在确保 MCP 架构内通信顺畅和数据高效交换方面起着重要作用。
Clients 是主机应用内的连接器。它们:
Servers 负责处理来自 MCP clients 的请求并提供相应的响应。它们管理数据检索、工具执行和提示生成等各种操作。Servers 确保客户端和 Hosts 之间的通信高效且可靠,维护交互过程的完整性。
Servers 是提供上下文和功能的服务。它们:
任何人都可以开发服务器,以专门功能扩展模型能力。
模型上下文协议(MCP)中的服务器提供基础构建模块,使客户端、主机和语言模型之间实现丰富交互。这些功能旨在通过提供结构化的上下文、工具和提示,增强 MCP 的能力。
MCP 服务器可以提供以下任一功能:
MCP 中的资源涵盖各种可供用户或 AI 模型使用的上下文和数据类型,包括:
资源示例可以是数据库模式或文件,访问方式如下:
file://log.txt database://schema
MCP 中的提示包括各种预定义模板和交互模式,旨在简化用户工作流程并增强沟通。这些包括:
提示模板示例如下:
Generate a product slogan based on the following {{product}} with the following {{keywords}}
MCP 中的工具是 AI 模型可执行以完成特定任务的函数。设计这些工具旨在通过提供结构化且可靠的操作,增强 AI 模型的能力。关键点包括:
工具示例可能如下:
server.tool( "GetProducts", { pageSize: z.string().optional(), pageCount: z.string().optional() }, () => { // return results from API } )
在 MCP 中,客户端向服务器提供多项关键功能,增强协议内的整体交互和功能。其中一个重要功能是采样。
模型上下文协议(MCP)定义了 Hosts、Clients、Servers 和模型之间结构化的信息流。理解此流程有助于澄清用户请求的处理方式以及外部工具和数据如何融入模型响应。
Host 发起连接
Host 应用(如 IDE 或聊天界面)通过 STDIO、WebSocket 或其他支持的传输方式与 MCP 服务器建立连接。
能力协商
嵌入 Host 的客户端与服务器交换关于支持的功能、工具、资源和协议版本的信息,确保双方明确会话可用能力。
用户请求
用户与 Host 交互(例如输入提示或命令),Host 收集输入并传递给客户端处理。
资源或工具使用
服务器执行
服务器接收资源或工具请求,执行必要操作(如运行函数、查询数据库或检索文件),并以结构化格式返回结果给客户端。
响应生成
客户端将服务器响应(资源数据、工具输出等)整合进持续的模型交互中。模型利用这些信息生成全面且符合上下文的响应。
结果呈现
Host 接收客户端的最终输出,并展示给用户,通常包括模型生成的文本及任何工具执行或资源查询的结果。
此流程使 MCP 能够支持先进、交互式且具上下文感知的 AI 应用,顺畅连接模型与外部工具及数据源。
MCP(模型上下文协议)基于 JSON-RPC 2.0 构建,提供标准化、语言无关的消息格式,用于 Hosts、Clients 和 Servers 之间的通信。该基础确保跨多平台和编程语言的可靠、结构化和可扩展交互。
MCP 在 JSON-RPC 2.0 基础上扩展了工具调用、资源访问和提示管理的约定。支持多种传输层(STDIO、WebSocket、SSE),实现组件间安全、可扩展且语言无关的通信。
以下是 MCP 提供的部分附加工具和协议扩展,旨在提升开发体验和支持高级场景:
借助这些协议特性,MCP 确保语言模型与外部工具或数据源之间的通信稳健、安全且灵活。
MCP 实现应遵循若干关键安全原则,确保交互安全可信:
遵循这些原则,MCP 在所有协议交互中维护用户信任、隐私和安全。
以下是多个流行编程语言中的代码示例,展示如何实现 MCP 服务器关键组件和工具。
这是一个实用的 .NET 代码示例,演示如何实现带自定义工具的简单 MCP 服务器。示例展示了如何定义和注册工具、处理请求以及使用模型上下文协议连接服务器。
using System; using System.Threading.Tasks; using ModelContextProtocol.Server; using ModelContextProtocol.Server.Transport; using ModelContextProtocol.Server.Tools; public class WeatherServer { public static async Task Main(string[] args) { // Create an MCP server var server = new McpServer( name: "Weather MCP Server", version: "1.0.0" ); // Register our custom weather tool server.AddTool<string, WeatherData>("weatherTool", description: "Gets current weather for a location", execute: async (location) => { // Call weather API (simplified) var weatherData = await GetWeatherDataAsync(location); return weatherData; }); // Connect the server using stdio transport var transport = new StdioServerTransport(); await server.ConnectAsync(transport); Console.WriteLine("Weather MCP Server started"); // Keep the server running until process is terminated await Task.Delay(-1); } private static async Task<WeatherData> GetWeatherDataAsync(string location) { // This would normally call a weather API // Simplified for demonstration await Task.Delay(100); // Simulate API call return new WeatherData { Temperature = 72.5, Conditions = "Sunny", Location = location }; } } public class WeatherData { public double Temperature { get; set; } public string Conditions { get; set; } public string Location { get; set; } }
本示例演示与上述 .NET 示例相同的 MCP 服务器及工具注册,但使用 Java 实现。
import io.modelcontextprotocol.server.McpServer; import io.modelcontextprotocol.server.McpToolDefinition; import io.modelcontextprotocol.server.transport.StdioServerTransport; import io.modelcontextprotocol.server.tool.ToolExecutionContext; import io.modelcontextprotocol.server.tool.ToolResponse; public class WeatherMcpServer { public static void main(String[] args) throws Exception { // Create an MCP server McpServer server = McpServer.builder() .name("Weather MCP Server") .version("1.0.0") .build(); // Register a weather tool server.registerTool(McpToolDefinition.builder("weatherTool") .description("Gets current weather for a location") .parameter("location", String.class) .execute((ToolExecutionContext ctx) -> { String location = ctx.getParameter("location", String.class); // Get weather data (simplified) WeatherData data = getWeatherData(location); // Return formatted response return ToolResponse.content( String.format("Temperature: %.1f°F, Conditions: %s, Location: %s", data.getTemperature(), data.getConditions(), data.getLocation()) ); }) .build()); // Connect the server using stdio transport try (StdioServerTransport transport = new StdioServerTransport()) { server.connect(transport); System.out.println("Weather MCP Server started"); // Keep server running until process is terminated Thread.currentThread().join(); } } private static WeatherData getWeatherData(String location) { // Implementation would call a weather API // Simplified for example purposes return new WeatherData(72.5, "Sunny", location); } } class WeatherData { private double temperature; private String conditions; private String location; public WeatherData(double temperature, String conditions, String location) { this.temperature = temperature; this.conditions = conditions; this.location = location; } public double getTemperature() { return temperature; } public String getConditions() { return conditions; } public String getLocation() { return location; } }
本示例展示如何使用 Python 构建 MCP 服务器,并介绍两种不同的创建工具方法。
#!/usr/bin/env python3 import asyncio from mcp.server.fastmcp import FastMCP from mcp.server.transports.stdio import serve_stdio # Create a FastMCP server mcp = FastMCP( name="Weather MCP Server", version="1.0.0" ) @mcp.tool() def get_weather(location: str) -> dict: """Gets current weather for a location.""" # This would normally call a weather API # Simplified for demonstration return { "temperature": 72.5, "conditions": "Sunny", "location": location } # Alternative approach using a class class WeatherTools: @mcp.tool() def forecast(self, location: str, days: int = 1) -> dict: """Gets weather forecast for a location for the specified number of days.""" # This would normally call a weather API forecast endpoint # Simplified for demonstration return { "location": location, "forecast": [ {"day": i+1, "temperature": 70 + i, "conditions": "Partly Cloudy"} for i in range(days) ] } # Instantiate the class to register its tools weather_tools = WeatherTools() # Start the server using stdio transport if __name__ == "__main__": asyncio.run(serve_stdio(mcp))
本示例展示如何用 JavaScript 创建 MCP 服务器,并注册两个与天气相关的工具。
// Using the official Model Context Protocol SDK import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; // For parameter validation // Create an MCP server const server = new McpServer({ name: "Weather MCP Server", version: "1.0.0" }); // Define a weather tool server.tool( "weatherTool", { location: z.string().describe("The location to get weather for") }, async ({ location }) => { // This would normally call a weather API // Simplified for demonstration const weatherData = await getWeatherData(location); return { content: [ { type: "text", text: `Temperature: ${weatherData.temperature}°F, Conditions: ${weatherData.conditions}, Location: ${weatherData.location}` } ] }; } ); // Define a forecast tool server.tool( "forecastTool", { location: z.string(), days: z.number().default(3).describe("Number of days for forecast") }, async ({ location, days }) => { // This would normally call a weather API // Simplified for demonstration const forecast = await getForecastData(location, days); return { content: [ { type: "text", text: `${days}-day forecast for ${location}: ${JSON.stringify(forecast)}` } ] }; } ); // Helper functions async function getWeatherData(location) { // Simulate API call return { temperature: 72.5, conditions: "Sunny", location: location }; } async function getForecastData(location, days) { // Simulate API call return Array.from({ length: days }, (_, i) => ({ day: i + 1, temperature: 70 + Math.floor(Math.random() * 10), conditions: i % 2 === 0 ? "Sunny" : "Partly Cloudy" })); } // Connect the server using stdio transport const transport = new StdioServerTransport(); server.connect(transport).catch(console.error); console.log("Weather MCP Server started");
此 JavaScript 示例演示如何创建 MCP 客户端,连接服务器、发送提示并处理响应,包括任何工具调用。
MCP 包含多项内置概念和机制,用于管理协议中的安全和授权:
工具权限控制
客户端可指定模型在会话中允许使用的工具,确保仅授权工具可访问,降低意外或不安全操作风险。权限可根据用户偏好、组织策略或交互上下文动态配置。
身份验证
服务器可要求身份验证后才允许访问工具、资源或敏感操作,可能采用 API 密钥、OAuth 令牌等方式。有效身份验证确保只有可信客户端和用户能调用服务器功能。
参数验证
所有工具调用均强制参数验证。每个工具定义其参数的预期类型、格式和约束,服务器据此验证请求,防止格式错误或恶意输入影响工具实现,维护操作完整性。
速率限制
为防止滥用并保障服务器资源公平使用,MCP 服务器可对工具调用和资源访问实施速率限制。限制可按用户、会话或全局应用,有效防御拒绝服务攻击或过度资源消耗。
结合这些机制,MCP 为语言模型与外部工具及数据源集成提供安全基础,同时赋予用户和开发者细粒度访问和使用控制。
MCP 通信使用结构化 JSON 消息,促进客户端、服务器和模型间清晰可靠的交互。主要消息类型包括:
客户端请求
由客户端发送给服务器,通常包含:
模型响应
由模型(通过客户端)返回,包含:
工具请求
当需要执行工具时,由客户端发送给服务器,包含:
工具响应
服务器执行工具后返回,提供:
这些结构化消息确保 MCP 工作流程的每一步都明确、可追踪且可扩展,支持多轮对话、工具链和健壮的错误处理等高级场景。
设计一个适用于你领域的简单 MCP 工具。定义:
下一章:第 2 章:安全
免责声明:
本文件使用 AI 翻译服务 Co-op Translator 进行翻译。尽管我们努力确保准确性,但请注意自动翻译可能包含错误或不准确之处。原始文件的母语版本应被视为权威来源。对于重要信息,建议采用专业人工翻译。我们不对因使用本翻译而产生的任何误解或错误解释承担责任。