ANALYSIS
概述
MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 于 2024 年底开源的协议标准,旨在为 AI 模型与外部数据源、工具之间建立标准化通信接口。
在 MCP 出现之前,每个 AI 应用都需要为不同的数据源和工具单独开发适配代码,导致:
- 重复开发,资源浪费
- 工具无法复用,生态碎片化
- 用户难以灵活组合不同工具
MCP 的出现解决了这些问题——它就像 AI 领域的 USB 接口标准,让不同的 AI 工具和数据源可以即插即用。
为什么需要 MCP
传统方案的痛点
| 痛点 | 说明 | 后果 |
|---|---|---|
| 重复开发 | 每个应用都要适配相同的数据源 | 开发成本高 |
| 生态封闭 | 工具只能被特定应用使用 | 用户被锁定 |
| 维护困难 | 多个版本需要同步更新 | 维护成本高 |
| 互操作性差 | 数据源之间无法直接通信 | 信息孤岛 |
MCP 的解决方案
| 改进 | 说明 |
|---|---|
| 标准化 | 统一协议,一次实现多处可用 |
| 可插拔 | 工具可以随时添加 / 移除 |
| 可发现 | 主机自动发现可用工具 |
| 安全可控 | 协议层统一鉴权和权限控制 |
核心概念与架构
整体架构
PRTCL // PLAINTEXT
┌──────────────────────────────────────────────────────────────┐│ MCP 生态系统 │├──────────────────────────────────────────────────────────────┤│ ││ ┌──────────────────────────────────────────────────────┐ ││ │ 主机应用 │ ││ │ (Claude Desktop / Zed / Cursor / Continue / ... ) │ ││ └──────────────────────────────────────────────────────┘ ││ │ ││ ┌─────────────────┼─────────────────┐ ││ ▼ ▼ ▼ ││ ┌────────────┐ ┌────────────┐ ┌────────────┐ ││ │ MCP │ │ MCP │ │ MCP │ ││ │ 客户端 1 │ │ 客户端 2 │ │ 客户端 N │ ││ │ ( 文件系统 ) │ │ ( 数据库 ) │ │ ( 搜索 ) │ ││ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘ ││ └─────────────────┼─────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────────────────────┐ ││ │ MCP 服务器 │ ││ │ ( 文件系统 / Git / Slack / 数据库 / ...) │ ││ └──────────────────────────────────────────────────────┘ ││ │└──────────────────────────────────────────────────────────────┘核心术语
| 术语 | 说明 | 类比 |
|---|---|---|
| Host(主机) | 运行 AI 应用并协调任务的程序 | 计算机 |
| Client(客户端) | 每个连接对应一个客户端,维护与服务器的 1:1 连接 | USB 控制器 |
| Server(服务器) | 提供特定能力的程序,暴露工具和资源 | USB 设备 |
| Transport(传输层) | 客户端与服务器的通信方式(stdio / HTTP) | USB 协议 |
四大核心原语
MCP 定义了四种核心能力抽象:
| 原语 | 说明 | AI 使用方式 |
|---|---|---|
| Resources(资源) | AI 可读取的结构化数据 | 主动获取信息 |
| Tools(工具) | AI 可调用的函数,执行后会返回结果 | 主动操作 |
| Prompts(提示) | 预定义的提示模板,可重复使用 | 模板复用 |
| Sampling(采样) | 服务器调用 AI(反向通信) | 服务器使用 AI |
Resources(资源)
资源是 AI 可以读取的结构化数据,属于被动获取。
资源类型
| 类型 | 说明 | 示例 |
|---|---|---|
| 文件资源 | 本地文件内容 | file:///path/to/file |
| 数据库资源 | 查询结果 | 数据库表内容 |
| API 资源 | API 响应数据 | 天气信息 |
| 配置资源 | 应用配置 | 环境变量 |
资源定义
PRTCL // TYPESCRIPT
// 服务器端定义资源const resources: Resource[] = [ { uri: "file:///home/user/documents/readme.md", name: "项目说明文档", description: "项目的详细说明和使用指南", mimeType: "text/markdown" }, { uri: "config:///app/settings", name: "应用设置", description: "当前应用的配置信息" }];资源订阅
AI 可以订阅资源变化:
PRTCL // JSON
// 订阅文件变化{ "method": "resources/subscribe", "params": { "uri": "file:///home/user/documents/project/tasks.md" }}Tools(工具)
工具是 AI 可以主动调用的函数,是 MCP 最核心的功能。
工具定义
PRTCL // TYPESCRIPT
const tools: Tool[] = [ { name: "filesystem_read", description: "读取本地文件内容,支持文本文件", inputSchema: { type: "object", properties: { path: { type: "string", description: "文件路径" }, encoding: { type: "string", description: "文件编码,默认 utf-8", default: "utf-8" } }, required: ["path"] } }, { name: "filesystem_write", description: "写入内容到本地文件", inputSchema: { type: "object", properties: { path: { type: "string", description: "文件路径" }, content: { type: "string", description: "要写入的内容" } }, required: ["path", "content"] } }];工具调用流程
PRTCL // PLAINTEXT
用户:"帮我读取 ~/Documents/readme.md"
主机分析意图 → 需要文件读取 ↓发送工具调用请求{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "filesystem_read", "arguments": { "path": "/home/user/Documents/readme.md" } }} ↓MCP 服务器执行 ↓返回结果{ "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "# 项目说明
这是项目文档..." } ] }} ↓主机将结果注入上下文 ↓AI 生成最终回答工具调用示例
文件搜索工具:
PRTCL // JSON
{ "name": "filesystem_search", "description": "在指定目录中搜索文件", "arguments": { "directory": "/home/user/projects", "pattern": "*.md", "recursive": true }}代码执行工具:
PRTCL // JSON
{ "name": "code_execute", "description": "执行代码片段", "arguments": { "language": "python", "code": "print('Hello, MCP!')", "timeout": 30000 }}Prompts(提示模板)
预定义的提示模板,可以被主机和服务器调用。
提示模板定义
PRTCL // TYPESCRIPT
const prompts: Prompt[] = [ { name: "code-review", description: "代码审查模板", arguments: [ { name: "language", description: "编程语言", required: true } ], prompt: ` 请审查以下{language}代码,关注: 1. 代码质量和可读性 2. 潜在的性能问题 3. 安全漏洞 4. 是否有更好的实现方式
代码: ${code} ` }];提示模板使用
PRTCL // JSON
{ "method": "prompts/get", "params": { "name": "code-review", "arguments": { "language": "python" } }}Sampling(采样 / 反向调用)
Sampling 允许 MCP 服务器反向调用 AI,是高级功能。
使用场景
| 场景 | 说明 |
|---|---|
| 智能文件处理 | 服务器不确定如何处理文件,调用 AI 决策 |
| 自动分类 | 需要 AI 判断数据类别 |
| 内容生成 | 服务器需要生成文本内容 |
安全考虑
Sampling 涉及服务器调用 AI,需要严格的安全控制:
- 权限控制:服务器不能无限制调用 AI
- 速率限制:防止资源滥用
- 内容过滤:防止恶意诱导
官方 MCP 服务器
文件系统服务器
PRTCL // BASH
# 安装npm install -g @anthropic/mcp-server-filesystem
# 配置(Claude Desktop)# 添加到 ~/.config/claude-desktop.json{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-filesystem", "/path/to/allowed/directory"] } }}Git 服务器
PRTCL // JSON
{ "command": "npx", "args": ["-y", "@anthropic/mcp-server-git", "/path/to/repo"]}PostgreSQL 服务器
PRTCL // JSON
{ "command": "npx", "args": ["-y", "@anthropic/mcp-server-postgres", "--url", "postgresql://user:pass@localhost/db"]}Slack 服务器
PRTCL // JSON
{ "command": "npx", "args": ["-y", "@anthropic/mcp-server-slack"], "env": { "SLACK_BOT_TOKEN": "xoxb-...", "SLACK_TEAM_ID": "T..." }}开发 MCP 服务器
Python SDK
PRTCL // PYTHON
from mcp.server import MCPServerfrom mcp.types import Tool, TextContentfrom mcp.server.stdio import stdio_server
server = MCPServer(name="my-server")
@server.list_tools()def list_tools() -> list[Tool]: return [ Tool( name="get_weather", description="获取城市天气信息", inputSchema={ "type": "object", "properties": { "city": { "type": "string", "description": "城市名称" } }, "required": ["city"] } ) ]
@server.call_tool()async def call_tool(name: str, arguments: dict) -> list[TextContent]: if name == "get_weather": city = arguments["city"] weather = fetch_weather(city) return [TextContent(type="text", text=weather)] raise ValueError(f"Unknown tool: {name}")
async def main(): async with stdio_server() as (read, write): await server.run(read, write)
if __name__ == "__main__": import asyncio asyncio.run(main())TypeScript SDK
PRTCL // TYPESCRIPT
import { MCPServer } from "@modelcontextprotocol/sdk/server";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";import { Tool } from "@modelcontextprotocol/sdk/types";
const server = new MCPServer({ name: "my-mcp-server", version: "1.0.0"});
server.setRequestHandler("tools/list", async () => ({ tools: [ { name: "get_weather", description: "获取城市天气", inputSchema: { type: "object", properties: { city: { type: "string", description: "城市名称" } }, required: ["city"] } } ]}));
server.setRequestHandler("tools/call", async (request) => { const { name, arguments: args } = request.params;
if (name === "get_weather") { const weather = await fetchWeather(args.city); return { content: [{ type: "text", text: weather }] }; }
throw new Error(`Unknown tool: ${name}`);});
const transport = new StdioServerTransport();server.run(transport);主机应用支持
Claude Desktop
- 编辑配置文件:
~/.config/claude-desktop.json - 添加 MCP 服务器配置
- 重启 Claude Desktop
Zed
PRTCL // JSON
{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-filesystem", "/path"] } }}Cursor
通过设置 → MCP 配置添加服务器。
Continue(VS Code 插件)
PRTCL // JSON
{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@anthropic/mcp-server-filesystem"] } }}MCP vs 传统方案对比
| 维度 | MCP | Function Calling | 传统 API |
|---|---|---|---|
| 标准化 | 统一协议 | 各平台自定义 | 各平台自定义 |
| 工具发现 | 自动发现 | 手动注册 | 无 |
| 安全性 | 协议层统一鉴权 | 各应用自行实现 | 各应用自行实现 |
| 扩展性 | 一次实现,处处可用 | 受限于单一应用 | 受限于单一应用 |
| 生态 | 开放共享 | 封闭 | 封闭 |
| 连接方式 | 持久连接 | 按需调用 | 按需调用 |
| 类型安全 | JSON Schema | JSON Schema | 各自定义 |
常见问题
| 问题 | 解答 |
|---|---|
| MCP 和 Function Calling 哪个更好? | 两者互补,MCP 定义协议,Function Calling 使用协议 |
| 如何调试 MCP 服务器? | 使用 MCP 官方提供的 Inspector 工具 |
| MCP 支持哪些传输协议? | stdio(标准输入输出)和 HTTP+SSE |
| 如何确保 MCP 安全? | 使用权限控制、输入验证、速率限制 |
总结
MCP 是 AI 工具生态走向开放互联的重要里程碑。它让 AI 不再是信息孤岛,能够像人类一样灵活调用各种数字工具。掌握 MCP 是构建现代 AI 应用的关键技能。
关于我
| 项目 | 内容 |
|---|---|
| 编辑 | echowang |
| 来源 | echospace |
| 邮箱 | echohaoran@gmail.com |
| 简介 | AI 爱好者,专注于大语言模型应用与智能体开发,分享技术与实践心得 |
| 社交 | 欢迎交流讨论,共同成长 |
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.03.21
Auth_Verified: 2026.03.21
