MCP (Model Context Protocol) 介绍与使用指南

MCP(Model Context Protocol)是 Anthropic 推出的开放标准协议,旨在让 AI 助手能够安全、便捷地连接各类外部数据源和工具。本文详细介绍 MCP 的核心概念、工作原理以及实际使用方法。

什么是 MCP

背景

当前 AI 助手虽然强大,但往往被困在”沙盒”里,无法直接访问你的文件、数据库、API 等外部资源。传统方案需要为每个 AI 工具编写定制化的集成代码,导致:

  • 碎片化:每个工具的集成方式都不同
  • 重复工作:类似的工具需要重复开发
  • 安全问题:缺乏统一的安全标准

MCP 的诞生就是为了解决这些问题。

定义

MCP(Model Context Protocol)是一种开放标准协议,它定义了 AI 助手(如 Claude)与外部工具、数据源之间的通信规范。

类比:

  • USB 是硬件设备的连接标准
  • MCP 是 AI 与外部世界的连接标准

核心价值

价值 说明
通用性 一次开发,处处运行
安全性 标准化权限控制,用户授权
可扩展性 轻松添加新的数据源和工具
双向通信 不仅获取数据,还能执行操作

MCP 工作原理

架构概览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
┌─────────────────────────────────────────────────────────────┐
│ Host (Claude Desktop) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MCP Client │ │
│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │
│ │ │ Server 1 │ │ Server 2 │ │ Server 3 │ │ │
│ │ │ (File) │ │ (Git) │ │ (DB) │ │ │
│ │ └───────────┘ └───────────┘ └───────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

│ MCP Protocol

┌─────────────────────────────────────────────────────────────┐
│ MCP Servers │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Files │ │ Git │ │ Postgres │ │
│ │ System │ │ Server │ │ Server │ │
│ └───────────┘ └───────────┘ └───────────┘ │
└─────────────────────────────────────────────────────────────┘

核心组件

1. MCP Host

运行 AI 助手的环境,如 Claude Desktop。它:

  • 管理多个 MCP Client
  • 处理用户交互
  • 控制权限和访问

2. MCP Client

嵌入在 Host 中的客户端,负责与对应的 Server 通信。

3. MCP Server

实现 MCP 协议的轻量级服务,每个 Server 提供一类能力:

  • 文件系统访问
  • Git 操作
  • 数据库查询
  • API 调用
  • 等等

4. Transport Layer

通信层,支持两种传输方式:

  • stdio:通过标准输入输出通信(本地服务)
  • HTTP + SSE:通过 HTTP + Server-Sent Events 通信(远程服务)

通信流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 1. 初始化握手
{
"jsonrpc": "2.0",
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {},
"sampling": {}
},
"clientInfo": {
"name": "claude-desktop",
"version": "1.0"
}
},
"id": 1
}

// 2. 工具调用
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/path/to/file.txt"
}
},
"id": 2
}

// 3. 响应
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "文件内容..."
}
]
},
"id": 2
}

MCP 核心概念

工具 (Tools)

工具是 MCP Server 暴露给 AI 的可执行操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "read_file",
"description": "读取文件内容",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "文件路径"
},
"limit": {
"type": "number",
"description": "最大读取字节数"
}
},
"required": ["path"]
}
}

资源 (Resources)

资源是 MCP Server 提供的数据访问:

1
2
3
4
5
6
{
"uri": "file:///path/to/config.json",
"name": "应用配置",
"mimeType": "application/json",
"description": "应用程序配置文件"
}

提示 (Prompts)

预定义的提示模板:

1
2
3
4
5
6
7
8
9
10
11
{
"name": "code_review",
"description": "代码审查提示",
"arguments": [
{
"name": "language",
"description": "编程语言"
}
],
"template": "请审查以下 ${language} 代码..."
}

采样 (Sampling)

允许 AI 主动请求采样(生成内容):

1
2
3
4
5
6
7
8
{
"method": "sampling/createMessage",
"params": {
"systemPrompt": "你是一个代码助手",
"messages": [...],
"maxTokens": 1000
}
}

MCP Server 生态

官方 MCP Servers

Server 功能 说明
filesystem 文件操作 读写本地文件
git Git 操作 查看提交历史、分支等
slack Slack 集成 发送消息、查看频道
postgres PostgreSQL 数据库查询
memory 持久记忆 跨会话记忆
браузер 浏览器控制 网页抓取

社区 Servers

Server 功能
sqlite SQLite 数据库
mongodb MongoDB
redis Redis
github GitHub API
jira Jira 集成
google-drive Google Drive

Claude Desktop 配置

安装 Claude Desktop

1
2
3
4
5
# macOS
brew install --cask claude

# 或从官网下载
# https://claude.ai/desktop

配置 MCP Servers

编辑 Claude Desktop 的配置文件:

1
2
3
4
5
# macOS
~/Library/Application Support/Claude/claude_desktop_config.json

# Windows
%APPDATA%\Claude\claude_desktop_config.json

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory"],
"env": {}
},
"git": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-git"],
"env": {}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
}
}
}
}

配置说明

字段 说明
command 启动命令
args 命令参数
env 环境变量
cwd 工作目录

