【斯坦福 AI 编程课 03】MCP 协议——AI Agent 的”万能接口”

# 【斯坦福 AI 编程课 03】MCP 协议——AI Agent 的"万能接口"

> CS146S: 现代软件开发学习笔记系列第三篇

上一篇我们解剖了 Coding Agent 的四大组件,最后提到了 MCP(Model Context Protocol)但没展开。今天我们来深入聊聊这个"万能接口"。

## 为什么需要 MCP?

在 MCP 出现之前,每个 AI Agent 都有自己的工具格式:

**Claude Code 的工具调用:**
```json
{
"name": "read_file",
"arguments": {"path": "data.csv"}
}
```

**Devin 的工具调用:**
```json
{
"tool": "file_read",
"params": {"file": "data.csv"}
}
```

**GPT 的工具调用:**
```json
{
"function": {
"name": "read_file",
"arguments": "{\"path\": \"data.csv\"}"
}
}
```

看出问题了吗?每个 Agent 都在"发明轮子"。

更糟糕的是:
- 你为 Claude 写的工具,Devin 用不了
- 你为 GPT 写的插件,Claude 不认识
- 每个 Agent 都要重新学习相同的工具

这就像每个手机都用不同的充电接口——USB-C 出现前的混乱时代。

## MCP:AI Agent 的 USB-C

MCP(Model Context Protocol)是一个开放标准,由 Anthropic 在 2024 年推出。

它的核心思想很简单:

**统一接口** + **插件生态** = **万能连接**

就像:
- USB-C 统一了充电接口
- HTTP 统一了网络通信
- JSON 统一了数据格式

MCP 要统一 AI Agent 和工具之间的通信。

## MCP 的架构

MCP 采用客户端-服务器架构:

```
┌─────────────┐
│ AI Agent │ (Claude, GPT, Devin...)
│ (Client) │
└──────┬──────┘
│ MCP Protocol

┌──────▼──────┐
│ MCP Server │ (工具提供者)
│ │
│ - 文件系统 │
│ - 数据库 │
│ - GitHub │
│ - Slack │
│ - ... │
└─────────────┘
```

### 角色 1:MCP Client(AI Agent)

任何 AI Agent 都可以实现 MCP Client:
- Claude Desktop
- Claude Code
- Cursor
- Windsurf
- 甚至你自己开发的 Agent

### 角色 2:MCP Server(工具提供者)

MCP Server 提供具体的能力:
- **文件系统 Server**:读写文件
- **GitHub Server**:管理代码仓库
- **数据库 Server**:查询数据库
- **Slack Server**:发送消息
- **浏览器 Server**:自动化浏览

## MCP 的三大核心概念

### 1. Resources(资源)

静态数据,Agent 可以读取:

```json
{
"uri": "file:///project/README.md",
"name": "README",
"mimeType": "text/markdown"
}
```

例子:
- 文件内容
- 数据库记录
- API 响应
- 配置信息

### 2. Tools(工具)

可执行的操作,Agent 可以调用:

```json
{
"name": "read_file",
"description": "读取文件内容",
"inputSchema": {
"type": "object",
"properties": {
"path": {"type": "string"}
},
"required": ["path"]
}
}
```

例子:
- 执行命令
- 发送邮件
- 创建文件
- 调用 API

### 3. Prompts(提示词模板)

预定义的提示词,Agent 可以使用:

```json
{
"name": "code_review",
"description": "代码审查提示词",
"arguments": [
{"name": "file", "required": true}
]
}
```

例子:
- 代码审查模板
- 文档生成模板
- 测试用例模板

## 实战:创建一个 MCP Server

让我们创建一个简单的 MCP Server,提供"读取文件"功能:

### 1. 安装依赖

```bash
npm install @modelcontextprotocol/sdk
```

### 2. 编写 Server

```typescript
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server({
name: 'filesystem-server',
version: '1.0.0'
}, {
capabilities: {
tools: {}
}
});

// 定义工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [{
name: 'read_file',
description: '读取文件内容',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string' }
},
required: ['path']
}
}]
};
});

// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'read_file') {
const { path } = request.params.arguments;
const content = await fs.readFile(path, 'utf-8');
return {
content: [{ type: 'text', text: content }]
};
}
});

// 启动服务器
const transport = new StdioServerTransport();
await server.connect(transport);
```

### 3. 配置到 Claude Desktop

编辑 `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
"mcpServers": {
"filesystem": {
"command": "node",
"args": ["/path/to/server.js"]
}
}
}
```

### 4. 测试

重启 Claude Desktop,现在你可以说:

