MCP(Model Context Protocol,模型上下文协议)介绍
MCP(Model Context Protocol,模型上下文协议) 是由 Anthropic 于 2024 年底开源的标准化开放协议。它的核心目标是统一 AI 大模型(Host/Client) 与 外部数据源及工具(Server) 之间的通信桥梁,类似于硬件接口中的 Type-C 标准,避免为每个工具单独编写胶水代码。
一、 核心架构与设计原理
MCP 采用典型的 Client-Server 架构,基于 JSON-RPC 2.0 协议进行双向通信。
1. 整体架构层次
MCP Host(宿主应用):发起 AI 请求的具体端点,如 Cursor、Claude Desktop、VS Code 等。 MCP Client(客户端):嵌入在 Host 内部,负责与服务器保持 1:1 连接、协议解析以及上下文管理。 MCP Server(服务端):轻量级服务,通过 MCP 协议暴露特定的上下文、工具或能力(例如读取 Git 仓库、操作 PostgreSQL 数据库、调用 Fetch 网页接口)。
+-------------------------------------------------------------+
| MCP Host |
| (e.g., Cursor, Claude Desktop, Custom Agent Framework) |
| |
| +---------------------+ +---------------------+ |
| | MCP Client | | MCP Client | |
| +----------+----------+ +----------+----------+ |
+--------------|-------------------------------+|-------------+
| (JSON-RPC) | (JSON-RPC)
| stdio / SSE | stdio / SSE
v v
+--------------------+ +--------------------+
| MCP Server | | MCP Server |
| (e.g., Git Tools) | | (e.g., Postgres) |
+---------+----------+ +---------+----------+
| |
v v
[ Git Repo ] [ Postgres DB ]
2. 三大核心能力原语 (Primitives)
MCP Server 通过以下三种机制向 LLM 提供能力:
| 核心概念 | 方向 | 作用说明 | 常见应用场景 |
|---|---|---|---|
| Resources (资源) | Server → Client | 被动读取的上下文数据(类似于 API 的 GET) | 读取本地文件、日志流、数据库 Schema |
| Tools (工具) | Client → Server | 主动执行的操作函数(模型可调用的 Function Calling) | 执行终端命令、提交 Git Commit、写数据库 |
| Prompts (提示词) | Server → Client | 预定义的交互模板或 Workflow | 提供常用的 Code Review 模板、调试 SOP |
3. 传输层协议 (Transport Layer)
MCP 目前支持两种标准传输协议:
stdio(标准输入输出):用于本地环境。Host 启动 Server 子进程,直接通过stdin/stdout通信,高效率、无网络开销。SSE(Server-Sent Events / HTTP):用于远程服务。客户端通过 HTTP SSE 接收服务端事件,通过 POST 提交数据。
二、 MCP 的核心优势
解耦与标准化:过去每个 AI Client(如 LangChain、AutoGPT、Cursor)都有自己的 Plugin/Tool 接口规范。MCP 统一标准后,写一次 MCP Server 即可在所有支持 MCP 的客户端中复用。 极简权限与隔离:服务端控制具体的底层操作,Host 控制给 LLM 的上下文。敏感数据在本地 Server 解析后仅返回核心字段给模型,提升安全性。 动态能力扩展:Host 连接 MCP Server 后,能自动发现(Discover)服务端提供的资源和工具列表,实现动态上下文注入。
三、 MCP 实战用法
1. 客户端配置(以 Claude Desktop 或 Cursor 为例)
以本地运行一个 PostgreSQL 的 MCP 服务为例,只需在 Host 配置文件(如 claude_desktop_config.json 或 Cursor MCP 设置)中增加以下配置:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://localhost/mydb"
]
}
}
}
配置完成后,LLM 即可自动识别 postgres 数据库相关的工具,并根据用户指令自发调用 SQL 校验或查询数据。
2. 实现一个简单的 Node.js/TypeScript MCP Server
使用官方 SDK(@modelcontextprotocol/sdk)编写自定义工具:
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
// 1. 初始化 Server 实例
const server = new Server(
{ name: "my-custom-tools", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
// 2. 注册可用工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "calculate_sum",
description: "计算两个数字的和",
inputSchema: {
type: "object",
properties: {
a: { type: "number" },
b: { type: "number" },
},
required: ["a", "b"],
},
},
],
};
});
// 3. 处理工具调用请求
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "calculate_sum") {
const { a, b } = request.params.arguments as { a: number; b: number };
return {
content: [{ type: "text", text: String(a + b) }],
};
}
throw new Error("Tool not found");
});
// 4. 使用 stdio 传输层启动服务
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main();
四、 常用生态与开源 MCP Server
目前官方和社区已经提供了丰富的开箱即用 MCP Server 列表(基于 smithery.ai 或 mcp-get):
Filesystem:安全的本地目录读写访问。 GitHub / Git:直接操作仓库、Issues、PR 和 Commit 历史。 Puppeteer / Fetch:无头浏览器爬虫与网络请求抓取。 PostgreSQL / SQLite:直接读写数据库表结构与数据。