常用 MCP Server 配置

文件系统

1
2
3
4
5
6
7
8
9
10
11
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": {
"ALLOWED_DIRECTORIES": "/Users/me/projects,/Users/me/docs"
}
}
}
}

Git

1
2
3
4
5
6
7
8
{
"mcpServers": {
"git": {
"command": "uvx",
"args": ["mcp-server-git", "--repository", "/path/to/repo"]
}
}
}

PostgreSQL

1
2
3
4
5
6
7
8
{
"mcpServers": {
"postgres": {
"command": "uvx",
"args": ["mcp-server-postgres", "--connection-string", "postgresql://user:pass@localhost:5432/db"]
}
}
}

开发自定义 MCP Server

项目结构

1
2
3
4
5
6
my-mcp-server/
├── src/
│ └── index.ts
├── package.json
├── tsconfig.json
└── README.md

基础代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { McpServer } from "@modelcontextprotocol/sdk/server";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
import { z } from "zod";

const server = new McpServer({
name: "my-mcp-server",
version: "1.0.0"
});

// 定义工具
server.tool(
"greet",
"打招呼",
{
name: z.string().describe("姓名"),
language: z.enum(["zh", "en"]).default("zh")
},
async ({ name, language }) => {
const greeting = language === "zh"
? `你好,${name}!`
: `Hello, ${name}!`;
return {
content: [{ type: "text", text: greeting }]
};
}
);

// 启动服务
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}

main();

使用 SDK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { McpServer } from "@modelcontextprotocol/sdk/server";
import { CallToolResult } from "@modelcontextprotocol/sdk/types";

// 创建服务器
const server = new McpServer({
name: "example-server",
version: "1.0.0"
});

// 注册工具
server.setRequestHandler(
"tools/list",
async () => ({
tools: [
{
name: "my_tool",
description: "我的工具",
inputSchema: {
type: "object",
properties: {
param: { type: "string" }
}
}
}
]
})
);

server.setRequestHandler(
"tools/call",
async (request): Promise<CallToolResult> => {
const { name, arguments: args } = request.params;

if (name === "my_tool") {
// 执行工具逻辑
return {
content: [{ type: "text", text: `Result: ${args.param}` }]
};
}

throw new Error(`Unknown tool: ${name}`);
}
);

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "my-mcp-server",
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^0.5.0",
"zod": "^3.22.0"
},
"devDependencies": {
"typescript": "^5.3.0"
}
}

TypeScript 配置

1
2
3
4
5
6
7
8
9
10
11
12
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}

实际应用场景

场景 1:智能代码助手

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
},
"git": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-git"]
},
"github": {
"command": "npx",
"args": ["-y", "mcp-server-github"],
"env": {
"GITHUB_TOKEN": "your-token"
}
}
}
}

Claude 可以:

  • 查看项目文件结构
  • 读取代码文件
  • 查看 Git 历史
  • 操作 GitHub Issues/PR

场景 2:数据库查询助手

1
2
3
4
5
6
7
8
9
10
11
{
"mcpServers": {
"postgres": {
"command": "uvx",
"args": ["mcp-server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/production"
}
}
}
}

Claude 可以:

  • 查询数据
  • 分析数据
  • 生成报告
  • 执行 SQL

场景 3:个人知识库

1
2
3
4
5
6
7
8
9
10
11
12
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/notes"]
},
"memory": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"]
}
}
}

Claude 可以:

  • 搜索笔记
  • 创建记忆
  • 跨会话记忆

安全考虑

权限控制

MCP 提供细粒度的权限控制:

1
2
3
4
5
6
7
8
9
10
11
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": {
"ALLOWED_DIRECTORIES": "/specific/path/only"
}
}
}
}

最佳实践

  1. 最小权限:只允许访问必要的目录和资源
  2. 环境变量:敏感信息使用环境变量,不要硬编码
  3. 定期审查:定期检查 MCP Server 配置
  4. 版本更新:保持 MCP SDK 更新以获得安全修复

信任原则

1
用户授权 → 明确范围 → 最小必要 → 可审计

常见问题

Q: MCP 和 API 有什么区别?

方面 MCP API
用途 AI 工具连接 应用间通信
特点 标准化、双向、AI 感知 通常单向、需要自己处理
交互 AI 可主动调用 通常被动响应

Q: 支持哪些编程语言?

MCP 协议是语言无关的,但官方 SDK 主要支持:

  • TypeScript/JavaScript
  • Python

Q: 如何调试 MCP Server?

1
2
3
4
5
6
# 查看 Claude 日志
# macOS
~/Library/Logs/Claude/

# 启用调试模式
# 在 Claude Desktop 设置中开启

相关资源

官方资源

社区资源

学习资源

总结

MCP 代表着 AI 与外部世界交互的新范式:

特点 说明
标准化 统一的协议,通用性强
安全性 用户授权,权限控制
可扩展 轻松添加新工具和数据源
双向通信 不仅读取,还能操作

价值总结

  • 开发者:一次开发,处处运行
  • 用户:更强大的 AI 助手能力
  • 生态:丰富的 MCP Servers 选择

MCP 正在成为 AI 工具集成的事实标准,推荐尝试配置体验。