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}`);
      }
    }

Tool Definition Quality

Score is being calculated. Check back soon.

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