MCP Weather Agent
🌤️ MCP 天气智能体
一个由 OpenAI 和 模型上下文协议(MCP) 驱动的智能多区域天气助手。
通过自然语言聊天界面,获取 以色列 和 美国 的实时天气预报和警报。该智能体会智能地将问题路由到相应的数据源,并从实时网页数据和官方天气 API 汇总答案。
✨ 功能特性
🤖 AI 驱动聊天:使用 GPT-4o-mini 进行对话式天气查询
🌍 双数据源:
🇮🇱 以色列:通过 Playwright 从 Weather2day 实时抓取网页数据
🇺🇸 美国:官方国家气象局 API
🔄 智能工具路由:智能体根据你的问题自动选择正确的工具
💬 自然语言:用纯英文提问;智能体理解上下文和意图
🔐 安全:API 密钥存储在
.env中,并被排除在版本控制之外🎯 交互式:实时聊天循环,以色列查询时可见浏览器自动化过程
Related MCP server: MCP Weather Assistant
📋 目录
🚀 快速开始
3 分钟内完成启动:
# 1. Install dependencies
uv sync
uv run playwright install chromium
# 2. Create .env file with your OpenAI API key
copy .env.example .env
# Edit .env and add: OPENAI_API_KEY=sk-...
# 3. Run the agent
uv run .\host.py
# 4. Ask a weather question!
# Example: "What is the weather forecast for Jerusalem?"📦 环境要求
组件 | 版本 | 用途 |
Python | 3.13+ | 运行时环境 |
OpenAI API 密钥 | — | GPT-4o-mini 模型访问权限 |
uv | 最新版 | 快速 Python 包管理器 |
Chromium | 最新版 | 浏览器自动化(Playwright) |
网络 | — | API 访问和网页抓取 |
🔧 安装配置
1. 安装依赖
在项目目录中打开终端并运行:
# Install Python dependencies
uv sync
# Download Chromium browser for Playwright (required for Israel weather)
uv run playwright install chromium首次安装需要较长时间? 是的——Playwright 会下载 Chromium(约 300 MB)。这是一次性操作。
2. 配置 OpenAI API 密钥
在项目根目录创建 .env 文件:
# Option A: Copy the template
copy .env.example .env
# Option B: Create manually
echo OPENAI_API_KEY=your_openai_api_key > .env将 your_openai_api_key 替换为你在 platform.openai.com/account/api-keys 获取的实际 OpenAI API 密钥。
⚠️ 重要提示:切勿提交 .env 文件或分享你的 API 密钥。.gitignore 已将其排除在外。
3. 验证安装
测试配置:
uv run .\host.py你应该看到:
Connected to server with tools: [...]
MCP Client Started!
Type your queries or 'quit' to exit.
Query:按 Ctrl+C 或输入 quit 退出。
▶️ 运行智能体
启动交互式聊天:
uv run .\host.py智能体以交互模式启动。输入天气问题并按回车。智能体将:
✅ 解析你的问题
🔍 路由到相应的天气工具(以色列或美国)
🌐 获取实时数据(以色列查询可能会打开浏览器窗口)
📊 处理并格式化响应
💬 返回答案
输入 quit 退出。
对于以色列查询:Chromium 浏览器窗口会自动打开。这是正常现象——智能体正在使用 Playwright 与 Weather2day 交互。查询完成后窗口会自动关闭。
🏗️ 架构
┌─────────────────────────────────────────────────────────────────┐
│ OpenAI (GPT-4o-mini) │
│ (Tool Selection & Reasoning) │
└────────────────────────────┬────────────────────────────────────┘
│
┌────────────┴────────────┐
│ │
┌───────▼────────┐ ┌───────▼────────┐
│ MCP Host │ │ MCP Host │
│ (client.py) │ │ (client.py) │
└───────┬────────┘ └───────┬────────┘
│ │
┌───────▼──────────────┐ ┌──────▼─────────────┐
│ weather_Israel.py │ │ weather_USA.py │
│ (Playwright + Web) │ │ (NWS API) │
└───────┬──────────────┘ └──────┬─────────────┘
│ │
┌───────▼──────────────┐ ┌──────▼─────────────┐
│ Weather2day.co.il │ │ api.weather.gov│
│ (Live Web Browser) │ │ (REST API) │
└──────────────────────┘ └───────────────────┘数据流:
你在聊天中提出问题
主机将问题连同可用工具发送给 OpenAI
OpenAI 根据问题选择要调用的工具
相应的 MCP 服务器执行并返回数据
主机格式化并返回答案
💬 示例查询
🇮🇱 以色列天气
What is the weather forecast for Jerusalem?
Give me the forecast for Tel Aviv.
What is the weather like in Haifa today?
Show me the forecast for Eilat.
What is the weather in Beer Sheva?
Is it going to rain in Kfar Saba tomorrow?
Tell me about the weather in Nazareth.
What's the forecast for Tiberias?支持的城市:耶路撒冷、特拉维夫、海法、埃拉特、贝尔谢巴、卡法萨巴、提比里亚、拿撒勒,以及 Weather2day 识别的大多数以色列主要城市。
🇺🇸 美国天气
What is the weather forecast for New York City? (40.7128, -74.0060)
What's the weather at latitude 34.0522, longitude -118.2437? (Los Angeles)
Are there any active weather alerts in California?
What weather alerts are in effect in New York?
Give me the forecast for Chicago coordinates. (41.8781, -87.6298)
Are there any severe weather warnings in Texas?格式:
天气预报:使用经纬度坐标
天气警报:使用两字母州代码(
CA、NY、TX等)
🎯 智能体行为
智能体理解上下文:
✅ "耶路撒冷的天气怎么样?" → 使用以色列工具
✅ "我要去纽约,天气预报如何?" → 使用美国工具(40.71, -74.01)
✅ "告诉我特拉维夫和洛杉矶的天气" → 同时调用两个工具
✅ "芝加哥现在在下雨吗?" → 路由到美国工具
📂 项目结构
MCP Weather/
├── host.py # Main chat host (OpenAI + tool orchestration)
├── client.py # MCP client connector
├── weather_Israel.py # Israel MCP server (Playwright + Web)
├── weather_USA.py # USA MCP server (NWS API)
├── pyproject.toml # Dependencies and project metadata
├── uv.lock # Locked dependency versions
├── .env.example # Template for environment variables
├── .env # Your API keys (git-ignored)
├── README.md # This file
└── .gitignore # Git exclusion rules🐛 故障排除
❌ OPENAI_API_KEY is missing
问题:智能体找不到你的 API 密钥。
解决方案:
确认
.env存在于项目根目录(与host.py同一文件夹)检查文件内容是否包含:
OPENAI_API_KEY=sk-your-actual-key-here重启主机:
uv run .\host.py
❌ Chromium 浏览器无法启动
问题:"Failed to launch browser" 错误。
解决方案:
uv run playwright install chromium如果仍然失败,请检查磁盘空间(Chromium 需要约 500 MB)。
❌ 连接超时或 API 错误
问题:"net::ERR_CONNECTION_RESET" 或请求失败。
解决方案:
检查你的网络连接
在 platform.openai.com 验证你的 OpenAI API 密钥是否有效
检查 API 使用量和计费情况
❌ 以色列浏览器打开但搜索失败
问题:城市搜索没有返回建议。
原因说明:Weather2day 的自动补全仅在 /forecast 页面上有效。工具会在每次搜索前自动返回该页面,但如果失败:
解决方案:
确认 Chromium 是最新版本:
uv run playwright install --with-deps chromium确保你能访问
weather2day.co.il检查浏览器弹窗或 Cookie 横幅(智能体会处理这些,但极慢的连接可能会超时)
❌ "A server fails to connect"
问题:MCP 服务器连接错误。
解决方案:
# Run from the project directory
Set-Location .\project-template
uv run .\host.py❓ 常见问题
问:智能体如何决定使用哪个工具?
答:OpenAI 的 GPT-4o-mini 会读取你的问题,并根据上下文(提到的国家/地区、提供的坐标等)选择最佳工具。这不是基于规则的——它使用语言理解。
问:我可以在一次查询中询问多个地区吗?
答:可以!智能体可以调用多个工具。试试:"特拉维夫和纽约的天气怎么样?"
问:为什么以色列浏览器会可见地打开?
答:Playwright 通过向实时搜索框输入内容、选择结果并读取页面来自动化 Weather2day。无头模式(不可见)不适用于该网站大量使用 JavaScript 的自动补全功能,因此浏览器以可见模式运行。
问:这需要多少费用?
答:你按 API 调用次数向 OpenAI 付费。每次查询约花费 $0.001–$0.01,具体取决于响应长度。以色列网页抓取是免费的;美国 API 也是免费的(NWS 是公共数据)。
问:如果我想添加更多地区怎么办?
答:创建一个新的 MCP 服务器(例如 weather_Europe.py),并在 host.py 的 self.mcp_clients 下注册。参考现有服务器的模式。
问:我的 API 密钥安全吗?
答:安全。你的 .env 已被 Git 排除,仅存储在本地。切勿在代码或公共聊天中粘贴你的密钥。
问:我可以将其用于生产环境吗?
答:这是一个演示项目。对于生产环境:
使用异步请求队列
添加日志记录和错误恢复
缓存天气预报(天气每小时变化,而非每次查询都变化)
设置监控和警报
使用基于环境的配置
🔒 安全
⚠️ 应该做 | ❌ 不应该做 |
✅ 保持 | ❌ 将 |
✅ 定期轮换 API 密钥 | ❌ 分享你的 API 密钥 |
✅ 在生产环境中使用环境变量 | ❌ 在代码中硬编码机密信息 |
✅ 检查 API 计费限额 | ❌ 让配额无限制 |
✅ API 调用使用 HTTPS | ❌ 在生产环境中使用 HTTP |
如果你的 API 密钥已泄露:
立即在 OpenAI 控制台 中撤销它
生成一个新密钥
更新
.env
📝 许可证
本项目按原样提供,仅供教育用途。详情请参阅 LICENSE。
🤝 贡献
有改进智能体的想法?欢迎贡献!
Fork 本仓库
创建功能分支(
git checkout -b feature/amazing-feature)提交你的更改(
git commit -m 'Add amazing feature')推送到分支(
git push origin feature/amazing-feature)打开 Pull Request
📞 支持
🐛 通过 GitHub Issues 报告错误
💡 在 Discussions 中建议功能
📧 对于安全问题,请私下发送邮件(不要公开提交 issue)
祝预报愉快!🌦️☀️
Available Tools
4 toolsenter_weather_forecast_city_israelC
מקבל שם עיר ומזין אותו בשדה החיפוש באתר מזג האוויר.
:param city_name: שם העיר בחיפוש (למשל: 'ירושלים', 'תל אביב')
| Name | Required | Description | Default |
|---|---|---|---|
| city_name | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full behavioral burden. It discloses only that it fills a search field; it does not say whether the search is submitted, what happens if the city is not found, whether the site must already be open, or what state the page is left in for the next sibling call.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two short lines with the action stated first and the parameter documented in a conventional :param block; nothing is padded. It is efficient, though the colon-prefixed param line is stylistically thin for a tool with a workflow dependency.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values need no explanation. However, for a browser-automation step in a four-tool sequence, the description omits the ordering/state assumptions an agent needs, leaving a real gap despite the adequate parameter hint.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0% for the single parameter, so the description must compensate, and it partially does by explaining that city_name is the search string and giving examples ('ירושלים', 'תל אביב'). It adds useful illustrative meaning but no format or validation constraints beyond that.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a concrete verb and resource: it receives a city name and types it into the search field of the weather site. That is specific enough to distinguish a UI-entry step, though it never names or contrasts the sibling tools (select_weather_forecast_city_israel, open_weather_forecast_israel), so an agent must infer the ordering itself.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no explicit when-to-use guidance, no prerequisites, and no mention of the sibling steps that presumably follow. The workflow role (enter search text, then select the city, then read content) is only implied by the tool names, not stated in the description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_weather_forecast_content_israelA
מחלקץ את הטקסט הגלוי מתוך דף התחזית הנוכחי שנפתח בדפדפן, מנקה רווחים מיותרים ומחזיר את התוכן ל-LLM לצורך מתן תשובה.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden. It discloses the extraction behavior and whitespace cleanup, which is useful, but omits what happens when no page is open, failure/error behavior, and any permission considerations. Adequate but incomplete for a zero-annotation tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single front-loaded sentence stating the action, with no wasted preamble. The trailing clause about returning content 'to the LLM to provide an answer' is mildly redundant but not harmful.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values need not be described, and there are no parameters to document. The main remaining gap is state-dependence (what it requires the browser to already be showing), which is only implied rather than guaranteed.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema has zero parameters, so the baseline of 4 applies. Nothing about parameters needs explaining and the description does not confuse the matter.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description gives a specific verb and resource: it extracts the visible text from the current forecast page open in the browser and returns a cleaned version. That is clear and distinguishable from open/enter/select siblings in the pipeline, though it never explicitly names how it differs from them.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Usage is implied rather than stated: it works on the page 'opened in the browser', so the agent can infer it must run after opening and selecting a city. There is no explicit statement of prerequisites, exclusions, or what to do instead if the page is not ready.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
open_weather_forecast_israelA
פותח את דפדפן האינטרנט ומנווט לדף הבית של אתר מזג האוויר הישראלי.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden. It usefully discloses the side effect that a browser window is opened, which is meaningful for an agent. It does not mention state (new tab vs. existing), auth, or what the user sees next, leaving gaps for a no-annotation tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single front-loaded sentence with no filler; the action and destination are stated immediately. Nothing needs trimming.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple (0 params, output schema present so return values need no explanation) and the description adequately covers the action. The remaining gap is routing context against the sibling tools, which is a moderate omission rather than a fatal one.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool takes zero parameters, and the schema coverage is 100%, so there is nothing for the description to disambiguate. Baseline 4 applies since no parameter semantics are needed.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description gives a concrete verb+resource in Hebrew: it opens the browser and navigates to the Israeli weather site's homepage. An agent can tell what the tool does. However, it never distinguishes itself from the three sibling tools (enter/select/get_weather_forecast_*), so it stops at 4.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The mention of navigating to the 'homepage' implies this is the entry/starting step before the city-selection and content siblings, but there is no explicit statement of when to use it versus enter_weather_forecast_city_israel or get_weather_forecast_content_israel. Usage is only inferred.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
select_weather_forecast_city_israelA
בוחר את התוצאה הראשונה ברשימת הערים שנפתחה בעקבות החיפוש.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries full disclosure burden. It usefully reveals that selection is deterministic ('first result'), meaning the agent cannot choose a specific city, but it omits what happens if the list is empty, whether it navigates to a new page, and any auth or error behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single, tight sentence with no padding, and the key constraint ('first result') is placed prominently. Appropriate length for a zero-argument UI step.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists so return values need not be explained, and there are no parameters. What remains unstated is the workflow contract (what must precede this call, what state follows it), which matters for a sequential UI-automation tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool takes zero parameters, so there is nothing for the description to disambiguate. The baseline for a parameterless tool is 4, and the description adds no misleading parameter claims.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names a specific verb (selects) and a specific target (the first result in the city list opened by the search), which distinguishes it from siblings like enter_weather_forecast_city_israel or open_weather_forecast_israel. It stops short of explicitly naming the alternative tools, but the action and target are clear.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'the city list that was opened following the search' implies this step follows a search and a list-opening step, giving sequencing context. However, it never states when to use this versus entering a city directly, nor any preconditions or failure conditions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
enter_weather_forecast_city_israel - First observed
get_weather_forecast_content_israel - First observed
open_weather_forecast_israel - First observed
select_weather_forecast_city_israel
TDQS
Scored across 4 tools
Each tool maps to a distinct browser-automation step (open site, enter city, select result, extract content), so they are separable in principle. However, they form a rigid ordered pipeline with no way to tell from the names alone that they must be chained, and enter vs. select could be momentarily confused by a hurried agent.
All names are snake_case and share a predictable verb_..._israel suffix (open/enter/select/get_weather_forecast_..._israel). Minor structural deviation: open_weather_forecast_israel omits the 'city' segment the other three include, but the pattern is still readable and consistent.
Four tools is a reasonable count for this narrow scraping workflow. It is slightly granular, since a single 'fetch forecast for city' operation is split into four browser steps, but each step is individually actionable and the set stays well-scoped.
The surface covers the happy path open -> search -> select -> extract, but has no tool to close/reset the browser session, no error or no-result handling, and despite the generic server name 'MCP Weather Agent' it only supports Israeli locations. Agents can complete the core task but will hit dead ends on edge cases.
Maintenance
Related MCP Connectors
US NWS weather alerts and 5-day forecasts for AI agents. $0.01 per call.
US weather & geo for AI agents: forecasts, alerts, earthquakes, elevation, geocoding. No keys.
US weather & geo for AI agents: forecasts, alerts, earthquakes, elevation, geocoding. No keys.
Provide real-time and forecast weather information for locations in the United States using natura…
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables users to query real-time weather data for Israeli cities using natural language, automatically scraping a weather website via Playwright and returning AI-generated answers.-
- FlicenseAqualityDmaintenanceEnables users to query weather information for Israel via Playwright browser automation and for the USA via a weather API, allowing an LLM to access real-time weather data and alerts.4-
- FlicenseNot gradedqualityCmaintenanceEnables natural language weather queries for Israeli cities with real-time data extracted via Playwright, plus USA weather alerts and forecasts via NWS API, all orchestrated by Groq LLM.1-
- FlicenseNot gradedqualityBmaintenanceEnables natural language weather queries for cities in Israel and the United States, combining browser automation and official API retrieval.-