Skip to main content
Glama

get_weather_forecast

Retrieve weather forecasts for cities in Portugal using IPMA data to plan activities and prepare for conditions.

Instructions

Obter previsão meteorológica para uma cidade específica em Portugal

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYesNome da cidade (ex: Lisboa, Porto, Coimbra, Faro, etc.)
daysNoNúmero de dias de previsão (máximo 10)

Implementation Reference

  • Implements the core tool logic: fetches location ID, retrieves forecast data and weather types from IPMA API, formats and limits to specified days, returns formatted text response.
    private async getWeatherForecast(city: string, days: number) {
      try {
        // Primeiro, obter a lista de locais para encontrar o globalIdLocal
        const locationsResponse = await fetch(`${this.baseUrl}/distrits-islands.json`);
        const locationsData = await locationsResponse.json() as ApiResponse<Location>;
        
        const location = locationsData.data.find((loc: Location) => 
          loc.local.toLowerCase().includes(city.toLowerCase())
        );
    
        if (!location) {
          return {
            content: [
              {
                type: "text",
                text: `Cidade "${city}" não encontrada. Use get_locations para ver cidades disponíveis.`
              }
            ]
          };
        }
    
        // Obter previsão para o local encontrado
        const forecastResponse = await fetch(
          `${this.baseUrl}/forecast/meteorology/cities/daily/${location.globalIdLocal}.json`
        );
        const forecastData = await forecastResponse.json() as ApiResponse<WeatherForecast>;
    
        // Obter tipos de tempo para descrições
        const weatherTypesResponse = await fetch(`${this.baseUrl}/weather-type-classe.json`);
        const weatherTypesData = await weatherTypesResponse.json() as ApiResponse<WeatherType>;
    
        const weatherTypes = weatherTypesData.data.reduce((acc: any, item: WeatherType) => {
          acc[item.idWeatherType] = item;
          return acc;
        }, {});
    
        const limitedData = forecastData.data.slice(0, days);
        
        let result = `📍 **Previsão para ${location.local}**\n\n`;
        result += `📍 Coordenadas: ${location.latitude}, ${location.longitude}\n`;
        result += `🕐 Última atualização: ${forecastData.dataUpdate}\n\n`;
    
        limitedData.forEach((day: WeatherForecast) => {
          const weatherDesc = weatherTypes[day.idWeatherType]?.descWeatherTypePT || "Desconhecido";
          result += `📅 **${day.forecastDate}**\n`;
          result += `🌡️ Temperatura: ${day.tMin}°C - ${day.tMax}°C\n`;
          result += `☁️ Condições: ${weatherDesc}\n`;
          result += `🌧️ Probabilidade de precipitação: ${day.precipitaProb}%\n`;
          result += `💨 Vento: ${day.predWindDir}\n\n`;
        });
    
        return {
          content: [
            {
              type: "text",
              text: result
            }
          ]
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        throw new McpError(ErrorCode.InternalError, `Erro ao obter previsão: ${errorMessage}`);
      }
    }
  • src/index.ts:132-150 (registration)
    Registers the 'get_weather_forecast' tool in the ListToolsRequestSchema handler with name, description, and input schema definition.
    {
      name: "get_weather_forecast",
      description: "Obter previsão meteorológica para uma cidade específica em Portugal",
      inputSchema: {
        type: "object",
        properties: {
          city: {
            type: "string",
            description: "Nome da cidade (ex: Lisboa, Porto, Coimbra, Faro, etc.)"
          },
          days: {
            type: "number",
            description: "Número de dias de previsão (máximo 10)",
            default: 5
          }
        },
        required: ["city"]
      }
    },
  • Defines the input schema for the tool, specifying parameters 'city' (required string) and 'days' (optional number, default 5).
    inputSchema: {
      type: "object",
      properties: {
        city: {
          type: "string",
          description: "Nome da cidade (ex: Lisboa, Porto, Coimbra, Faro, etc.)"
        },
        days: {
          type: "number",
          description: "Número de dias de previsão (máximo 10)",
          default: 5
        }
      },
      required: ["city"]
    }
  • Dispatcher case in CallToolRequestSchema handler that validates input and invokes the getWeatherForecast method.
    case "get_weather_forecast":
      if (!toolArgs?.city) {
        throw new McpError(ErrorCode.InvalidParams, "City parameter is required");
      }
      return await this.getWeatherForecast(toolArgs.city, toolArgs.days || 5);

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
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 states the tool gets forecasts for cities in Portugal, but doesn't describe what the forecast includes (e.g., temperature, precipitation), how it's formatted, whether it's real-time or cached, rate limits, error handling, or data sources. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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 in Portuguese that directly states the tool's purpose. It's appropriately sized and front-loaded with the core functionality, with no redundant or verbose language. Every word earns its place by specifying the action, resource, and geographic scope.

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 tool's complexity (2 parameters, no output schema, no annotations), the description is incomplete. It lacks details on what the forecast returns (e.g., data structure, units), behavioral traits like rate limits or errors, and usage context relative to siblings. Without an output schema, the description should ideally hint at return values, but it doesn't, leaving the agent with insufficient information for effective use.

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 description adds no parameter semantics beyond what the input schema provides. The schema has 100% description coverage, with clear documentation for 'city' (city name with examples) and 'days' (number of forecast days, maximum 10, default 5). Since schema coverage is high (>80%), the baseline score is 3, as the description doesn't compensate with additional context like valid city formats or day-range implications.

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 tool's purpose: 'Obter previsão meteorológica para uma cidade específica em Portugal' (Get weather forecast for a specific city in Portugal). It specifies the verb ('obter' - get) and resource ('previsão meteorológica' - weather forecast), and distinguishes from siblings by focusing on city-specific forecasts rather than locations, seismic data, UV forecasts, stations, or warnings. However, it doesn't explicitly differentiate from all siblings (e.g., 'get_weather_warnings' might also be city-specific).

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. It doesn't mention when to prefer this over 'get_weather_warnings' for alerts, 'get_uv_forecast' for UV data, or 'get_weather_stations' for station-specific data. There's no context about prerequisites, limitations, or typical use cases beyond the basic purpose.

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