Appearance
MCP开发者入门教程:Model Context Protocol完全指南
MCP(Model Context Protocol)是Anthropic于2024年11月推出的开放协议,旨在标准化AI模型与外部数据源、工具之间的连接方式。像USB-C统一硬件接口一样,为AI应用提供统一的能力接入标准。
一、MCP是什么?
产生背景
| 问题 | 说明 |
|---|---|
| 工具碎片化 | 每个AI应用都需要为不同数据源写定制集成代码 |
| 重复造轮子 | 文件系统、数据库、API等通用能力的集成被反复实现 |
| 生态割裂 | 不同AI助手之间的工具无法复用 |
| 安全难控 | 缺乏标准化的权限和安全模型 |
解决思路
- 像USB-C统一硬件接口一样,为AI应用提供统一的能力接入标准
- 让AI模型和外部工具通过标准化协议通信
- 实现「一次开发,处处可用」的工具生态
二、工作原理
架构概览
┌─────────────────────────────────────────────────────────────┐
│ AI 应用层 (Clients) │
│ Claude Desktop │ Cursor │ Claude Code │ 其他 AI 助手... │
└──────────────────────────┬──────────────────────────────────┘
│ MCP Protocol
┌──────────────────────────┴──────────────────────────────────┐
│ MCP 服务器层 (Servers) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 文件系统 │ │ GitHub │ │ 数据库 │ │ 自定义 │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────┘核心设计理念
| 理念 | 说明 |
|---|---|
| 协议优先 | 通过标准化协议解耦AI应用与工具实现 |
| 双向通信 | 不仅AI调用工具,工具也可请求AI能力(Sampling) |
| 安全可控 | 内置权限模型,细粒度控制资源访问 |
| 即插即用 | MCP Server可以被任何MCP Client使用 |
传输层(Transports)
| 传输方式 | 适用场景 | 特点 |
|---|---|---|
| stdio | 本地进程通信 | 通过标准输入输出,适合本地工具 |
| SSE | 远程流式传输 | Server-Sent Events,适合实时通信 |
| HTTP | 远程REST调用 | 无状态请求,适合云部署 |
协议层
基于JSON-RPC 2.0构建,定义标准消息格式:
请求消息:
json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": "read_file", "arguments": {"path": "/path/to/file.txt"}}
}核心能力
| 能力 | 说明 | 示例 |
|---|---|---|
| Tools | 可执行函数 | 文件读写、API调用、代码执行 |
| Resources | 可读数据资源 | 文件内容、数据库记录、配置 |
| Prompts | 预定义提示模板 | 代码审查模板、分析模板 |
| Sampling | 请求AI生成内容 | Server请求Client完成LLM调用 |
三、实战案例
案例:天气查询MCP Server
python
# weather_server.py
from mcp.server import Server
from mcp.types import Tool, TextContent
import httpx
app = Server("weather-server")
@app.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="get_weather",
description="获取指定城市的天气信息",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name == "get_weather":
city = arguments["city"]
async with httpx.AsyncClient() as client:
response = await client.get(f"https://api.weather.com/v1/current?city={city}")
data = response.json()
return [TextContent(type="text", text=f"{city}当前天气:{data['temperature']}°C")]
raise ValueError(f"Unknown tool: {name}")配置Claude Desktop
json
// ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}官方文件系统Server
bash
npx -y @modelcontextprotocol/server-filesystem /path/to/allowed/directory支持的Tools:read_file、write_file、list_directory、create_directory、move_file、search_files、get_file_info
四、技术生态
官方SDK
| 语言 | 包名 | 成熟度 |
|---|---|---|
| Python | mcp | ⭐⭐⭐ 官方维护 |
| TypeScript | @modelcontextprotocol/sdk | ⭐⭐⭐ 官方维护 |
| Java | io.modelcontextprotocol | ⭐⭐ 社区维护 |
| Kotlin | io.modelcontextprotocol | ⭐⭐ 社区维护 |
| C# | ModelContextProtocol | ⭐⭐ 社区维护 |
官方Servers
| Server | 功能 |
|---|---|
| @modelcontextprotocol/server-filesystem | 文件系统操作 |
| @modelcontextprotocol/server-github | GitHub API集成 |
| @modelcontextprotocol/server-postgres | PostgreSQL数据库 |
| @modelcontextprotocol/server-sqlite | SQLite数据库 |
| @modelcontextprotocol/server-brave-search | Brave搜索引擎 |
| @modelcontextprotocol/server-fetch | HTTP请求 |
支持MCP的客户端
| 客户端 | 支持程度 |
|---|---|
| Claude Desktop | ⭐⭐⭐ 完整支持 |
| Claude Code | ⭐⭐⭐ 完整支持 |
| Cursor | ⭐⭐⭐ 完整支持 |
| Zed | ⭐⭐⭐ 完整支持 |
| Cline | ⭐⭐⭐ 完整支持 |
| OpenClaw | ⭐⭐⭐ 完整支持 |
五、最佳实践
Server开发规范
| 规范 | 说明 |
|---|---|
| 工具命名 | 动词_名词格式,如read_file、search_github |
| 参数设计 | 使用清晰参数名、提供完整JSON Schema、添加描述、标记必填 |
| 错误处理 | 抛出标准McpError |
安全配置
| 安全措施 | 说明 |
|---|---|
| 资源隔离 | 只允许访问指定目录 |
| 权限控制 | 严格限制访问范围 |
| 调试 | 使用MCP Inspector |
调试技巧
bash
# 安装Inspector
npm install -g @modelcontextprotocol/inspector
# 调试Server
mcp-inspector node ./server.js六、进阶主题
Sampling:Server调用AI
MCP支持双向通信,Server可以请求Client完成LLM调用。
Resources:暴露数据资源
python
@app.list_resources()
async def list_resources() -> list[Resource]:
return [Resource(uri="file:///config.json", name="配置文件", mimeType="application/json")]Prompts:预定义模板
python
@app.list_prompts()
async def list_prompts() -> list[Prompt]:
return [Prompt(name="code_review", description="代码审查模板")]七、常见问题
| 问题 | 回答 |
|---|---|
| MCP和API区别? | MCP提供动态工具发现、内置权限安全模型、支持双向通信、工具可被任何Client使用 |
| 如何发布Server? | 开发测试→发布到npm/pypi→提交到MCP Registry→编写文档 |
| 支持哪些传输? | stdio(本地)、SSE(远程流式)、HTTP(RESTful) |
| 安全性如何? | 资源访问可严格限制、支持OAuth授权、每个工具调用有明确权限边界 |
关键词:MCP开发, Model Context Protocol, MCP Server, JSON-RPC 2.0, stdio传输
