用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密钥
相关推荐
Thneonl2 小时前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
清桔2 小时前
模型的调用
python
小小张说故事2 小时前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python
10年前端老司机2 小时前
干货分享|企业智能知识库 Rerank 重排序落地实践与踩坑总结
python·aigc·agent
天天被压力2 小时前
【Python 量化取数指南 #13】Python 把行情落库:sqlite 一键存,回测随用随取
java·人工智能·python
天天被压力2 小时前
【Python 量化取数指南 #14】Python 清洗行情数据:复权停牌对齐,回测不翻车
java·人工智能·python
Python私教2 小时前
Python环境配置:conda+PyCharm+换源,附6个坑
人工智能·python·pycharm
databook2 小时前
检测数据异常值的五种统计技术
python·数据挖掘·数据分析
小小张说故事2 小时前
Selenium 装驱动太麻烦?Playwright 入门指南:Python 网页自动化新标准
python
海宇数科2 小时前
Python数据工程:利用海宇车型识别精准优化车险理赔合规体验
人工智能·python