@pipeworx/mcp-open-meteo 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Pipeworx
3
+ Copyright (c) 2026 Mojibake Inc.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,19 +1,21 @@
1
- # mcp-open-meteo
1
+ # @pipeworx/open-meteo
2
2
 
3
- Open-Meteo MCP — weather forecast + historical reanalysis + sister APIs
3
+ Open-Meteo MCP — global weather forecasts + historical reanalysis. No auth (non-commercial fair-use only).
4
4
 
5
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1339+ live data sources.
5
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1679+ live data sources.
6
6
 
7
7
  ## Tools
8
8
 
9
- | Tool | Description |
10
- |------|-------------|
11
- | `forecast` | "What\'s the weather in [city]" / "weather forecast for [location]" / "will it rain tomorrow", "rain chance / probability this week" / "temperature in [place] this week" / "wind / precipitation / humidity forecast" — global weather forecast up to 16 days ahead, hourly or daily, at any lat/lng. Returns temperature, precipitation, wind, humidity, cloud cover, weather codes by default; pass hourly/daily arg for custom variables. Free, keyless, no signup (Open-Meteo / ECMWF + national weather services). Pair with geocode to convert "Paris" → lat/lng first. |
12
- | `historical` | "What was the weather on [date]" / "historical weather for [location]" / "temperature in [city] last summer" / "rainfall during [period]" / "past weather data" — ERA5 reanalysis covering 1940-present at any global lat/lng. Returns hourly or daily temperature, precipitation, wind, humidity etc. for any date range. Use for climate analysis, retrospective event weather, or training data. |
13
- | `geocode` | "What are the coordinates of [city]" / "lat lng for [place]" / "find [town] location" — resolve a place name (city, village, region) to lat/lng so the other Open-Meteo tools can use them. Free, keyless, multilingual; returns up to 100 matches ranked by population. Use before forecast / historical / air_quality / marine / flood when you only have a place name. |
14
- | `air_quality` | "Air quality / AQI in [city]" / "is the air safe to breathe in [location]" / "pollution levels for [place]" / "smoke / smog / wildfire-smoke forecast" / "pollen forecast" — global air quality and pollen forecast at any lat/lng. Returns PM2.5, PM10, ozone (O3), NO2, SO2, CO, dust, and pollen (alder/birch/grass/mugwort/olive/ragweed) up to 5 days ahead, plus European AQI / US AQI. Free, keyless. |
15
- | `marine` | "Wave / swell / surf forecast for [beach]" / "sea conditions in [bay]" / "wave height at [coordinates]" / "is it safe to sail" — global marine weather forecast (wave height, wave period, wave direction, wind waves, swell waves) at any ocean lat/lng. Free, keyless. Use for surf reports, sailing prep, fishing conditions, coastal planning. |
16
- | `flood` | "Flood risk for [river]" / "river discharge forecast" / "will [river] flood" / "water levels at [location]" — daily river discharge forecast from the GloFAS global flood model. Returns predicted m³/s discharge up to 30 days ahead for any river-bearing lat/lng worldwide. Use for flood risk assessment, agriculture planning, hydrology research. |
9
+ - `forecast(latitude, longitude, hourly?, daily?, forecast_days?, timezone?)` — up to 16-day forecast
10
+ - `historical(latitude, longitude, start_date, end_date, hourly?, daily?)` — ERA5 reanalysis 1940→
11
+ - `geocode(name, count?, language?)` — place-name → coordinates
12
+ - `air_quality(latitude, longitude, hourly?)` — global PM/O3/NO2 forecast
13
+ - `marine(latitude, longitude, hourly?)` — wave height + period
14
+ - `flood(latitude, longitude, daily?)` — river discharge forecast (GloFAS)
15
+
16
+ ## Data source
17
+
18
+ `https://api.open-meteo.com/v1/` and friends — public, no auth. Fair-use limit 10k req/day per IP.
17
19
 
18
20
  ## Quick Start
19
21
 
@@ -29,7 +31,25 @@ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
29
31
  }
30
32
  ```
31
33
 
32
- Or connect to the full Pipeworx gateway for access to all 1339+ data sources:
34
+ ### What this endpoint actually serves
35
+
36
+ `tools/list` at `https://gateway.pipeworx.io/open-meteo/mcp` returns the tools in the table
37
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
38
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
39
+ gateway-wide set. So the tool count you see is larger than this table: a
40
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
41
+ pack's own. The connection's `initialize` response states its exact scope, and
42
+ is the authoritative answer for a given day.
43
+
44
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
45
+ scoped connection answer a question this pack does not cover — via
46
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
47
+ second MCP server. There is currently no way to mount a pack endpoint without
48
+ them; if the extra schemas cost you more context than the routing is worth,
49
+ connect to the full gateway once rather than to several pack endpoints.
50
+
51
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
52
+ directly, instead of just this one's:
33
53
 
34
54
  ```json
35
55
  {
@@ -41,9 +61,50 @@ Or connect to the full Pipeworx gateway for access to all 1339+ data sources:
41
61
  }
42
62
  ```
43
63
 
