用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密钥
相关推荐
2501_947575801 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计
骑士雄师1 小时前
java面试题 4:鉴权
java·开发语言
Byron__2 小时前
AI学习_06_短期记忆与长期记忆
人工智能·python·学习
时间的拾荒人2 小时前
C语言字符函数与字符串函数完全指南
c语言·开发语言
2501_948106913 小时前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
夏玉林的学习之路3 小时前
如何远程连接服务器
运维·服务器
取经蜗牛3 小时前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
创世宇图3 小时前
【Python工程化实战】OpenTelemetry 在 Python 中的全链路追踪落地:从埋点到可视化的完整实战指南
python·分布式链路追踪·性能监控·opentelemetry·微服务可观测性
dog2503 小时前
从重尾到截断流量模型的演进
开发语言·php
qq_401700414 小时前
Qt QSS 完全入门写出漂亮界面以及解决样式不生效问题
开发语言·qt