使用说明
🌦️ 天气MCP
天气MCP 是一个FastAPI服务器,与 FastMCP 和 Pydantic 人工智能 提供实时天气警报和预报。用户可以通过自然语言提示与服务器交互,从而无缝访问天气信息。
📋 目录
🚀 特性
- 获取美国各州的活跃天气警报。
- 根据地理坐标检索详细的天气预报。
- Pydantic AI支持的自然语言交互。
- 通过FastMCP可扩展工具集。
🛠️ 安装
先决条件
- Python 3.8或更高版本
- 一个OpenAI API密钥(
OPENAI_API_KEY):若要获取OpenAI API密钥,请访问 OpenAI API密钥页面
在继续安装之前,请确保您已具备这些先决条件。
步骤
-
克隆存储库:
git clone https://github.com/yourusername/weather-mcp.git cd weather-mcp -
创建并激活虚拟环境:
pip install uv uv venv source venv/bin/activate # On Windows: venv\Scripts\activate -
安装依赖项:
uv sync -
设置OpenAI API密钥
要安全地使用OpenAI服务,请设置 OPENAI_API_KEY 环境变量。([DEV社区][1])
在Unix/Linux/macOS上:
export OPENAI_API_KEY="your-api-key-here"
要使此更改永久化,请将上述行添加到shell的配置文件中(例如。, ~/.bashrc, ~/.zshrc)并重新加载shell:([黑客新闻][2])
source ~/.bashrc # or source ~/.zshrc
在Windows上(命令提示符):
setx OPENAI_API_KEY "your-api-key-here"
设置变量后,重新启动命令提示符以应用更改。
在Windows(PowerShell)上:
$env:OPENAI_API_KEY = "your-api-key-here"
-
启动服务器:
python weather_server.py
服务器将可在以下位置访问 http://localhost:8000/sse.
💡 用法
通过Pydantic AI进行交互
您可以通过Pydantic AI使用自然语言提示与服务器交互。([YouTube][1])
例子:
import asyncio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerHTTP
# Define the MCP server connection
mcp_server = MCPServerHTTP(url="http://localhost:8000/sse")
# Create the Pydantic AI agent
agent = Agent(
model="openai:gpt-4o-mini",
mcp_servers=[mcp_server],
system_prompt="You are a helpful assistant that provides weather information."
)
async def main():
prompt = "Are there any weather alerts for California?"
async with agent.run_mcp_servers():
result = await agent.run(prompt)
print(result.output)
if __name__ == "__main__":
asyncio.run(main())
直接刀具调用
或者,您可以使用FastMCP的客户端直接调用这些工具。
例子:
import asyncio
from fastmcp import Client
async def main():
async with Client("http://localhost:8000/sse") as client:
tools = await client.list_tools()
print("Available tools:")
for tool in tools:
print(f"- {tool.name}: {tool.description}")
# Call the get_weather_alerts tool
state_code = "CA"
alerts_result = await client.call_tool("get_weather_alerts", {"state": state_code})
print(f"\nWeather alerts for {state_code}:\n{alerts_result[0].text}")
# Call the get_weather_forecast tool
latitude = 34.05
longitude = -118.25
forecast_result = await client.call_tool("get_weather_forecast", {
"latitude": latitude,
"longitude": longitude
})
print(f"\nWeather forecast for ({latitude}, {longitude}):\n{forecast_result[0].text}")
if __name__ == "__main__":
asyncio.run(main())
📡 API终点
服务器通过MCP协议公开以下工具:
-
get_weather_alerts(state: str) -> str获取指定美国州的活动天气警报。 -
get_weather_forecast(latitude: float, longitude: float) -> str检索给定地理坐标的天气预报。
🤝 贡献
欢迎投稿!请按照以下步骤操作:
- 分叉存储库。
- 创建新分支:
git checkout -b feature-name. - 进行更改并提交:
git commit -m 'Add feature'. - 推到分支:
git push origin feature-name. - 打开一个pull请求。([GitHub][2])
对于重大更改,请先打开一个问题来讨论您想要更改的内容。([编写自述文件][3])
📄 许可证
该项目根据 MIT许可证.