33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
# uv add fastmcp
|
|
import os
|
|
import logging
|
|
import requests
|
|
from fastmcp import FastMCP
|
|
|
|
mcp = FastMCP("mcp demo")
|
|
WEATHER_API_KEY = os.getenv("WEATHER_API_KEY")
|
|
|
|
# @mcp.tool()
|
|
# async def get_weather(city: str) -> str:
|
|
# """获取传入的城市的天气信息"""
|
|
# logging.info(f"调用了查询天气服务,传入的参数为{city}")
|
|
# return f"{city}的天气很好,阳光明媚,晴空万里"
|
|
|
|
|
|
@mcp.tool()
|
|
async def get_weather(city: str) -> str:
|
|
"""获取传入的城市的天气信息"""
|
|
logging.info("The get_weather method is called: city=%s", city)
|
|
api_key = os.getenv("WEATHER_API_KEY")
|
|
# url = f"https://api.weatherapi.com/v1/current.json?key=6056d3b7245449069d0152825252910&q={city}"
|
|
url = f"https://api.weatherapi.com/v1/current.json?key={WEATHER_API_KEY}&q={city}"
|
|
response = requests.get(url, timeout=10)
|
|
response.raise_for_status()
|
|
return response.text
|
|
|
|
|
|
if __name__ == "__main__":
|
|
logging.info("启动一个可以通过MCP调用获取天气的服务")
|
|
mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
|
|
# mcp.run(transport="stdio", host="127.0.0.1", port=9000)
|