> "帮我读取 /project/README.md"

Claude 会自动调用你的 MCP Server!

## MCP 的优势

### 1. 一次开发,处处使用

你写的 MCP Server 可以被任何支持 MCP 的 Agent 使用:
- Claude Desktop ✅
- Claude Code ✅
- Cursor ✅
- Windsurf ✅
- 未来更多的 Agent ✅

### 2. 标准化生态

社区已经开发了数百个 MCP Server:
- **@modelcontextprotocol/server-filesystem** - 文件系统
- **@modelcontextprotocol/server-github** - GitHub 集成
- **@modelcontextprotocol/server-postgres** - PostgreSQL
- **@modelcontextprotocol/server-slack** - Slack 消息
- **@modelcontextprotocol/server-puppeteer** - 浏览器自动化

直接安装使用,不用重复开发!

### 3. 安全可控

MCP 的设计考虑了安全性:
- 每个 Server 都是独立进程,隔离运行
- Agent 只能调用已授权的工具
- 敏感操作需要用户确认
- 所有调用都有日志记录

### 4. 可扩展

MCP 的扩展性极强:
- 可以连接任何数据源
- 可以调用任何 API
- 可以执行任何命令(在安全限制下)
- 可以组合多个 Server 形成工作流

## MCP vs 传统工具调用

| 特性 | 传统工具调用 | MCP |
|------|------------|-----|
| 标准化 | ❌ 每个Agent不同 | ✅ 统一标准 |
| 生态共享 | ❌ 各自开发 | ✅ 社区共享 |
| 跨Agent使用 | ❌ 不兼容 | ✅ 即插即用 |
| 开发成本 | 🔴 高(重复造轮子) | 🟢 低(复用生态) |
| 维护成本 | 🔴 高(多处维护) | 🟢 低(统一维护) |

## 实际应用案例

### 案例1:GitHub 集成

使用官方 GitHub MCP Server:

```bash
npm install -g @modelcontextprotocol/server-github
```

配置到 Claude Desktop:

```json
{
"mcpServers": {
"github": {
"command": "mcp-server-github",
"env": {
"GITHUB_TOKEN": "your-token"
}
}
}
}
```

现在你可以说:

> "帮我创建一个新 issue,标题是'修复登录bug',内容是..."

Claude 会自动调用 GitHub MCP Server 创建 issue!

### 案例2:数据库查询

使用 PostgreSQL MCP Server:

```json
{
"mcpServers": {
"postgres": {
"command": "mcp-server-postgres",
"args": ["postgresql://user:pass@localhost/db"]
}
}
}
```

现在你可以说:

> "查询最近一周的订单数据,按日期排序"

Claude 会自动:
1. 连接数据库
2. 执行 SQL 查询
3. 返回格式化结果

### 案例3:浏览器自动化

使用 Puppeteer MCP Server:

```json
{
"mcpServers": {
"puppeteer": {
"command": "mcp-server-puppeteer"
}
}
}
```

现在你可以说:

> "打开百度,搜索'AI Agent',截图保存"

Claude 会自动:
1. 启动浏览器
2. 打开百度
3. 输入搜索词
4. 截图保存

## MCP 的未来

MCP 还在快速发展中,未来可能会支持:

- **流式响应**:工具可以流式返回数据
- **双向通信**:Server 可以主动推送消息
- **可视化**:支持图表、图像等富媒体
- **协作**:多个 Agent 共享同一个 MCP Server

## 总结

MCP 是 AI Agent 领域的重要突破:

1. **统一标准**:解决了工具调用的碎片化问题
2. **生态共享**:一次开发,处处使用
3. **降低成本**:不用为每个 Agent 重复开发
4. **加速创新**:专注业务逻辑,不重复造轮子

就像 USB-C 统一了充电接口,MCP 正在统一 AI Agent 的工具接口。

## 下期预告

下一篇我们来聊聊 **上下文管理**——Agent 如何"记住"之前做的事,以及如何处理超长对话。

---

**参考资料**:
- [MCP 官方文档](https://modelcontextprotocol.io/)
- [Anthropic MCP 公告](https://www.anthropic.com/news/model-context-protocol)
- [Claude Desktop MCP 配置](https://docs.anthropic.com/claude/docs/mcp)
- [Awesome MCP Servers](https://github.com/punkpeye/awesome-mcp-servers)

---

*这是斯坦福 CS146S 课程学习笔记系列的第三篇。上一篇:[从"会话"到"会做"——Coding Agent 解剖](https://delucia.cn/3254/2026-03-18/)*

Views: 0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注