MCP实战进阶:集成DeepSeek模型与MCP的天气信息助手
今天,我们将更进一步,将DeepSeek大模型集成到MCP客户端中,打造一个真正智能的天气助手。DeepSeek与MCP的结合优势将DeepSeek等大模型与MCP结合,能够带来以下优势:自然语言理解:用户可以用自然语言提问,无需记忆特定命令格式上下文感知:模型可以记住对话历史,提供连贯的体验智能推理:根据用户需求自动选择合适的工具和参数信息整合:将工具返回的原始数据转化为易于理解的格式
前言
今天,我们将更进一步,将DeepSeek大模型集成到MCP客户端中,打造一个真正智能的天气助手。
DeepSeek与MCP的结合优势
将DeepSeek等大模型与MCP结合,能够带来以下优势:
- 自然语言理解:用户可以用自然语言提问,无需记忆特定命令格式
- 上下文感知:模型可以记住对话历史,提供连贯的体验
- 智能推理:根据用户需求自动选择合适的工具和参数
- 信息整合:将工具返回的原始数据转化为易于理解的格式
简而言之,这种结合让工具调用变得更加人性化和智能化。
DeepSeek MCP客户端实现
架构概览
新实现的DeepSeek MCP客户端采用模块化设计,包含以下核心组件:
┌─────────────┐ 查询 ┌──────────────┐ 工具列表 ┌──────────────┐
│ │────────────►│ │◄──────────────│ │
│ 用户 │ │ MCP 客户端 │ │ MCP 服务器 │
│ │◄────────────│ (DeepSeek) │──────────────►│ (天气工具) │
└─────────────┘ 响应 └──────────────┘ 执行工具 └──────────────┘
│
│ API调用
▼
┌─────────────┐
│ │
│ DeepSeek API│
│ │
└─────────────┘
核心组件详解
1. 配置管理 (Configuration)
该组件负责管理环境变量和API配置:
class Configuration:
"""配置管理类,负责管理和验证环境变量"""
def__init__(self) -> None:
"""初始化配置并加载环境变量"""
self.load_env()
self._validate_env()
@property
defapi_key(self) -> str:
"""获取 DeepSeek API 密钥"""
return os.getenv("DEEPSEEK_API_KEY", "")
@property
defbase_url(self) -> str:
"""获取 DeepSeek API 基础 URL"""
return os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
@property
defmodel(self) -> str:
"""获取 DeepSeek 模型名称"""
return os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
2. 工具定义 (Tool)
将MCP工具转换为DeepSeek API可以识别的格式:
class Tool:
"""MCP 工具类,表示一个具有属性的工具"""
def__init__(self, name: str, description: str, input_schema: Dict[str, Any]) -> None:
self.name = name
self.description = description
self.input_schema = input_schema
defto_openai_format(self) -> Dict[str, Any]:
"""将工具转换为 OpenAI API 格式"""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.input_schema
}
}
3. 服务器管理 (MCPServer)
负责MCP服务器的连接和工具调用:
class MCPServer:
"""MCP 服务器管理类,处理服务器连接和工具执行"""
asyncdefinitialize(self) -> None:
"""初始化服务器连接,包含重试机制"""
# 服务器连接逻辑...
asyncdeflist_tools(self) -> List[Tool]:
"""获取服务器提供的可用工具列表"""
# 工具列表获取逻辑...
asyncdefexecute_tool(
self,
tool_name: str,
arguments: Dict[str, Any],
retries: int = 2,
delay: float = 1.0
) -> Any:
"""执行工具,包含重试机制"""
# 工具执行逻辑...
4. 客户端核心 (MCPClient)
集成DeepSeek API和MCP服务器的核心组件:
class MCPClient:
"""MCP 客户端实现,集成了 DeepSeek API"""
def__init__(self, config: Configuration) -> None:
self.config = config
self.server: Optional[MCPServer] = None
self.client = OpenAI(
api_key=config.api_key,
base_url=config.base_url
)
asyncdefprocess_query(self, query: str) -> str:
"""处理用户查询,集成工具调用"""
# 查询处理逻辑...
asyncdefchat_loop(self) -> None:
"""运行交互式聊天循环"""
# 聊天循环逻辑...

