MalkaBruk-MCPProject

MalkaBruk-MCPProject

An MCP server that provides weather forecasts and alerts for the USA and Israel, using the National Weather Service API and Playwright-based browser automation.

Category
访问服务器

README

MCP Weather Forecast Project

📋 Project Overview

This project demonstrates a complete Model Context Protocol (MCP) Server implementation with Playwright-based browser automation. It enables Claude AI to fetch real-time weather forecasts from Israeli and USA weather websites by automating browser interactions without manual intervention.

The project implements two MCP servers:

  1. weather_USA.py - Fetches USA weather alerts and forecasts from the National Weather Service API
  2. weather_Israel.py - Automates browser interactions with the Israel Weather 2 Day website using Playwright

🎯 Learning Objectives

By working through this project, you will understand:

  • ✅ How to implement your own MCP Server for custom needs
  • ✅ How to use Playwright to add browser control capabilities to LLMs
  • ✅ How to manage browser automation sessions across multiple tool calls
  • ✅ How to create an orchestrator that manages multiple MCP clients
  • ✅ How to integrate Claude AI with custom tools

🛠️ Technology Stack

  • MCP SDK: Anthropic's official library for exposing tools to LLMs
  • Playwright: Microsoft's browser automation library for reliable browser control
  • FastMCP: Decorator-based framework for building MCP servers quickly
  • Cohere API: Cohere's advanced LLM for intelligent tool selection and execution
  • Python 3.13+: Async-first Python implementation

📦 Installation

Prerequisites

  • Python 3.13 or higher
  • Pip or Uv package manager

Setup Steps

  1. Clone or navigate to the project directory:
cd MCPProject
  1. Install dependencies:
uv sync

Or with pip:

pip install -r requirements.txt
  1. Set up environment variables: Create a .env file in the project root:
COHERE_API_KEY=your-cohere-api-key-here

You can get a Cohere API key from cohere.com

  1. Install Playwright browsers:
playwright install

🚀 How to Run

Running the Interactive Chat Host

uv run host.py

The host will:

  1. Connect to both MCP servers (USA and Israel weather)
  2. Display available tools
  3. Start an interactive chat loop
  4. Allow you to ask questions about weather forecasts

Type your weather-related questions and press Enter. Type quit to exit.

💬 Example Questions and Answers

For USA Weather:

Query: What are the active weather alerts in California?
[System connects to weather_USA MCP and calls get_alerts_in_USA tool]
Response: [Weather alerts for California displayed]
Query: What's the forecast for latitude 40.7128 and longitude -74.0060 (New York)?
[System calls get_forecast_in_USA tool with coordinates]
Response: [5-day forecast for NYC]

For Israel Weather:

Query: Tell me the weather forecast for Tel Aviv
[System performs the following steps]
1. Opens browser with open_weather_forecast_israel()
2. Enters "Tel Aviv" with enter_weather_forecast_city_israel("Tel Aviv")
3. Selects first city option with select_weather_forecast_city_israel()
4. Extracts forecast with extract_weather_forecast_israel()
Response: [Current weather and forecast for Tel Aviv]
Query: What's the weather like in Jerusalem?
[Same process as above, but for Jerusalem]
Response: [Weather forecast for Jerusalem]

📐 Architecture

System Components

┌─────────────────────────────────────────────────────────┐
│                 host.py (ChatHost)                       │
│  - Orchestrates multiple MCP clients                     │
│  - Manages tool discovery and execution                  │
│  - Handles Claude AI interaction                         │
└─────────────────────────────────────────────────────────┘
         │                                          │
         ▼                                          ▼
┌──────────────────────┐              ┌──────────────────────┐
│  weather_USA.py      │              │  weather_Israel.py   │
│  (MCP Server)        │              │  (MCP Server)        │
│                      │              │                      │
│ Tools:               │              │ Tools:               │
│ • get_alerts_in_USA  │              │ • open_browser       │
│ • get_forecast_USA   │              │ • enter_city         │
│                      │              │ • select_city        │
│                      │              │ • extract_forecast   │
└──────────────────────┘              └──────────────────────┘
         │                                          │
         ▼                                          ▼
┌──────────────────────┐              ┌──────────────────────┐
│ NWS API              │              │ Chromium Browser     │
│ (weather.gov)        │              │ (Playwright)         │
└──────────────────────┘              └──────────────────────┘

Tool Execution Flow

  1. User Query → ChatHost
  2. Tool Discovery → List available tools from all MCP servers
  3. Cohere Analysis → Cohere AI determines which tools to use
  4. Tool Execution → Execute tools in sequence with results
  5. Response Loop → If more tools needed, repeat; otherwise return final answer

