MCP协议之天气演练

🔍 为什么要手动实现MCP服务器?

大型语言模型(如Claude、GPT)虽能生成文本,但无法直接操作现实世界的数据和工具。MCP服务器就像AI的"双手" ,让模型能够:

✅ 查询数据库获取实时数据

✅ 调用API执行具体操作(如发送邮件)

✅ 访问本地文件系统

通过Simple-MCP-Server项目,开发者无需从零造轮子,可快速实现以下功能:

  • 标准化JSON-RPC 2.0协议通信
  • 自动工具发现与路由
  • 类型安全的参数校验

🛠️ 环境准备(3分钟)

1. 安装基础工具

bash 复制代码
bash
 体验AI代码助手
 代码解读
复制代码
# 创建虚拟环境
python -m venv mcp-env
source mcp-env/bin/activate  # Windows: mcp-env\Scripts\activate

# 安装依赖
pip install mcp-sdk requests  # 核心SDK+HTTP库

注:推荐Python 3.8+,避免SSL兼容性问题

2. 克隆示例项目

vbscript 复制代码
bash
 体验AI代码助手
 代码解读
复制代码
git clone https://github.com/ruslanmv/Simple-MCP-Server-with-Python.git
cd Simple-MCP-Server-with-Python

💻 核心代码解析(带优化建议)

1. 工具类定义(原始代码优化)

python 复制代码
python
 体验AI代码助手
 代码解读
复制代码
from mcp_sdk import Tool
import requests

class WeatherTool(Tool):
    """获取城市天气(优化版)"""
    def run(self, city: str) -> dict:
        """添加类型注解和错误处理"""
        try:
            url = f"https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q={city}"
            response = requests.get(url, timeout=5.0)
            data = response.json()
            return {
                "temperature": data["current"]["temp_c"],
                "condition": data["current"]["condition"]["text"]
            }
        except Exception as e:
            return {"error": f"Weather API failed: {str(e)}"}

优化点

  • 增加类型提示(city: str
  • 添加超时和异常处理
  • 返回结构化数据而非原始API响应

2. 服务器启动(支持热重载)

ini 复制代码
python
 体验AI代码助手
 代码解读
复制代码
from mcp_sdk import MCP
from weather_tool import WeatherTool  # 导入自定义工具

mcp = MCP(port=8080, debug=True)  # 开启调试模式
mcp.register_tool(WeatherTool(), name="get_weather")

if __name__ == "__main__":
    mcp.start(auto_reload=True)  # 开发时自动重载

关键参数说明

  • port: 指定服务端口(默认8080)
  • auto_reload: 代码修改后自动重启

🌐 实战演示:查询天气

1. 启动服务器

arduino 复制代码
bash
 体验AI代码助手
 代码解读
复制代码
python server.py
# 输出示例:MCP Server running on http://0.0.0.0:8080

2. 通过客户端调用

sql 复制代码
python
 体验AI代码助手
 代码解读
复制代码
from mcp_sdk import MCPClient

client = MCPClient("http://localhost:8080")
result = client.call_tool("get_weather", {"city": "北京"})
print(result)  # 输出:{'temperature': 25, 'condition': '晴'}

3. 在AI应用中集成

配置Cursor/Claude Desktop连接本地MCP服务器:

  1. 打开设置 → MCP → 添加服务器
  2. 输入URL:http://localhost:8080
  3. 测试工具是否可见
相关推荐
曲幽19 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战19 小时前
Pydantic配置管理最佳实践(一)
python
神秘的猪头21 小时前
🔌 把 MCP 装进大脑!手把手带你构建能“热插拔”工具的 AI Agent
langchain·llm·mcp
小兵张健1 天前
AI 页面与交互迁移流程参考
前端·ai编程·mcp
小兵张健1 天前
掘金发布 SOP(Codex + Playwright MCP + Edge)
前端·mcp
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
Qinana1 天前
从代码到智能体:MCP 协议如何重塑 AI Agent 的边界
前端·javascript·mcp
神秘的猪头1 天前
🚀 拒绝“手搓”工具!带你硬核手写 MCP Server,解锁 Agent 的无限潜能
agent·mcp·trae
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python