系统提示词设计
为了让DeepSeek模型更好地理解天气工具的功能和使用方法,我们设计了专门的系统提示词:
system_prompt = (
"You are a helpful assistant specializing in weather information.\n"
"You have access to the MCP Weather Server tool with the following functions:\n"
"- get_weather_warning(city_id=None, latitude=None, longitude=None): Retrieves weather disaster warnings for a specified city ID or coordinates.\n"
"- get_daily_forecast(city_id=None, latitude=None, longitude=None): Retrieves the multi-day weather forecast for a specified city ID or coordinates.\n"
"\n"
"Core Instructions:\n"
"1. **Carefully analyze the user's request**: Understand all components of the user's query. Determine if the user needs weather warning information, weather forecast information, or both.\n"
"2. **Identify Information Needs**:\n"
" * If the user only asks for warnings (e.g., \"Are there any warnings in Beijing?\"), only use `get_weather_warning`.\n"
" * If the user only asks for the forecast (e.g., \"What's the weather like in Beijing tomorrow?\"), only use `get_daily_forecast`.\n"
" * **If the user's question includes multiple aspects**, such as asking about **warning status** and also asking **if it's suitable for a certain activity** (which implies a query about future weather, like \"Have there been high temperature warnings in Beijing in the last week? Is it suitable for outdoor activities?\"), you need to **call both tools sequentially**.\n"
"3. **Call Tools as Needed**:\n"
" * **Prioritize getting warning information**: If warning information is needed, first call `get_weather_warning`.\n"
" * **Get the weather forecast**: If the user mentions a specific time period (e.g., \"weekend\", \"next three days\", \"next week\") or asks about activity suitability (which typically concerns the next few days), call `get_daily_forecast` to get the forecast for the corresponding period. For vague phrases like \"last week\" or \"recently\", interpret it as asking about *current* conditions and the *upcoming* few days (covered by the forecast). For questions like \"Is it suitable for outdoor activities?\", you should get the forecast for at least the next 2-3 days (e.g., today, tomorrow, the day after tomorrow, or the upcoming weekend) to support your judgment.\n"
" * **Ensure tool call order**: When multiple tools need to be called, they should be called in a logical sequence. For example, first get the warning, then get the forecast. Wait for one tool to finish executing before deciding whether to call the next tool or generate a response.\n"
"4. **Information Integration and Response**:\n"
" * After obtaining all necessary information (warning, forecast), you **must synthesize and analyze this information**.\n"
" * **Completely answer the user's question**: Ensure you answer all parts of the user's query.\n"
" * **Provide advice**: If the user asks about activity suitability, based on the retrieved warning status and forecast information (temperature, weather condition - clear/rainy, wind strength, etc.), provide a clear, data-supported recommendation (e.g., \"Currently there are no high temperature warnings, but it's expected to rain this weekend, so it's not very suitable for outdoor activities,\" or \"It will be sunny for the next few days with no warnings, suitable for outdoor activities.\").\n"
"5. **Tool Usage Details**:\n"
" * When using the tools, retain the full context of the user's original question.\n"
" * Unless explicitly requested by the user, do not insert specific times of day (e.g., \"3 PM\") into the search query or your response.\n"
" * When city information is needed, if the user provides a city name (e.g., \"Beijing\"), use the corresponding `city_id` (e.g., Beijing's city_id might be '101010100').\n"
)
这个系统提示词明确告诉模型:
- \1. 它是一个天气信息专家
- \2. 它有哪些工具可以使用
- \3. 何时应该使用这些工具
工具调用流程
当用户提出天气相关问题时,整个系统的工作流程如下:
- \1. 用户输入处理:接收用户的自然语言查询
- \2. 模型分析:DeepSeek模型分析查询内容,决定是否需要调用工具
- \3. 工具选择:模型选择合适的工具并提供必要参数
- \4. 工具执行:MCP服务器执行工具并返回结果
- \5. 结果处理:模型将工具结果转化为用户友好的回答
- \6. 响应生成:向用户展示最终的、易于理解的响应
代码示例:
# 处理用户查询
response = self.client.chat.completions.create(
model=self.config.model,
messages=messages,
tools=available_tools
)
# 检查是否需要工具调用
content = response.choices[0]
if content.finish_reason == "tool_calls":
tool_call = content.message.tool_calls[0]
tool_name = tool_call.function.name
tool_args = json.loads(tool_call.function.arguments)
# 执行工具
result = awaitself.server.execute_tool(tool_name, tool_args)
# 将工具结果添加到对话历史
messages.extend([
content.message.model_dump(),
{
"role": "tool",
"content": result.content[0].text,
"tool_call_id": tool_call.id,
}
])
# 生成最终响应
final_response = self.client.chat.completions.create(
model=self.config.model,
messages=messages
)
return final_response.choices[0].message.content
错误处理与健壮性
新客户端实现了多层错误处理策略,确保系统的健壮性:
- \1. 服务器连接重试:当服务器无法连接时自动重试
- \2. 工具执行重试:工具调用失败时自动重试
- \3. 环境变量验证:启动时验证必要的环境变量
- \4. 异常捕获与日志:全面的异常捕获和详细日志记录
示例:
async def execute_tool(self, tool_name, arguments, retries=2, delay=1.0):
for attempt in range(retries):
try:
result = await self.session.call_tool(tool_name, arguments)
return result
except Exception as e:
logger.error(f"工具执行失败 (第 {attempt + 1}/{retries} 次尝试): {str(e)}")
if attempt < retries - 1:
await asyncio.sleep(delay)
else:
raise
实际使用效果
简单天气查询
用户:北京今天天气怎么样?
系统处理流程:
- \1. DeepSeek模型识别出这是天气查询
- \2. 自动选择
get_daily_forecast
工具 - \3. 确定参数:
location="101010100"
(北京城市ID) - \4. 执行工具并获取天气数据
- \5. 生成人性化响应
智能助手:
(venv_mcp_demo) root@fly:~/AI-Box/code/rag/mcp-in-action/mcp_demo# python client/mcp_client_deepseek.py
2025-05-03 14:25:12,273 - INFO - 成功连接到 MCP 服务器
2025-05-03 14:25:12,273 - INFO - 开始聊天会话...
请输入您的问题 (输入 'quit' 或 'exit' 退出): 北京今天天气怎么样?
2025-05-03 14:25:20,775 - INFO - HTTP Request: POST https://api.deepseek.com/chat/completions "HTTP/1.1 200 OK"
2025-05-03 14:25:25,736 - INFO - 执行工具 get_daily_forecast,参数: {'location': 101010100, 'days': 1}
2025-05-03 14:25:26,850 - INFO - 工具执行完成: get_daily_forecast
2025-05-03 14:25:26,918 - INFO - HTTP Request: POST https://api.deepseek.com/chat/completions "HTTP/1.1 200 OK"
助手: 今天是2025年5月3日,北京的天气情况如下:
- 天气:全天晴朗
- 温度:最低10°C,最高25°C(昼夜温差较大请注意增减衣物)
- 风向风力:白天西北风1-3级(3km/h),夜间转为西南风1-3级
- 湿度:干燥(相对湿度仅15%)
- 紫外线:强(指数9,需做好防晒措施)
- 能见度:极佳(25公里)
日出时间05:13,日落时间19:11。今天无降水概率,适合户外活动。
复杂天气查询
用户:最近一周郑州有没有高温或大风预警?周末适合户外活动吗?
系统处理流程:
- \1. 模型识别出需要两类信息:预警信息和天气预报
- \2. 首先调用
get_weather_warning
工具获取预警信息 - \3. 然后调用
get_daily_forecast
工具获取周末天气 - \4. 综合分析两种数据,给出建议
智能助手:
(venv_mcp_demo) root@fly:~/AI-Box/code/rag/mcp-in-action/mcp_demo# python client/mcp_client_deepseek.py
2025-05-03 14:44:29,883 - INFO - 成功连接到 MCP 服务器
2025-05-03 14:44:29,883 - INFO - 开始聊天会话...
请输入您的问题 (输入 'quit' 或 'exit' 退出): 最近一周郑州有没有高温或大风预警?周末适合户外活动吗?
2025-05-03 14:44:32,300 - INFO - HTTP Request: POST https://api.deepseek.com/chat/completions "HTTP/1.1 200 OK"
2025-05-03 14:44:37,864 - INFO - 执行工具 get_weather_warning,参数: {'location': '101180101'}
2025-05-03 14:44:38,220 - INFO - 工具执行完成: get_weather_warning
2025-05-03 14:44:38,221 - INFO - 执行工具 get_daily_forecast,参数: {'location': '101180101', 'days': 7}
2025-05-03 14:44:38,879 - INFO - 工具执行完成: get_daily_forecast
2025-05-03 14:44:38,879 - INFO - 工具调用回合完成,继续与模型交互...
2025-05-03 14:44:38,955 - INFO - HTTP Request: POST https://api.deepseek.com/chat/completions "HTTP/1.1 200 OK"
助手: ### 郑州最近一周的天气情况:
1. **高温或大风预警**:
目前郑州没有高温或大风预警。
2. **周末天气(5月3日-5月4日)**:
- **5月3日(周六)**:多云转阴,气温14°C~25°C,东北风1-3级。
- **5月4日(周日)**:多云转阴,气温18°C~28°C,南风1-3级。
3. **户外活动建议**:
- 周末天气以多云为主,气温适中,风力较小,适合户外活动。
- 紫外线指数较高(周六10,周日6),建议做好防晒措施。
总结:周末天气条件良好,适合户外活动,但需注意防晒。
请输入您的问题 (输入 'quit' 或 'exit' 退出):
与前代客户端的对比
让我们对比旧版命令行客户端与新版DeepSeek客户端:
特性 | 命令行客户端 | DeepSeek客户端 |
---|---|---|
交互方式 | 命令行指令 | 自然语言对话 |
参数输入 | 手动指定参数 | 自动从问题中提取 |
错误处理 | 基础错误提示 | 智能重试与详细提示 |
结果展示 | 原始数据输出 | 人性化解释与建议 |
多轮对话 | 不支持 | 完整支持 |
多工具协同 | 单次单工具 | 可组合多工具 |
未来展望
基于当前的DeepSeek MCP客户端实现,我们可以进一步扩展系统的功能:
- \1. 工具扩展:添加更多天气相关工具,如空气质量、旅游指数等
- \2. 多模态支持:集成图表生成,直观展示天气趋势
- \3. 个性化推荐:基于用户偏好和历史提供个性化天气建议
- \4. 跨平台部署:将系统部署到网页、移动应用等多平台
- \5. 多语言支持:增加多语言处理能力,支持全球用户
结语
通过将DeepSeek大模型与MCP协议结合,我们实现了一个更加智能、人性化的天气助手系统。这种集成不仅提升了用户体验,也展示了大模型与外部工具协同的强大潜力。
MCP协议为AI应用开发提供了标准化、安全的工具调用机制,而像DeepSeek这样的大模型则为工具使用带来了智能决策能力。这种结合将成为未来AI应用开发的主流范式。
希望本文对你实现自己的MCP+大模型应用有所启发。欢迎在评论区分享你的想法和建议!
配置说明
要运行DeepSeek MCP客户端,除了和风天气API配置外,还需要在.env
文件中添加以下配置:
# DeepSeek API配置
DEEPSEEK_API_KEY=sk-xxxxx # 替换为你的DeepSeek API密钥
DEEPSEEK_BASE_URL=https://api.deepseek.com # DeepSeek API基础URL
DEEPSEEK_MODEL=deepseek-chat # 使用的模型名称
获取DeepSeek API Key的方法请参考DeepSeek官方文档[1]。
完整代码参考mcp deepseek[2]
最后的最后
感谢你们的阅读和喜欢,作为一位在一线互联网行业奋斗多年的老兵,我深知在这个瞬息万变的技术领域中,持续学习和进步的重要性。
为了帮助更多热爱技术、渴望成长的朋友,我特别整理了一份涵盖大模型领域的宝贵资料集。
这些资料不仅是我多年积累的心血结晶,也是我在行业一线实战经验的总结。
这些学习资料不仅深入浅出,而且非常实用,让大家系统而高效地掌握AI大模型的各个知识点。如果你愿意花时间沉下心来学习,相信它们一定能为你提供实质性的帮助。
这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费
】

大模型知识脑图
为了成为更好的 AI大模型 开发者,这里为大家提供了总的路线图。它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
经典书籍阅读
阅读AI大模型经典书籍可以帮助读者提高技术水平,开拓视野,掌握核心技术,提高解决问题的能力,同时也可以借鉴他人的经验。对于想要深入学习AI大模型开发的读者来说,阅读经典书籍是非常有必要的。
实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
面试资料
我们学习AI大模型必然是想找到高薪的工作,下面这些面试题都是总结当前最新、最热、最高频的面试题,并且每道题都有详细的答案,面试前刷完这套面试题资料,小小offer,不在话下
640套AI大模型报告合集
这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。
这份完整版的大模型 AI 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费
】

更多推荐
所有评论(0)