Skip to main content
Glama
dimonets

MCP Weather Server

by dimonets

get-forecast

Retrieve 7-day weather forecasts including temperatures, precipitation, and sunrise/sunset times for any city worldwide.

Instructions

Get 7-day weather forecast for any city including daily temperatures, precipitation, and sunrise/sunset times

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYesThe name of the city to get forecast information for (e.g., 'New York', 'London', 'Tokyo')

Implementation Reference

  • main.ts:535-586 (registration)
    Registration of the 'get-forecast' tool using McpServer.tool(), including description, input schema with Zod validation for city parameter, and async handler function that delegates to getForecastForCity and formats response as text or JSON.
    server.tool(
      'get-forecast',
      'Get 7-day weather forecast for any city including daily temperatures, precipitation, and sunrise/sunset times',
      {
        city: z.string()
          .min(1, "City name cannot be empty")
          .max(100, "City name is too long")
          .describe("The name of the city to get forecast information for (e.g., 'New York', 'London', 'Tokyo')")
      },
      async({ city }) => {
        try {
          const result = await getForecastForCity(city);
          
          // If it's an error string, return it as text
          if (typeof result === 'string') {
            return {
              content: [
                {
                  type: "text",
                  text: result
                }
              ]
            };
          }
          
          // If it's processed data, return it as JSON string for structured access
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(result, null, 2)
              }
            ]
          };
        } catch (error) {
          console.error('Forecast fetch error:', error);
          
          const errorMessage = error instanceof Error && error.message.includes('fetch') 
            ? `❌ Unable to fetch forecast data. Please check your internet connection and try again.`
            : `❌ Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
          
          return {
            content: [
              {
                type: "text",
                text: errorMessage
              }
            ]
          };
        }
      }
    );
  • main.ts:356-406 (handler)
    Core implementation of the forecast tool logic: performs geocoding to get lat/long for the city, fetches 7-day daily forecast data from Open-Meteo API, processes it into a structured ProcessedForecastData object with formatted strings and descriptions, returns error string if city not found.
    async function getForecastForCity(city: string): Promise<ProcessedForecastData | string> {
      // Step 1: Get coordinates for the city
      const geoUrl = `${CONFIG.GEOCODING_API}?name=${encodeURIComponent(city)}&count=1&language=en&format=json`;
      const geoResponse = await fetchWithRetry(geoUrl);
      const geoData: GeocodingResponse = await geoResponse.json();
    
      // Handle city not found
      if (!geoData.results || geoData.results.length === 0) {
        return `❌ Sorry, I couldn't find a city named "${city}". Please check the spelling and try again.`;
      }
    
      const location = geoData.results[0];
      
      // Step 2: Get 7-day forecast data
      const forecastUrl = `${CONFIG.WEATHER_API}?latitude=${location.latitude}&longitude=${location.longitude}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,weather_code,sunrise,sunset&timezone=auto`;
      const forecastResponse = await fetchWithRetry(forecastUrl);
      const forecastData: ExtendedWeatherResponse = await forecastResponse.json();
    
      // Process and structure the forecast data
      const locationName = location.admin1 ? `${location.name}, ${location.admin1}, ${location.country}` : `${location.name}, ${location.country}`;
      
      const processedData: ProcessedForecastData = {
        location: {
          name: location.name,
          fullName: locationName,
          latitude: location.latitude,
          longitude: location.longitude,
          country: location.country,
          admin1: location.admin1
        },
        daily: forecastData.daily.time.map((date, index) => ({
          date: date,
          formattedDate: formatDate(date),
          maxTemperature: forecastData.daily.temperature_2m_max[index],
          formattedMaxTemperature: formatTemperature(forecastData.daily.temperature_2m_max[index]),
          minTemperature: forecastData.daily.temperature_2m_min[index],
          formattedMinTemperature: formatTemperature(forecastData.daily.temperature_2m_min[index]),
          precipitation: forecastData.daily.precipitation_sum[index],
          formattedPrecipitation: formatPrecipitation(forecastData.daily.precipitation_sum[index]),
          weatherCode: forecastData.daily.weather_code[index],
          weatherDescription: getWeatherDescription(forecastData.daily.weather_code[index]),
          sunrise: forecastData.daily.sunrise[index],
          formattedSunrise: formatTime(forecastData.daily.sunrise[index]),
          sunset: forecastData.daily.sunset[index],
          formattedSunset: formatTime(forecastData.daily.sunset[index])
        })),
        raw: forecastData
      };
    
      return processedData;
    }
  • Zod input schema for the 'get-forecast' tool, validating the 'city' parameter as a non-empty string up to 100 chars with description.
      city: z.string()
        .min(1, "City name cannot be empty")
        .max(100, "City name is too long")
        .describe("The name of the city to get forecast information for (e.g., 'New York', 'London', 'Tokyo')")
    },
  • TypeScript interface defining the structured output format of the processed forecast data returned by getForecastForCity.
    interface ProcessedForecastData {
      location: {
        name: string;
        fullName: string;
        latitude: number;
        longitude: number;
        country: string;
        admin1?: string;
      };
      daily: Array<{
        date: string;
        formattedDate: string;
        maxTemperature: number;
        formattedMaxTemperature: string;
        minTemperature: number;
        formattedMinTemperature: string;
        precipitation: number;
        formattedPrecipitation: string;
        weatherCode: number;
        weatherDescription: string;
        sunrise: string;
        formattedSunrise: string;
        sunset: string;
        formattedSunset: string;
      }>;
      raw: ExtendedWeatherResponse;
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions what data is returned but doesn't disclose behavioral traits like rate limits, authentication requirements, error conditions, or whether this is a read-only operation. The description is functional but lacks operational context.

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 front-loads the core purpose and includes all essential details without waste. Every element (duration, resource, data scope) earns its place, making it optimally concise.

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 (1 parameter, no output schema, no annotations), the description covers the basic purpose and data scope adequately. However, it lacks details about behavioral aspects and doesn't help differentiate from sibling tools, making it minimally complete but with clear gaps.

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 the city parameter well-documented in the schema. The description adds no additional parameter semantics beyond what's already in the schema, so it meets the baseline score of 3 for high schema coverage without adding value.

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 7-day weather forecast'), the resource ('for any city'), and the scope of data returned ('including daily temperatures, precipitation, and sunrise/sunset times'). It distinguishes from sibling tools by specifying forecast data rather than current weather or air quality.

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 ('for any city') but doesn't explicitly state when to use this tool versus the sibling tools get-weather and get-air-quality. No guidance is provided about alternatives or exclusions, leaving the agent to infer based on the data types mentioned.

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/dimonets/mcp-weather-server'

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