用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密钥
相关推荐
Dxy12393102164 分钟前
Python请求方式介绍:JSON、表单及其他常见数据传输格式
数据库·python·json
迷渡10 分钟前
聊一聊 Bun 用 Rust 重写这件事
开发语言·后端·rust
西洼工作室11 分钟前
个人开发者接入阿里云号码认证服务AliCloud-NirvanaPns实现一键登录
python·阿里云·uni-app·全栈·认证授权
古怪今人18 分钟前
Gradle构建工具 Groovy/Kotlin DSL的现代化自动化构建工具
开发语言·kotlin·自动化
赏金术士19 分钟前
Kotlin 协程与挂起函数(Coroutines & suspend)入门到实战
android·开发语言·kotlin
fiveym30 分钟前
二层核心网络技术通俗解析(VLAN/Access/Trunk/LACP/ARP)
服务器·网络·网络协议
半城抹茶41 分钟前
TradingAgents-CN 项目目录文档
python
光影62744 分钟前
Selenium自动化测试---实战踩坑实录
python·selenium·测试工具·百度
y = xⁿ1 小时前
Java并发八股学习日记
java·开发语言·学习
magic_now1 小时前
Linux 内核启动流程详解(基于 5.15.119 源码)
linux·运维·服务器