Skip to main content
Glama

🌤️ MCP Weather Agent

Python 3.13+ OpenAI MCP Playwright

OpenAI と Model Context Protocol (MCP) を搭載した、インテリジェントな多地域対応の天気アシスタントです。

自然言語チャットインターフェースを通じて、イスラエルとアメリカ合衆国のリアルタイムの天気予報と警報を取得できます。エージェントは質問を適切なデータソースにインテリジェントにルーティングし、ライブのウェブデータと公式の天気APIから回答をまとめます。


✨ 特徴

  • 🤖 AI搭載チャット: GPT-4o-miniを使用した会話形式の天気クエリ

  • 🌍 2つのデータソース:

    • 🇮🇱 イスラエル: Playwrightを使用したWeather2dayからのライブウェブスクレイピング

    • 🇺🇸 アメリカ: 公式National Weather Service 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 Key

—

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(約300MB)をダウンロードします。これは一度きりの操作です。

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

エージェントはインタラクティブモードで起動します。天気の質問を入力してEnterを押してください。エージェントは次のことを行います:

  1. ✅ 質問を解析

  2. 🔍 適切な天気ツール(イスラエルまたはアメリカ)にルーティング

  3. 🌐 リアルタイムデータを取得(イスラエルの場合はブラウザウィンドウが開く場合があります)

  4. 📊 レスポンスを処理して整形

  5. 💬 回答を返す

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)      │
        └──────────────────────┘  └───────────────────┘

データフロー:

  1. チャットで質問をします

  2. ホストが利用可能なツールとともにOpenAIに送信します

  3. OpenAIが質問に基づいて呼び出すツールを選択します

  4. 適切なMCPサーバーが実行され、データを返します

  5. ホストが回答を整形して返します


💬 クエリ例

🇮🇱 イスラエルの天気

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?

