Skip to main content
Glama
sun873087

MCP Weather Sample

by sun873087

MCP Weather Sample

一個完整的 Model Context Protocol (MCP) 示範專案,展示如何整合天氣服務與多種 AI 模型。

專案簡介

MCP Weather Sample 是一個基於 MCP (Model Context Protocol) 的示範應用程式,展示如何建立一個完整的客戶端-伺服器架構,整合天氣 API 服務與多種 AI 模型 (Claude、GPT、Gemini)。專案支援兩種傳輸模式:STDIO 和 SSE (Server-Sent Events),提供靈活的部署選項。

核心功能

  • 🌤️ 天氣查詢服務: 整合 NOAA Weather API,提供即時天氣預報和警報

  • 🤖 多 AI 模型支援: 支援 Anthropic Claude、OpenAI GPT 和 Google Gemini 模型

  • 🔄 雙傳輸模式: 支援 STDIO(本地)和 SSE(遠端)兩種連接方式

  • 🔐 安全認證: 內建 API 金鑰驗證機制

  • 異步架構: 全面使用 Python asyncio 提供高效能處理

  • 🛠️ 工具導向: 基於 MCP 工具呼叫模式的 AI 互動

技術亮點

  • 現代 Python: 使用 Python 3.12+ 的最新特性

  • FastAPI 整合: 使用 FastAPI 和 FastMCP 建構 SSE 伺服器

  • 模組化設計: 清晰的客戶端和伺服器分離架構

  • 配置驅動: 透過 JSON 配置文件管理多伺服器設定

Related MCP server: mcp-weather

技術堆疊

核心框架

  • Python 3.12+: 主要開發語言

  • MCP >=1.12.2: Model Context Protocol 核心框架

  • FastAPI >=0.116.1: 現代 Web 框架(SSE 模式)

  • FastMCP: 基於 FastAPI 的 MCP 伺服器實現

AI 模型整合

  • Anthropic >=0.59.0: Claude AI 模型

  • OpenAI >=1.97.1: GPT 模型

  • Google GenAI >=1.27.0: Gemini 模型

網路與資料處理

  • httpx >=0.28.1: 異步 HTTP 客戶端

  • jsonschema >=4.25.0: JSON Schema 驗證

  • python-dotenv >=1.1.1: 環境變數管理

快速開始

環境需求

  • Python 3.12 或更高版本

  • UV 套件管理器(建議)或 pip

  • 有效的 API 金鑰:

    • NOAA Weather API(免費)

    • AI 模型 API 金鑰(Anthropic、OpenAI 或 Google)

安裝步驟

  1. 複製專案

    git clone <repository-url>
    cd mcp-sample
  2. 安裝依賴

    # 使用 UV(建議)
    uv sync
  3. 配置環境變數

    # 建立 .env 檔案
    cp .env.example .env
    
    # 編輯 .env 檔案,添加您的 API 金鑰
    ANTHROPIC_API_KEY=your_anthropic_key
    OPENAI_API_KEY=your_openai_key
    GOOGLE_API_KEY=your_google_key
  4. 設定伺服器配置

    檢查並修改 servers-config.json 檔案中的設定:

    {
      "mcpServers": {
        "sse_weather": {
          "type": "sse",
          "url": "http://localhost:8080/sse",
          "accessToken": "your_access_token"
        },
        "stdio_weather": {
          "type": "stdio",
          "command": "uv",
          "args": ["run", "python", "weather.py"],
          "cwd": "src/servers/weather/stdio"
        }
      }
    }

    註意: your_access_token 設定在 src/servers/weather/sse/user_db.py 中。

     users = {
         "felix": {
             "api_key": "password123",
             "full_name": "Felix Kewa",
             "role": "admin"
         },
         "alice": {
             "api_key": "alicepass456",
             "full_name": "Alice Johnson",
             "role": "developer"
         },
         "bob": {
             "api_key": "bobsecret789",
             "full_name": "Bob Smith",
             "role": "viewer"
         }
     }   

基本使用範例

1. 啟動 SSE 天氣伺服器

uv run src/servers/weather/sse/mcp-weather.py

2. 啟動 MCP 客戶端

# 在另一個終端機中
uv run src/client/client.py

3. 基本天氣查詢

MCP Client Started!
Type your queries or 'quit' to exit.

Query: 阿拉巴馬州是否有天氣警報?
Calling tool get_alerts with args {'state': 'AL'}]
是的,阿拉巴馬州有多個天氣警報生效中:

