Table of Contents


IPMA MCP Server

A FastMCP server that exposes hourly weather observations from IPMA (Instituto Português do Mar e da Atmosfera, the Portuguese weather institute) as MCP tools, so an LLM client can query them during a conversation.

  • Data sources
    • Observations: https://api.ipma.pt/open-data/observation/meteorology/stations/observations.json
    • Stations: https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json
  • Transport: stdio (local subprocess)
  • Run: .venv/bin/python ipma_mcp.py

What is MCP?

Model Context Protocol

(MCP) is an open protocol that standardizes how AI applications (“hosts”) talk to external data sources and capabilities. Think of it as USB-C for LLM apps: one plug shape, many devices.

Architecture roles

RoleWho it is here
HostThe AI app the user talks to (Claude Desktop, an IDE, a CLI agent)
ClientLives inside the host; maintains a 1:1 connection with each server
Serveripma_mcp.py — exposes capabilities (tools) over the protocol

Server primitives — what a server can expose:

PrimitiveControlled byExample in this server
ToolsThe model decides when to call themlist_stations, get_latest_observations, get_station_observations
ResourcesThe app reads them (files/data)not used here
PromptsThe user picks them (templates)not used here

Transport — how messages travel:

  • stdio: server runs as a local subprocess, messages over stdin/stdout. Used by this server via mcp.run().
  • Streamable HTTP: server is a remote web service.

Tool-call flow

User asks: "What's the temperature in Lisbon?"
    │
    ▼
Host → client → server:  tools/list        (discover tools + JSON schemas)
    │
    ▼
Model sees tools in context, emits a tool call
    │
    ▼
Host → client → server:  tools/call        (e.g. get_latest_observations(station_id=1200545))
    │
    ▼
Server executes → returns result → host feeds it back to the model

The protocol layer (schema discovery, JSON-RPC framing, validation) is handled entirely by FastMCP; this file only writes three Python functions and decorators.


How this server is built

Imports and constants

import time
 
import httpx
from fastmcp import FastMCP
 
OBSERVATIONS_URL = (
    "https://api.ipma.pt/open-data/observation/meteorology/stations/observations.json"
)
STATIONS_URL = (
    "https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json"
)
 
NODATA = -99.0
  • httpx — async-capable HTTP client, fits FastMCP’s async tool functions.
  • NODATA = -99.0 — IPMA’s sentinel value for missing measurement. Filtering these out early keeps tool output compact and prevents the LLM from misreading -99.0 °C as real data.

Server instance

WIND_DIRECTIONS = {
    0: "sem rumo",
    1: "N", 2: "NE", 3: "E", 4: "SE",
    5: "S", 6: "SW", 7: "W", 8: "NW", 9: "N",
}
 
mcp = FastMCP(
    "ipma",
    instructions=(
        "Dados de observações meteorológicas horárias das estações do IPMA (Portugal). "
        "Valores -99.0 significam sem dados. Atualização horária."
    ),
)
  • FastMCP("ipma") creates the server; "ipma" is the server name clients display.
  • instructions is free-text sent to the host — good place to teach the model domain conventions (here: nodata semantics, hourly cadence).
  • WIND_DIRECTIONS maps IPMA’s numeric wind-direction class to a human-readable compass name. Class 9 also maps to N (the sensor range wraps).

Caching layer

_cache: dict[str, tuple[float, object]] = {}
_CACHE_TTL = 300  # seconds; the API itself updates hourly
 
 
async def _get(url: str):
    async with httpx.AsyncClient(
        timeout=30, headers={"User-Agent": "ipma-mcp/1.0"}
    ) as client:
        resp = await client.get(url)
        resp.raise_for_status()
        return resp.json()
 
 
async def _get_cached(url: str, key: str):
    now = time.monotonic()
    if key not in _cache or now - _cache[key][0] > _CACHE_TTL:
        _cache[key] = (now, await _get(url))
    return _cache[key][1]

Why cache?

The dataset is a single JSON blob updated hourly. Without caching, every tool call re-downloads hundreds of KB of station history. A module-level _cache keyed by a short alias ("stations", "observations") holds (fetched_at, payload) tuples; entries older than _CACHE_TTL (5 min) are refetched.
time.monotonic() is used instead of time.time() so wall-clock changes (NTP sync, DST) can’t corrupt TTL math.

Cleaning observations

def _clean(observation: dict | None) -> dict:
    """Drop -99.0 nodata fields and add a readable wind direction name."""
    if not observation:
        return {}
    cleaned = {
        field: value
        for field, value in observation.items()
        if value != NODATA
    }
    wind_class = observation.get("idDireccVento")
    if wind_class is not None:
        cleaned["idDireccVentoNome"] = WIND_DIRECTIONS.get(wind_class, "desconhecido")
    return cleaned
  • Removes every -99.0 field (this doubles as the “empty station” detector: _clean of a fully-missing station yields {}).
  • Decorates output with idDireccVentoNome so the model doesn’t have to guess what class 3 means.