🔧 Implementation Details

weather_USA.py - API-Based Approach

  • Uses the National Weather Service API
  • No browser automation needed
  • Direct HTTP requests to fetch structured data
  • Tools:
    • get_alerts_in_USA(state) - Fetches active alerts for a US state
    • get_forecast_in_USA(latitude, longitude) - Gets 5-day forecast for coordinates

weather_Israel.py - Browser Automation Approach

  • Uses Playwright for browser control
  • Automates the weather2day.co.il website
  • Maintains browser session across tool calls
  • Tools:
    • open_weather_forecast_israel() - Opens browser and navigates to website
    • enter_weather_forecast_city_israel(city_name) - Types city name in search field
    • select_weather_forecast_city_israel() - Clicks first matching city from dropdown
    • extract_weather_forecast_israel() - Extracts and cleans forecast data from page

Key Implementation Features

Browser Session Management:

# Global browser/page instances to keep browser open
_browser: Browser | None = None
_page: Page | None = None

async def ensure_browser_initialized():
    """Initialize browser if not already done"""
    # Browser persists across tool calls

Tool Definition with FastMCP:

@mcp.tool()
async def tool_name(param1: str) -> str:
    """Tool description for Claude"""
    # Implementation

MCP Client Integration:

  • Each MCP server runs as a subprocess
  • Host communicates via stdio (MCP protocol)
  • Tools are prefixed with server name to avoid conflicts

📝 Project Structure

MCPProject/
├── host.py                 # Main orchestrator
├── client.py              # MCP client implementation
├── weather_USA.py         # USA weather MCP server
├── weather_Israel.py      # Israel weather MCP server
├── pyproject.toml         # Project dependencies
├── python-version.txt     # Required Python version
└── README.md             # This file

🔍 Understanding MCP Tools

Tool Definition

Each tool is a Python async function decorated with @mcp.tool():

@mcp.tool()
async def my_tool(param: str) -> str:
    """
    Detailed description of what the tool does.
    This docstring is sent to Cohere to help it understand when to use this tool.
    
    Args:
        param: Parameter description
    
    Returns:
        str: Description of return value
    """
    # Implementation
    return result

Tool Discovery

When the host connects to an MCP server, it:

  1. Sends a list_tools() request
  2. Receives tool metadata (name, description, input schema)
  3. Registers tools with namespace: {server_name}__{tool_name}
  4. Sends full tool list to Claude

Tool Execution

When Cohere calls a tool:

  1. Host receives the tool name and arguments
  2. Maps to original tool name and MCP client
  3. Calls the tool on the specific MCP server
  4. Receives result and provides to Cohere
  5. Cohere uses result for next reasoning step

🧪 Testing Individual Tools

You can test tools directly in Python:

import asyncio
from weather_Israel import open_weather_forecast_israel, enter_weather_forecast_city_israel

async def test():
    result1 = await open_weather_forecast_israel()
    print(result1)
    
    result2 = await enter_weather_forecast_city_israel("Tel Aviv")
    print(result2)

asyncio.run(test())

🐛 Troubleshooting

Browser Not Opening

  • Ensure Playwright browsers are installed: playwright install
  • Check if Chromium is blocked by antivirus
  • Try adding headless=True to browser launch for background mode

Tool Not Found

  • Ensure both weather_*.py files are in the same directory
  • Check that MCP servers are starting successfully (look for "Connected to server with tools" messages)
  • Verify tool names match exactly

Timeout Issues

  • Increase the timeout in Playwright selectors
  • Check if the website structure has changed
  • Add wait conditions for specific elements

SSL/Certificate Issues

The code handles Netfree networks with SSL verification disabled. For production, remove verify=False from httpx configuration.

🎓 Extension Ideas

  1. Add more weather sources - Create additional MCP servers for different weather APIs
  2. Caching layer - Store forecast data to avoid repeated browser automation
  3. Notification system - Alert when severe weather is forecasted
  4. Multi-language support - Handle queries in Hebrew and English
  5. Historical data - Compare current forecast with historical weather patterns
  6. GUI Dashboard - Create a web interface showing forecasts from all sources

📚 Resources

🤝 Contributing

To add new weather sources:

  1. Create a new weather_*.py file with MCP server implementation
  2. Add MCPClient entry in host.py
  3. Test with sample queries
  4. Document tools in README

📄 License

This project is for educational purposes.


Happy weather forecasting! 🌤️

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选