**高溫警告
**
*   **北阿拉巴馬州與田納西州中南部部分地區**:預計酷
熱指數將高達華氏106度。
*   **阿拉巴馬州西南部、佛
羅里達州西北部與密西西比州東南部部分地區**:預計酷熱指數將高達
華氏109度。
*   **阿拉巴馬州中部**:包括 Autauga、Bibb
、Blount、Bullock、Calhoun、Chilton、Coosa、Dallas、Elmore、Etowah、F
ayette、Greene、Hale、Jefferson、Lamar、Lowndes、Macon、Marengo、Marion、Montgomery、Perry
、Pickens、Pike、Shelby、St. Clair、Sumter、Talladega、Tallapoosa、Tus
caloosa、Walker 與 Winston 等郡,預計酷熱指數將高達華氏106度。


高溫與高濕度可能導致與高溫相關的疾病。建議多喝水、待在有空調
的室內、避免日曬,並關心親友鄰居。在戶外時需格外小心,穿
著輕便寬鬆的衣物,並盡量將劇烈活動安排在清晨或傍晚。

**
離岸流聲明**
*   **阿拉巴馬州沿海地區(Mobile Coastal, Baldwin Coastal)
與佛羅里達州沿海地區**:有危險的離岸流。離岸流即使對
泳技最好的人也可能造成危險,將他們從岸邊捲入深水區。建議在有救生員
看管的區域游泳。若被捲入離岸流,請保持冷靜並漂浮,不要逆
流游泳。

架構概覽

graph TB
    subgraph "客戶端層"
        Client[MCP Client]
        Host[MCP Host]
        AI[AI Models]
    end
    
    subgraph "傳輸層"
        STDIO[STDIO Transport]
        SSE[SSE Transport]
    end
    
    subgraph "伺服器層"
        StdioServer[STDIO Weather Server]
        SSEServer[SSE Weather Server]
    end
    
    subgraph "外部服務"
        Weather[NOAA Weather API]
    end
    
    Client --> Host
    Host --> AI
    AI --> Host
    Host --> STDIO
    Host --> SSE
    STDIO --> StdioServer
    SSE --> SSEServer
    StdioServer --> Weather
    SSEServer --> Weather

主要元件

MCP 客戶端 (src/client/client.py)

  • MCPClient: 單一 MCP 伺服器連接管理

  • MCPHost: 多伺服器管理和 AI 模型整合

  • ModelVendor: AI 模型供應商枚舉

天氣伺服器

  • STDIO 模式 (src/servers/weather/stdio/weather.py): 本地標準輸入輸出連接

  • SSE 模式 (src/servers/weather/sse/mcp-weather.py): HTTP SSE 遠端連接

提供的工具

  • get_alerts: 獲取美國州份的天氣警報

  • get_forecast: 獲取指定座標的詳細天氣預報

進階功能

工具權限控制

透過 servers-config.json 精確控制每個伺服器可使用的工具:

{
  "allowedTools": ["get_alerts", "get_forecast"],
  "notAllowedTools": ["get_forecast"]
}

API 金鑰管理

SSE 模式支援多種認證方式:

  • HTTP Header: x-api-key

  • Bearer Token: Authorization: Bearer <token>

  • Query Parameter: ?api_key=<key>

文件導覽

授權條款

本專案採用 MIT 授權條款

貢獻指南

歡迎參與專案貢獻!請參閱 貢獻指南 了解如何:

  • 回報問題

  • 提交功能請求

  • 提供程式碼貢獻

  • 改進文件

支援與回饋

如有問題或建議,請:

  1. 查閱 常見問題

  2. 搜尋現有的 Issues

  3. 建立新的 Issue 或 Discussion


開始您的 MCP 之旅! 🚀 探索如何用 Model Context Protocol 建構智慧應用程式。

Available Tools

2 tools
get_alertsB
獲取美國特定州份的警報資料.

Args:
    state (str): 美國州份的縮寫 (e.g., "CA", "TX", "NY")
    
Returns:
    str: 警報資料的文字描述
ParametersJSON Schema
NameRequiredDescriptionDefault
stateYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions what the tool does but doesn't describe important behavioral aspects: whether this is a read-only operation, what permissions might be needed, rate limits, error conditions, or what happens with invalid state codes. For a tool with zero annotation coverage, this leaves significant gaps in understanding its 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?

The description is appropriately concise with three clear sections: purpose statement, Args section with parameter details, and Returns section. Each sentence earns its place by providing essential information. The structure is logical and front-loaded with the main purpose. Minor improvement could be made by integrating the parameter details more seamlessly.

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?