Measurement fields

FieldMeaning
temperaturaair temperature (°C)
humidaderelative humidity (%)
pressaopressure (hPa)
precAcumuladaaccumulated precipitation (mm)
intensidadeVentowind speed (m/s)
intensidadeVentoKMwind speed (km/h)
idDireccVento / idDireccVentoNomewind direction class / name
radiacaosolar radiation (kJ/m²)

The tools

Tools are declared with @mcp.tool. FastMCP derives the JSON schema from the type hints (int | None, int = 6) and the docstring becomes the tool description the model reads. Docstrings are therefore prompt-engineering: they carry argument semantics, units, and constraints the LLM will rely on.

list_stations

@mcp.tool
async def list_stations() -> list[dict]:
    """Lista de identificadores das estações meteorológicas do IPMA.
    ...
    """
    features = await _get_cached(STATIONS_URL, "stations")
    stations = []
    for feature in features:
        props = feature["properties"]
        lon, lat = feature["geometry"]["coordinates"]
        stations.append(
            {
                "idEstacao": props["idEstacao"],
                "localEstacao": props["localEstacao"],
                "latitude": lat,
                "longitude": lon,
            }
        )
    _cache["station_index"] = (
        time.monotonic(),
        {str(s["idEstacao"]): s["localEstacao"] for s in stations},
    )
    return sorted(stations, key=lambda s: s["localEstacao"])
  • Flattens the GeoJSON feature collection into flat dicts. Note lon, lat order — GeoJSON coordinates are [longitude, latitude].
  • Sorts alphabetically so LLM output is stable.
  • Side effect: stores an id → name index in _cache for future display use.

Typical usage: the model calls this first to discover valid idEstacao values.

get_latest_observations

@mcp.tool
async def get_latest_observations(station_id: int | None = None) -> dict:
    ...
    observations = await _get_cached(OBSERVATIONS_URL, "observations")
    latest_ts = max(observations)
    latest = observations[latest_ts]
 
    if station_id is not None:
        sid = str(station_id)
        if sid not in latest:
            raise ValueError(f"Estação {sid} sem dados na observação mais recente")
        return {"datahora": latest_ts, "idEstacao": sid, **_clean(latest[sid])}
 
    return {
        "datahora": latest_ts,
        "observacoes": {
            sid: cleaned for sid, obs in latest.items() if (cleaned := _clean(obs))
        },
    }
  • observations is a dict keyed by timestamp → {station_id: measurements}.
  • max(observations) picks the newest key — it works because the timestamps sort lexicographically (ISO-like format). The result is the most recent hour that has any data, not necessarily the current hour.
  • The LLM passes an int, but JSON keys are strings — hence str(station_id).

Two subtle behaviors

  1. The walrus operator (cleaned := _clean(obs)) filters out stations whose entire record is nodata, so the “all stations” payload stays lean.
  2. Raising ValueError is the idiomatic FastMCP way to signal “tool failed”; the exception text is returned to the model, which can react (e.g. fall back to list_stations).

get_station_observations

@mcp.tool
async def get_station_observations(station_id: int, last_hours: int = 6) -> dict:
    ...
    if not 1 <= last_hours <= 24:
        raise ValueError("last_hours deve estar entre 1 e 24")
 
    observations = await _get_cached(OBSERVATIONS_URL, "observations")
    sid = str(station_id)
    series = [
        {"datahora": ts, **_clean(obs[sid])}
        for ts, obs in sorted(observations.items())
        if obs.get(sid)
    ][-last_hours:]
    if not series:
        raise ValueError(f"Estação {sid} sem observações disponíveis")
    return {"idEstacao": sid, "observacoes": series}
  • Input validation (1 ≤ last_hours ≤ 24) happens before any fetch.
  • Sorts all hourly snapshots oldest → newest, keeps only hours where this station reported, takes the last last_hours with [-last_hours:].

Tool reference

ToolSignaturePurpose
list_stations() -> list[dict]Discover stations: id, name, lat/lon (sorted by name)
get_latest_observations(station_id: int \| None = None) -> dictNewest hourly observation; one station or all
get_station_observations(station_id: int, last_hours: int = 6) -> dictLast N (≤24) hourly observations, oldest → newest

Running and connecting

.venv/bin/python ipma_mcp.py

Because it speaks stdio, a host launches it as a subprocess. Typical client config (Claude Desktop style):

{
  "mcpServers": {
    "ipma": {
      "command": "/absolute/path/to/.venv/bin/python",
      "args": ["ipma_mcp.py"]
    }
  }
}

Use an absolute interpreter path — hosts spawn the process without your shell environment/venv activated.


Gotchas and design notes

