К основному содержанию
скилл CX Codex

connector-weatherapi — скилл для Claude Code: погода из канистры

Скилл задаёт правильный способ читать погоду в Caffeine-сборках: через mops-пакет weatherapi-client, а не самодельные вызовы ic.http_request.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add caffeinelabs/skills --skill connector-weatherapi -a claude-code
Открыть на GitHub

Что делает connector-weatherapi

Скилл описывает девять read-only операций WeatherAPI.com, сгенерированных из OpenAPI-спеки в один модуль Apis/APIsApi: текущая погода, прогноз, история, будущая погода, морской прогноз, астрономия, часовой пояс, IP-геолокация и автодополнение локаций. Внутри — готовые Motoko-биндинги и пример актора, который читает температуру и трёхдневный ряд максимумов.

Ключ API передаётся как query-string-параметр, а не заголовком, поэтому он попадает в URL запроса. Держите его в stable-переменной, которую пишет админский вызов, и не логируйте собранный адрес. Бесплатный тариф покрывает текущую погоду, прогноз на 3 дня, астрономию, часовой пояс, поиск и IP-поиск; история, будущая погода, морской прогноз и 14-дневный прогноз требуют платного плана и возвращают 403 на бесплатном ключе.

Вызовы по умолчанию нереплицируемые — это требование корректности, а не экономия. Ответы несут посекундные метки времени, и реплицируемый outcall сломал бы консенсус на большинстве запросов. Все поля ответа опциональны, поэтому доставать их удобнее через do ?. Пустая строка и ноль означают «параметр не передан»: hour = 0 не выбирает полночь, а убирает фильтр целиком.

Какие задачи решает

  • прочитать текущую температуру из канистры
  • получить трёхдневный ряд дневных максимумов
  • подключить прогноз погоды без ручных HTTP-запросов
  • разобрать опциональные поля ответа WeatherAPI
  • отличить 401 от 403 и 400 по тексту ошибки

Примеры запросов агенту

  • добавь в бэкенд чтение текущей температуры через weatherapi-client
  • сделай прогноз максимумов на три дня для Цюриха
  • почему мой ic.http_request к api.weatherapi.com падает на консенсусе?

Как установить connector-weatherapi

1Через Skills CLI (Vercel)

npx skills add caffeinelabs/skills --skill connector-weatherapi -a claude-code

2Вручную: положить файлы

~/.claude/skills/connector-weatherapi/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/connector-weatherapi/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о connector-weatherapi

Как установить connector-weatherapi в Claude?

Выполните npx skills add caffeinelabs/skills --skill connector-weatherapi -a claude-code. Скилл окажется в ~/.claude/skills/connector-weatherapi/SKILL.md.

Что делает connector-weatherapi?

Описывает поддерживаемый путь чтения погоды в Caffeine-сборках: mops-пакет weatherapi-client с девятью операциями WeatherAPI.com и корректной обработкой ключа.

Почему нельзя вызывать api.weatherapi.com напрямую?

Ручные ic.http_request обходят защиту нереплицируемого outcall: тела ответов содержат посекундные метки, из-за которых реплицируемый вызов не соберёт консенсус.

Исходный текст

SKILL.md · Apache-2.0
---
name: connector-weatherapi
description: >-
  MANDATORY recipe for every Caffeine build that reads weather data from a
  canister. The supported path is the `weatherapi-client` mops package
  (WeatherAPI.com) over outbound HTTPS, authenticated with a query-string API
  key. Hand-rolling `ic.http_request` calls to `api.weatherapi.com` is a
  FORBIDDEN anti-pattern — it bypasses the non-replicated-outcall safeguard
  (WeatherAPI bodies carry per-request clocks and fail consensus), the generated
  JSON decoding, and the API-key handling. Load this skill whenever the user,
  spec, or any prior task mentions weather, forecast, temperature, humidity,
  wind, rain, snow, conditions, sunrise, sunset, moon phase, astronomy,
  timezone, IP geolocation, marine or tide forecasts, or location autocomplete —
  and BEFORE writing any code that touches a weather endpoint.
version: 0.2.2
caffeineai-subscription: [none]
compatibility:
  mops:
    weatherapi-client: "~0.3.0"
---

# Weather data with `weatherapi-client`

