13.1 MCP 协议概述

什么是 MCP

MCP (Model Context Protocol) 是 Anthropic 开发的开放协议,用于连接 AI 应用和数据源。它定义了一种标准化的方式,使 AI Assistant 能够访问外部工具、资源和提示词。

设计目标

MCP 的核心设计目标是:

  1. 统一接口 - 为所有数据源提供统一的访问方式
  2. 标准化 - 定义清晰的协议规范
  3. 可扩展 - 支持自定义数据源和工具
  4. 安全性 - 控制数据访问权限
  5. 灵活性 - 支持多种通信方式

MCP 的价值

传统方式的问题:

1
2
3
4
5
每个数据源需要单独集成
├── GitHub API → 自己实现
├── Filesystem → 自己实现
├── Database → 自己实现
└── Custom API → 自己实现

使用 MCP:

1
2
3
4
5
统一的客户端接口
├── GitHub MCP Server
├── Filesystem MCP Server
├── PostgreSQL MCP Server
└── Custom MCP Server

核心概念

1. MCP Client

MCP Client 是使用 MCP 协议的应用程序(如我们的 Agent):

1
2
3
4
5
6
7
8
9
10
11
import { Client } from "@modelcontextprotocol/sdk/client/index.js";

const client = new Client(
{
name: "my-agent",
version: "1.0.0"
},
{
capabilities: {}
}
);

2. MCP Server

MCP Server 提供工具、资源和提示词:

1
2
3
4
MCP Server
├── Tools (工具) - 可执行的函数
├── Resources (资源) - 数据访问
└── Prompts (提示词) - 预定义的提示模板

3. Transport

Transport 定义 Client 和 Server 之间的通信方式:

Stdio Transport(进程间通信):

1
2
3
4
5
6
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
});

SSE Transport(HTTP):

1
2
3
4
5
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";

const transport = new SSEClientTransport(
new URL("http://localhost:3000/sse")
);

MCP 的三大能力

Tools(工具)

可由 AI Agent 调用的函数,类似于我们的工具系统:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// MCP 工具定义
{
name: "read_file",
description: "读取文件内容",
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: "文件路径"
}
},
required: ["path"]
}
}

// 调用工具
const result = await client.callTool({
name: "read_file",
arguments: { path: "/tmp/test.txt" }
});

Resources(资源)

对数据源的结构化访问,如文件、数据库记录:

1
2
3
4
5
6
7
// 列出资源
const resources = await client.listResources();

// 读取资源内容
const content = await client.readResource({
uri: "file:///tmp/test.txt"
});

资源示例:

  • file:///path/to/file - 文件内容
  • postgresql://table/users - 数据库查询
  • github://repo/file - GitHub 仓库文件

Prompts(提示词)

预定义的提示模板,可填充参数:

1
2
3
4
5
6
7
8
9
10
11
// 列出提示词
const prompts = await client.listPrompts();

// 获取提示词内容
const promptContent = await client.getPrompt({
name: "code-review",
arguments: {
language: "typescript",
file: "agent.ts"
}
});

MCP 通信流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
┌──────────────┐                    ┌──────────────┐
│ MCP Client │ │ MCP Server │
│ (Agent) │ │ (外部服务) │
└──────┬───────┘ └──────┬───────┘
│ │
│ 1. connect() │
│ ───────────────────────────────→│
│ │
│ 2. listTools() │
│ ───────────────────────────────→│
│ │
│ 3. tools: [...] │
│ ←───────────────────────────────│
│ │
│ 4. callTool(name, args) │
│ ───────────────────────────────→│
│ │
│ 5. tool result │
│ ←───────────────────────────────│
│ │
│ 6. close() │
│ ───────────────────────────────→│

与现有工具系统的关系

MCP 与我们已有的工具系统是互补关系:

内置工具 vs MCP 工具

方面 内置工具 MCP 工具
位置 Agent 代码中 外部进程
语言 TypeScript 任意语言
更新 需要重新构建 独立更新
复杂度 简单 可复杂
范围 本地操作 外部服务

工具统一

通过适配器模式,MCP 工具可以无缝集成到现有工具系统:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// MCP 工具 → IToolPlugin 适配器
class MCPToolAdapter implements IToolPlugin {
readonly metadata: ToolMetadata;

constructor(serverName: string, mcpTool: MCPTool) {
this.metadata = {
name: `${serverName}:${mcpTool.name}`, // 命名空间
description: mcpTool.description,
category: "mcp",
parameters: convertParameters(mcpTool.inputSchema)
};
}

async execute(params: any): Promise<ToolResult> {
// 调用 MCP 服务器
return await mcpManager.callTool(this.metadata.name, params);
}
}

MCP 生态

官方 MCP Servers

Server 功能 安装命令
Filesystem 文件系统访问 npx @modelcontextprotocol/server-filesystem <path>
GitHub GitHub 仓库操作 npx @modelcontextprotocol/server-github
PostgreSQL PostgreSQL 数据库 npx @modelcontextprotocol/server-postgres
Brave Search 网页搜索 npx @modelcontextprotocol/server-brave-search
Puppeteer 网页自动化 npx @modelcontextprotocol/server-puppeteer

社区 MCP Servers

  • Google Drive - Google Drive 文件访问
  • Slack - Slack 消息和频道
  • AWS - AWS 服务管理
  • Kubernetes - K8s 集群管理

为什么使用 MCP

1. 无需重复造轮

1
2
3
4
5
6
7
8
传统方式:
- GitHub API → 自己实现认证、请求、解析
- Filesystem → 自己实现路径处理、权限检查
- Database → 自己实现连接池、查询构建

MCP 方式:
- 直接使用现成的 MCP Server
- 统一的接口,无需了解底层实现

2. 安全隔离

1
2
3
4
5
6
7
8
9
内置工具:
- 在 Agent 进程中执行
- 代码错误可能导致 Agent 崩溃
- 权限控制复杂

MCP 工具:
- 在独立进程中运行
- 崩溃不影响 Agent
- 沙箱环境,权限受限

3. 易于扩展

1
2
3
添加新功能:
- 内置工具 → 修改代码,重新构建
- MCP 工具 → 只需配置新 Server

配置示例

config.json 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"mcp": {
"enabled": true,
"servers": [
{
"name": "filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
"enabled": true
},
{
"name": "github",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxxxx"
},
"enabled": false
}
]
}
}

环境变量配置

1
2
3
4
5
6
7
8
# GitHub 访问令牌
export GITHUB_TOKEN="ghp_xxxxx"

# PostgreSQL 连接字符串
export POSTGRES_CONNECTION_STRING="postgresql://..."

# Brave Search API Key
export BRAVE_SEARCH_API_KEY="xxxx"

小结

本节介绍了 MCP 协议的基本概念:

  • MCP 的定义和设计目标
  • 核心概念(Client、Server、Transport)
  • 三大能力(Tools、Resources、Prompts)
  • 通信流程
  • 与现有工具系统的关系
  • MCP 生态系统

导航

上一篇: 12.5 搜索场景与最佳实践

下一篇: 13.2 MCP 服务器连接