演示:具体的mcp server如何配置,有mcp server和无mcp server的区别
🎯 本章目标 :理解 MCP(Model Context Protocol)协议的设计思想,学会开发 MCP Server 暴露自定义工具,理解 MCP 如何解决 N×M 工具集成困境。
N×M 困境:工具集成的痛
假设你有:
3 个大模型 :ChatGPT、Claude、本地 LlaMA
5 个工具 :天气查询、数据库、邮件、文件操作、搜索引擎
传统方式:每个模型 × 每个工具 = 15 套集成代码 。
graph LR
subgraph 没有MCP
L1[LLM1] -.-> T1[工具1]
L1 -.-> T2[工具2]
L1 -.-> T3[工具3]
L2[LLM2] -.-> T1
L2 -.-> T2
L2 -.-> T3
L3[LLM3] -.-> T1
L3 -.-> T2
L3 -.-> T3
end
style L1 fill:#FFB6C1
style L2 fill:#FFB6C1
style L3 fill:#FFB6C1
❓ 痛点 :每接入一个新工具,就要为每个 LLM 各写一套集成代码。每换一个 LLM,又要为所有工具重写一遍。这就是 N×M 集成困境 。
MCP:AI 世界的 USB 接口
MCP(Model Context Protocol) = Anthropic 2024 年 11 月发布的开放标准协议
类比:USB 统一了电脑和外设的接口, MCP 统一了 LLM 和工具的接口。
graph LR
subgraph 有MCP
L1[LLM1] --> C[MCP Client]
L2[LLM2] --> C
L3[LLM3] --> C
C --> S[MCP Server]
S --> T1[工具1]
S --> T2[工具2]
S --> T3[工具3]
S --> T4[工具4]
S --> T5[工具5]
end
style C fill:#90EE90
style S fill:#87CEEB
三大特性 :
✅ 统一协议 :Client-Server 架构,一次接入到处可用
✅ 动态发现 :Server 启动时 Client 自动发现其能力
✅ 一次开发 :MCP Server 可被所有支持 MCP 的 Client 使用
四大核心概念
概念
含义
类比
是否可执行
Resources
数据/知识容器
数据库 View
只读
Tools
可执行动作
API 操作
有副作用
Embeddings
语义检索接口
向量库
查询
Transports
通信层
USB / 蓝牙
底层
① Resources(资源)—— "数据容器"
Resources 是 MCP Server 向模型暴露的"数据对象接口",模型通过 URI 读取数据。
Python
复制 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from mcp.server.fastmcp import FastMCP
import json
mcp = FastMCP ( "hr-knowledge" )
@mcp . resource ( "employees://list" )
def list_employees () -> str :
"""返回员工列表(JSON 格式)"""
employees = [
{ "id" : 1 , "name" : "Alice" , "dept" : "Sales" },
{ "id" : 2 , "name" : "Bob" , "dept" : "R&D" },
]
return json . dumps ( employees , ensure_ascii = False )
@mcp . resource ( "employee:// {emp_id} " )
def get_employee ( emp_id : int ) -> str :
"""根据 ID 获取员工详情"""
return json . dumps ({ "id" : emp_id , "name" : "Alice" , "credit" : 720 })
类比:数据库中的 View(视图) ,模型通过 URI 直接读取数据。Resources 是只读的 。
Tool 是 MCP Server 对外暴露的"可执行动作",模型通过调用 Tool 完成任务。Tools 有副作用 (会修改状态)。
Plain Text
复制 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 @mcp . tool ()
def add_employee ( name : str , dept : str ) -> str :
"""新增员工
Args:
name: 员工姓名
dept: 部门名称
"""
new_emp = { "id" : 999 , "name" : name , "dept" : dept }
return json . dumps ({ "ok" : True , "employee" : new_emp }, ensure_ascii = False )
@mcp . tool ()
def calculate ( expression : str ) -> str :
"""计算数学表达式"""
try :
result = eval ( expression , { "__builtins__" : {}}, {})
return f "计算结果: { result } "
except Exception as e :
return f "计算错误: { e } "
③ Transports(传输层)—— "通信电缆"
传输方式
适用场景
特点
stdio
本地 Agent、IDE 集成
最简单,进程内通信
HTTP/S
云端部署、远程调用
跨网络,需处理认证
WebSocket
实时双向通信
支持流式响应
完整 MCP Server 代码
Python
复制 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 import json
from datetime import datetime
from mcp.server.fastmcp import FastMCP
# ========== 1. 创建 MCP Server ==========
mcp = FastMCP ( "employee-management" )
# 模拟数据库
database = {
"employees" : [
{ "id" : 1 , "name" : "张三" , "dept" : "技术部" , "salary" : 25000 },
{ "id" : 2 , "name" : "李四" , "dept" : "产品部" , "salary" : 22000 },
{ "id" : 3 , "name" : "王五" , "dept" : "技术部" , "salary" : 28000 },
{ "id" : 4 , "name" : "赵六" , "dept" : "销售部" , "salary" : 20000 },
]
}
# ========== 2. 注册 Resources(只读) ==========
@mcp . resource ( "employees://list" )
def list_all_employees () -> str :
"""获取所有员工列表"""
return json . dumps ( database [ "employees" ], ensure_ascii = False , indent = 2 )
@mcp . resource ( "stats://summary" )
def get_stats () -> str :
"""获取员工统计摘要"""
total = len ( database [ "employees" ])
avg_salary = sum ( e [ "salary" ] for e in database [ "employees" ]) / total
return json . dumps (
{
"total_employees" : total ,
"average_salary" : avg_salary ,
"updated_at" : datetime . now () . isoformat (),
},
ensure_ascii = False ,
)
# ========== 3. 注册 Tools(可执行) ==========
@mcp . tool ()
def add_employee ( name : str , dept : str , salary : int ) -> str :
"""添加新员工
Args:
name: 员工姓名
dept: 部门名称
salary: 月薪
"""
new_id = max ( e [ "id" ] for e in database [ "employees" ]) + 1
new_emp = { "id" : new_id , "name" : name , "dept" : dept , "salary" : salary }
database [ "employees" ] . append ( new_emp )
return json . dumps ({ "success" : True , "employee" : new_emp }, ensure_ascii = False )
@mcp . tool ()
def calculate_dept_budget ( dept : str ) -> str :
"""计算部门薪资预算
Args:
dept: 部门名称
"""
dept_employees = [ e for e in database [ "employees" ] if e [ "dept" ] == dept ]
total_salary = sum ( e [ "salary" ] for e in dept_employees )
return json . dumps (
{
"department" : dept ,
"employee_count" : len ( dept_employees ),
"total_monthly_salary" : total_salary ,
"annual_budget" : total_salary * 12 ,
},
ensure_ascii = False ,
)
# ========== 4. 启动 Server ==========
if __name__ == "__main__" :
# 默认 stdio 传输(本地)
mcp . run ( transport = "stdio" )
# 生产环境用 HTTP:
# mcp.run(transport="streamable-http", host="0.0.0.0", port=8080)
将 MCP Server 接入 Agent
MCP Server 写好之后,任何支持 MCP 的 Agent 客户端(Claude Desktop、Cursor、LobeChat)都能直接接入。
Plain Text
复制 {
"mcpServers" : {
"employee-management" : {
"command" : "python" ,
"args" : [ "/path/to/05_mcp_server.py" ]
}
}
}
在 LangGraph Agent 中使用:
Python
复制 from langchain_mcp import MCPToolkit
from langgraph.prebuilt import create_react_agent
# 连接 MCP Server
toolkit = MCPToolkit . from_server ( "employee-management" , "stdio://localhost" )
# 创建 Agent(自动获得 MCP Server 暴露的所有工具)
agent = create_react_agent ( model = "gpt-4o" , tools = toolkit . get_tools ())
# 使用
result = agent . invoke ({ "messages" : [( "user" , "技术部一共多少薪资预算?" )]})
MCP 适用场景
场景
MCP 怎么用
企业知识库问答
FAQ/政策文档向量库暴露成 Resource
IDE 编程助手
代码符号索引为 Resource,重构为 Tool
运营报表自动化
Sheet 操作 + 图表生成 + IM 通知全封装为 Tool
设备监控
IoT 数据为 Resource,调速/告警为 Tool
📝 MCP 的价值 :一次开发,所有支持 MCP 的 Agent 都能用。截至 2025 年中,已有 1000+ 社区贡献的 MCP Server,从 GitHub 到 Slack 到数据库全都有。MCP 正在成为 AI 工具生态的"事实标准"。
常用mcp server
数据类:爬虫/数据库存储
文件系统类:
mcp收录网站:
https://mcp.so/
https://mcphub.dev/
https://smithery.ai/
演示:使用mcp server进行git代码提交