Lesson 3: MCP 协议基础
学习目标
- 理解 Model Context Protocol (MCP) 的设计理念
- 掌握 MCP 的核心概念:Tools, Resources, Prompts
- 了解 MCP 如何让 Agent 与外部世界交互
为什么需要 MCP?
在 MCP 出现之前,每个 AI 应用都要自己实现与外部工具的集成。你想让 Claude 读文件?写一个 function call。想让它查数据库?再写一个。想让它发邮件?又一个。
这导致了 N×M 的集成问题:N 个 AI 模型 × M 个工具 = N×M 种集成方式。
MCP 解决这个问题的方式跟 USB 解决外设连接问题一样——定义一个标准协议。任何工具只要实现 MCP Server 接口,就能被任何支持 MCP 的 AI 客户端调用。
之前: Claude → 自定义代码 → Gmail API
Claude → 自定义代码 → Slack API
Claude → 自定义代码 → 数据库
MCP: Claude → MCP Client → MCP Server (Gmail)
→ MCP Server (Slack)
→ MCP Server (Database)MCP 架构
MCP 是一个 Client-Server 协议:
- MCP Host: 运行 AI 模型的应用(如 Claude Desktop, VS Code + Claude)
- MCP Client: Host 中负责与 Server 通信的模块
- MCP Server: 提供工具/资源的独立进程
通信方式:
- stdio: Server 作为子进程,通过标准输入/输出通信(最常用)
- SSE (Server-Sent Events): 通过 HTTP 通信,适合远程 Server
三大核心概念
1. Tools(工具)
Tools 是 Agent 的"双手"——可以执行的操作。
// MCP Server 定义一个 Tool
const sendEmailTool = {
name: 'send_email',
description: 'Send an email to a recipient',
inputSchema: {
type: 'object',
properties: {
to: { type: 'string', description: 'Recipient email' },
subject: { type: 'string', description: 'Email subject' },
body: { type: 'string', description: 'Email body' },
},
required: ['to', 'subject', 'body'],
},
}AI 看到这个 Tool 定义后,就知道什么时候该调用它。当用户说"给张三发一封会议确认邮件",AI 会自动:
- 决定需要使用
send_email工具 - 从上下文中提取参数
- 调用工具并将结果反馈给用户
2. Resources(资源)
Resources 是 Agent 的"眼睛"——可以读取的数据源。
// 暴露一个可读资源
const recentEmails = {
uri: 'email://inbox/recent',
name: 'Recent Emails',
description: 'Last 20 emails in inbox',
mimeType: 'application/json',
}与 Tools 的区别:Resources 是读取数据,Tools 是执行操作。Resources 让 AI 能"看到"外部数据而不修改它。
3. Prompts(提示模板)
Prompts 是预定义的交互模板,帮助用户高效使用 Agent。
const analyzeEmailPrompt = {
name: 'analyze_email',
description: 'Analyze an email and suggest a reply',
arguments: [
{ name: 'emailId', description: 'ID of the email to analyze', required: true },
],
}MCP Server 生命周期
1. 初始化
Client → Server: initialize (发送能力声明)
Server → Client: 返回支持的 Tools, Resources, Prompts
2. 正常运行
Client → Server: tools/call (调用工具)
Client → Server: resources/read (读取资源)
Server → Client: 返回结果
3. 关闭
Client → Server: shutdown安全考虑
MCP Server 运行在用户的机器上,拥有真实的系统权限。这意味着:
- 最小权限原则: Server 只应访问必要的资源
- 用户确认: 敏感操作(发邮件、删文件)应该让用户确认
- 输入验证: 永远不要信任 AI 传来的参数,做严格验证
- 审计日志: 记录所有工具调用,方便排查问题
当前 MCP 生态
已有的官方和社区 MCP Server:
- 文件系统: 读写本地文件
- Git: 仓库操作
- 数据库: PostgreSQL, SQLite 查询
- 浏览器: Playwright 自动化
- Slack, GitHub, Google Drive: 常见 SaaS 集成
这个生态在快速增长。理解 MCP 就是理解 Agent 的"工具层"标准。
关键收获
- MCP 是 Agent 工具使用的标准协议,解决 N×M 集成问题
- 三大概念:Tools(操作)、Resources(数据)、Prompts(模板)
- Client-Server 架构,支持 stdio 和 SSE 两种通信
- 安全是第一优先级——最小权限、用户确认、输入验证