Skip to main content
Glama

get-weather

Retrieve current weather conditions and hourly forecasts for any city worldwide to plan activities and stay informed about local atmospheric conditions.

Instructions

Get detailed weather information for any city including current conditions and hourly forecast

Input Schema

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

Implementation Reference

  • main.ts:297-353 (handler)
    Core handler function implementing the get-weather tool logic: geocodes the city, fetches current and hourly weather data from Open-Meteo API, processes and formats the data into a structured ProcessedWeatherData object.
    async function getWeatherForCity(city: string): Promise<ProcessedWeatherData | 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 weather data using coordinates const weatherUrl = `${CONFIG.WEATHER_API}?latitude=${location.latitude}&longitude=${location.longitude}&current=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation,weather_code&hourly=temperature_2m,precipitation&forecast_days=1&timezone=auto`; const weatherResponse = await fetchWithRetry(weatherUrl); const weatherData: WeatherResponse = await weatherResponse.json(); // Process and structure the weather data const current = weatherData.current; const locationName = location.admin1 ? `${location.name}, ${location.admin1}, ${location.country}` : `${location.name}, ${location.country}`; const processedData: ProcessedWeatherData = { location: { name: location.name, fullName: locationName, latitude: location.latitude, longitude: location.longitude, country: location.country, admin1: location.admin1 }, current: { time: current.time, formattedTime: formatTime(current.time), temperature: current.temperature_2m, formattedTemperature: formatTemperature(current.temperature_2m), feelsLike: current.apparent_temperature, formattedFeelsLike: formatTemperature(current.apparent_temperature), humidity: current.relative_humidity_2m, precipitation: current.precipitation, formattedPrecipitation: formatPrecipitation(current.precipitation), weatherCode: current.weather_code, weatherDescription: getWeatherDescription(current.weather_code) }, hourly: weatherData.hourly.time.slice(0, 24).map((time, index) => ({ time: time, formattedTime: formatTime(time), temperature: weatherData.hourly.temperature_2m[index], formattedTemperature: formatTemperature(weatherData.hourly.temperature_2m[index]), precipitation: weatherData.hourly.precipitation[index], formattedPrecipitation: formatPrecipitation(weatherData.hourly.precipitation[index]) })), raw: weatherData }; return processedData; }
  • main.ts:481-532 (registration)
    MCP tool registration for 'get-weather': defines name, description, Zod input schema for city parameter, and execution handler that calls getWeatherForCity and returns formatted MCP response.
    server.tool( 'get-weather', 'Get detailed weather information for any city including current conditions and hourly forecast', { 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 weather information for (e.g., 'New York', 'London', 'Tokyo')") }, async({ city }) => { try { const result = await getWeatherForCity(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('Weather fetch error:', error); const errorMessage = error instanceof Error && error.message.includes('fetch') ? `❌ Unable to fetch weather data. Please check your internet connection and try again.` : `❌ Error: ${error instanceof Error ? error.message : 'Unknown error'}`; return { content: [ { type: "text", text: errorMessage } ] }; } } );
  • Zod input schema validating the 'city' parameter: 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 weather information for (e.g., 'New York', 'London', 'Tokyo')") },
  • Utility function for robust HTTP requests with timeout, retry logic on failures and 5xx errors, used by weather fetching.
    async function fetchWithRetry(url: string, options: RequestInit = {}, retries: number = CONFIG.MAX_RETRIES): Promise<Response> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), CONFIG.REQUEST_TIMEOUT); try { const response = await fetch(url, { ...options, signal: controller.signal }); clearTimeout(timeoutId); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return response; } catch (error) { clearTimeout(timeoutId); if (retries > 0 && (error instanceof Error && (error.name === 'AbortError' || error.message.includes('HTTP 5')))) { await delay(CONFIG.RETRY_DELAY); return fetchWithRetry(url, options, retries - 1); } throw error; } }
  • Mapping of weather codes to human-readable descriptions, used to interpret API weather_code values.
    const WEATHER_CODES: Record<number, string> = { 0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast', 45: 'Foggy', 48: 'Depositing rime fog', 51: 'Light drizzle', 53: 'Moderate drizzle', 55: 'Dense drizzle', 61: 'Slight rain', 63: 'Moderate rain', 65: 'Heavy rain', 71: 'Slight snow', 73: 'Moderate snow', 75: 'Heavy snow', 77: 'Snow grains', 80: 'Slight rain showers', 81: 'Moderate rain showers', 82: 'Violent rain showers', 85: 'Slight snow showers', 86: 'Heavy snow showers', 95: 'Thunderstorm', 96: 'Thunderstorm with slight hail', 99: 'Thunderstorm with heavy hail', };

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