Skip to content

MCP开发者入门教程:Model Context Protocol完全指南

2026年4月27日

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

语言包名成熟度
Pythonmcp⭐⭐⭐ 官方维护
TypeScript@modelcontextprotocol/sdk⭐⭐⭐ 官方维护
Javaio.modelcontextprotocol⭐⭐ 社区维护
Kotlinio.modelcontextprotocol⭐⭐ 社区维护
C#ModelContextProtocol⭐⭐ 社区维护

官方Servers

Server功能
@modelcontextprotocol/server-filesystem文件系统操作
@modelcontextprotocol/server-githubGitHub API集成
@modelcontextprotocol/server-postgresPostgreSQL数据库
@modelcontextprotocol/server-sqliteSQLite数据库
@modelcontextprotocol/server-brave-searchBrave搜索引擎
@modelcontextprotocol/server-fetchHTTP请求

支持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传输

不要孤军奋战啦!

加入微信群一起学习交流 AI

与大神一起使用 OpenClaw、Hermes、Claude Code、Seedance 2.0、GPT-Image-2 等

微信公众号

扫码关注微信公众号
私信 "加群",将自动获取微信群二维码

探索 AI 世界,掌握智能未来