Motoko bindings for [WeatherAPI.com](https://www.weatherapi.com/), generated
from its OpenAPI spec. All nine operations live in a single module,
**`Apis/APIsApi`**, and all nine are read-only `GET`s.

# Backend

A canister that reads the current temperature and a three-day maximum series.
Non-replicated is the default, so you only supply the key:

```motoko filepath=src/backend/main.mo
import { realtimeWeather; forecastWeather } "mo:weatherapi-client/Apis/APIsApi";
import { type Config; defaultConfig } "mo:weatherapi-client/Config";
import Array "mo:core/Array"; // in scope so `days.map(…)` dot notation resolves

actor {
  // The key is a query-string credential. Hold it in a stable variable set by
  // an admin call; never hard-code it in source.
  func config(apiKey : Text) : Config = { defaultConfig with auth = ?#apiKey apiKey };

  // `q` is any WeatherAPI location query: "Zurich", "47.37,8.55", a postcode,
  // an IATA code, or "auto:ip".
  public func currentTempC(apiKey : Text, q : Text) : async ?Float {
    let res = await* realtimeWeather(config apiKey, q, "");
    do ? { res.current!.temp_c! };
  };

  // Daily maxima for the next three days.
  public func maxTempsC(apiKey : Text, q : Text) : async [?Float] {
    let res = await* forecastWeather(config apiKey, q, #_3_, "", 0, 0, "", "no", "no", 0);
    let ?forecast = res.forecast else return [];
    let ?days = forecast.forecastday else return [];
    days.map(func(d) = do ? { d.day!.maxtemp_c! });
  };
}
```

## The nine operations

| Function | Endpoint | Returns |
|---|---|---|
| `realtimeWeather(cfg, q, lang)` | `/current.json` | `RealtimeWeather200Response` |
| `forecastWeather(cfg, q, days, dt, unixdt, hour, lang, alerts, aqi, tp)` | `/forecast.json` | `ForecastWeather200Response` |
| `historyWeather(cfg, q, dt, unixdt, endDt, unixendDt, hour, lang)` | `/history.json` | `FutureWeather200Response` |
| `futureWeather(cfg, q, dt, lang)` | `/future.json` | `FutureWeather200Response` |
| `marineWeather(cfg, q, days, dt, unixdt, hour, lang)` | `/marine.json` | `MarineWeather200Response` |
| `astronomy(cfg, q, dt)` | `/astronomy.json` | `Astronomy200Response` |
| `timeZone(cfg, q)` | `/timezone.json` | `Location` |
| `ipLookup(cfg, q)` | `/ip.json` | `Ip` |
| `searchAutocompleteWeather(cfg, q)` | `/search.json` | `[Search]` |

`days` is an enum, not a number: `ForecastWeatherDaysParameter` is `#_1_` … `#_14_`
and `MarineWeatherDaysParameter` is `#_1_` … `#_7_` (the underscores are how the
generator escapes numeric enum values — `#_3_`, not `#_3` or `3`).

## API key setup

1. Sign up at [weatherapi.com](https://www.weatherapi.com/signup.aspx) — the
   free tier covers current weather, 3-day forecast, astronomy, timezone,
   search and IP lookup. History, future, marine and 14-day forecasts need a
   paid plan and return **403** on free keys.
2. Copy the key from the dashboard and pass it as `auth = ?#apiKey key`.
3. The client appends it as `?key=…` (WeatherAPI takes no `Authorization`
   header), so **it appears in the request URL**. Keep it in a stable variable
   written by an admin-only call, and never log the built URL.

## Calls are non-replicated by default

The package ships `is_replicated = ?false` in `defaultConfig`, and that is a
*correctness* requirement here, not just a cost saving. Every response carries
per-request clocks — `Location.localtime` / `localtime_epoch`,
`Current.last_updated` / `last_updated_epoch` — which change second to second. A
*replicated* outcall has every subnet node issue its own request and demands
bit-identical bodies, so those fields would break consensus on most calls while
burning ~13× the cycles. You don't set it yourself; the default is correct.

Override with `is_replicated = ?true` only together with a `transform` that
strips the volatile fields.

## Everything is optional

WeatherAPI marks no response field required, so the generated models are
all-optional: `RealtimeWeather200Response.current : ?Current`,
`Current.temp_c : ?Float`, and so on. Reach through them with a `do ?` block
(`do ? { res.current!.temp_c! }`) rather than nested `switch`es, and decide what
an absent field means for your caller — the API omits fields your plan does not
cover (for example `air_quality` without the `aqi=yes` parameter).

## Empty string and zero mean "omit"

Optional query parameters are dropped when they are `""` or `0`, because
WeatherAPI rejects empty `lang=` and zero-valued numerics. So passing `""` for
`lang`, `dt`, `alerts`, `aqi` and `0` for `unixdt`, `tp` is how you say "not
supplied" — there is no `?Text` parameter to leave `null`.

One consequence worth knowing: **`hour = 0` does not select midnight**, it omits
the `hour` filter entirely and you get the whole day's hourly array. Filter the
returned `hour : ?[ForecastForecastdayInnerHourInner]` yourself if you need
00:00.

## Errors

Non-2xx responses and decode failures `throw Error.reject(…)`. The client is
generated with `diagnostics`, so the message is
`HTTP <status> body[<n>B]=<first 100 chars>: <reason>` — enough to tell a 401
(bad key) from a 403 (endpoint not on your plan) from a 400 (`q` not resolvable)
without extra logging. Catch with `try`/`catch` and surface
`Error.message(err)`.

© caffeinelabs · Apache-2.0 · caffeinelabs/skills

Похожие скиллы

Всё по теме «Бэкенд и API» →
etl-connector-strategy Samuel Berthe Помогает решить, стоит ли SaaS-продукту появляться источником в чужих ETL/ELT-каталогах, на какой платформе и какой путь сборки выбрать. CX Codex +1 8 000установок api-connector-builder affaan-m Скилл добавляет новый API-коннектор по шаблону существующих интеграций в репозитории. Пригодится, когда нужно расширить проект без второй архитектуры. CX Codex +1 4 500установок Weather Automation Claude Office Skills Скилл получает текущую погоду и прогноз, создаёт предупреждения по условиям и запускает погодные сценарии для выбранных локаций. CX Codex +1 4 500установок power-platform-mcp-connector-suite официальный github Создаёт Power Platform custom connector с MCP-интеграцией для Copilot Studio. Нужен при разработке, проверке и отладке схемы коннектора. 8 700установок pp-weather-goat Trevin Chow Скилл для Claude и других агентов: погода, штормовые предупреждения NWS, качество воздуха и совет — ехать на велосипеде или нет. CX Codex +1 501установок power-platform-connector официальный github Правило для GitHub Copilot, которое подсказывает, как писать JSON-схемы кастомных коннекторов Power Platform: Swagger 2.0, apiProperties и settings. ★ 40 418звёзд репо

Из того же набора25

connector-slack Скилл учит агента отправлять сообщения в канал Slack из Caffeine-канистры через пакет slack-client. Рецепт помечен как экспериментальный. CX Codex +1 14 300установок extension-inference Скилл задаёт единственный поддерживаемый способ подключить LLM к Caffeine-приложению: через пакет caffeineai-inference-client и Config.fromEnv, без ключа от пользователя. CX Codex +1 11 900установок connector-twilio Скилл для отправки SMS и MMS из Caffeine-канистры через пакет twilio-client. Экспериментальный: ни один вызов ещё не проверяли на живом Twilio. CX Codex +1 11 200установок connector-googledrive Скилл подключает Google Drive к сборкам на Caffeine: списки файлов, папки, доступы и комментарии через готовые mops-пакеты. CX Codex +1 9 100установок connector-spotify Скилл для Caffeine-сборок на Motoko: подключает Spotify Web API через пакет spotify-client и запрещает самодельные HTTP-вызовы. CX Codex +1 6 500установок connector-tmdb Скилл подключает The Movie Database к Caffeine-проектам на Motoko через пакет tmdb-client. Нужен, когда приложение читает фильмы, сериалы или данные о людях. CX Codex +1 6 200установок migrating-motoko-actors Помогает переносить состояние актора Motoko между апгрейдами канистры и менять схему stable-полей через цепочку миграций в migrations/. CX Codex +1 4 300установок troubleshooting-motoko-migrations Справочник по ошибкам цепочки миграций Motoko: когда диагностика не сходится с main.mo или правка файла миграции не срабатывает. CX Codex +1 4 500установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой