Skip to main content
Glama
ctermiii

Weather MCP Server

by ctermiii

get_weather

Retrieve weather forecasts for any city worldwide, providing temperature, wind, precipitation, and comfort data for 1-16 days to support planning decisions.

Instructions

获取指定城市的天气预报信息。支持1-16天的天气预报,包括温度、风力、舒适度、降雨降雪、紫外线指数、PM2.5等详细信息。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYes城市名称,可以是中文或英文,例如:北京、Shanghai、New York等
daysNo预报天数,范围1-16天,默认7天

Implementation Reference

  • MCP CallToolRequest handler block for 'get_weather' tool. Geocodes city, fetches weather forecast, formats and returns as JSON text content.
    if (request.params.name === "get_weather") {
      const cityName = request.params.arguments.city;
      const days = request.params.arguments.days || 7;
    
      try {
        // 1. 获取城市坐标
        const location = await geocodeCity(cityName);
    
        // 2. 获取天气数据
        const weather = await getWeatherForecast(
          location.latitude,
          location.longitude,
          location.timezone,
          days
        );
    
        // 3. 构建返回结果
        const result = {
          城市信息: {
            名称: location.name,
            国家: location.country,
            坐标: `${location.latitude}, ${location.longitude}`,
            时区: location.timezone
          },
          ...weather
        };
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `错误: ${error.message}`
            }
          ],
          isError: true
        };
      }
    }
  • Input schema definition for the 'get_weather' tool in ListTools response.
    inputSchema: {
      type: "object",
      properties: {
        city: {
          type: "string",
          description: "城市名称,可以是中文或英文,例如:北京、Shanghai、New York等"
        },
        days: {
          type: "number",
          description: "预报天数,范围1-16天,默认7天",
          default: 7,
          minimum: 1,
          maximum: 16
        }
      },
      required: ["city"]
    }
  • index.js:327-346 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining name, description, and input schema for 'get_weather'.
      name: "get_weather",
      description: "获取指定城市的天气预报信息。支持1-16天的天气预报,包括温度、风力、舒适度、降雨降雪、紫外线指数、PM2.5等详细信息。",
      inputSchema: {
        type: "object",
        properties: {
          city: {
            type: "string",
            description: "城市名称,可以是中文或英文,例如:北京、Shanghai、New York等"
          },
          days: {
            type: "number",
            description: "预报天数,范围1-16天,默认7天",
            default: 7,
            minimum: 1,
            maximum: 16
          }
        },
        required: ["city"]
      }
    }
  • Primary helper function that fetches current and forecast weather data from Open-Meteo API using coordinates, including air quality, and formats it.
    async function getWeatherForecast(latitude, longitude, timezone = 'auto', days = 7) {
      try {
        // 限制天数范围在 1-16 之间
        const forecastDays = Math.max(1, Math.min(16, days));
    
        // 构建天气 API URL
        const weatherParams = new URLSearchParams({
          latitude: latitude.toString(),
          longitude: longitude.toString(),
          timezone: timezone,
          // 每日天气数据
          daily: [
            'temperature_2m_max',           // 最高温度
            'temperature_2m_min',           // 最低温度
            'weathercode',                  // 天气代码
            'precipitation_sum',            // 降水量
            'rain_sum',                     // 降雨量
            'snowfall_sum',                 // 降雪量
            'windspeed_10m_max',           // 最大风速
            'windgusts_10m_max',           // 最大阵风
            'winddirection_10m_dominant',  // 主导风向
            'sunrise',                      // 日出时间
            'sunset',                       // 日落时间
            'uv_index_max'                  // 紫外线指数
          ].join(','),
          // 当前天气数据
          current: [
            'temperature_2m',
            'relative_humidity_2m',
            'apparent_temperature',         // 体感温度
            'weathercode',
            'windspeed_10m',
            'winddirection_10m',
            'uv_index'                      // 当前紫外线指数
          ].join(','),
          forecast_days: forecastDays.toString()
        });
    
        const weatherUrl = `https://api.open-meteo.com/v1/forecast?${weatherParams}`;
        const weatherResponse = await fetch(weatherUrl);
        const weatherData = await weatherResponse.json();
    
        if (weatherData.error) {
          throw new Error(`天气API错误: ${weatherData.reason || '未知错误'}`);
        }
    
        // 构建空气质量 API URL
        const airParams = new URLSearchParams({
          latitude: latitude.toString(),
          longitude: longitude.toString(),
          current: ['pm2_5', 'pm10'].join(',')
        });
    
        const airUrl = `https://air-quality-api.open-meteo.com/v1/air-quality?${airParams}`;
        let airData = null;
    
        try {
          const airResponse = await fetch(airUrl);
          airData = await airResponse.json();
          if (airData.error) {
            console.error('空气质量数据获取失败,将显示为无数据');
            airData = null;
          }
        } catch (error) {
          console.error('空气质量API调用失败:', error.message);
        }
    
        return formatWeatherData(weatherData, airData, forecastDays);
      } catch (error) {
        throw new Error(`获取天气数据失败: ${error.message}`);
      }
    }
  • Helper function to convert city name to geographic coordinates (lat, lon, timezone) using Open-Meteo geocoding API.
    async function geocodeCity(cityName) {
      try {
        const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(cityName)}&count=1&language=zh&format=json`;
        const response = await fetch(url);
        const data = await response.json();
    
        if (!data.results || data.results.length === 0) {
          throw new Error(`无法找到城市: ${cityName}`);
        }
    
        const result = data.results[0];
        return {
          name: result.name,
          country: result.country,
          latitude: result.latitude,
          longitude: result.longitude,
          timezone: result.timezone || 'auto'
        };
      } catch (error) {
        throw new Error(`地理编码失败: ${error.message}`);
      }
    }
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. It mentions the forecast range and data types but lacks details on error handling, rate limits, authentication needs, or response format. For a tool with no annotations, this leaves significant behavioral gaps, though it does add some context about the forecast capabilities.

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 a single, efficient sentence that front-loads the core purpose and includes relevant details without unnecessary elaboration. Every part contributes to understanding the tool's functionality, though it could be slightly more structured for clarity.

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's moderate complexity (2 parameters, no output schema, no annotations), the description is adequate but incomplete. It covers the purpose and data types well but lacks details on behavioral aspects like error handling or response structure, which are important for a weather API tool with no annotations to guide the agent.

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 100%, with clear documentation for both parameters (city and days). The description adds minimal value beyond the schema by implying the 'days' parameter relates to the 1-16 day forecast range mentioned, but it does not provide additional syntax or format details. This meets the baseline for high schema coverage.

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

Purpose5/5

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

The description clearly states the specific action ('获取...天气预报信息' - get weather forecast information) and resource ('指定城市' - specified city). It distinguishes the tool by detailing the comprehensive data returned (temperature, wind, comfort level, precipitation, UV index, PM2.5, etc.) and the 1-16 day forecast range, making its purpose explicit and well-defined.

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 by specifying the forecast range (1-16 days) and the types of information provided, but it does not explicitly state when to use this tool versus alternatives. Since there are no sibling tools mentioned, the lack of comparative guidance is less critical, but no explicit prerequisites or exclusions are provided.

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

Install Server

Other Tools

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/ctermiii/weather-mcp-metro'

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