Gotchas and design notes

  • max(observations) assumes sortable timestamp keys. If IPMA ever changes the key format (e.g. epoch ints mixed with ISO strings), the “latest” pick breaks silently.
  • Cache is per-process. Restarting the server resets it; two server instances (two clients) each fetch independently.
  • Wind class 9 maps to N — the code treats it as equivalent to class 1.
  • No error handling around resp.raise_for_status() beyond letting it propagate — an IPMA outage surfaces as a tool error to the model rather than stale-but-available cached data.
  • last_hours counts hours with data, not calendar hours: a station that reports sparsely returns fewer rows than requested.
  • MCP — protocol overview
  • FastMCP — Python framework used here
  • IPMA open data: https://api.ipma.pt

Full code

"""MCP server exposing IPMA (Portuguese weather institute) station observations.
 
Run:  .venv/bin/python ipma_mcp.py        (stdio transport)
"""
import time
import httpx
from fastmcp import FastMCP
 
OBSERVATIONS_URL = "https://api.ipma.pt/open-data/observation/meteorology/stations/observations.json"
STATIONS_URL     = "https://api.ipma.pt/open-data/observation/meteorology/stations/stations.json"
NODATA = -99.0
WIND_DIRECTIONS = {0: "sem rumo", 1: "N", 2: "NE", 3: "E", 4: "SE",
                   5: "S", 6: "SW", 7: "W", 8: "NW", 9: "N"}
 
mcp = FastMCP("ipma", instructions=(
    "Dados de observações meteorológicas horárias das estações do IPMA (Portugal). "
    "Valores -99.0 significam sem dados. Atualização horária."))
 
_cache: dict[str, tuple[float, object]] = {}
_CACHE_TTL = 300  # seconds; the API itself updates hourly
 
async def _get(url: str):
    async with httpx.AsyncClient(timeout=30,
            headers={"User-Agent": "ipma-mcp/1.0"}) as client:
        resp = await client.get(url); resp.raise_for_status()
        return resp.json()
 
async def _get_cached(url: str, key: str):
    now = time.monotonic()
    if key not in _cache or now - _cache[key][0] > _CACHE_TTL:
        _cache[key] = (now, await _get(url))
    return _cache[key][1]
 
def _clean(observation: dict | None) -> dict:
    """Drop -99.0 nodata fields and add a readable wind direction name."""
    if not observation: return {}
    cleaned = {f: v for f, v in observation.items() if v != NODATA}
    w = observation.get("idDireccVento")
    if w is not None:
        cleaned["idDireccVentoNome"] = WIND_DIRECTIONS.get(w, "desconhecido")
    return cleaned
 
@mcp.tool
async def list_stations() -> list[dict]:
    """Lista de identificadores das estações meteorológicas do IPMA."""
    features = await _get_cached(STATIONS_URL, "stations")
    stations = [{"idEstacao": p["properties"]["idEstacao"],
                 "localEstacao": p["properties"]["localEstacao"],
                 "latitude": lat, "longitude": lon}
                for p in features
                for lon, lat in [p["geometry"]["coordinates"]]]
    _cache["station_index"] = (time.monotonic(),
        {str(s["idEstacao"]): s["localEstacao"] for s in stations})
    return sorted(stations, key=lambda s: s["localEstacao"])
 
@mcp.tool
async def get_latest_observations(station_id: int | None = None) -> dict:
    """Observação mais recente (todas as estações ou uma estação).
 
    Field meanings: intensidadeVentoKM (km/h), temperatura (°C),
    precAcumulada (mm), humidade (%), pressao (hPa), radiacao (kJ/m2).
    """
    observations = await _get_cached(OBSERVATIONS_URL, "observations")
    latest_ts = max(observations)
    latest = observations[latest_ts]
    if station_id is not None:
        sid = str(station_id)
        if sid not in latest:
            raise ValueError(f"Estação {sid} sem dados")
        return {"datahora": latest_ts, "idEstacao": sid, **_clean(latest[sid])}
    return {"datahora": latest_ts,
            "observacoes": {sid: c for sid, obs in latest.items()
                            if (c := _clean(obs))}}
 
@mcp.tool
async def get_station_observations(station_id: int, last_hours: int = 6) -> dict:
    """Histórico de observações horárias de uma estação (últimas N horas)."""
    if not 1 <= last_hours <= 24:
        raise ValueError("last_hours deve estar entre 1 e 24")
    observations = await _get_cached(OBSERVATIONS_URL, "observations")
    sid = str(station_id)
    series = [{"datahora": ts, **_clean(obs[sid])}
              for ts, obs in sorted(observations.items()) if obs.get(sid)]
    if not series:
        raise ValueError(f"Estação {sid} sem observações disponíveis")
    return {"idEstacao": sid, "observacoes": series[-last_hours:]}
 
if __name__ == "__main__":
    mcp.run()