Skip to main content
Glama
terisuke

MCP Weather Service

by terisuke

get-weather

Retrieve current weather data for any city by providing the city name as input. This tool fetches weather information from the MCP Weather Service.

Instructions

Get weather information for a city

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYesCity name to get weather for

Implementation Reference

  • src/index.ts:178-238 (registration)
    Registers the 'get-weather' tool using server.tool() with name, description, input schema using Zod, and inline handler function.
    server.tool(
      'get-weather', 
      'Get weather information for a city', 
      {
        city: z.string().describe('City name to get weather for')
      }, 
      async ({ city }) => {
        debug(`Handling get-weather request for city: ${city}`);
        
        try {
          let attempts = 0;
          const maxAttempts = 3;
          let lastError: Error | null = null;
          
          while (attempts < maxAttempts) {
            try {
              attempts++;
              debug(`Attempt ${attempts}/${maxAttempts} for city: ${city}`);
              
              // 最後の試行では、可能であればモックデータを使用
              const useMockData = attempts === maxAttempts;
              const weather = await getWeatherForCity(city, useMockData);
              
              const conditionJapanese = weather.condition;
              
              return {
                content: [{
                  type: 'text',
                  text: `${weather.cityName}の天気:\n気温: ${weather.temperature}\n状態: ${conditionJapanese}`
                }]
              };
            } catch (error) {
              lastError = error instanceof Error ? error : new Error(String(error));
              debug(`Attempt ${attempts} failed:`, lastError.message);
              
              if (attempts < maxAttempts) {
                const waitTime = 1000 * attempts;
                debug(`Waiting ${waitTime}ms before next retry`);
                await new Promise(resolve => setTimeout(resolve, waitTime));
              }
            }
          }
          
          return {
            content: [{
              type: 'text',
              text: `${city}の天気情報の取得に失敗しました: ${lastError?.message || '不明なエラー'}`
            }]
          };
        } catch (error) {
          debug(`Error processing weather request:`, error);
          
          return {
            content: [{
              type: 'text',
              text: `${city}の天気情報の取得に失敗しました: ${error instanceof Error ? error.message : String(error)}`
            }]
          };
        }
      }
    );
  • Handler function implementing the 'get-weather' tool logic: retries API calls via getWeatherForCity, handles errors, formats response as MCP text content.
    async ({ city }) => {
      debug(`Handling get-weather request for city: ${city}`);
      
      try {
        let attempts = 0;
        const maxAttempts = 3;
        let lastError: Error | null = null;
        
        while (attempts < maxAttempts) {
          try {
            attempts++;
            debug(`Attempt ${attempts}/${maxAttempts} for city: ${city}`);
            
            // 最後の試行では、可能であればモックデータを使用
            const useMockData = attempts === maxAttempts;
            const weather = await getWeatherForCity(city, useMockData);
            
            const conditionJapanese = weather.condition;
            
            return {
              content: [{
                type: 'text',
                text: `${weather.cityName}の天気:\n気温: ${weather.temperature}\n状態: ${conditionJapanese}`
              }]
            };
          } catch (error) {
            lastError = error instanceof Error ? error : new Error(String(error));
            debug(`Attempt ${attempts} failed:`, lastError.message);
            
            if (attempts < maxAttempts) {
              const waitTime = 1000 * attempts;
              debug(`Waiting ${waitTime}ms before next retry`);
              await new Promise(resolve => setTimeout(resolve, waitTime));
            }
          }
        }
        
        return {
          content: [{
            type: 'text',
            text: `${city}の天気情報の取得に失敗しました: ${lastError?.message || '不明なエラー'}`
          }]
        };
      } catch (error) {
        debug(`Error processing weather request:`, error);
        
        return {
          content: [{
            type: 'text',
            text: `${city}の天気情報の取得に失敗しました: ${error instanceof Error ? error.message : String(error)}`
          }]
        };
      }
    }
  • Zod input schema defining the 'city' parameter as a required string.
    {
      city: z.string().describe('City name to get weather for')
    }, 
  • Helper function to fetch real weather data from Open-Meteo APIs (geocoding + forecast) or use mock data, translates weather codes to Japanese.
    async function getWeatherForCity(city: string, useMockData: boolean = false) {
      try {
        const normalizedCity = city.trim();
        debug(`Getting weather for city: ${normalizedCity}`);
        
        if (useMockData && MOCK_WEATHER_DATA[normalizedCity]) {
          debug(`Using mock data for ${normalizedCity}`);
          return MOCK_WEATHER_DATA[normalizedCity];
        }
        
        // ジオコーディングAPIを使用して座標を取得
        const geocodingResponse = await axios.get(
          `https://geocoding-api.open-meteo.com/v1/search`,
          {
            params: {
              name: normalizedCity,
              count: 1,
              language: 'en'
            },
            timeout: 5000
          }
        );
        
        if (!geocodingResponse.data.results || geocodingResponse.data.results.length === 0) {
          throw new Error(`City "${normalizedCity}" not found`);
        }
        
        const { latitude, longitude, name } = geocodingResponse.data.results[0];
        debug(`Found coordinates for ${name}: ${latitude}, ${longitude}`);
        
        // 天気APIを使用して天気情報を取得
        const weatherResponse = await axios.get(
          `https://api.open-meteo.com/v1/forecast`,
          {
            params: {
              latitude,
              longitude,
              current: 'temperature_2m,weather_code',
              timezone: 'Asia/Tokyo'
            },
            timeout: 5000
          }
        );
        
        const weatherCode = weatherResponse.data.current.weather_code;
        const weatherDescription = weatherCodes[weatherCode] || "不明";
        
        return {
          cityName: name,
          temperature: `${weatherResponse.data.current.temperature_2m}${weatherResponse.data.current_units.temperature_2m}`,
          condition: weatherDescription
        };
      } catch (error) {
        debug(`Error getting weather for city ${city}:`, error);
        
        if (MOCK_WEATHER_DATA[city]) {
          debug(`Falling back to mock data for ${city}`);
          return MOCK_WEATHER_DATA[city];
        }
        
        throw error;
      }
    }
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 only states the basic function without mentioning any behavioral traits such as rate limits, error handling, data freshness, or authentication requirements. For a tool with no annotations, this is a significant gap in transparency.

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?

The description is a single, efficient sentence that directly states the tool's purpose without any unnecessary words. It is appropriately sized and front-loaded, making it easy to understand at a glance. Every part of the sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It doesn't cover behavioral aspects like performance, errors, or return format, which are crucial for a tool that fetches dynamic data like weather. The description alone is insufficient for full contextual understanding.

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 input schema has 100% description coverage, with the single parameter 'city' documented as 'City name to get weather for'. The description adds no additional semantic context beyond what the schema provides, such as format examples or constraints. With high schema coverage, the baseline score of 3 is appropriate.

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 the verb ('Get') and resource ('weather information') with the target ('for a city'). It's specific about what the tool does, but since there are no sibling tools, it doesn't need to differentiate from alternatives. It avoids tautology by not just restating the name.

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?

The description provides no guidance on when to use this tool versus alternatives or any contextual prerequisites. It simply states the function without indicating scenarios, limitations, or comparisons to other tools. This leaves usage entirely implicit.

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/terisuke/my-weather-mcp'

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