Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-03: janas-quakes - the earthquakes from INGV and the USGS

camauri485910a5a33e
diff --git a/ChangeLog.md b/ChangeLog.md
index 3622a9e..0ae604f 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,10 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-03] - janas-quakes: the earthquakes
+
+- **janas-quakes**, an MCP service of the earthquakes: the latest near a place, where the user is, or within a sea of the built-in tables (by its polygons), the strongest in the world with the USGS's expected impact and its tsunami flag (told as a flag, not as a tsunami), one in detail (how many felt it, the strongest shaking estimated, the link to the source's page). INGV (CC BY 4.0) for Italy and the seas that reach into it, the USGS (public domain) elsewhere, each the other's fallback; the answers give the model each event's id, to name the one meant. Run over the protocol and in janas-chat; `tests/test_quakes_parse.c` checks the reading of both sources and the layouts.
+
## [2026-10-02] - janas-system: this computer
- **janas-system**, an MCP service that only reads and reaches no network: how the computer is (the processor and the kernel's share of it, the memory and the swap, on Linux the pressure, every disk, the battery and its wear, the temperatures a device), what fills a directory (8 seconds and 64 levels at most, never across filesystems or links; "at least" when the time runs out), the programs using the most processor or memory or those of a name, the errors of the logs (the same message but for its numbers counted once, the latest read first) and the services that failed, the updates by the package manager's last list (apt, dnf, pacman; nothing fetched), the network interfaces, the Wi-Fi signal, the gateway. Run over the protocol on the development laptop; `tests/test_system_parse.c` checks the reading of Linux's texts and the layouts.
diff --git a/README.md b/README.md
index ca1577b..7dbfe15 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,7 @@ Everything the engine does is chosen from what it measures, so another machine w
- **`janas-prices`:** prices and finance, for information: currencies at the ECB's rates, crypto-assets, shares (with a free key of yours), inflation, central banks' rates, electricity where it is open data, the cheapest fuel near a place in Italy, France, Spain and Austria ([docs/services/prices.md](docs/services/prices.md)).
- **`janas-github`:** a project on GitHub: its issues and pull requests (the new ones since you last asked), its latest releases, its recent commits, what it is; it only reads, with the gh command's token when you have one ([docs/services/github.md](docs/services/github.md)).
- **`janas-git`:** the git repositories of your computer: what has changed, the commits, the branches, a diff; and a commit, pull, push or switch of branch, each shown whole and asked of you first; nothing that throws work away ([docs/services/git.md](docs/services/git.md)).
+- **`janas-quakes`:** the earthquakes: the latest near a place or where you are, the strongest in the world, one in detail, from INGV (Italy and its seas) and the USGS ([docs/services/quakes.md](docs/services/quakes.md)).
- **`janas-system`:** this computer: how it is (memory, processor, disks, battery, temperatures), what fills a directory, the programs running, the errors of its logs, the updates, the network; it only reads, and none of its tools reaches the network ([docs/services/system.md](docs/services/system.md)).
- **`janas-wiki`:** Wikipedia when you ask for it: its search, a page shown to you as it is (the introduction, then the section asked for) while the model reads only a note of it, and the pages about what lies around a place ([docs/services/wiki.md](docs/services/wiki.md)).
- **`janas-server`:** the model behind an HTTP API that follows OpenAI's, so that clients written for it can use a model running on this machine: chat and completions with tools, JSON output held to a schema and log-probabilities, the Responses API with its conversations, embeddings and moderations, a chat page of its own to try it from a browser ([below](#using-it-over-http)), and code completion for VSCodium and VS Code ([docs/code-completion.md](docs/code-completion.md)).
@@ -299,7 +300,7 @@ printf 'Explain mixture of experts in one paragraph.\n/quit\n' \
### Janas's services
-The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-prices`, `janas-system`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?", "where is diesel cheapest near here?", "what is filling my disk?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
+The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-prices`, `janas-quakes`, `janas-system`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?", "where is diesel cheapest near here?", "what is filling my disk?", "was there an earthquake?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
**The services' tools are given when they are needed.** Written into the system message, the tools of three services made it four thousand tokens, over a minute of a large model before the first message, and every service more made it longer. The system message now holds a catalog, a line a service, and the model opens a service when a question needs it: that service's instructions and tools come back as the answer of the call, its tools can be called from then on, and the next reply is held to be a call (a small model told to call one made the answer up instead). With Qwen3.6-35B-A3B the system message went from 4,057 tokens to 616, and opening the weather costs about a thousand tokens, once in a conversation, when the first question about the weather comes. `--all-tools` writes them all into the system message as before.
@@ -599,6 +600,7 @@ It stands on the work of others, and says so:
- **The Unicode Character Database** gives the tokenizer its tables (`tools/gen_unicode`), and **OpenAI's OpenAPI specification** gives `janas-server` its route table (`tools/openapi_routes`).
- **GNU libmicrohttpd, yyjson and Mbed TLS** are compiled into the programs named below.
- **`janas-flights`** reads the positions of aircraft from [adsb.lol](https://adsb.lol) (data under the Open Database License) and [adsb.fi](https://adsb.fi), routes from [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's, schedules from [AviationStack](https://aviationstack.com); its tables of places are built from [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0) and [Natural Earth](https://www.naturalearthdata.com) (public domain).
+- **`janas-quakes`** reads the earthquakes from [INGV](https://terremoti.ingv.it) (Istituto Nazionale di Geofisica e Vulcanologia, CC BY 4.0) for Italy and its seas and from the [USGS](https://earthquake.usgs.gov) (public domain) elsewhere, and places from [Nominatim](https://nominatim.org) (© OpenStreetMap contributors, ODbL).
- **`janas-weather`** reads forecasts and the sea from [Open-Meteo](https://open-meteo.com) (CC BY 4.0) and [MET Norway](https://api.met.no) (CC BY 4.0), the stations' reports from [aviationweather.gov](https://aviationweather.gov) (NOAA), warnings from [MeteoAlarm](https://meteoalarm.org) (EUMETNET) and the Italian alert levels from the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica) (CC BY 4.0). With no place named, the services ask [GeoJS](https://www.geojs.io) or [ipwho.is](https://ipwho.is) where the internet connection is.
- **`janas-maps`** reads [OpenStreetMap](https://www.openstreetmap.org)'s data (© OpenStreetMap contributors, ODbL) through [Nominatim](https://nominatim.org), [Photon](https://photon.komoot.io), [Valhalla](https://github.com/valhalla/valhalla) and [OSRM](https://project-osrm.org) on the servers of [FOSSGIS](https://fossgis.de), and the [Overpass API](https://overpass-api.de) (with [Private.coffee's instance](https://overpass.private.coffee) when it is busy), and journeys by public transport from [Transitous](https://transitous.org), over the operators' open timetables.
- **`janas-prices`** reads the [European Central Bank](https://www.ecb.europa.eu) (through [Frankfurter](https://frankfurter.dev)), [CoinGecko](https://www.coingecko.com/en/api) (data provided by CoinGecko) and [Coinbase](https://www.coinbase.com), [Alpha Vantage](https://www.alphavantage.co) with the user's key, [Eurostat](https://ec.europa.eu/eurostat) and the [World Bank](https://data.worldbank.org) (CC BY 4.0), the [New York Fed](https://www.newyorkfed.org), the [Bank of England](https://www.bankofengland.co.uk) and the [Swiss National Bank](https://data.snb.ch), [energy-charts.info](https://www.energy-charts.info) (Fraunhofer ISE; the zones under CC BY 4.0, from the Bundesnetzagentur's SMARD), and the fuel prices of Italy's [MIMIT](https://www.mimit.gov.it) (IODL 2.0), France's [prix-carburants](https://data.economie.gouv.fr), Spain's [ministry](https://energia.serviciosmin.gob.es) and Austria's [E-Control](https://www.e-control.at); places through [Nominatim](https://nominatim.org).
diff --git a/docs/services/README.md b/docs/services/README.md
index c6fcfc1..edb51ba 100644
--- a/docs/services/README.md
+++ b/docs/services/README.md
@@ -1,6 +1,6 @@
# Janas's services
-A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, prices and finance, GitHub's projects, the git repositories of your computer, the computer itself - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
+A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, prices and finance, GitHub's projects, the git repositories of your computer, the computer itself, the earthquakes - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
| Service | What it answers | Key |
|---|---|---|
@@ -9,6 +9,7 @@ A service of Janas is a program that brings data of the world - flights, the wea
| [`janas-github`](github.md) | a project's issues and pull requests (the new ones), its latest releases, its recent commits, what it is | none; the gh command's token when you have one |
| [`janas-maps`](maps.md) | a route by car, bike or on foot, step by step; journeys by public transport; what is near a place; where an address is | none |
| [`janas-prices`](prices.md) | for information: currencies, crypto-assets, shares, inflation, central banks' rates, electricity, the cheapest fuel near a place | none; a free one of your own for shares |
+| [`janas-quakes`](quakes.md) | the earthquakes near a place or where you are, the strongest in the world, one in detail | none |
| [`janas-system`](system.md) | this computer: how it is (memory, processor, disks, battery, temperatures), what fills a directory, the programs running, the errors, the updates, the network | none; nothing reaches the network |
| [`janas-weather`](weather.md) | the weather now (a model's and a station's), the forecast, the sea and its waves, the warnings in force | none |
| [`janas-wiki`](wiki.md) | Wikipedia's search, its pages as text, the pages about what lies around a place | none |
diff --git a/docs/services/quakes.md b/docs/services/quakes.md
new file mode 100644
index 0000000..889190c
--- /dev/null
+++ b/docs/services/quakes.md
@@ -0,0 +1,49 @@
+# janas-quakes
+
+The earthquakes for `janas-chat` or any other MCP client (see [the services](README.md)): the latest near a place or where you are, the strongest in the world, one in detail. It only reads, from open sources, without a key.
+
+## The tools
+
+- **`quakes_near`** - the earthquakes around a place (`place`: a town, a region, or a sea, whose earthquakes are those within it; where you are unless asked), within a radius (`radius`, 300 km unless asked, 1,000 at most), of the last days (`days`, 7 unless asked, 30 at most), of a magnitude or more (`min_mag`, 2.5 unless asked): the latest first, each with its time (and how long ago, when it was today), its magnitude, its depth, its distance and way from the place, and where the source says it was.
+- **`quakes_strong`** - the strongest earthquakes in the world of the last days (`days`, 7), of a magnitude or more (`min_mag`, 5), the strongest first, each with the impact the USGS expects (PAGER's alert: green, yellow, orange, red) and whether it was at sea and strong enough for a tsunami.
+- **`quakes_event`** - one earthquake in detail: by its id (each answer gives them, in brackets, to the model), or the latest near a place, or with neither the latest near you ("the one just felt"): its magnitude and its kind, the time, where it was (a sea or a region, the nearest town), its depth, its distance from the place asked; from the USGS, how many people told it they felt it, the strongest shaking estimated (on the Mercalli scale), the impact; the link to the source's page of it.
+
+## Where the data comes from
+
+| Data | Source | Where | Licence |
+|---|---|---|---|
+| earthquakes in Italy and the seas around it (35-48° N, 6-19° E, and the seas that reach into it) | [INGV](https://terremoti.ingv.it), Istituto Nazionale di Geofisica e Vulcanologia, through its [FDSN event service](https://webservices.ingv.it) | the Italian network's; the strongest of the Mediterranean and of the world too | CC BY 4.0 |
+| earthquakes everywhere else, the strongest in the world | the [USGS](https://earthquake.usgs.gov/fdsnws/event/1/), U.S. Geological Survey | the world; not every small one (in the Aegean, on 3 October, it gave none of magnitude 3 or more in a week) | public domain |
+| places | [Nominatim](https://nominatim.org) (OpenStreetMap), the built-in tables of cities and seas | - | - |
+
+- **Each source the other's fallback.** When the one for a place does not answer, the other is asked, and the answer says which gave it.
+- **As the sources tell them.** The magnitude, the time, the point and its depth are the sources' own, as they stood when asked: the first estimates change in the first hours, and every answer says so, and that in an emergency the civil protection's word counts. The names of places are the sources' (INGV's in Italian, the USGS's in English); where an event was is also told by the built-in tables (a sea, a region, the nearest town), in the same words for both.
+- **The tsunami flag is not a tsunami.** The USGS sets it for large earthquakes at sea; the answer says they were at sea and strong enough for one, and to look at the warning centres.
+- **The sources' rules are kept.** A User-Agent naming the program, a second between two requests to a server, the answers kept a minute.
+- **No source run from Russia or China.**
+
+## The answers
+
+Every answer is data with a layout (see [the services](README.md)): `janas-chat` shows you the whole list in your language, and gives the model only a brief, from which it answers in a line or two.
+
+## Running it
+
+```sh
+janas-quakes
+```
+
+It speaks MCP over its standard input and output and writes what it does on its standard error. In other clients:
+
+```sh
+claude mcp add quakes -- /path/to/janas-quakes
+```
+
+```json
+{"mcpServers": {"quakes": {"command": "/path/to/janas-quakes"}}}
+```
+
+## What has been run
+
+3 October 2026, over the protocol, in the release build: the earthquakes near the user (Palermo, by GeoJS: INGV), near Norcia in 30 days and 50 km, in the Tyrrhenian and the Ionian seas (INGV, within their polygons), in the Aegean (the USGS: none of magnitude 3 or more in 7 days), near Tokyo of magnitude 4 or more (the USGS); the strongest in the world; an event by the USGS's id, one by INGV's, the latest near the user; an id that is not one and a place that does not exist (refused). The reading of both sources' answers and the layouts are checked by `tests/test_quakes_parse.c`, on answers they gave that night.
+
+In `janas-chat` with Qwen3.6-35B-A3B, the same night, in Italian, on a pipe: "C'è stato un terremoto qui vicino?" (INGV's four near Palermo), "Quali sono stati i terremoti più forti di questa settimana nel mondo?", "Ci sono stati terremoti nel mar Tirreno questo mese?" (thirteen): each answered from its tool, the lists shown in Italian. "Dov'era esattamente quello di poco fa?", after the world's list, was taken by the model as a town of that list, and answered with an earthquake near it: the answers now give the model each event's id, to name the one meant, and run again, the model passed the id of the latest near Palermo. The seas' names of the built-in tables are English: the line telling where an event was says "Tyrrhenian Sea" in an Italian answer too.
diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.c
index 8b971bb..0df645f 100644
--- a/src/chat/mcp_chat.c
+++ b/src/chat/mcp_chat.c
@@ -50,6 +50,8 @@ static const struct {
{"prices", "prices and finance, for information: currencies, "
"crypto-assets, shares, inflation, central banks' rates, "
"electricity, the cheapest fuel near a place"},
+ {"quakes", "earthquakes: the latest near a place or where the user is, "
+ "the strongest in the world, one in detail"},
{"system", "this computer: how it is (memory, processor, disks, "
"battery, temperatures), what fills a folder, the programs "
"running, the errors, the updates, the network"},
diff --git a/src/services/quakes/data.c b/src/services/quakes/data.c
new file mode 100644
index 0000000..012acc4
--- /dev/null
+++ b/src/services/quakes/data.c
@@ -0,0 +1,141 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * data.c - what janas-quakes read, as the data of its layouts (see
+ * quakes.h, layouts.c and services/common/template.h). Every field is
+ * written, even empty: a layout looks a name up in the item, then in what
+ * holds it. The times are the computer's local ones, with how long ago;
+ * the distance and the way are from the place asked about; where an event
+ * was is told by the built-in tables (a sea, a region, the nearest city)
+ * besides the source's own words.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+#include "quakes.h"
+#include "services/common/geo.h"
+
+static void jstr(struct janas_buf *b, const char *key, const char *v)
+{
+ if (!v)
+ v = "";
+ janas_buf_printf(b, ", \"%s\": ", key);
+ janas_json_write_str(b, v, strlen(v));
+}
+
+static const char *tf(int v)
+{
+ return v ? "true" : "false";
+}
+
+static void jwhen(struct janas_buf *b, long long at)
+{
+ time_t t = (time_t)at, now = time(NULL);
+ struct tm lt, nt;
+ localtime_r(&t, &lt);
+ localtime_r(&now, &nt);
+ long ago = now > t ? (long)(now - t) : 0;
+ janas_buf_printf(b,
+ ", \"when\": {\"day\": %d, \"mon\": %d, \"at\": "
+ "\"%02d:%02d\", \"today\": %s}, \"ago\": {\"d\": %ld, "
+ "\"h\": %ld, \"m\": %ld}",
+ lt.tm_mday, lt.tm_mon + 1, lt.tm_hour, lt.tm_min,
+ tf(lt.tm_yday == nt.tm_yday && lt.tm_year == nt.tm_year),
+ ago / 86400, ago / 3600 % 24, ago / 60 % 60);
+}
+
+/* an event; from: the place its distance is told from, or NULL */
+static void event(struct janas_buf *b, const struct qk_event *e,
+ const struct qk_place *from)
+{
+ janas_buf_puts(b, "{\"id\": ");
+ janas_json_write_str(b, e->id, strlen(e->id));
+ janas_buf_printf(b, ", \"src\": \"%s\", \"mag\": %.1f", e->src, e->mag);
+ jstr(b, "magtype", e->magtype);
+ janas_buf_printf(b, ", \"depth\": %.0f, \"deep\": %s", e->depth_km,
+ tf(e->depth_km >= 70));
+ jwhen(b, e->at);
+ if (from) {
+ double km = geo_km(from->lat, from->lon, e->lat, e->lon);
+ janas_buf_printf(
+ b, ", \"km\": %.0f, \"dir\": \"%s\"", km,
+ geo_compass(geo_bearing(from->lat, from->lon, e->lat, e->lon)));
+ } else
+ janas_buf_puts(b, ", \"km\": 0, \"dir\": \"\"");
+ janas_buf_puts(b, ", \"where\": ");
+ geo_describe_json(e->lat, e->lon, b);
+ jstr(b, "place", e->place);
+ jstr(b, "kind", strcmp(e->kind, "earthquake") ? e->kind : "");
+ janas_buf_printf(b,
+ ", \"felt\": %d, \"has_felt\": %s, \"mmi\": %.0f, "
+ "\"has_mmi\": %s",
+ e->felt > 0 ? e->felt : 0, tf(e->felt > 0),
+ e->mmi > 0 ? floor(e->mmi + 0.5) : 0, tf(e->mmi > 0));
+ jstr(b, "alert", e->alert);
+ janas_buf_printf(b, ", \"tsunami\": %s, \"auto\": %s", tf(e->tsunami),
+ tf(!strcmp(e->src, "usgs") && !e->reviewed));
+ jstr(b, "url", e->url);
+ janas_buf_printf(b, ", \"lat\": %.3f, \"lon\": %.3f}", e->lat, e->lon);
+}
+
+static void list(struct janas_buf *b, const struct qk_list *l,
+ const struct qk_place *from)
+{
+ double top = -9;
+ for (int i = 0; i < l->n; i++)
+ if (l->e[i].mag > top)
+ top = l->e[i].mag;
+ janas_buf_printf(b, ", \"n\": %d, \"more\": %d, \"top\": %.1f", l->n,
+ l->more, top);
+ janas_buf_puts(b, ", \"items\": [");
+ for (int i = 0; i < l->n; i++) {
+ janas_buf_puts(b, i ? ", " : "");
+ event(b, &l->e[i], from);
+ }
+ janas_buf_puts(b, "]");
+}
+
+void qk_near_data(struct janas_buf *b, const struct qk_place *p,
+ double radius_km, int days, double min_mag,
+ const struct qk_list *l, const char *src)
+{
+ janas_buf_puts(b, "{\"name\": ");
+ janas_json_write_str(b, p->name, strlen(p->name));
+ jstr(b, "country", p->country);
+ jstr(b, "how", p->how);
+ janas_buf_printf(b,
+ ", \"sea\": %s, \"radius\": %.0f, \"days\": %d, "
+ "\"min_mag\": %.1f, \"source\": \"%s\"",
+ tf(p->is_sea), radius_km, days, min_mag, src);
+ list(b, l, p);
+ janas_buf_puts(b, "}");
+}
+
+void qk_strong_data(struct janas_buf *b, int days, double min_mag,
+ const struct qk_list *l)
+{
+ janas_buf_printf(b,
+ "{\"days\": %d, \"min_mag\": %.1f, \"source\": \"usgs\"",
+ days, min_mag);
+ int alerts = 0, tsunamis = 0;
+ for (int i = 0; i < l->n; i++) {
+ alerts += l->e[i].alert[0] && strcmp(l->e[i].alert, "green");
+ tsunamis += l->e[i].tsunami;
+ }
+ janas_buf_printf(b, ", \"alerts\": %d, \"tsunamis\": %d", alerts, tsunamis);
+ list(b, l, NULL);
+ janas_buf_puts(b, "}");
+}
+
+void qk_event_data(struct janas_buf *b, const struct qk_event *e,
+ const struct qk_place *from)
+{
+ janas_buf_puts(b, "{\"from\": ");
+ janas_json_write_str(b, from ? from->name : "",
+ from ? strlen(from->name) : 0);
+ janas_buf_printf(b, ", \"source\": \"%s\", \"e\": ", e->src);
+ event(b, e, from);
+ janas_buf_puts(b, "}");
+}
diff --git a/src/services/quakes/fetch.c b/src/services/quakes/fetch.c
new file mode 100644
index 0000000..de40f1f
--- /dev/null
+++ b/src/services/quakes/fetch.c
@@ -0,0 +1,116 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * fetch.c - janas-quakes asks its sources (see quakes.h): a User-Agent
+ * naming the program, a pause between two requests to the same server, the
+ * answers kept a minute, so that a question asked again costs the sources
+ * nothing.
+ */
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "quakes.h"
+#include "services/common/https_get.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+#define N_KEPT 16
+#define N_HOSTS 6
+
+static struct {
+ char *url;
+ time_t at;
+ int status;
+ struct janas_buf body;
+} kept[N_KEPT];
+
+static struct {
+ char host[96];
+ struct timespec last;
+} hosts[N_HOSTS];
+
+static double since(const struct timespec *t)
+{
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ return (double)(now.tv_sec - t->tv_sec) +
+ (double)(now.tv_nsec - t->tv_nsec) * 1e-9;
+}
+
+static void pace(const char *url)
+{
+ const char *h = strstr(url, "://");
+ h = h ? h + 3 : url;
+ size_t n = strcspn(h, "/?:");
+ int slot = -1, empty = -1;
+ for (int i = 0; i < N_HOSTS && slot < 0; i++) {
+ if (strlen(hosts[i].host) == n && strncmp(hosts[i].host, h, n) == 0)
+ slot = i;
+ else if (empty < 0 && !hosts[i].host[0])
+ empty = i;
+ }
+ if (slot >= 0) {
+ double wait = QK_PAUSE_S - since(&hosts[slot].last);
+ if (wait > 0 && wait <= QK_PAUSE_S) {
+ struct timespec ts = {.tv_sec = (time_t)wait};
+ ts.tv_nsec = (long)((wait - (double)ts.tv_sec) * 1e9);
+ nanosleep(&ts, NULL);
+ }
+ } else {
+ slot = empty >= 0 ? empty : 0;
+ snprintf(hosts[slot].host, sizeof hosts[slot].host, "%.*s", (int)n, h);
+ }
+ clock_gettime(CLOCK_MONOTONIC, &hosts[slot].last);
+}
+
+int qk_fetch(const char *url, struct janas_buf *out, char *err, size_t err_len)
+{
+ time_t now = time(NULL);
+ int slot = 0;
+ for (int i = 0; i < N_KEPT; i++) {
+ if (kept[i].url && strcmp(kept[i].url, url) == 0 &&
+ now - kept[i].at < QK_KEEP_S) {
+ out->n = 0;
+ janas_buf_put(out, kept[i].body.p ? kept[i].body.p : "",
+ kept[i].body.n);
+ janas_buf_put(out, "", 1);
+ out->n--;
+ return out->oom ? -1 : kept[i].status;
+ }
+ if (kept[i].at < kept[slot].at)
+ slot = i;
+ }
+ static const char *const agent[] = {
+ "User-Agent: janas-quakes/" JANAS_VERSION
+ " (+https://github.com/prabanta-dev/janas)"};
+ pace(url);
+ int status = janas_https_get_ms(url, agent, 1, QK_MS, out, err, err_len);
+ if ((status == 200 || status == 204) && !out->oom) {
+ free(kept[slot].url);
+ janas_buf_free(&kept[slot].body);
+ kept[slot].url = strdup(url);
+ kept[slot].at = now;
+ kept[slot].status = status;
+ janas_buf_put(&kept[slot].body, out->p ? out->p : "", out->n);
+ }
+ return status;
+}
+
+void qk_url_put(struct janas_buf *b, const char *s)
+{
+ static const char hex[] = "0123456789ABCDEF";
+ for (; *s; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
+ janas_buf_put(b, (const char *)&c, 1);
+ else {
+ char e[3] = {'%', hex[c >> 4], hex[c & 15]};
+ janas_buf_put(b, e, 3);
+ }
+ }
+}
diff --git a/src/services/quakes/layouts.c b/src/services/quakes/layouts.c
new file mode 100644
index 0000000..42f2ca8
--- /dev/null
+++ b/src/services/quakes/layouts.c
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * layouts.c - the layouts of janas-quakes' answers (see quakes.h and
+ * services/common/template.h): the text the user reads, filled with the
+ * data in English here and in the user's language by a client that
+ * translates the layout once (janas-chat), and the brief, all the model
+ * reads of it. The sources' names of places stay as they give them (INGV's
+ * in Italian, the USGS's in English).
+ *
+ * The USGS's tsunami flag is set for large events at sea: it does not say
+ * that a tsunami was, and the words say so. Its alert is PAGER's, the
+ * impact it expects.
+ */
+#include "quakes.h"
+
+#define WORDS \
+ "dir.N = N\n" \
+ "dir.NNE = NNE\n" \
+ "dir.NE = NE\n" \
+ "dir.ENE = ENE\n" \
+ "dir.E = E\n" \
+ "dir.ESE = ESE\n" \
+ "dir.SE = SE\n" \
+ "dir.SSE = SSE\n" \
+ "dir.S = S\n" \
+ "dir.SSW = SSW\n" \
+ "dir.SW = SW\n" \
+ "dir.WSW = WSW\n" \
+ "dir.W = W\n" \
+ "dir.WNW = WNW\n" \
+ "dir.NW = NW\n" \
+ "dir.NNW = NNW\n" \
+ "alert.green = green, little damage expected\n" \
+ "alert.yellow = yellow, some damage expected\n" \
+ "alert.orange = orange, serious damage expected\n" \
+ "alert.red = red, extensive damage expected\n" \
+ "src.ingv = INGV (Istituto Nazionale di Geofisica e Vulcanologia, CC BY " \
+ "4.0)\n" \
+ "src.usgs = USGS (U.S. Geological Survey)\n"
+
+#define WHEN \
+ "{{#when.today}}today{{/when.today}}{{^when.today}}{{when.day}}/" \
+ "{{when.mon}}{{/when.today}} {{when.at}}"
+#define AGO \
+ "{{#ago.d}}{{ago.d}} d {{/ago.d}}{{#ago.h}}{{ago.h}} h " \
+ "{{/ago.h}}{{ago.m}} min ago"
+#define CARE \
+ "Source: {{source|src}}. The first estimates change in the first hours; " \
+ "in an emergency, follow the civil protection's word.\n"
+#define SHOWN \
+ " Shown to the user: do not repeat the list; answer in a line or two, " \
+ "in the user's language."
+
+const char QK_NEAR_LAYOUT[] =
+ "{{#n}}Earthquakes {{#sea}}in the {{name}}{{/sea}}{{^sea}}within "
+ "{{radius}} km of {{name}}{{/sea}} in the last {{days}} days, of "
+ "magnitude {{min_mag}} or more{{#more}} ({{n}} listed, {{more}} "
+ "more){{/more}}:"
+ "{{/n}}{{^n}}No earthquake of magnitude {{min_mag}} or more "
+ "{{#sea}}in the {{name}}{{/sea}}{{^sea}}within {{radius}} km of "
+ "{{name}}{{/sea}} in the last {{days}} days.{{/n}}\n"
+ "{{#items}}\n"
+ " " WHEN "{{#when.today}} (" AGO ")"
+ "{{/when.today}}: magnitude {{mag}}, {{depth}} km deep, {{^sea}}{{km}} "
+ "km {{dir|dir}} of {{name}}: {{/sea}}{{place}}{{#auto}} (first "
+ "estimate){{/auto}}\n"
+ "{{/items}}\n" CARE "---\n" WORDS;
+
+const char QK_NEAR_BRIEF[] =
+ "{{n}}{{#more}}+{{more}}{{/more}} earthquakes M{{min_mag}}+ "
+ "{{#sea}}in the {{name}}{{/sea}}{{^sea}}within {{radius}} km of "
+ "{{name}}{{/sea}}{{#how}} ({{how}}){{/how}}, last {{days}} "
+ "days{{#n}}, strongest M{{top}}{{/n}}: {{#items}}[{{id}}] " WHEN
+ " M{{mag}} "
+ "{{^sea}}{{km}} km {{dir}} {{/sea}}{{place}}, {{depth}} km deep; "
+ "{{/items}}" SHOWN;
+
+const char QK_STRONG_LAYOUT[] =
+ "{{#n}}The strongest earthquakes in the world in the last {{days}} days, "
+ "of magnitude {{min_mag}} or more{{#more}} ({{n}} listed, {{more}} "
+ "more){{/more}}:"
+ "{{/n}}{{^n}}No earthquake of magnitude {{min_mag}} or more in the world "
+ "in the last {{days}} days.{{/n}}\n"
+ "{{#items}}\n"
+ " magnitude {{mag}}, " WHEN ": {{place}}, {{depth}} km "
+ "deep{{#alert}}; impact: {{alert|alert}}{{/alert}}{{#tsunami}}; at sea "
+ "and strong enough for a tsunami: see the warning centres{{/tsunami}}\n"
+ "{{/items}}\n" CARE "---\n" WORDS;
+
+const char QK_STRONG_BRIEF[] =
+ "{{n}} earthquakes M{{min_mag}}+ in the world, last {{days}} days; "
+ "impact alerts above green: {{alerts}}; at sea and strong: {{tsunamis}}. "
+ "{{#items}}[{{id}}] M{{mag}} " WHEN " {{place}}{{#alert}} alert "
+ "{{alert}}{{/alert}}{{#tsunami}} tsunami flag (not a tsunami "
+ "seen){{/tsunami}}; {{/items}}" SHOWN;
+
+const char QK_EVENT_LAYOUT[] =
+ "{{#e}}\n"
+ "Earthquake of magnitude {{mag}} ({{magtype}}){{#kind}}, {{kind}}"
+ "{{/kind}}: {{place}}\n"
+ " when: " WHEN " (" AGO ")\n"
+ " where: {{#where.sea}}in the {{where.sea}}{{/where.sea}}{{^where.sea}}"
+ "{{where.region}}{{/where.sea}}{{#where.city}}, {{#where.km}}{{where.km}} "
+ "km {{where.dir|dir}} of {{/where.km}}{{where.city}}{{/where.city}}; "
+ "{{depth}} km deep{{#deep}}, a deep one{{/deep}}\n"
+ "{{#from}}\n"
+ " from {{from}}: {{km}} km {{dir|dir}}\n"
+ "{{/from}}\n"
+ "{{#has_felt}}\n"
+ " felt: {{felt}} people told the USGS they felt it\n"
+ "{{/has_felt}}\n"
+ "{{#has_mmi}}\n"
+ " the strongest shaking, estimated: {{mmi}} on the Mercalli scale\n"
+ "{{/has_mmi}}\n"
+ "{{#alert}}\n"
+ " impact: {{alert|alert}}\n"
+ "{{/alert}}\n"
+ "{{#tsunami}}\n"
+ " at sea and strong enough for a tsunami: see the warning centres\n"
+ "{{/tsunami}}\n"
+ "{{#auto}}\n"
+ " an automatic first estimate: it may change\n"
+ "{{/auto}}\n"
+ " more: {{url}}\n"
+ "{{/e}}\n" CARE "---\n" WORDS;
+
+const char QK_EVENT_BRIEF[] =
+ "{{#e}}[{{id}}] M{{mag}} {{magtype}}, " WHEN " (" AGO
+ "), {{place}}, {{depth}} km "
+ "deep{{#from}}, {{km}} km {{dir}} of {{from}}{{/from}}{{#has_felt}}, "
+ "felt by {{felt}}{{/has_felt}}{{#has_mmi}}, MMI {{mmi}}{{/has_mmi}}"
+ "{{#alert}}, alert {{alert}}{{/alert}}{{#tsunami}}, tsunami flag (not a "
+ "tsunami seen){{/tsunami}}{{#auto}}, automatic{{/auto}}.{{/e}}" SHOWN;
diff --git a/src/services/quakes/main.c b/src/services/quakes/main.c
new file mode 100644
index 0000000..079fcf8
--- /dev/null
+++ b/src/services/quakes/main.c
@@ -0,0 +1,63 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * main.c - janas-quakes: the earthquakes as an MCP server over stdio, for
+ * janas-chat (which starts it by itself) and any other MCP client: those
+ * near a place, the strongest in the world, one in detail, from INGV (CC
+ * BY 4.0) for Italy and its seas and the USGS (public domain) elsewhere.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "common/mcp_server.h"
+#include "quakes.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+static const char INSTRUCTIONS[] =
+ "Use these tools by yourself when the user asks about earthquakes: was "
+ "there one, where, how strong, the latest near a place or where the "
+ "user is, the strongest in the world; never name them. For one of an "
+ "earlier answer, pass its id (in brackets there). Tell the "
+ "magnitude, the place and the time as the answer gives them; the first "
+ "estimates change in the first hours, and in an emergency the civil "
+ "protection's word counts, not yours.";
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "usage: janas-quakes\n"
+ "An MCP server over stdio: a client starts it and calls its\n"
+ "tools - quakes_near, quakes_strong and quakes_event. They only\n"
+ "read, from INGV (Italy and its seas) and the USGS (the world).\n"
+ "janas-chat starts it by itself when it is beside it.\n"
+ "Configured in a client as, for instance:\n"
+ " {\"mcpServers\": {\"quakes\": {\"command\": "
+ "\"janas-quakes\"}}}\n");
+}
+
+int main(int argc, char **argv)
+{
+ for (int i = 1; i < argc; i++) {
+ usage();
+ return strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 ? 0
+ : 2;
+ }
+ struct janas_mcps srv = {.name = "janas-quakes",
+ .version = JANAS_VERSION,
+ .instructions = INSTRUCTIONS,
+ .tools_list = qk_tools_list,
+ .tools_call = qk_tools_call};
+ if (janas_mcps_open(&srv) != 0) {
+ fprintf(stderr, "janas-quakes: cannot set its output aside\n");
+ return 1;
+ }
+ fprintf(stderr,
+ "janas-quakes %s: ready, 3 tools (quakes_near, quakes_strong, "
+ "quakes_event)\n",
+ JANAS_VERSION);
+ janas_mcps_run(&srv);
+ return 0;
+}
diff --git a/src/services/quakes/place.c b/src/services/quakes/place.c
new file mode 100644
index 0000000..2dbb8ec
--- /dev/null
+++ b/src/services/quakes/place.c
@@ -0,0 +1,154 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * place.c - the place a question means (see quakes.h): where the user is
+ * through the locator, "lat,lon", a sea of the built-in tables ("mar
+ * Tirreno": the middle of it), a name through Nominatim (OpenStreetMap,
+ * names in every language, at most a request a second), the built-in
+ * cities when it does not answer.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "quakes.h"
+#include "services/common/geo.h"
+#include "services/common/locate.h"
+
+static void copy(char *to, size_t cap, const char *s)
+{
+ size_t n = s ? strlen(s) : 0;
+ if (n >= cap)
+ n = cap - 1;
+ memcpy(to, s ? s : "", n);
+ to[n] = 0;
+}
+
+static void from_tables(struct qk_place *p)
+{
+ double km;
+ const struct geo_city *c = geo_city_near(p->lat, p->lon, &km);
+ if (!c)
+ return;
+ if (!p->name[0])
+ copy(p->name, sizeof p->name, c->name);
+ if (!p->cc[0])
+ copy(p->cc, sizeof p->cc, geo_country_iso2(c->country));
+ if (!p->country[0])
+ copy(p->country, sizeof p->country, geo_country_name(c->country));
+}
+
+int qk_in_ingv(double lat, double lon)
+{
+ return lat >= QK_INGV_LAT0 && lat <= QK_INGV_LAT1 && lon >= QK_INGV_LON0 &&
+ lon <= QK_INGV_LON1;
+}
+
+/* the computer's language, for the names Nominatim gives */
+static const char *lang(void)
+{
+ static char l[8];
+ const char *v = getenv("LC_ALL");
+ if (!v || !*v)
+ v = getenv("LC_MESSAGES");
+ if (!v || !*v)
+ v = getenv("LANG");
+ if (!v || strlen(v) < 2 || !strncmp(v, "C", 1) || !strncmp(v, "POSIX", 5))
+ return "en";
+ snprintf(l, sizeof l, "%.2s", v);
+ return l;
+}
+
+static int nominatim(const char *name, struct qk_place *p, char *err,
+ size_t err_len)
+{
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_puts(&url, "https://nominatim.openstreetmap.org/search?q=");
+ qk_url_put(&url, name);
+ janas_buf_printf(&url,
+ "&format=jsonv2&limit=1&addressdetails=1"
+ "&accept-language=%s",
+ lang());
+ int st = url.oom ? -1 : qk_fetch(url.p, &body, err, err_len);
+ janas_buf_free(&url);
+ int ok = 0;
+ if (st == 200) {
+ char why[128];
+ struct janas_json_doc *d =
+ janas_json_parse(body.p, body.n, why, sizeof why);
+ const struct janas_json *x = d ? janas_json_root(d) : NULL;
+ x = x && x->type == JANAS_JSON_ARRAY ? x->child : NULL;
+ const char *la = janas_json_str(janas_json_get(x, "lat"));
+ const char *lo = janas_json_str(janas_json_get(x, "lon"));
+ if (la && lo) {
+ p->lat = strtod(la, NULL);
+ p->lon = strtod(lo, NULL);
+ copy(p->name, sizeof p->name,
+ janas_json_str(janas_json_get(x, "name")));
+ const struct janas_json *a = janas_json_get(x, "address");
+ const char *cc = janas_json_str(janas_json_get(a, "country_code"));
+ for (int i = 0; cc && i < 2 && cc[i]; i++)
+ p->cc[i] = (char)(cc[i] & ~0x20); /* "it" -> "IT" */
+ copy(p->country, sizeof p->country,
+ janas_json_str(janas_json_get(a, "country")));
+ ok = 1;
+ } else
+ snprintf(err, err_len, "no place named %s", name);
+ janas_json_free(d);
+ } else if (st > 0)
+ snprintf(err, err_len, "Nominatim: HTTP %d", st);
+ janas_buf_free(&body);
+ return ok ? 0 : -1;
+}
+
+int qk_place_find(const char *q, struct qk_place *p, char *err, size_t err_len)
+{
+ memset(p, 0, sizeof *p);
+ if (!q) {
+ struct janas_where w;
+ if (janas_where(&w, err, err_len) != 0)
+ return -1;
+ p->lat = w.lat;
+ p->lon = w.lon;
+ copy(p->name, sizeof p->name, w.city);
+ copy(p->cc, sizeof p->cc, w.cc);
+ copy(p->country, sizeof p->country, w.country);
+ copy(p->how, sizeof p->how, w.how);
+ from_tables(p);
+ return 0;
+ }
+ double lat, lon;
+ char tail;
+ if (sscanf(q, "%lf , %lf %c", &lat, &lon, &tail) == 2 && fabs(lat) <= 90 &&
+ fabs(lon) <= 180) {
+ p->lat = lat;
+ p->lon = lon;
+ from_tables(p);
+ return 0;
+ }
+ struct geo_area a;
+ if (geo_area_find(q, &a)) { /* a sea: what is within it */
+ p->is_sea = 1;
+ p->sea = a;
+ p->lat = (a.lat_min + a.lat_max) / 2e5;
+ p->lon = (a.lon_min + a.lon_max) / 2e5;
+ copy(p->name, sizeof p->name, q); /* as the user wrote it */
+ return 0;
+ }
+ if (nominatim(q, p, err, err_len) == 0) {
+ /* the name as asked: Nominatim's is the local one (八日市場 for
+ Yokaichiba) */
+ copy(p->name, sizeof p->name, q);
+ from_tables(p);
+ return 0;
+ }
+ const struct geo_city *c = geo_city_find(q); /* the tables, offline */
+ if (!c)
+ return -1;
+ p->lat = c->lat / 1e5;
+ p->lon = c->lon / 1e5;
+ copy(p->name, sizeof p->name, c->name);
+ from_tables(p);
+ return 0;
+}
diff --git a/src/services/quakes/quakes.h b/src/services/quakes/quakes.h
new file mode 100644
index 0000000..455f405
--- /dev/null
+++ b/src/services/quakes/quakes.h
@@ -0,0 +1,108 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * quakes.h - janas-quakes, the earthquakes as an MCP service: those near a
+ * place, the strongest in the world, one in detail. It only reads, from
+ * open sources: INGV (Istituto Nazionale di Geofisica e Vulcanologia, CC
+ * BY 4.0) for Italy and the seas around it, the USGS (public domain)
+ * everywhere, each the other's fallback.
+ *
+ * What its parts share: fetch.c asks the sources, place.c finds the place
+ * meant, read.c reads their GeoJSON (no network: the tests read kept
+ * answers), data.c and layouts.c write the answers as data with a layout,
+ * tools.c offers the tools.
+ */
+#ifndef JANAS_QUAKES_H
+#define JANAS_QUAKES_H
+
+#include <stddef.h>
+
+#include "llm/json.h"
+#include "services/common/geo.h"
+
+#define QK_MAX 20 /* events told */
+#define QK_KEEP_S 60 /* an answer kept, so a question again costs none */
+#define QK_PAUSE_S 1.0 /* between two requests to a server */
+#define QK_MS 20000
+
+/* the area where INGV's catalogue is the reference: Italy and its seas */
+#define QK_INGV_LAT0 35.0
+#define QK_INGV_LAT1 48.0
+#define QK_INGV_LON0 6.0
+#define QK_INGV_LON1 19.0
+
+/* ---- fetch.c ---- */
+
+/* GET of url, kept QK_KEEP_S; the HTTP status (204: none), or -1 */
+int qk_fetch(const char *url, struct janas_buf *out, char *err, size_t err_len);
+/* s into b, escaped for a URL */
+void qk_url_put(struct janas_buf *b, const char *s);
+
+/* ---- place.c ---- */
+
+struct qk_place {
+ char name[96], country[64], cc[3];
+ double lat, lon;
+ char how[96]; /* where the user is, when no place was named */
+ int is_sea; /* a sea: the events within it, not around a point */
+ struct geo_area sea;
+};
+
+/* A place by name ("Norcia", "mar Tirreno"), "lat,lon", or, with q NULL,
+ where the user is. 0, or -1 with the reason in err. */
+int qk_place_find(const char *q, struct qk_place *p, char *err, size_t err_len);
+/* Whether the point is in INGV's area */
+int qk_in_ingv(double lat, double lon);
+
+/* ---- read.c ---- */
+
+struct qk_event {
+ char id[32], src[8]; /* src: ingv, usgs */
+ char place[160]; /* the source's own words for where it was */
+ char magtype[8], kind[24], alert[8], url[200];
+ double lat, lon, depth_km, mag, mmi; /* mmi: -1 when not told */
+ long long at; /* seconds since 1970 */
+ int felt; /* people who told they felt it, -1 not told */
+ int tsunami, reviewed;
+};
+
+struct qk_list {
+ struct qk_event e[QK_MAX];
+ int n, more;
+ const struct geo_area *within; /* set: only the events over that sea */
+};
+
+/* the FDSN GeoJSON of INGV or of the USGS (src); the events after those
+ already in l, up to QK_MAX, the others counted in more */
+int qk_read(const char *text, size_t n, const char *src, struct qk_list *l,
+ char *err, size_t err_len);
+/* "2026-10-01T22:46:42.590000" (UTC) into seconds since 1970, -1 */
+long long qk_utc(const char *s);
+/* the latest first; the strongest first */
+void qk_by_time(struct qk_list *l);
+void qk_by_mag(struct qk_list *l);
+
+/* ---- data.c ---- */
+
+/* the events near a place: their distance and way from it */
+void qk_near_data(struct janas_buf *b, const struct qk_place *p,
+ double radius_km, int days, double min_mag,
+ const struct qk_list *l, const char *src);
+void qk_strong_data(struct janas_buf *b, int days, double min_mag,
+ const struct qk_list *l);
+void qk_event_data(struct janas_buf *b, const struct qk_event *e,
+ const struct qk_place *from);
+
+/* ---- layouts.c ---- */
+
+extern const char QK_NEAR_LAYOUT[], QK_NEAR_BRIEF[];
+extern const char QK_STRONG_LAYOUT[], QK_STRONG_BRIEF[];
+extern const char QK_EVENT_LAYOUT[], QK_EVENT_BRIEF[];
+
+/* ---- tools.c ---- */
+
+void qk_tools_list(void *ctx, struct janas_buf *b);
+int qk_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b);
+
+#endif
diff --git a/src/services/quakes/read.c b/src/services/quakes/read.c
new file mode 100644
index 0000000..4ed822a
--- /dev/null
+++ b/src/services/quakes/read.c
@@ -0,0 +1,158 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * read.c - janas-quakes reads its sources' answers (see quakes.h): the FDSN
+ * event service's GeoJSON, as INGV and the USGS give it. INGV: eventId,
+ * time in UTC as text, mag, magType, place, type. The USGS: id, time in
+ * milliseconds, mag, magType, place, type, felt, mmi, alert, tsunami,
+ * status, url. Both: the point as [lon, lat, depth in km]. No network
+ * here: the tests give it kept answers.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "quakes.h"
+
+static void copy(char *to, size_t cap, const char *s)
+{
+ size_t n = s ? strlen(s) : 0;
+ if (n >= cap)
+ n = cap - 1;
+ memcpy(to, s ? s : "", n);
+ to[n] = 0;
+}
+
+/* days from 1970-01-01 to y-m-d (proleptic Gregorian) */
+static long long days_from_civil(int y, int m, int d)
+{
+ y -= m <= 2;
+ long long era = (y >= 0 ? y : y - 399) / 400;
+ long long yoe = y - era * 400;
+ long long doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
+ long long doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+ return era * 146097 + doe - 719468;
+}
+
+long long qk_utc(const char *s)
+{
+ int y, mo, d, h, mi;
+ double sec;
+ if (!s || sscanf(s, "%d-%d-%dT%d:%d:%lf", &y, &mo, &d, &h, &mi, &sec) != 6)
+ return -1;
+ return days_from_civil(y, mo, d) * 86400 + h * 3600 + mi * 60 +
+ (long long)sec;
+}
+
+static double num(const struct janas_json *o, const char *k, double def)
+{
+ const struct janas_json *v = janas_json_get(o, k);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, def) : def;
+}
+
+int qk_read(const char *text, size_t n, const char *src, struct qk_list *l,
+ char *err, size_t err_len)
+{
+ if (!n) /* INGV's 204: none */
+ return 0;
+ char why[200];
+ struct janas_json_doc *d = janas_json_parse(text, n, why, sizeof why);
+ if (!d) {
+ snprintf(err, err_len, "the answer of %s is not JSON: %s", src, why);
+ return -1;
+ }
+ /* a list of events, or one (the USGS's answer for an event's id) */
+ const struct janas_json *r = janas_json_root(d);
+ const struct janas_json *f = janas_json_get(r, "features");
+ const struct janas_json *first =
+ f && f->type == JANAS_JSON_ARRAY ? f->child : NULL;
+ int single = !f && janas_json_is(janas_json_get(r, "type"), "Feature");
+ if (!f && !single) {
+ janas_json_free(d);
+ snprintf(err, err_len, "the answer of %s has no events", src);
+ return -1;
+ }
+ if (single)
+ first = r;
+ int usgs = !strcmp(src, "usgs");
+ for (const struct janas_json *x = first; x; x = single ? NULL : x->next) {
+ const struct janas_json *pr = janas_json_get(x, "properties");
+ const struct janas_json *c =
+ janas_json_get(janas_json_get(x, "geometry"), "coordinates");
+ if (!pr || !c || c->type != JANAS_JSON_ARRAY || !c->child ||
+ !c->child->next)
+ continue;
+ if (l->n == QK_MAX) { /* counted, if within the sea asked */
+ double la = janas_json_num(c->child->next, 0),
+ lo = janas_json_num(c->child, 0);
+ l->more += !l->within || geo_area_has(l->within, la, lo);
+ continue;
+ }
+ struct qk_event *e = &l->e[l->n];
+ memset(e, 0, sizeof *e);
+ copy(e->src, sizeof e->src, src);
+ e->lon = janas_json_num(c->child, 0);
+ e->lat = janas_json_num(c->child->next, 0);
+ e->depth_km =
+ c->child->next->next ? janas_json_num(c->child->next->next, 0) : 0;
+ e->mag = num(pr, "mag", -9);
+ copy(e->magtype, sizeof e->magtype,
+ janas_json_str(janas_json_get(pr, "magType")));
+ copy(e->place, sizeof e->place,
+ janas_json_str(janas_json_get(pr, "place")));
+ copy(e->kind, sizeof e->kind,
+ janas_json_str(janas_json_get(pr, "type")));
+ e->felt = -1;
+ e->mmi = -1;
+ if (usgs) {
+ copy(e->id, sizeof e->id, janas_json_str(janas_json_get(x, "id")));
+ e->at = (long long)(num(pr, "time", -1000) / 1000);
+ e->felt = (int)num(pr, "felt", -1);
+ e->mmi = num(pr, "mmi", -1);
+ copy(e->alert, sizeof e->alert,
+ janas_json_str(janas_json_get(pr, "alert")));
+ e->tsunami = num(pr, "tsunami", 0) != 0;
+ e->reviewed =
+ janas_json_is(janas_json_get(pr, "status"), "reviewed");
+ copy(e->url, sizeof e->url,
+ janas_json_str(janas_json_get(pr, "url")));
+ } else {
+ long long id = (long long)num(pr, "eventId", 0);
+ snprintf(e->id, sizeof e->id, "%lld", id);
+ e->at = qk_utc(janas_json_str(janas_json_get(pr, "time")));
+ snprintf(e->url, sizeof e->url,
+ "https://terremoti.ingv.it/event/%lld", id);
+ e->reviewed = 0; /* INGV's automatic locations are told so */
+ }
+ if (e->mag > -9 && e->at > 0 &&
+ (!l->within || geo_area_has(l->within, e->lat, e->lon)))
+ l->n++;
+ }
+ janas_json_free(d);
+ return 0;
+}
+
+static int later(const void *a, const void *b)
+{
+ long long x = ((const struct qk_event *)a)->at,
+ y = ((const struct qk_event *)b)->at;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+static int stronger(const void *a, const void *b)
+{
+ double x = ((const struct qk_event *)a)->mag,
+ y = ((const struct qk_event *)b)->mag;
+ return x < y ? 1 : x > y ? -1 : later(a, b);
+}
+
+void qk_by_time(struct qk_list *l)
+{
+ qsort(l->e, (size_t)l->n, sizeof *l->e, later);
+}
+
+void qk_by_mag(struct qk_list *l)
+{
+ qsort(l->e, (size_t)l->n, sizeof *l->e, stronger);
+}
diff --git a/src/services/quakes/tools.c b/src/services/quakes/tools.c
new file mode 100644
index 0000000..e7ba21f
--- /dev/null
+++ b/src/services/quakes/tools.c
@@ -0,0 +1,306 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * tools.c - janas-quakes' tools (see quakes.h). They only read, and say so
+ * (readOnlyHint): the earthquakes near a place, the strongest in the
+ * world, one in detail. A point in Italy or its seas is asked of INGV,
+ * any other of the USGS; each source is the other's fallback.
+ */
+#include <ctype.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/mcp_server.h"
+#include "quakes.h"
+#include "services/common/template.h"
+
+#define READS \
+ "\"annotations\": {\"readOnlyHint\": true, \"openWorldHint\": true}"
+#define PLACE_ARG \
+ "\"place\": {\"type\": \"string\", \"description\": \"a town, a region " \
+ "or a sea; leave it out for where the user is\"}"
+
+#define INGV "https://webservices.ingv.it/fdsnws/event/1/query?format=geojson"
+#define USGS "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson"
+
+void qk_tools_list(void *ctx, struct janas_buf *b)
+{
+ (void)ctx;
+ janas_buf_puts(
+ b,
+ "\"tools\": [{\"name\": \"quakes_near\", \"title\": \"Earthquakes "
+ "near a place\", \"description\": \"The latest earthquakes around a "
+ "place: was there one, where was it, how strong.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": "
+ "{" PLACE_ARG ", \"radius\": {\"type\": \"number\", \"description\": "
+ "\"km, 300 by default, at most 1000\"}, \"days\": {\"type\": "
+ "\"number\", \"description\": \"7 by default, at most 30\"}, "
+ "\"min_mag\": {\"type\": \"number\", \"description\": \"2.5 by "
+ "default\"}}, \"additionalProperties\": false}, " READS "}, "
+ "{\"name\": \"quakes_strong\", \"title\": \"The strongest "
+ "earthquakes\", \"description\": \"The strongest earthquakes in the "
+ "world in the last days, with the impact expected.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {\"days\": "
+ "{\"type\": \"number\", \"description\": \"7 by default, at most "
+ "30\"}, \"min_mag\": {\"type\": \"number\", \"description\": \"5 by "
+ "default\"}}, \"additionalProperties\": false}, " READS "}, "
+ "{\"name\": \"quakes_event\", \"title\": \"An earthquake\", "
+ "\"description\": \"One earthquake in detail: by its id (in "
+ "brackets in an earlier answer), or the latest near a place; with "
+ "neither, the latest near the user (the one just felt).\", \"inputSchema\": {\"type\": \"object\", \"properties\": "
+ "{\"id\": {\"type\": \"string\"}, " PLACE_ARG
+ "}, \"additionalProperties\": false}, " READS "}]");
+}
+
+static const char *arg_str(const struct janas_json *args, const char *name)
+{
+ const char *s = janas_json_str(janas_json_get(args, name));
+ return s && *s ? s : NULL;
+}
+
+static double arg_num(const struct janas_json *args, const char *name,
+ double def, double lo, double hi)
+{
+ const struct janas_json *v = janas_json_get(args, name);
+ double x = v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, def) : def;
+ return x < lo ? lo : x > hi ? hi : x;
+}
+
+static int fail(struct janas_buf *b, const char *fmt, ...)
+ __attribute__((format(printf, 2, 3)));
+
+static int fail(struct janas_buf *b, const char *fmt, ...)
+{
+ char line[1024];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(line, sizeof line, fmt, ap);
+ va_end(ap);
+ janas_mcps_text_result(b, line, strlen(line), 1);
+ return 0;
+}
+
+static int answer(struct janas_buf *b, const char *name, struct janas_buf *d,
+ const char *layout, const char *brief)
+{
+ char err[300];
+ int oom = d->oom;
+ int r = oom ? -1
+ : janas_tpl_result(b, name, d->p, d->n, layout, brief, err,
+ sizeof err);
+ janas_buf_free(d);
+ if (r != 0)
+ return fail(b, "The answer could not be written: %s.",
+ oom ? "out of memory" : err);
+ return 0;
+}
+
+/* "&starttime=2026-09-26T08:00:00", days ago, in UTC */
+static void since(struct janas_buf *u, int days)
+{
+ time_t t = time(NULL) - (time_t)days * 86400;
+ struct tm g;
+ gmtime_r(&t, &g);
+ janas_buf_printf(u, "&starttime=%04d-%02d-%02dT%02d:%02d:%02d",
+ g.tm_year + 1900, g.tm_mon + 1, g.tm_mday, g.tm_hour,
+ g.tm_min, g.tm_sec);
+}
+
+/* the events near p from src (ingv, usgs) into l; 0, or -1 */
+static int near(const char *src, const struct qk_place *p, double radius,
+ int days, double min_mag, int limit, struct qk_list *l,
+ char *err, size_t err_len)
+{
+ int ingv = !strcmp(src, "ingv");
+ struct janas_buf u = {0}, body = {0};
+ janas_buf_puts(&u, ingv ? INGV : USGS);
+ since(&u, days);
+ if (p->is_sea) { /* its box, then its polygons */
+ const struct geo_area *a = &p->sea;
+ janas_buf_printf(&u,
+ ingv ? "&minlat=%.3f&maxlat=%.3f&minlon=%.3f"
+ "&maxlon=%.3f&minmag=%.1f"
+ : "&minlatitude=%.3f&maxlatitude=%.3f"
+ "&minlongitude=%.3f&maxlongitude=%.3f"
+ "&minmagnitude=%.1f",
+ a->s_lat_min / 1e5, a->s_lat_max / 1e5,
+ a->s_lon_min / 1e5, a->s_lon_max / 1e5, min_mag);
+ l->within = a;
+ } else
+ janas_buf_printf(&u,
+ ingv ? "&lat=%.4f&lon=%.4f&maxradiuskm=%.0f"
+ "&minmag=%.1f"
+ : "&latitude=%.4f&longitude=%.4f"
+ "&maxradiuskm=%.0f&minmagnitude=%.1f",
+ p->lat, p->lon, radius, min_mag);
+ janas_buf_printf(&u, "&orderby=time&limit=%d", limit);
+ int st = u.oom ? -1 : qk_fetch(u.p, &body, err, err_len);
+ janas_buf_free(&u);
+ int ok = (st == 200 || st == 204) &&
+ qk_read(st == 204 ? "" : body.p, st == 204 ? 0 : body.n, src, l,
+ err, err_len) == 0;
+ if (st > 0 && st != 200 && st != 204)
+ snprintf(err, err_len, "%s: HTTP %d", ingv ? "INGV" : "the USGS", st);
+ janas_buf_free(&body);
+ return ok ? 0 : -1;
+}
+
+/* the source for a place (INGV for a point in its area, or a sea that
+ reaches into it), and the other */
+static const char *first_src(const struct qk_place *p)
+{
+ if (p->is_sea) {
+ const struct geo_area *a = &p->sea;
+ return a->s_lat_max / 1e5 >= QK_INGV_LAT0 &&
+ a->s_lat_min / 1e5 <= QK_INGV_LAT1 &&
+ a->s_lon_max / 1e5 >= QK_INGV_LON0 &&
+ a->s_lon_min / 1e5 <= QK_INGV_LON1
+ ? "ingv"
+ : "usgs";
+ }
+ return qk_in_ingv(p->lat, p->lon) ? "ingv" : "usgs";
+}
+
+static const char *other_src(const char *s)
+{
+ return strcmp(s, "ingv") ? "ingv" : "usgs";
+}
+
+static struct qk_list L;
+
+static int t_near(const struct janas_json *args, struct janas_buf *b)
+{
+ struct qk_place p;
+ char err[400] = "";
+ if (qk_place_find(arg_str(args, "place"), &p, err, sizeof err) != 0)
+ return fail(b, "%s. Ask the user which place.", err);
+ double radius = arg_num(args, "radius", 300, 10, 1000);
+ int days = (int)arg_num(args, "days", 7, 1, 30);
+ double min_mag = arg_num(args, "min_mag", 2.5, 0, 9);
+ const char *src = first_src(&p);
+ memset(&L, 0, sizeof L);
+ if (near(src, &p, radius, days, min_mag, 500, &L, err, sizeof err) != 0) {
+ char e2[300];
+ memset(&L, 0, sizeof L);
+ src = other_src(src);
+ if (near(src, &p, radius, days, min_mag, 500, &L, e2, sizeof e2) != 0)
+ return fail(b, "The earthquakes could not be read: %s; %s.", err,
+ e2);
+ }
+ qk_by_time(&L);
+ struct janas_buf d = {0};
+ qk_near_data(&d, &p, radius, days, min_mag, &L, src);
+ return answer(b, "quakes_near", &d, QK_NEAR_LAYOUT, QK_NEAR_BRIEF);
+}
+
+static int t_strong(const struct janas_json *args, struct janas_buf *b)
+{
+ int days = (int)arg_num(args, "days", 7, 1, 30);
+ double min_mag = arg_num(args, "min_mag", 5, 3, 9);
+ char err[400] = "";
+ struct janas_buf u = {0}, body = {0};
+ janas_buf_puts(&u, USGS);
+ since(&u, days);
+ janas_buf_printf(&u, "&minmagnitude=%.1f&orderby=magnitude&limit=200",
+ min_mag);
+ int st = u.oom ? -1 : qk_fetch(u.p, &body, err, sizeof err);
+ janas_buf_free(&u);
+ memset(&L, 0, sizeof L);
+ int ok =
+ st == 200 && qk_read(body.p, body.n, "usgs", &L, err, sizeof err) == 0;
+ if (st > 0 && st != 200)
+ snprintf(err, sizeof err, "the USGS: HTTP %d", st);
+ janas_buf_free(&body);
+ if (!ok)
+ return fail(b, "The earthquakes could not be read: %s.", err);
+ qk_by_mag(&L);
+ struct janas_buf d = {0};
+ qk_strong_data(&d, days, min_mag, &L);
+ return answer(b, "quakes_strong", &d, QK_STRONG_LAYOUT, QK_STRONG_BRIEF);
+}
+
+/* an id of INGV's is a number, the USGS's letters and digits ("us6000tz62") */
+static int plain_id(const char *s, int *digits)
+{
+ size_t n = strlen(s);
+ *digits = 1;
+ for (size_t i = 0; i < n; i++) {
+ if (!isalnum((unsigned char)s[i]))
+ return 0;
+ if (!isdigit((unsigned char)s[i]))
+ *digits = 0;
+ }
+ return n > 0 && n < 32;
+}
+
+static int t_event(const struct janas_json *args, struct janas_buf *b)
+{
+ char err[400] = "";
+ const char *id = arg_str(args, "id");
+ const char *q = arg_str(args, "place");
+ struct qk_place p;
+ int have_place = 0;
+ memset(&L, 0, sizeof L);
+ if (id) {
+ int digits;
+ if (!plain_id(id, &digits))
+ return fail(b, "\"%s\" is not an earthquake's id.", id);
+ struct janas_buf u = {0}, body = {0};
+ janas_buf_printf(&u, "%s&eventid=%s", digits ? INGV : USGS, id);
+ int st = u.oom ? -1 : qk_fetch(u.p, &body, err, sizeof err);
+ janas_buf_free(&u);
+ int ok = (st == 200 || st == 204) &&
+ qk_read(st == 204 ? "" : body.p, st == 204 ? 0 : body.n,
+ digits ? "ingv" : "usgs", &L, err, sizeof err) == 0;
+ janas_buf_free(&body);
+ if (!ok && st > 0 && st != 200 && st != 204)
+ snprintf(err, sizeof err, "HTTP %d", st);
+ if (!ok)
+ return fail(b, "The earthquake %s could not be read: %s.", id, err);
+ if (!L.n)
+ return fail(b, "No earthquake has the id %s.", id);
+ have_place = q && qk_place_find(q, &p, err, sizeof err) == 0;
+ } else {
+ /* the latest near the place: the one just felt */
+ if (qk_place_find(q, &p, err, sizeof err) != 0)
+ return fail(b, "%s. Ask the user which place.", err);
+ have_place = 1;
+ const char *src = first_src(&p);
+ if (near(src, &p, 300, 2, 2.5, 1, &L, err, sizeof err) != 0) {
+ memset(&L, 0, sizeof L);
+ src = other_src(src);
+ if (near(src, &p, 300, 2, 2.5, 1, &L, err, sizeof err) != 0)
+ return fail(b, "The earthquakes could not be read: %s.", err);
+ }
+ if (!L.n)
+ return fail(b,
+ "No earthquake of magnitude 2.5 or more within 300 "
+ "km of %s in the last two days. Tell the user so.",
+ p.name[0] ? p.name : "the place");
+ }
+ struct janas_buf d = {0};
+ qk_event_data(&d, &L.e[0], have_place ? &p : NULL);
+ return answer(b, "quakes_event", &d, QK_EVENT_LAYOUT, QK_EVENT_BRIEF);
+}
+
+int qk_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b)
+{
+ (void)ctx;
+ const struct janas_json *name = janas_json_get(params, "name");
+ const struct janas_json *args = janas_json_get(params, "arguments");
+ if (args && args->type != JANAS_JSON_OBJECT)
+ args = NULL;
+ static const struct {
+ const char *name;
+ int (*fn)(const struct janas_json *, struct janas_buf *);
+ } T[] = {{"quakes_near", t_near},
+ {"quakes_strong", t_strong},
+ {"quakes_event", t_event}};
+ for (size_t i = 0; i < sizeof T / sizeof *T; i++)
+ if (janas_json_is(name, T[i].name))
+ return T[i].fn(args, b);
+ return -1;
+}
diff --git a/tests/test_quakes_parse.c b/tests/test_quakes_parse.c
new file mode 100644
index 0000000..fee3725
--- /dev/null
+++ b/tests/test_quakes_parse.c
@@ -0,0 +1,209 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_quakes_parse.c - janas-quakes' reading of its sources, without the
+ * network, and the layouts filled with what was read: INGV's two latest
+ * earthquakes within 300 km of Palermo, the USGS's two strongest of a
+ * week and its answer for one event's id, as they gave them on 3 October
+ * 2026 (the USGS's cut to the fields read). The times are told in UTC.
+ * The sources belong to the program, so they are compiled in here.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "services/common/template.h"
+#include "services/quakes/data.c"
+#include "services/quakes/layouts.c"
+#include "services/quakes/read.c"
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+static const char S_INGV[] =
+ "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"p"
+ "roperties\":{\"eventId\":46749431,\"originId\":147776221,\"time\":\""
+ "2026-10-01T22:46:42.590000\",\"author\":\"SURVEY-INGV\",\"magType\""
+ ":\"ML\",\"mag\":2.4,\"magAuthor\":\"--\",\"type\":\"earthquake\",\"place\""
+ ":\"Costa Siciliana nord-orientale (Messina)\",\"version\":100,\"g"
+ "eojson_creationTime\":\"2026-10-02T22:41:03\"},\"geometry\":{\"typ"
+ "e\":\"Point\",\"coordinates\":[15.2578,38.3912,168.3]}},{\"type\":\""
+ "Feature\",\"properties\":{\"eventId\":46749241,\"originId\":1477758"
+ "31,\"time\":\"2026-10-01T20:28:14.590000\",\"author\":\"SURVEY-INGV"
+ "\",\"magType\":\"ML\",\"mag\":3,\"magAuthor\":\"--\",\"type\":\"earthquake"
+ "\",\"place\":\"Costa Calabra nord-occidentale (Cosenza)\",\"versio"
+ "n\":100,\"geojson_creationTime\":\"2026-10-02T22:41:03\"},\"geomet"
+ "ry\":{\"type\":\"Point\",\"coordinates\":[15.6732,39.5417,271.4]}}]"
+ "}";
+
+static const char S_USGS[] =
+ "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"p"
+ "roperties\":{\"mag\":5.8,\"place\":\"165 km SSE of Vilyuchinsk, Ru"
+ "ssia\",\"time\":1790958881010,\"felt\":null,\"mmi\":3.738,\"alert\":\""
+ "green\",\"status\":\"reviewed\",\"tsunami\":0,\"magType\":\"mww\",\"type"
+ "\":\"earthquake\",\"url\":\"https://earthquake.usgs.gov/earthquake"
+ "s/eventpage/us6000tz62\"},\"geometry\":{\"type\":\"Point\",\"coordin"
+ "ates\":[159.7398,51.6873,29.477]},\"id\":\"us6000tz62\"},{\"type\":"
+ "\"Feature\",\"properties\":{\"mag\":5.6,\"place\":\"72 km ESE of Koko"
+ "po, Papua New Guinea\",\"time\":1790431698875,\"felt\":1,\"mmi\":4."
+ "2,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\"magType\":"
+ "\"mww\",\"type\":\"earthquake\",\"url\":\"https://earthquake.usgs.gov"
+ "/earthquakes/eventpage/us6000txtc\"},\"geometry\":{\"type\":\"Poin"
+ "t\",\"coordinates\":[152.8611,-4.6288,69.51]},\"id\":\"us6000txtc\""
+ "}],\"bbox\":[152.8611,-4.6288,29.477,159.7398,51.6873,69.51]}";
+
+static const char S_USGS_ONE[] =
+ "{\"type\":\"Feature\",\"properties\":{\"mag\":5.8,\"place\":\"165 km SS"
+ "E of Vilyuchinsk, Russia\",\"time\":1790958881010,\"felt\":null,\""
+ "mmi\":3.738,\"alert\":\"green\",\"status\":\"reviewed\",\"tsunami\":0,\""
+ "magType\":\"mww\",\"type\":\"earthquake\",\"url\":\"https://earthquake"
+ ".usgs.gov/earthquakes/eventpage/us6000tz62\"},\"geometry\":{\"ty"
+ "pe\":\"Point\",\"coordinates\":[159.7398,51.6873,29.477]},\"id\":\"u"
+ "s6000tz62\"}";
+
+/* the layout filled with the data d; the text, or "" (counted) */
+static char *fill(const char *layout, struct janas_buf *d)
+{
+ static char out[16384];
+ char why[200];
+ struct janas_json_doc *doc = janas_json_parse(d->p, d->n, why, sizeof why);
+ CHECK(doc, "the data is not JSON: %s\n%.*s", why, (int)d->n, d->p);
+ out[0] = 0;
+ if (doc) {
+ struct janas_buf o = {0};
+ char err[200];
+ int r = janas_tpl_render(layout, strlen(layout), janas_json_root(doc),
+ &o, err, sizeof err);
+ CHECK(r == 0, "not filled: %s", err);
+ if (r == 0 && o.p)
+ snprintf(out, sizeof out, "%.*s", (int)o.n, o.p);
+ janas_buf_free(&o);
+ janas_json_free(doc);
+ }
+ janas_buf_free(d);
+ return out;
+}
+
+static struct qk_list l;
+
+static void test_read(void)
+{
+ char err[300] = "";
+ CHECK(qk_utc("2026-10-01T22:46:42.590000") == 1790894802LL, "utc %lld",
+ qk_utc("2026-10-01T22:46:42.590000"));
+ CHECK(qk_utc("1970-01-01T00:00:00") == 0 && qk_utc("x") == -1, "utc ends");
+ memset(&l, 0, sizeof l);
+ CHECK(qk_read(S_INGV, sizeof S_INGV - 1, "ingv", &l, err, sizeof err) == 0,
+ "ingv: %s", err);
+ CHECK(
+ l.n == 2 && !strcmp(l.e[0].id, "46749431") && l.e[0].mag == 2.4 &&
+ l.e[0].depth_km == 168.3 && l.e[0].lat == 38.3912 &&
+ l.e[0].lon == 15.2578 && !strcmp(l.e[0].magtype, "ML") &&
+ !strcmp(l.e[0].place, "Costa Siciliana nord-orientale (Messina)") &&
+ !strcmp(l.e[0].url, "https://terremoti.ingv.it/event/46749431") &&
+ l.e[0].felt == -1 && l.e[0].mmi == -1,
+ "ingv event: %d %s", l.n, l.e[0].id);
+ CHECK(l.n == 2 && l.e[1].mag == 3, "an integer magnitude");
+ CHECK(qk_read("", 0, "ingv", &l, err, sizeof err) == 0 && l.n == 2,
+ "INGV's 204, none");
+ memset(&l, 0, sizeof l);
+ CHECK(qk_read(S_USGS, sizeof S_USGS - 1, "usgs", &l, err, sizeof err) == 0,
+ "usgs: %s", err);
+ CHECK(l.n == 2 && !strcmp(l.e[0].id, "us6000tz62") && l.e[0].mag == 5.8 &&
+ l.e[0].at == 1790958881LL && l.e[0].felt == -1 &&
+ l.e[0].mmi == 3.738 && !strcmp(l.e[0].alert, "green") &&
+ l.e[0].reviewed && !l.e[0].tsunami && l.e[1].felt == 1,
+ "usgs event: %s %lld %d", l.e[0].id, l.e[0].at, l.e[0].felt);
+ struct qk_list one;
+ memset(&one, 0, sizeof one);
+ CHECK(qk_read(S_USGS_ONE, sizeof S_USGS_ONE - 1, "usgs", &one, err,
+ sizeof err) == 0 &&
+ one.n == 1 && !strcmp(one.e[0].id, "us6000tz62"),
+ "one event: %d", one.n);
+ CHECK(qk_read("{\"x\": 1}", 8, "usgs", &one, err, sizeof err) == -1,
+ "not an answer of events");
+ qk_by_time(&l);
+ CHECK(l.e[0].at > l.e[1].at, "the latest first");
+}
+
+static void test_layouts(void)
+{
+ char err[300];
+ struct qk_place p = {
+ .name = "Palermo", .country = "Italy", .lat = 38.1157, .lon = 13.3615};
+ memset(&l, 0, sizeof l);
+ qk_read(S_INGV, sizeof S_INGV - 1, "ingv", &l, err, sizeof err);
+ qk_by_time(&l);
+ struct janas_buf d = {0};
+ qk_near_data(&d, &p, 300, 7, 2.5, &l, "ingv");
+ const char *t = fill(QK_NEAR_LAYOUT, &d);
+ CHECK(strstr(t, "Earthquakes within 300 km of Palermo in the last 7 "
+ "days, of magnitude 2.5 or more:\n"),
+ "near head:\n%s", t);
+ CHECK(strstr(t, " 1/10 22:46: magnitude 2.4, 168 km deep, 168 km E of "
+ "Palermo: Costa Siciliana nord-orientale (Messina)\n"),
+ "near item:\n%s", t);
+ CHECK(strstr(t, "magnitude 3.0, 271 km deep"), "a magnitude 3.0:\n%s", t);
+ CHECK(strstr(t, "Source: INGV (Istituto Nazionale di Geofisica e "
+ "Vulcanologia, CC BY 4.0)."),
+ "source:\n%s", t);
+ memset(&l, 0, sizeof l);
+ qk_near_data(&d, &p, 300, 7, 2.5, &l, "ingv");
+ t = fill(QK_NEAR_LAYOUT, &d);
+ CHECK(strstr(t, "No earthquake of magnitude 2.5 or more within 300 km of "
+ "Palermo in the last 7 days.\n"),
+ "none:\n%s", t);
+
+ memset(&l, 0, sizeof l);
+ qk_read(S_USGS, sizeof S_USGS - 1, "usgs", &l, err, sizeof err);
+ l.e[1].tsunami = 1; /* to see the words */
+ qk_by_mag(&l);
+ qk_strong_data(&d, 7, 5, &l);
+ t = fill(QK_STRONG_LAYOUT, &d);
+ /* the day is "today" or 2/10, as the test is run: left out */
+ CHECK(strstr(t, " magnitude 5.8, ") &&
+ strstr(t, " 16:34: 165 km SSE of Vilyuchinsk, Russia, 29 km "
+ "deep; impact: green, little damage expected\n"),
+ "strong:\n%s", t);
+ CHECK(strstr(t, "at sea and strong enough for a tsunami: see the warning "
+ "centres"),
+ "tsunami words:\n%s", t);
+ qk_strong_data(&d, 7, 5, &l);
+ t = fill(QK_STRONG_BRIEF, &d);
+ CHECK(strstr(t, "tsunami flag (not a tsunami seen)"), "brief:\n%s", t);
+
+ qk_event_data(&d, &l.e[1], NULL);
+ t = fill(QK_EVENT_LAYOUT, &d);
+ CHECK(strstr(t, "Earthquake of magnitude 5.6 (mww): 72 km ESE of Kokopo, "
+ "Papua New Guinea\n") &&
+ strstr(t, " felt: 1 people told the USGS they felt it\n") &&
+ strstr(t, " the strongest shaking, estimated: 4 on the "
+ "Mercalli scale\n") &&
+ strstr(t, " more: https://earthquake.usgs.gov/earthquakes/"
+ "eventpage/us6000txtc\n") &&
+ !strstr(t, "from "),
+ "event:\n%s", t);
+}
+
+int main(void)
+{
+ setenv("TZ", "UTC", 1);
+ tzset();
+ test_read();
+ test_layouts();
+ if (failures) {
+ printf("test_quakes_parse: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_quakes_parse: ok\n");
+ return 0;
+}