64
+ Both URLs reach the same gateway and the same 1679+ data sources. The
65
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
66
+ reaches all of them from either one.
67
+
68
+ ## No MCP client? Call it over HTTP
69
+
70
+ ```bash
71
+ curl -X POST https://gateway.pipeworx.io/v1/tools/open_meteo_forecast \
72
+ -H 'Content-Type: application/json' \
73
+ -d '{"latitude":40.7128,"longitude":-74.006,"temperature_unit":"fahrenheit","forecast_days":10}'
74
+ ```
75
+
76
+ No account needed for the first calls. Inspect any tool: `GET https://gateway.pipeworx.io/v1/tools/open_meteo_forecast`. Find one: `POST https://gateway.pipeworx.io/v1/tools/search_packs` with `{"query":"..."}`.
77
+
78
+ ## Standalone (no gateway account)
79
+
80
+ This package also runs as a local stdio MCP server — no Pipeworx account, no
81
+ gateway round-trip:
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "open-meteo": {
87
+ "command": "npx",
88
+ "args": ["-y", "@pipeworx/mcp-open-meteo"]
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ Or run it directly to confirm it starts:
95
+
96
+ ```bash
97
+ npx -y @pipeworx/mcp-open-meteo
98
+ ```
99
+
100
+ It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
101
+ for **only** this pack's tools — none of the shared meta-tools the gateway
102
+ connection above adds. Same source, same tools, no ask_pipeworx routing.
103
+
44
104
  ## Using with ask_pipeworx
45
105
 
46
- Instead of calling tools directly, you can ask questions in plain English:
106
+ Instead of calling tools directly, you can ask questions in plain English —
107
+ this works on the pack endpoint above as well as on the full gateway:
47
108
 
48
109
  ```
49
110
  ask_pipeworx({ question: "your question about Open Meteo data" })
@@ -53,7 +114,7 @@ The gateway picks the right tool and fills the arguments automatically.
53
114
 
54
115
  ## More
55
116
 
56
- - [All tools and guides](https://github.com/pipeworx-io/examples)
117
+ - [Docs and guides](https://pipeworx.io/docs)
57
118
  - [pipeworx.io](https://pipeworx.io)
58
119
 
59
120
  ## License
package/bin/cli.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // Entry point for `npx @pipeworx/mcp-<slug>`.
4
+ //
5
+ // Packs ship as raw TypeScript (no build step — see publish-pack.sh for why:
6
+ // tsx sidesteps every extensionless-import / bare-JSON-import edge case a
7
+ // per-pack tsc build would have to solve one pack at a time). This file
8
+ // registers tsx's ESM loader programmatically, then hands off to src/server.ts,
9
+ // which wraps the pack's {tools, callTool} export in a stdio MCP server.
10
+ //
11
+ // Copied verbatim into every published pack repo by scripts/publish-pack.sh —
12
+ // edit this file, not a per-pack copy.
13
+ import { register } from 'tsx/esm/api';
14
+
15
+ register();
16
+
17
+ await import('../src/server.ts');
package/package.json CHANGED
@@ -1,20 +1,32 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-open-meteo",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Open-Meteo MCP — weather forecast + historical reanalysis + sister APIs",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "types": "src/index.ts",
8
+ "bin": {
9
+ "mcp-open-meteo": "bin/cli.js"
10
+ },
8
11
  "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "open-meteo"],
9
12
  "license": "MIT",
10
13
  "repository": {
11
14
  "type": "git",
12
- "url": "https://github.com/pipeworx-io/mcp-open-meteo"
15
+ "url": "git+https://github.com/pipeworx-io/mcp-open-meteo.git"
13
16
  },
14
17
  "scripts": {
15
18
  "typecheck": "tsc --noEmit"
16
19
  },
20
+ "dependencies": {
21
+ "@modelcontextprotocol/sdk": "^1.30.0",
22
+ "tsx": "^4.19.0"
23
+ },
17
24
  "devDependencies": {
18
- "typescript": "^5.7.0"
25
+ "typescript": "^5.9.3",
26
+ "@cloudflare/workers-types": "^4.20260405.1"
27
+ },
28
+ "pipeworx": {
29
+ "sourceHash": "v1-0808c6e49b8fd48434ad1f32b86d9fe9c4562f04594da17923baa0f41cf03d2a",
30
+ "sourceCommit": "adb69d997f82a62e8e22b594488c7d04a227db35"
19
31
  }
20
32
  }
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/open-meteo",
4
4
  "title": "Open Meteo",
5
5
  "description": "Open-Meteo MCP — weather forecast + historical reanalysis + sister APIs",
6
- "version": "0.1.1",
6
+ "version": "0.1.3",
7
7
  "websiteUrl": "https://pipeworx.io/packs/open-meteo",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-open-meteo",
package/src/index.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  interface McpToolDefinition {
2
2
  name: string;
3
3
  description: string;
4
+ /** Human-facing one-liner (fleet #1967). Optional; consumers fall back to
5
+ * description. Kept in step with shared/src/types.ts — scripts/lib/
6
+ * check-inlined-types.mjs reports drift at publish time. */
7
+ summary?: string;
4
8
  inputSchema: {
5
9
  type: 'object';
6
10
  properties: Record<string, unknown>;
7
11
  required?: string[];
12
+ anyOf?: Array<{ required: string[] }>;
13
+ oneOf?: Array<{ required: string[] }>;
14
+ allOf?: Array<{ required: string[] }>;
8
15
  };
16
+ outputSchema?: Record<string, unknown>;
9
17
  }
10
18
 
11
19
  interface McpToolExport {
@@ -16,6 +24,840 @@ interface McpToolExport {
16
24
  provider?: string;
17
25
  }
18
26
 
27
+ /**
28
+ * Place name -> coordinates, ranked so the answer is the city the asker meant.
29
+ *
30
+ * Extracted 2026-08-04 after the SAME defect was found in four packs in three
31
+ * days (weather, open-meteo, openaq, openchargemap). Every one of them called
32
+ * Open-Meteo's geocoder with `count=1` (or took `results[0]`) under a comment
33
+ * asserting the upstream ranks by relevance and population. **That comment is
34
+ * false.** Open-Meteo returns exact-name matches in no useful order, so a
35
+ * 3,218-person Romanian village named Roma outranks Rome.
36
+ *
37
+ * Two things make this correct, and the second is the one that surprises people:
38
+ *
39
+ * 1. RANK BY POPULATION, with a feature-code boost to break ties when the
40
+ * population field is thin or zero.
41
+ * 2. RETRY IN OTHER LANGUAGES. Sorting alone is NOT enough. Verified live:
42
+ * for `name=Roma&language=en`, Rome is ABSENT from the result set entirely
43
+ * (the two Roma/IT rows are population 87 and 33), so a population sort
44
+ * moves the answer from Roma, Romania to Roma, LESOTHO — still wrong.
45
+ * `language=it` returns Roma, IT at 2,318,895. Endonyms live under the
46
+ * local language, so when the English answer looks like nowhere we widen.
47
+ *
48
+ * The extra requests only happen when the first answer looks weak, so the
49
+ * common case ("Chicago") still costs exactly one call.
50
+ */
51
+
52
+ const GEOCODE_URL = 'https://geocoding-api.open-meteo.com/v1/search';
53
+
54
+ /** Languages tried when the English answer looks like nowhere. Ordered by how
55
+ * often a major world city hides behind its endonym (Roma, München, Köln,
56
+ * Sevilla, Lisboa). */
57
+ const EXONYM_LANGS = ['it', 'es', 'de', 'fr', 'pt'] as const;
58
+
59
+ /** Population is the primary signal. These only lift real administrative places
60
+ * above same-named villages when population data is thin or zero.
61
+ * PPLC = national capital, PPLA = first-order admin seat, and so on.
62
+ *
63
+ * Fleet #111 (2026-08-06): these were 50x too big — PPLA's flat +1,000,000
64
+ * outweighed San Francisco CA's real 811K-person lead over San Francisco,
65
+ * Morazan, El Salvador (pop 16,152), so the department capital won on
66
+ * feature-code alone. Scaled down so the boost can still break a genuine
67
+ * thin/zero-population tie (a real capital vs an unrelated small hamlet)
68
+ * but can never overturn a population gap in the tens-of-thousands or up —
69
+ * which is every case that actually distinguishes a major city from a
70
+ * same-named foreign administrative seat. */
71
+ const FEATURE_BOOST: Record<string, number> = {
72
+ PPLC: 100_000, PPLA: 20_000, PPLA2: 4_000, PPLA3: 800,
73
+ };
74
+
75
+ interface GeoHit {
76
+ name?: string;
77
+ admin1?: string;
78
+ country?: string;
79
+ country_code?: string;
80
+ latitude: number;
81
+ longitude: number;
82
+ population?: number;
83
+ feature_code?: string;
84
+ }
85
+
86
+ interface ResolvedPlace {
87
+ name: string;
88
+ admin1: string | null;
89
+ /** Full country name (e.g. "United States") as Open-Meteo returns it —
90
+ * added migrating mcps/weather onto this module, which surfaces the full
91
+ * name in tool output and keys a US-vs-not check off it (fleet #74). */
92
+ country: string | null;
93
+ country_code: string | null;
94
+ latitude: number;
95
+ longitude: number;
96
+ population: number | null;
97
+ /** What we searched to find it — surfaced so a caller can SEE that "Roma"
98
+ * was resolved via Italian, rather than wonder why it worked. */
99
+ matched_language: string;
100
+ }
101
+
102
+ function geoScore(r: GeoHit): number {
103
+ return (r.population ?? 0) + (FEATURE_BOOST[r.feature_code ?? ''] ?? 0);
104
+ }
105
+
106
+ function bestOf(results: GeoHit[]): GeoHit | undefined {
107
+ return results.length ? results.reduce((a, b) => (geoScore(b) > geoScore(a) ? b : a)) : undefined;
108
+ }
109
+
110
+ /**
111
+ * "No real city found here."
112
+ *
113
+ * Deliberately reads RAW population, not geoScore. The feature boost exists to
114
+ * break ties during ranking; letting it feed this decision made a 3,218-person
115
+ * PPLA2 town in Romania look strong enough to suppress the very fan-out that
116
+ * finds Rome. Boost ranks; population decides whether to keep looking.
117
+ */
118
+ function looksWeak(hit: GeoHit | undefined): boolean {
119
+ return !hit || (hit.population ?? 0) < 50_000;
120
+ }
121
+
122
+ async function search(name: string, language: string, count: number): Promise<GeoHit[]> {
123
+ const url = `${GEOCODE_URL}?name=${encodeURIComponent(name)}&count=${count}&language=${language}&format=json`;
124
+ const res = await fetch(url, { headers: { Accept: 'application/json' } });
125
+ if (!res.ok) throw new Error(`Geocoding service error (HTTP ${res.status}) resolving "${name}".`);
126
+ const data = (await res.json()) as { results?: GeoHit[] };
127
+ return (data.results ?? []).filter(
128
+ (r) => typeof r?.latitude === 'number' && typeof r?.longitude === 'number',
129
+ );
130
+ }
131
+
132
+ function toResolved(hit: GeoHit, fallbackName: string, lang: string): ResolvedPlace {
133
+ return {
134
+ name: hit.name ?? fallbackName,
135
+ admin1: hit.admin1 ?? null,
136
+ country: hit.country ?? null,
137
+ country_code: hit.country_code ?? null,
138
+ latitude: hit.latitude,
139
+ longitude: hit.longitude,
140
+ population: typeof hit.population === 'number' ? hit.population : null,
141
+ matched_language: lang,
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Resolve one place name to the most plausible real city.
147
+ *
148
+ * `language` is the caller's preferred language; other languages are only tried
149
+ * when the best hit so far looks weak.
150
+ */
151
+ async function resolvePlace(
152
+ name: string,
153
+ opts: { language?: string; count?: number } = {},
154
+ ): Promise<ResolvedPlace | null> {
155
+ const lang = opts.language ?? 'en';
156
+ // At least 10 candidates: with count=1 there is nothing to rank, which is how
157
+ // every instance of this bug shipped.
158
+ const count = Math.max(10, opts.count ?? 10);
159
+
160
+ const seen = new Map<string, string>(); // hit key -> language it came from
161
+ const key = (h: GeoHit) => `${h.latitude},${h.longitude}`;
162
+ let pool: GeoHit[] = [];
163
+ const absorb = (hits: GeoHit[], viaLang: string) => {
164
+ for (const h of hits) if (!seen.has(key(h))) { seen.set(key(h), viaLang); pool.push(h); }
165
+ };
166
+
167
+ absorb(await search(name, lang, count), lang);
168
+ if (!pool.length && lang !== 'en') absorb(await search(name, 'en', count), 'en');
169
+
170
+ if (looksWeak(bestOf(pool))) {
171
+ for (const alt of EXONYM_LANGS) {
172
+ if (alt === lang) continue;
173
+ absorb(await search(name, alt, count), alt);
174
+ if (!looksWeak(bestOf(pool))) break;
175
+ }
176
+ }
177
+
178
+ let hit = bestOf(pool);
179
+ // Open-Meteo matches on the bare place name and returns nothing for
180
+ // "City, ST" / "City, State" — but routers routinely produce exactly that
181
+ // ("Des Moines, IA"). Retry with the city part before giving up.
182
+ if (!hit && name.includes(',')) {
183
+ const city = name.split(',')[0]!.trim();
184
+ if (city && city.toLowerCase() !== name.toLowerCase()) {
185
+ const retry = await search(city, 'en', count);
186
+ absorb(retry, 'en');
187
+ hit = bestOf(retry);
188
+ }
189
+ }
190
+ return hit ? toResolved(hit, name, seen.get(key(hit)) ?? lang) : null;
191
+ }
192
+
193
+ /**
194
+ * Ranked RAW hits, best first — for packs that must keep the upstream's own
195
+ * response shape (open-meteo's `geocode` returns Open-Meteo objects verbatim,
196
+ * and normalising them would be a breaking change for its callers).
197
+ *
198
+ * Same two-part algorithm as resolvePlace: rank by population+boost, and widen
199
+ * across endonym languages only when the best hit still looks weak.
200
+ */
201
+ async function rankedPlaceHits(
202
+ name: string,
203
+ opts: { language?: string; count?: number } = {},
204
+ ): Promise<GeoHit[]> {
205
+ const lang = opts.language ?? 'en';
206
+ const count = Math.max(10, opts.count ?? 10);
207
+ const seen = new Set<string>();
208
+ const pool: GeoHit[] = [];
209
+ const key = (h: GeoHit) => `${h.latitude},${h.longitude}`;
210
+ const absorb = (hits: GeoHit[]) => {
211
+ for (const h of hits) if (!seen.has(key(h))) { seen.add(key(h)); pool.push(h); }
212
+ };
213
+
214
+ absorb(await search(name, lang, count));
215
+ if (!pool.length && lang !== 'en') absorb(await search(name, 'en', count));
216
+ if (looksWeak(bestOf(pool))) {
217
+ for (const alt of EXONYM_LANGS) {
218
+ if (alt === lang) continue;
219
+ absorb(await search(name, alt, count));
220
+ if (!looksWeak(bestOf(pool))) break;
221
+ }
222
+ }
223
+ if (!pool.length && name.includes(',')) {
224
+ const city = name.split(',')[0]!.trim();
225
+ if (city && city.toLowerCase() !== name.toLowerCase()) absorb(await search(city, 'en', count));
226
+ }
227
+ return pool.sort((a, b) => geoScore(b) - geoScore(a));
228
+ }
229
+
230
+ /** Ranked candidates, best first — for packs that offer alternatives. */
231
+ async function resolvePlaceCandidates(
232
+ name: string,
233
+ opts: { language?: string; count?: number; limit?: number } = {},
234
+ ): Promise<ResolvedPlace[]> {
235
+ const best = await resolvePlace(name, opts);
236
+ if (!best) return [];
237
+ const lang = best.matched_language;
238
+ const hits = await search(name, lang, Math.max(10, opts.count ?? 10));
239
+ const ranked = [...hits].sort((a, b) => geoScore(b) - geoScore(a));
240
+ const out = ranked.map((h) => toResolved(h, name, lang));
241
+ // Guarantee the chosen answer leads, even if it came from a different
242
+ // language pass than the one we just re-queried.
243
+ if (!out.length || out[0]!.latitude !== best.latitude || out[0]!.longitude !== best.longitude) {
244
+ out.unshift(best);
245
+ }
246
+ return out.slice(0, opts.limit ?? 5);
247
+ }
248
+
249
+
250
+ /**
251
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
252
+ *
253
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
254
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
255
+ * covered the majority and structurally could not cover the rest: the rest
256
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
257
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
258
+ *
259
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
260
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
261
+ *
262
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
263
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
264
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
265
+ * our own Supabase for fleet. There is no third party anywhere in either call.
266
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
267
+ * class that means "the source is unreachable and there is nothing for us to
268
+ * fix", which is why the problem-tools triage skips it.
269
+ *
270
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
271
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
272
+ * one site today, so it would work today. It would also rot the first time
273
+ * somebody rewords a label — silently, and in the direction of hiding our own
274
+ * outage, which is worse than the bug being fixed. Every prose rule in
275
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
276
+ * #584); that history is most of that file's comment budget.
277
+ *
278
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
279
+ * hostname is a fact about the call, not a guess about its prose. Two
280
+ * consequences that a pack-level flag could not give us, and the reason the
281
+ * flag was rejected:
282
+ *
283
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
284
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
285
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
286
+ * either pack would relabel a real third-party outage as ours — inventing
287
+ * work, which is the same class of error in the opposite direction.
288
+ * - It covers every future internal pack for free, instead of one declared
289
+ * slug at a time.
290
+ *
291
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
292
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
293
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
294
+ * this module — so changing the wording changes both sides in the same edit and
295
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
296
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
297
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
298
+ * from its own classifier three times and needed a CI gate to hold them
299
+ * together.
300
+ *
301
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
302
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
303
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
304
+ * availability failure" is decided from the actual status code, never re-derived
305
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
306
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
307
+ */
308
+
309
+ /**
310
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
311
+ *
312
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
313
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
314
+ * and different fixes. Here there is only one story to tell — an origin we run
315
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
316
+ * value is decoration; #724 is what happens when a class holds several
317
+ * situations, and inventing sub-values ahead of a reason to act on them
318
+ * differently is the same mistake with the sign flipped.
319
+ *
320
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
321
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
322
+ * hint paths, which only care whether retrying or a sibling tool might work —
323
+ * and it might. Nothing a caller sees or is charged changes here.
324
+ *
325
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
326
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
327
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
328
+ * worked on the write side and was invisible for weeks.
329
+ */
330
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
331
+
332
+ /**
333
+ * The token that carries "this origin is ours" from the call site to the
334
+ * classifier.
335
+ *
336
+ * Appended to the error message rather than attached to the Error object,
337
+ * because the object does not survive the trip: 275 packs return `{ error:
338
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
339
+ * and the fleet pack rebuilds its error from a captured status + body across a
340
+ * retry loop. A property on an Error would be dropped by every one of those
341
+ * paths and the class would work in tests and vanish in production.
342
+ *
343
+ * WORDING IS LOAD-BEARING, same rule as labelAge's note in authority.ts. This
344
+ * string is appended to a pack's thrown Error message (shared/src/http.ts),
345
+ * and a thrown Error's message is exactly what the gateway hands back to the
346
+ * caller as `content[0].text` when nothing rewrites it (workers/gateway/src
347
+ * catches the throw and sets `rawResult.message = stripClassPrefix(error)`,
348
+ * which does not touch this suffix) — so the original wording,
349
+ * " [pipeworx-hosted origin — our own service, not a third party]", was not a
350
+ * theoretical leak: it shipped live on pipeworx-catalog's 522s, 7 times in 6
351
+ * hours on 2026-09-02 (see tests/golden-internal-service.test.ts), verbatim
352
+ * naming Pipeworx as the host. check:hosting-claims never caught it because it
353
+ * did not scan shared/ at all (task #2009). Reworded to describe the
354
+ * OBSERVATION (the origin did not answer) without a claim about who runs it —
355
+ * the identical fix labelAge got: drop the possessive, keep the fact.
356
+ */
357
+ const INTERNAL_ORIGIN_MARKER = ' [origin did not respond — retry before concluding the named source is down]';
358
+
359
+ /**
360
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
361
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
362
+ *
363
+ * Matching the shape rather than listing the ref keeps this correct when we add
364
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
365
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
366
+ * own status page and emphatically not our database. Verified 2026-09-02 by
367
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
368
+ * only real project ref anywhere in the tree is ours, the rest are doc
369
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
370
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
371
+ * by construction.
372
+ */
373
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
374
+
375
+ /**
376
+ * Is this a host WE run?
377
+ *
378
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
379
+ * hosted on workers.dev, so the suffix says where something runs and not who
380
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
381
+ * hostname or to our Supabase project, both of which are ownership facts.
382
+ *
383
+ * `workers/gateway/src/provenance.ts`'s `OUR_HOSTS` answers the same
384
+ * question and DOES include `workers.dev` — a documented divergence
385
+ * (task #2051), not a bug to converge. That list decides what a response may
386
+ * cite as a data SOURCE, where a false negative (citing our own worker as an
387
+ * external source) is the hosting-disclosure leak this whole file exists to
388
+ * prevent, so it errs broad. This one decides who gets BLAMED for a 5xx in
389
+ * outage metrics read by on-call, where a false positive (crediting our own
390
+ * infra with a third party's outage) hides the real failure, so it errs
391
+ * narrow. Same suffix, opposite direction, because they are never called for
392
+ * the same reason.
393
+ *
394
+ * Returns false on anything unparseable rather than throwing — this runs inside
395
+ * an error path, and an error path that can itself throw turns a diagnosable
396
+ * failure into a mystery.
397
+ */
398
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
399
+ if (!url) return false;
400
+ let host: string;
401
+ try {
402
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
403
+ } catch {
404
+ return false;
405
+ }
406
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
407
+ return SUPABASE_PROJECT_HOST.test(host);
408
+ }
409
+
410
+ /**
411
+ * Append the marker when this failure was OUR origin failing to answer.
412
+ *
413
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
414
+ * where there is no response at all, and "the origin did not answer" is the
415
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
416
+ * registry for a slug that does not exist is the caller's argument, not our
417
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
418
+ *
419
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
420
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
421
+ */
422
+ function markInternalOrigin(
423
+ message: string,
424
+ url: string | URL | undefined | null,
425
+ status?: number,
426
+ ): string {
427
+ if (status !== undefined && status < 500) return message;
428
+ if (!isPipeworxOrigin(url)) return message;
429
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
430
+ return message + INTERNAL_ORIGIN_MARKER;
431
+ }
432
+
433
+ /**
434
+ * Which blob4 value a failure from our own web services books as, or undefined
435
+ * if this is not one.
436
+ *
437
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
438
+ * from our own Supabase is a strictly more specific statement about the same
439
+ * row (which of our services, and why), and the two cannot disagree about
440
+ * whether the failure is ours.
441
+ */
442
+ function internalHostMetricsClass(error: string): string | undefined {
443
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
444
+ }
445
+
446
+
447
+ /**
448
+ * One place to turn a failed `fetch` into an error a caller can act on.
449
+ *
450
+ * Nearly every pack was written the same way:
451
+ *
452
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
453
+ *
454
+ * which discards the response body — and the body is usually where the upstream
455
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
456
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
457
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
458
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
459
+ *
460
+ * It also hides bugs one level down. Two of the first three packs audited had a
461
+ * second defect that only existed because of this line: unsplash's rate-limit
462
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
463
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
464
+ * parsing dead code for every non-200.
465
+ *
466
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
467
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
468
+ * `error` tier is what the daily problem-tools list is built from — it means
469
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
470
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
471
+ * values into something TED rejected, and that bug was found only because it sat
472
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
473
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
474
+ * for the 481 that say nothing at all.
475
+ */
476
+
477
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
478
+ * short enough that an HTML page or a stack trace can't swamp the error. */
479
+
480
+ const MAX_DETAIL = 300;
481
+
482
+ /**
483
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
484
+ *
485
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
486
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
487
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
488
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
489
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
490
+ * fast, actionable error instead of holding the connection, and long enough
491
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
492
+ */
493
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
494
+
495
+ /**
496
+ * Read the body of a failed response and fold it into a throwable Error.
497
+ *
498
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
499
+ * change rather than a drop-in:
500
+ *
501
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
502
+ *
503
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
504
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
505
+ * something new from inside the error path.
506
+ */
507
+ async function httpError(res: Response, name: string): Promise<Error> {
508
+ return new Error(await httpErrorMessage(res, name));
509
+ }
510
+
511
+ /** The message text without constructing an Error — for packs that need to wrap
512
+ * it in their own envelope or add an explicit classification prefix. */
513
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
514
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
515
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
516
+ // about the call rather than a guess from the `name` the pack passed in —
517
+ // reword that label freely, the class does not move. See
518
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
519
+ // this touches 481 packs' error text and changes none of it.
520
+ return markInternalOrigin(
521
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
522
+ res.url,
523
+ res.status,
524
+ );
525
+ }
526
+
527
+ /**
528
+ * Just the upstream's own explanation — no name, no status.
529
+ *
530
+ * For a pack that has already said both in its own sentence. epo-ops reads
531
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
532
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
533
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
534
+ * actually said ("Not enough characters before truncation character") nowhere
535
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
536
+ * can fall back to its own wording.
537
+ */
538
+ async function upstreamDetail(res: Response): Promise<string> {
539
+ return readDetail(res);
540
+ }
541
+
542
+ /**
543
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
544
+ *
545
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
546
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
547
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
548
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
549
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
550
+ *
551
+ * That string is the problem. It names no upstream, carries no status, and
552
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
553
+ * means "we have a defect", and the caller is told nothing they can act on.
554
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
555
+ * status-code health check we own reported it green (7889a845). A zero-length
556
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
557
+ * uk-gazette (83% of external calls) and census.
558
+ *
559
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
560
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
561
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
562
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
563
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
564
+ * a statement of fact rather than a guess, and it keeps these out of the
565
+ * problem-tools list where they crowd out real defects.
566
+ *
567
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
568
+ *
569
+ * Call it only after the `!res.ok` check — on a failed response you want
570
+ * `httpError`, which mines the body for the upstream's own explanation.
571
+ */
572
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
573
+ let raw: string;
574
+ try {
575
+ raw = await res.text();
576
+ } catch {
577
+ throw new Error(
578
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
579
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
580
+ );
581
+ }
582
+
583
+ const type = res.headers.get('content-type') ?? 'no content-type';
584
+
585
+ if (!raw.trim()) {
586
+ throw new Error(
587
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
588
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
589
+ );
590
+ }
591
+
592
+ // Checked before parsing rather than in the catch, because knowing it is
593
+ // markup is what turns "we failed to parse something" into "they served a
594
+ // web page" — the second is diagnosable, the first is not.
595
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
596
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
597
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
598
+ // The summary, not the source. Pasting the first 120 characters of a web
599
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
600
+ // this branch exists to describe (fleet #712).
601
+ throw new Error(
602
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
603
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
604
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
605
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
606
+ );
607
+ }
608
+
609
+ try {
610
+ return JSON.parse(raw) as T;
611
+ } catch {
612
+ throw new Error(
613
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
614
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
615
+ );
616
+ }
617
+ }
618
+
619
+ /**
620
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
621
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
622
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
623
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
624
+ * existed — every unguarded call carries the same risk, just unconfirmed.
625
+ *
626
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
627
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
628
+ * an `upstream_down:` error that names the upstream and the bound rather than
629
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
630
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
631
+ * argument a caller passes can make an upstream hang, so it is always the
632
+ * upstream's fault, and marking it that way keeps a slow API off the
633
+ * problem-tools list where it would crowd out our own defects.
634
+ *
635
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
636
+ *
637
+ * const res = await fetchWithTimeout(url, init, 'Some API');
638
+ *
639
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
640
+ * with a known-slower upstream; the label should be the same short name you'd
641
+ * pass to `httpError`/`httpErrorMessage` for that call.
642
+ */
643
+ async function fetchWithTimeout(
644
+ url: string | URL,
645
+ init: RequestInit = {},
646
+ name: string,
647
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
648
+ ): Promise<Response> {
649
+ try {
650
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
651
+ } catch (err) {
652
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
653
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
654
+ // "appears to be degraded" is an inference about the vendor that we have
655
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
656
+ // a timeout from a Worker can equally mean OUR egress is blocked.
657
+ //
658
+ // Measured today (2026-09-01, fleet #1047): every call to
659
+ // mainnet.base.org failed from the x402 facilitator while the identical
660
+ // request from a laptop returned 200. Base was entirely healthy; the
661
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
662
+ // there it would have blamed Base by name, and the next person would have
663
+ // waited for a vendor outage to clear that did not exist.
664
+ // A timeout has no status to test — there is no response at all — so
665
+ // `markInternalOrigin` is called without one: an origin we run that never
666
+ // answered is an availability failure by definition. This is the half of
667
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
668
+ throw new Error(
669
+ markInternalOrigin(
670
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
671
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
672
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
673
+ `from elsewhere before concluding ${name} is down.`,
674
+ url,
675
+ ),
676
+ );
677
+ }
678
+ throw err;
679
+ }
680
+ }
681
+
682
+ function detailSuffix(detail: string): string {
683
+ return detail ? ` — ${detail}` : '';
684
+ }
685
+
686
+ async function readDetail(res: Response): Promise<string> {
687
+ let raw: string;
688
+ try {
689
+ raw = await res.text();
690
+ } catch {
691
+ // Body already consumed, or the connection died mid-read. The status alone
692
+ // is still worth throwing — never let the error path throw its own error.
693
+ return '';
694
+ }
695
+ return summarizeErrorBody(raw);
696
+ }
697
+
698
+ /**
699
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
700
+ * that never contains markup.
701
+ *
702
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
703
+ * that markup crowds out the status. That was half right. Dropping it loses the
704
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
705
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
706
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
707
+ * verbatim, across 11 packs, and in every one of them the useful content —
708
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
709
+ * buried in markup the agent had to parse out of a string (fleet #712).
710
+ *
711
+ * So: extract the meaning, discard the markup. The output is passed through
712
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
713
+ * assert mechanically that no caller-facing message can contain `<?xml`,
714
+ * `<!DOCTYPE` or `<html`.
715
+ */
716
+ function summarizeErrorBody(raw: string): string {
717
+ if (!raw || !raw.trim()) return '';
718
+
719
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
720
+
721
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
722
+ // redirect) says what it is in its <title>, and almost nowhere else.
723
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
724
+ const title = htmlTitle(raw);
725
+ return title
726
+ ? `${title} (upstream returned an HTML error page, not an API response)`
727
+ : 'upstream returned an HTML error page, not an API response';
728
+ }
729
+
730
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
731
+ // human sentence sits in a child element whose tag name says what it is.
732
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
733
+ const fault = xmlFaultText(raw);
734
+ return fault
735
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
736
+ : 'upstream returned an XML error document with no readable message';
737
+ }
738
+
739
+ // Most JSON error bodies bury one human sentence among ids and echoed request
740
+ // params. Prefer that sentence; fall back to the whole body when the shape is
741
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
742
+ // guess wrong and show nothing.
743
+ const fromJson = messageFromJson(raw);
744
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
745
+ }
746
+
747
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
748
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
749
+ function htmlTitle(raw: string): string | null {
750
+ const head = raw.slice(0, 4000);
751
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
752
+ const m = re.exec(head);
753
+ const text = m ? stripMarkup(m[1]) : '';
754
+ if (text) return text.slice(0, 160);
755
+ }
756
+ return null;
757
+ }
758
+
759
+ /** Tag names that carry the explanation in an XML fault document, namespace
760
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
761
+ const XML_FAULT_TAG_RE =
762
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
763
+
764
+ function xmlFaultText(raw: string): string | null {
765
+ const head = raw.slice(0, 8000);
766
+ const tagged = XML_FAULT_TAG_RE.exec(head);
767
+ if (tagged && tagged[1].trim()) return tagged[1];
768
+
769
+ // Nothing conventionally named — take the longest text node instead. A fault
770
+ // document with one sentence in an oddly named element is still readable;
771
+ // returning nothing at all is not.
772
+ let best = '';
773
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
774
+ const text = m[1].trim();
775
+ if (text.length > best.length) best = text;
776
+ }
777
+ return best || null;
778
+ }
779
+
780
+ /**
781
+ * Remove every tag and stray angle bracket, then collapse whitespace.
782
+ *
783
+ * Applied to everything on the way out, including the JSON and plain-text
784
+ * paths, because an upstream is free to embed markup in a JSON string field —
785
+ * and a leak is a leak regardless of which branch produced it.
786
+ */
787
+ function stripMarkup(s: string): string {
788
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
789
+ }
790
+
791
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
792
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
793
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
794
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
795
+ function decodeEntities(s: string): string {
796
+ return s
797
+ .replace(/&(?:amp|#0*38);/gi, '&')
798
+ .replace(/&(?:lt|#0*60);/gi, '<')
799
+ .replace(/&(?:gt|#0*62);/gi, '>')
800
+ .replace(/&(?:quot|#0*34);/gi, '"')
801
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
802
+ .replace(/&nbsp;/gi, ' ');
803
+ }
804
+
805
+ /** The conventional "what went wrong" field, under any of the names upstreams
806
+ * actually use. Checked in order; first non-empty string wins. */
807
+ const MESSAGE_KEYS = [
808
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
809
+ 'description', 'error_description', 'reason', 'title', 'fault',
810
+ ];
811
+
812
+ function messageFromJson(raw: string): string | null {
813
+ let parsed: unknown;
814
+ try {
815
+ parsed = JSON.parse(raw);
816
+ } catch {
817
+ return null;
818
+ }
819
+ return pickMessage(parsed, 0);
820
+ }
821
+
822
+ function pickMessage(node: unknown, depth: number): string | null {
823
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
824
+ // shapes that account for nearly all of them, without walking a large payload.
825
+ if (depth > 2 || node == null) return null;
826
+
827
+ if (typeof node === 'string') return node.trim() || null;
828
+
829
+ if (Array.isArray(node)) {
830
+ for (const item of node) {
831
+ const found = pickMessage(item, depth + 1);
832
+ if (found) return found;
833
+ }
834
+ return null;
835
+ }
836
+
837
+ if (typeof node !== 'object') return null;
838
+ const obj = node as Record<string, unknown>;
839
+
840
+ for (const key of MESSAGE_KEYS) {
841
+ const v = obj[key];
842
+ if (typeof v === 'string' && v.trim()) return v.trim();
843
+ }
844
+ // `{error: …}` where error is itself an object or a string — the single most
845
+ // common wrapper, so it is worth descending into by name rather than scanning
846
+ // every key and risking picking up an echoed request parameter.
847
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
848
+ if (key in obj) {
849
+ const found = pickMessage(obj[key], depth + 1);
850
+ if (found) return found;
851
+ }
852
+ }
853
+ return null;
854
+ }
855
+
856
+ /** Errors are read in a single line of log output; newlines and runs of
857
+ * whitespace make a multi-line body unreadable there. */
858
+ function collapse(s: string): string {
859
+ return s.replace(/\s+/g, ' ').trim();
860
+ }
19
861
  /**
20
862
  * Open-Meteo MCP — weather forecast + historical reanalysis + sister APIs
21
863
  *
@@ -24,9 +866,16 @@ interface McpToolExport {
24
866
  */
25
867
 
26
868
 
869
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
870
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
871
+ // until its own execution budget kills the request (minutes, not seconds).
872
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
873
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
874
+ return fetchWithTimeout(url, init ?? {}, 'Open-Meteo');
875
+ }
876
+
27
877
  const FORECAST = 'https://api.open-meteo.com/v1/forecast';
28
878
  const HISTORICAL = 'https://archive-api.open-meteo.com/v1/archive';
29
- const GEO = 'https://geocoding-api.open-meteo.com/v1/search';
30
879
  const AIR = 'https://air-quality-api.open-meteo.com/v1/air-quality';
31
880
  const MARINE = 'https://marine-api.open-meteo.com/v1/marine';
32
881
  const FLOOD = 'https://flood-api.open-meteo.com/v1/flood';
@@ -35,7 +884,7 @@ const DEFAULT_HOURLY = 'temperature_2m,relative_humidity_2m,precipitation,precip
35
884
  // precipitation_probability_max (rain CHANCE %) is included alongside
36
885
  // precipitation_sum (rain AMOUNT mm) so "will it rain" / "which day has the
37
886
  // lowest rain probability" (e.g. crop-spraying planning) is answerable by default.
38
- const DEFAULT_DAILY = 'temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,wind_speed_10m_max,weather_code';
887
+ const DEFAULT_DAILY = 'temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,wind_speed_10m_max,wind_gusts_10m_max,weather_code';
39
888
 
40
889
  const tools: McpToolExport['tools'] = [
41
890
  {
@@ -174,22 +1023,18 @@ async function historical(args: Record<string, unknown>) {
174
1023
 
175
1024
  async function geocode(args: Record<string, unknown>) {
176
1025
  const name = reqStr(args, 'name', '"Tokyo"');
177
- const count = String(Math.min(100, Math.max(1, (args.count as number) ?? 10)));
1026
+ const requestedCount = Math.min(100, Math.max(1, (args.count as number) ?? 10));
178
1027
  const language = String(args.language ?? 'en');
179
- const search = (n: string) =>
180
- meteoGet(GEO, new URLSearchParams({ name: n, count, language, format: 'json' })) as Promise<{ results?: unknown[] }>;
181
-
182
- let result = await search(name);
183
- // Open-Meteo's geocoder matches on the bare place name and returns 0 results for
184
- // "City, ST" / "City, State" — but the router routinely produces exactly that.
185
- // Retry with the city part so "Fresno, CA" resolves like "Fresno".
186
- if ((!result.results || result.results.length === 0) && name.includes(',')) {
187
- const city = name.split(',')[0].trim();
188
- if (city && city.toLowerCase() !== name.toLowerCase()) {
189
- result = await search(city);
190
- }
191
- }
192
- return result;
1028
+ // fetched 10 candidates and sorted by population, under a comment saying that
1029
+ // "returns the right city". It does not, and the live proof is the exact
1030
+ // example that comment used: `Roma` came back as Roma, LESOTHO (pop 14,259).
1031
+ // Rome is ABSENT from Open-Meteo's ENGLISH results entirely, so no amount of
1032
+ // re-sorting an English result set can surface it — the query has to be
1033
+ // reissued in Italian. Population sort is necessary and not sufficient.
1034
+ const hits = await rankedPlaceHits(name, { language, count: requestedCount });
1035
+ // Upstream's own object shape is preserved: callers of this tool read
1036
+ // Open-Meteo fields directly, so normalising here would be a breaking change.
1037
+ return { results: hits.slice(0, requestedCount) };
193
1038
  }
194
1039
 
195
1040
  async function airQuality(args: Record<string, unknown>) {
@@ -221,7 +1066,7 @@ function baseLatLon(args: Record<string, unknown>): URLSearchParams {
221
1066
  }
222
1067
 
223
1068
  async function meteoGet(url: string, params: URLSearchParams) {
224
- const res = await fetch(`${url}?${params}`, { headers: { Accept: 'application/json' } });
1069
+ const res = await pwFetch(`${url}?${params}`, { headers: { Accept: 'application/json' } });
225
1070
  if (res.status === 429) throw new Error('Open-Meteo: rate-limit (HTTP 429)');
226
1071
  if (!res.ok) {
227
1072
  const t = await res.text();
package/src/server.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stdio MCP server entry point for @pipeworx/mcp-open-meteo.
3
+ * Generated by scripts/publish-pack.sh — do not hand-edit in the pack repo;
4
+ * edit scripts/publish-pack.sh (the server.ts heredoc) and republish instead.
5
+ */
6
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
9
+ import pack from './index.js';
10
+
11
+ const server = new Server(
12
+ { name: '@pipeworx/mcp-open-meteo', version: '0.1.3' },
13
+ { capabilities: { tools: {} } },
14
+ );
15
+
16
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
17
+ tools: pack.tools.map((t) => ({
18
+ name: t.name,
19
+ description: t.description,
20
+ inputSchema: t.inputSchema,
21
+ })),
22
+ }));
23
+
24
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
25
+ const { name, arguments: args } = request.params;
26
+ try {
27
+ const result = await pack.callTool(name, (args ?? {}) as Record<string, unknown>);
28
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
29
+ } catch (err) {
30
+ return {
31
+ content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],
32
+ isError: true,
33
+ };
34
+ }
35
+ });
36
+
37
+ async function main() {
38
+ const transport = new StdioServerTransport();
39
+ await server.connect(transport);
40
+ }
41
+
42
+ main().catch((err) => {
43
+ console.error('Fatal error running server:', err);
44
+ process.exit(1);
45
+ });
package/tsconfig.json CHANGED
@@ -3,12 +3,16 @@
3
3
  "target": "ES2022",
4
4
  "module": "ESNext",
5
5
  "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "types": ["@cloudflare/workers-types"],
6
8
  "strict": true,
7
9
  "esModuleInterop": true,
8
10
  "skipLibCheck": true,
11
+ "resolveJsonModule": true,
9
12
  "outDir": "dist",
10
13
  "rootDir": "src",
11
14
  "declaration": true
12
15
  },
13
- "include": ["src"]
16
+ "include": ["src"],
17
+ "exclude": ["src/server.ts"]
14
18
  }