形式:

  • 予報: 緯度/経度座標を使用

  • 警報: 2文字の州コード(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キーを見つけられません。

解決策:

  1. .envがプロジェクトルート(host.pyと同じフォルダ)に存在することを確認

  2. ファイルにOPENAI_API_KEY=sk-your-actual-key-hereが含まれていることを確認

  3. ホストを再起動: uv run .\host.py

❌ Chromiumブラウザが起動しない

問題: 「Failed to launch browser」エラー。

解決策:

uv run playwright install chromium

それでも失敗する場合は、ディスク容量を確認してください(Chromiumは約500MB必要です)。

❌ 接続タイムアウトまたはAPIエラー

問題: 「net::ERR_CONNECTION_RESET」またはリクエスト失敗。

解決策:

  • インターネット接続を確認

  • OpenAI APIキーがplatform.openai.comで有効か確認

  • APIの使用量と請求を確認

❌ イスラエルのブラウザは開くが検索が失敗する

問題: 都市検索が候補を返しません。

説明: Weather2dayのオートコンプリートは/forecastページでのみ機能します。ツールは各検索の前にそのページに自動的に戻りますが、失敗した場合は:

解決策:

  • Chromiumが最新であることを確認: uv run playwright install --with-deps chromium

  • weather2day.co.ilへのインターネット接続があることを確認

  • ブラウザのポップアップやCookieバナーを確認(エージェントはこれらを処理しますが、非常に遅い接続ではタイムアウトする可能性があります)

❌ 「サーバーに接続できません」

問題: MCPサーバー接続エラー。

解決策:

# Run from the project directory
Set-Location .\project-template
uv run .\host.py

❓ よくある質問

Q: エージェントはどのツールを使うかをどうやって決めますか?
A: OpenAIのGPT-4o-miniが質問を読み取り、文脈(国/地域、提供された座標など)に基づいて最適なツールを選択します。ルールベースではなく、言語理解を使用します。

Q: 1つのクエリで複数の地域について質問できますか?
A: はい!エージェントは複数のツールを呼び出すことができます。例:「テルアビブとニューヨークの天気は?」

Q: なぜイスラエルのブラウザは表示されるのですか?
A: Playwrightはライブ検索に文字を入力し、結果を選択し、ページを読み取ることでWeather2dayを自動化します。ヘッドレスモード(非表示)はこのサイトのJavaScriptを多用したオートコンプリートでは機能しないため、ブラウザは表示された状態で実行されます。

Q: 費用はどのくらいかかりますか?
A: OpenAIからAPI呼び出しに基づいて請求されます。各クエリは応答の長さに応じて約$0.001〜$0.01かかります。イスラエルのウェブスクレイピングは無料、アメリカのAPIは無料です(NWSは公開されています)。

Q: さらに地域を追加したい場合は?
A: 新しいMCPサーバー(例:weather_Europe.py)を作成し、host.pyのself.mcp_clientsに登録します。既存のサーバーをパターンとして参照してください。

Q: APIキーは安全ですか?
A: はい。.envはGitから除外され、ローカルのみに保存されます。キーをコードや公開チャットに貼り付けないでください。

Q: 本番環境で使用できますか?
A: これはデモプロジェクトです。本番用には:

  • 非同期リクエストキューを使用

  • ロギングとエラーリカバリを追加

  • 予報をキャッシュ(天気はクエリごとではなく毎時間変化します)

  • 監視とアラートを設定

  • 環境ベースの設定を使用


🔒 セキュリティ

⚠️ 実行すべきこと

❌ 実行してはいけないこと

✅ .envをローカルかつ非公開に保つ

❌ .envをGitにコミットする

✅ APIキーを定期的にローテーションする

❌ APIキーを共有する

✅ 本番環境で環境変数を使用する

❌ コードにシークレットをハードコードする

✅ APIの請求限度を確認する

❌ クォータを無制限のままにする

✅ API呼び出しにHTTPSを使用する

❌ 本番環境でHTTPを使用する

APIキーが漏洩した場合:

  1. OpenAI Dashboardで直ちに失効させる

  2. 新しいキーを生成する

  3. .envを更新する


📝 ライセンス

このプロジェクトは教育目的で現状のまま提供されます。詳細はLICENSEを参照してください。


🤝 貢献

エージェントを改善するアイデアがありますか?貢献を歓迎します!

  1. リポジトリをフォーク

  2. フィーチャーブランチを作成(git checkout -b feature/amazing-feature)

  3. 変更をコミット(git commit -m 'Add amazing feature')

  4. ブランチにプッシュ(git push origin feature/amazing-feature)

  5. プルリクエストを開く


📞 サポート

  • 🐛 GitHub Issuesでバグを報告

  • 💡 Discussionsで機能を提案

  • 📧 セキュリティ問題は非公開でメール(公開イシューを開かないでください)


楽しい予報を!🌦️☀️

Available Tools

4 tools
enter_weather_forecast_city_israelC

מקבל שם עיר ומזין אותו בשדה החיפוש באתר מזג האוויר.

:param city_name: שם העיר בחיפוש (למשל: 'ירושלים', 'תל אביב')

NameRequiredDescriptionDefault
city_nameYes

Output Schema

NameRequiredDescription
resultYes

TDQS

C2.9/5.0
Behavior2/5

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.

Conciseness4/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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 לצורך מתן תשובה.

NameRequiredDescriptionDefault

No parameters

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

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.

Conciseness4/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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

פותח את דפדפן האינטרנט ומנווט לדף הבית של אתר מזג האוויר הישראלי.

NameRequiredDescriptionDefault

No parameters

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.7/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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

בוחר את התוצאה הראשונה ברשימת הערים שנפתחה בעקבות החיפוש.

NameRequiredDescriptionDefault

No parameters

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

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.

Conciseness4/5

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.

Completeness3/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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.

  1. 4 tool updatesv0.1.0
    • First observedenter_weather_forecast_city_israel
    • First observedget_weather_forecast_content_israel
    • First observedopen_weather_forecast_israel
    • First observedselect_weather_forecast_city_israel

TDQS

B3.4/5.0

Scored across 4 tools

Disambiguation4/5

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.

Naming Consistency4/5

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.

Tool Count4/5

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.

Completeness3/5

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

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers