用python实现一个查询当天天气的MCP服务器

我们通过MCP通过模型去调用外部工具,那么外部工具如何设计,让MCP能够调用到呢

本文介绍了一个基于Python的MCP服务器实现,用于查询深圳当天天气。该服务器通过HTTP接口提供天气数据查询服务,主要特点包括:1) 使用Python标准库http.server实现;2) 集成OpenWeatherMap天气API;3) 返回JSON格式的天气数据,包含温度、湿度、风速等关键信息。实现步骤包括:配置API密钥、构建请求URL、处理API响应等。服务器运行后可通过/weather/shenzhen路径获取深圳天气数据,为MCP模型提供标准化的外部工具调用接口。

用python实现一个查询深圳当天天气的MCP服务器

python 复制代码
import http.server
import socketserver
import json
import urllib.request
import urllib.parse

# 天气API配置
API_KEY = "YOUR_API_KEY"  # 请替换为实际的API密钥
WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather"

class WeatherHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        # 解析请求路径
        if self.path == "/weather/shenzhen":
            try:
                # 构建API请求URL
                params = {
                    "q": "Shenzhen,CN",
                    "appid": API_KEY,
                    "units": "metric",  # 使用摄氏度
                    "lang": "zh_cn"  # 使用中文
                }
                url = WEATHER_API_URL + "?" + urllib.parse.urlencode(params)
                
                # 发送API请求
                with urllib.request.urlopen(url) as response:
                    data = json.loads(response.read().decode())
                
                # 处理天气数据
                weather_info = {
                    "city": data.get("name"),
                    "temperature": data.get("main", {}).get("temp"),
                    "humidity": data.get("main", {}).get("humidity"),
                    "weather": data.get("weather", [{}])[0].get("description"),
                    "wind_speed": data.get("wind", {}).get("speed"),
                    "pressure": data.get("main", {}).get("pressure"),
                    "timestamp": data.get("dt")
                }
                
                # 发送响应
                self.send_response(200)
                self.send_header("Content-type", "application/json")
                self.end_headers()
                self.wfile.write(json.dumps(weather_info, ensure_ascii=False).encode("utf-8"))
                
            except Exception as e:
                # 处理错误
                self.send_response(500)
                self.send_header("Content-type", "application/json")
                self.end_headers()
                error_info = {"error": str(e)}
                self.wfile.write(json.dumps(error_info).encode("utf-8"))
        else:
            # 处理其他路径
            self.send_response(404)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            error_info = {"error": "Not Found"}
            self.wfile.write(json.dumps(error_info).encode("utf-8"))

def run_server(port=8000):
    """运行天气查询服务器"""
    handler = WeatherHandler
    with socketserver.TCPServer(("", port), handler) as httpd:
        print(f"天气查询服务器运行在 http://localhost:{port}")
        print(f"查询深圳天气: http://localhost:{port}/weather/shenzhen")
        httpd.serve_forever()

if __name__ == "__main__":
    # 运行服务器,默认端口8000
    run_server()

服务器功能

  • 基于Python标准库实现的HTTP服务器
  • 使用OpenWeatherMap API获取深圳天气数据
  • 提供RESTful API接口
  • 返回JSON格式的天气信息

使用步骤

  1. 获取API密钥

    • 访问 OpenWeatherMap官网 注册账号
    • 获取免费的API密钥
    • 将代码中的 API_KEY = "YOUR_API_KEY" 替换为实际的API密钥
相关推荐
点云-激光雷达-Slam-三维牙齿28 分钟前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐61 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能8 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
WWJA王文举8 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境9 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13149 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
我是谁??9 小时前
Ubuntu22.04更换清华源
linux·运维·服务器
Python私教9 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
圣殿骑士-Khtangc10 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
Python私教10 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi