什么是MCP
MCP(Model Context Protocol)是由Anthropic提出的开放协议,旨在标准化AI模型与外部工具、数据源的连接方式。
💡 核心价值
- 统一接口:一套API连接多种工具
- 可扩展:轻松添加新工具支持
- 安全可控:明确的权限边界
- 开源生态:社区驱动的工具库
架构设计
Host(宿主)
运行AI模型的应用,如Claude Desktop
Client(客户端)
协议实现,连接Host与Server
Server(服务端)
提供工具、资源、提示词
通信流程
MCP通信
Host ←→ Client ←→ Server
│ │ │
│ 初始化连接 │
│ ──────────────→ │
│ │ 返回能力列表
│ ←────────────── │
│ │ │
│ 调用工具 │
│ ──────────────→ │
│ │ 返回结果
│ ←────────────── │
核心概念
| 组件 | 说明 | 示例 |
|---|---|---|
| Tools | 可调用的函数 | 文件读写、API调用 |
| Resources | 可访问的数据 | 文件内容、数据库记录 |
| Prompts | 预定义提示词 | 代码审查模板 |
快速开始
Python MCP Server
from mcp.server import Server
from mcp.types import Tool, TextContent
server = Server("example-server")
@server.list_tools()
async def list_tools():
return [
Tool(
name="echo",
description="返回输入文本",
inputSchema={
"type": "object",
"properties": {
"message": {"type": "string"}
}
}
)
]
@server.call_tool()
async def call_tool(name, arguments):
if name == "echo":
return [TextContent(
type="text",
text=arguments["message"]
)]