Given the tool has 1 parameter with 0% schema coverage but an output schema exists (returns string), the description provides adequate basic context. It covers the purpose and parameter semantics reasonably well. However, for a tool with no annotations, it should ideally include more behavioral context about what happens with invalid inputs, authentication needs, or rate limits to be fully complete.

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 description adds meaningful context beyond the input schema, which has 0% description coverage. It specifies that the 'state' parameter should be a US state abbreviation and provides examples ('CA', 'TX', 'NY'). This clarifies the expected format and valid values, compensating well for the schema's lack of descriptions. However, it doesn't mention whether all 50 states are supported or if there are restrictions.

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 clearly states '獲取美國特定州份的警報資料' (Get alert data for specific US states), which is a specific verb+resource combination. It distinguishes from the sibling tool 'get_forecast' by focusing on alerts rather than weather forecasts. However, it doesn't explicitly mention what type of alerts (weather, emergency, etc.), keeping it from a perfect score.

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 description implies usage context by specifying '美國特定州份' (specific US states), suggesting it should be used for US state alerts. However, it provides no explicit guidance on when to use this versus the 'get_forecast' sibling tool, nor does it mention any prerequisites or exclusions. The usage is implied but not clearly articulated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_forecastC
獲取特定位置的預報資料

Args:
    latitude (float): 緯度
    longitude (float): 經度
ParametersJSON Schema
NameRequiredDescriptionDefault
latitudeYes
longitudeYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

C2.7/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 burden of behavioral disclosure. The description only states what the tool does at a high level ('get forecast data') without explaining what the response contains, whether there are rate limits, authentication requirements, data freshness, or any other behavioral characteristics. This is inadequate for a tool with no annotation coverage.

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?

The description is appropriately concise with a clear purpose statement followed by parameter documentation. The two-sentence structure is efficient with no wasted words. However, the front-loading could be improved as the parameter documentation immediately follows the purpose statement without additional context.

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?

Given that there's an output schema (which handles return values) and only 2 simple parameters, the description provides the minimum viable information. However, with no annotations and a sibling tool present, the description should do more to distinguish this tool and explain its behavioral characteristics. The description is adequate but has clear gaps in contextual information.

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?

The description includes parameter information in the Args section, documenting both latitude and longitude parameters with their types. However, with 0% schema description coverage, the description compensates by providing this parameter documentation. The parameter documentation is minimal but covers the basics, meeting the baseline expectation when schema coverage is low.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the purpose ('獲取特定位置的預報資料' - 'Get forecast data for a specific location') which is clear but somewhat vague. It specifies the action (get/retrieve) and resource (forecast data) but doesn't distinguish from the sibling 'get_alerts' tool or provide details about what type of forecast data (weather, temperature, precipitation, etc.).

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?

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention the sibling 'get_alerts' tool or provide any context about when this forecast tool is appropriate versus other tools that might exist. There's no information about prerequisites or constraints.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

B3.1/5.0
Disambiguation5/5

The two tools have clearly distinct purposes: get_alerts retrieves weather alerts for a U.S. state, while get_forecast provides forecast data for a specific latitude/longitude location. There is no overlap or ambiguity between these functions.

Naming Consistency5/5

Both tools follow a consistent verb_noun naming pattern (get_alerts, get_forecast) with identical verb usage and snake_case formatting. The naming is perfectly predictable and readable.

Tool Count2/5

With only 2 tools for a weather server, the surface feels too thin for the domain. A weather service typically needs more operations like current conditions, historical data, or multi-day forecasts to be useful for agents. The count is borderline insufficient.

Completeness2/5

The tool set is severely incomplete for a weather domain. It lacks core operations like getting current conditions, historical weather data, or multi-location forecasts. Agents will hit dead ends trying to perform basic weather-related tasks with only alerts and single-location forecasts.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    This is a Model Context Protocol (MCP) server that provides weather information using the National Weather Service (NWS) API. Features Get weather alerts for a US state Get weather forecast for a specific location (using latitude and longitude)
  • F
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol (MCP) server that enables AI assistants and LLMs to access real-time weather data and forecasts by connecting to the OpenWeatherMap API.
  • A
    license
    B
    quality
    D
    maintenance
    A simple Model Context Protocol server that provides real-time weather data to AI agents like GitHub Copilot, allowing users to get current weather information for any city through natural language queries.
    2
    32
    97
    MIT
  • -
    license
    Not graded
    quality
    Not graded
    maintenance
    A basic Model Context Protocol server implementation that demonstrates core MCP functionality including tools and resources. Provides weather alerts through the Weather API and serves as a learning example for MCP development.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sun873087/mcp-sample'

If you have feedback or need assistance with the MCP directory API, please join our Discord server