mcp-weather-connector
mcp-weather-connector
MCP-сервер, который даёт ИИ-агенту доступ к прогнозу погоды через Open-Meteo — публичное API без ключа и регистрации.
Небольшой, намеренно: репозиторий про то, как устроен инструментальный слой для агента, а не про погоду. Погода здесь — понятный предлог показать границу доверия между моделью и внешним миром.
Зачем это
Model Context Protocol — способ дать языковой модели право совершать действия во внешних сервисах. Как только такое право появляется, возникает вопрос: что будет, если модель передаст в инструмент мусор, а чужой сервис в этот момент отдаст 503.
Три решения, которые в этом коде показаны явно:
Вход от модели — недоверенный. Модель может передать пустую строку, простыню на десять килобайт или управляющие символы. Всё это отсекается в server.py до сетевого вызова, а не в чужом API.
Ошибки различаются по типу. 4xx повторять бессмысленно — это ошибка запроса, повтор её не исправит. 5xx чаще разовый сбой — один повтор с паузой. Логика в _get_json, проверяется тестами на счётчик вызовов.
Наружу уходит текст, а не сырой JSON. Агенту нечего домысливать и не в чем ошибиться при пересказе. Ответ 200 без нужного поля считается сбоем, а не поводом отдать пустоту.
Отдельно: число дней вне диапазона приводится к границе, а не считается ошибкой. Если модель попросила прогноз на 30 дней, полезнее отдать семь, чем уронить диалог сообщением об ошибке.
Related MCP server: open-meteo-mcp-server
Инструменты
Инструмент | Что делает |
| Текущая погода: температура, ощущается как, влажность, ветер |
| Прогноз на 1–7 дней с осадками |
| Проверяет существование населённого пункта и уточняет страну |
locate существует ради одного сценария: когда агент не уверен в написании, лучше уточнить у пользователя, чем молча выдать погоду не того города.
Установка
pip install -e .Подключение к Claude Desktop
В claude_desktop_config.json:
{
"mcpServers": {
"weather": {
"command": "mcp-weather"
}
}
}После перезапуска приложения инструменты появятся в списке доступных.
Разработка
pip install -e ".[dev]"
pytest
ruff check .Тесты покрывают то, что реально ломается: пустой и переразмеренный ввод, нечисловое количество дней, 4xx без повтора, 5xx с одним повтором, успех со второй попытки, ответ 200 без полезной нагрузки, неизвестный код погоды. HTTP замокан через respx — сеть в тестах не нужна.
Структура
src/mcp_weather/
client.py — работа с Open-Meteo: типы, повторы, разбор ответа
server.py — MCP-слой: валидация входа и форматирование вывода
tests/
test_tools.pyСетевой код отделён от MCP-слоя намеренно: клиент тестируется сам по себе, а инструменты агента остаются тонкой обёрткой над понятными функциями.
Лицензия
MIT
Available Tools
3 toolscurrent_weatherB
Текущая погода в указанном городе.
Args: city: Название населённого пункта, например «Ижевск» или «Berlin».
| Name | Required | Description | Default |
|---|---|---|---|
| city | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must fully explain behavioral traits, but it only says 'current weather'. It does not mention data source, units, freshness, failure behavior, or any other operational considerations that an agent should know before invoking it.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concisely four intuitive sentences, directly states the core function, and uses a simple 'Args' outline for the parameter. There is no repetition or unstructured detail, making it easy to parse.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple one-parameter tool, the description is mostly sufficient, and an output schema exists so the return value is largely handled. However, the lack of usage guidance and behavioral disclosure leaves the agent with incomplete context beyond the essential call pattern, bringing it to a minimal viable level.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema only has 'city' with no description, so the description's extra explanation of the city parameter is valuable. It defines city as a locality and gives concrete examples like 'Ижевск' or 'Berlin', which adds meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states the specific verb and resource: 'Текущая погода в указанном городе' (current weather in a specified city). It clearly identifies city as the target and provides examples, and the word 'текущая' distinguishes it from the sibling 'forecast', though it does not explicitly name alternatives.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is given about when to use this tool versus the siblings 'forecast' or 'locate'. The description only defines the tool's function; it does not mention exclusions, alternative conditions, or scenarios that would favor another tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
forecastA
Прогноз погоды на несколько дней вперёд.
Args: city: Название населённого пункта. days: Сколько дней показать, от 1 до 7. Значения вне диапазона приводятся к границе, а не считаются ошибкой.
| Name | Required | Description | Default |
|---|---|---|---|
| city | Yes | ||
| days | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are present, so the description carries the behavioral disclosure burden. It adds a useful non-obvious behavior: out-of-range days are clamped to the bounds rather than treated as errors. It does not cover invalid city behavior or errors, but this is a low-risk read-style tool and the main complexity is disclosed.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact, front-loaded with the purpose, and uses a clean Args block. Every sentence contributes either to selecting the tool or calling it correctly, with no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given an output schema and only two self-explanatory parameters, the description is largely sufficient for a correct call. The main missing piece is explicit guidance about choosing between forecast and current_weather, which remains implicit rather than stated.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description compensates by explaining both parameters: city is the populated place name, and days controls how many days to return with the 1–7 range. It adds the clamping behavior, which the schema cannot express. The default value is left to the schema, which is acceptable.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool returns a weather forecast for multiple upcoming days, which identifies the resource and the specific purpose. It also differentiates it from current_weather by the 'несколько дней' framing, though it does not explicitly name the sibling.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The multi-day forecast purpose and 1–7 day range imply when it should be used, especially compared to current_weather. However, the description never explicitly says 'use current_weather for current conditions' or states when forecast should not be used, leaving the choice to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
locateA
Проверяет, что населённый пункт существует, и уточняет страну.
Полезно, когда агент не уверен в написании: лучше уточнить у пользователя, чем молча выдать погоду не того города.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are present, so the description carries the behavioral disclosure burden. It explains that the tool verifies existence and returns country information, and it includes a useful user-facing safety rule. However, it does not describe error behavior, ambiguous results, or what happens when the query matches multiple places.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two short sentences: the first states the core behavior, the second gives a concrete usage scenario. There is no filler, and the most important information is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a single-parameter lookup tool with an output schema present, the description is sufficient for basic calling decisions. It would benefit from covering edge cases like ambiguous or nonexistent places, but given the small surface and clear sibling context, the definition is adequately complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema says only that 'query' is a string with no description (0% coverage). The description compensates by indicating that the parameter is a populated place name whose spelling the agent may be uncertain about, adding meaningful semantics to the otherwise empty schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action — 'checks that a populated place exists' and 'clarifies the country' — with a clear resource. It also distinguishes itself from weather siblings by focusing on location verification rather than weather output.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly tells the agent when to use this tool: when uncertain about the spelling of a place name, it is better to ask the user than to silently return weather for the wrong city. It clearly implies when this tool matters, though it does not explicitly name alternatives or 'when not to use.'
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v1.0.0- First observed
current_weather - First observed
forecast - First observed
locate
TDQS
Scored across 3 tools
Each tool has a clearly distinct purpose: current conditions, multi-day forecast, and location validation. There is no overlap or ambiguity between them, even though two tools accept a city argument.
Naming is readable but inconsistent: current_weather is a noun phrase, forecast is a bare noun, and locate is a verb. A more consistent pattern like get_current_weather, get_forecast, and validate_location would be clearer.
Three tools is well-scoped for a weather connector. Each tool covers a necessary function without unnecessary overlap or bloat.
The core weather workflows are covered: current conditions and multi-day forecasts, with optional location validation. Minor gaps exist, such as lacking unit selection or weather alerts, but these are not essential for most use cases.
Maintenance
Related MCP Connectors
Global weather via Open-Meteo: forecast, historical, marine, air quality, geocoding, elevation.
NOAA weather for AI agents: conditions, forecasts, observed history. 3 tools, free, no key.
US weather & geo for AI agents: forecasts, alerts, earthquakes, elevation, geocoding. No keys.
US weather & geo for AI agents: forecasts, alerts, earthquakes, elevation, geocoding. No keys.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceEnables AI assistants to retrieve current weather, forecasts, and summaries for any global location using the Open-Meteo API, with no API key required.17 npmCreative Commons Zero v1.0 Universal
- AlicenseAqualityDmaintenanceProvides comprehensive access to Open-Meteo weather APIs, including forecasts, historical data, air quality, marine weather, and geocoding, enabling LLMs to retrieve weather information and location data.17609 npmMIT
- AlicenseNot gradedqualityDmaintenanceProvides live weather data (current conditions, forecasts) and city geocoding through Open-Meteo API, enabling AI assistants to answer weather queries without an API key.MIT
- AlicenseAqualityDmaintenanceProvides weather forecasts and geocoding lookup using free Open-Meteo APIs, enabling LLMs to query real-time weather and multi-day forecasts for any location.13 npmISC