@pipeworx/mcp-adsb 0.1.0 → 0.1.1

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
@@ -2,12 +2,16 @@
2
2
 
3
3
  adsb.lol MCP — live aircraft tracking via community ADS-B.
4
4
 
5
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 770+ 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
9
  | Tool | Description |
10
10
  |------|-------------|
11
+ | `aircraft_near` | Live aircraft tracking: what planes are flying overhead or near a location right now. Returns real-time ADS-B positions (altitude, ground speed, heading, vertical rate) for every aircraft within a radius of a lat/lon point. Use this for "what is flying above me" / "planes near <place>". |
12
+ | `get_aircraft` | Track a specific aircraft by its 24-bit ICAO hex address (e.g. "a835af"). Returns the live ADS-B position (lat/lon, altitude, speed, heading) of that exact airframe if it is currently transmitting. Real-time position data, not schedules. |
13
+ | `find_by_callsign` | Track a flight by its callsign (e.g. "UAL123"). Returns the live real-time ADS-B position (lat/lon, altitude, ground speed, heading) of the aircraft currently broadcasting that flight callsign. Live position, not a schedule lookup. |
14
+ | `military_aircraft` | Live military and government aircraft currently being tracked worldwide via ADS-B. Returns real-time positions (lat/lon, altitude, speed, heading) for military/government airframes transmitting right now. |
11
15
 
12
16
  ## Quick Start
13
17
 
@@ -23,7 +27,25 @@ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
23
27
  }
24
28
  ```
25
29
 
26
- Or connect to the full Pipeworx gateway for access to all 770+ data sources:
30
+ ### What this endpoint actually serves
31
+
32
+ `tools/list` at `https://gateway.pipeworx.io/adsb/mcp` returns the tools in the table
33
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
34
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
35
+ gateway-wide set. So the tool count you see is larger than this table: a
36
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
37
+ pack's own. The connection's `initialize` response states its exact scope, and
38
+ is the authoritative answer for a given day.
39
+
40
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
41
+ scoped connection answer a question this pack does not cover — via
42
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
43
+ second MCP server. There is currently no way to mount a pack endpoint without
44
+ them; if the extra schemas cost you more context than the routing is worth,
45
+ connect to the full gateway once rather than to several pack endpoints.
46
+
47
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
48
+ directly, instead of just this one's:
27
49
 
28
50
  ```json
29
51
  {
@@ -35,9 +57,50 @@ Or connect to the full Pipeworx gateway for access to all 770+ data sources:
35
57
  }
36
58
  ```
37
59
 
60
+ Both URLs reach the same gateway and the same 1679+ data sources. The
61
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
62
+ reaches all of them from either one.
63
+
64
+ ## No MCP client? Call it over HTTP
65
+
66
+ ```bash
67
+ curl -X POST https://gateway.pipeworx.io/v1/tools/aircraft_near \
68
+ -H 'Content-Type: application/json' \
69
+ -d '{"latitude":51.5,"longitude":-0.1}'
70
+ ```
71
+
72
+ No account needed for the first calls. Inspect any tool: `GET https://gateway.pipeworx.io/v1/tools/aircraft_near`. Find one: `POST https://gateway.pipeworx.io/v1/tools/search_packs` with `{"query":"..."}`.
73
+
74
+ ## Standalone (no gateway account)
75
+
76
+ This package also runs as a local stdio MCP server — no Pipeworx account, no
77
+ gateway round-trip:
78
+
79
+ ```json
80
+ {
81
+ "mcpServers": {
82
+ "adsb": {
83
+ "command": "npx",
84
+ "args": ["-y", "@pipeworx/mcp-adsb"]
85
+ }
86
+ }
87
+ }
88
+ ```
89
+
90
+ Or run it directly to confirm it starts:
91
+
92
+ ```bash
93
+ npx -y @pipeworx/mcp-adsb
94
+ ```
95
+
96
+ It speaks MCP over stdin/stdout and answers `initialize`/`tools/list`/`tools/call`
97
+ for **only** this pack's tools — none of the shared meta-tools the gateway
98
+ connection above adds. Same source, same tools, no ask_pipeworx routing.
99
+
38
100
  ## Using with ask_pipeworx
39
101
 
40
- Instead of calling tools directly, you can ask questions in plain English:
102
+ Instead of calling tools directly, you can ask questions in plain English —
103
+ this works on the pack endpoint above as well as on the full gateway:
41
104
 
42
105
  ```
43
106
  ask_pipeworx({ question: "your question about Adsb data" })
@@ -47,7 +110,7 @@ The gateway picks the right tool and fills the arguments automatically.
47
110
 
48
111
  ## More
49
112
 
50
- - [All tools and guides](https://github.com/pipeworx-io/examples)
113
+ - [Docs and guides](https://pipeworx.io/docs)
51
114
  - [pipeworx.io](https://pipeworx.io)
52
115
 
53
116
  ## 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-adsb",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "adsb.lol MCP — live aircraft tracking via community ADS-B.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
7
7
  "types": "src/index.ts",
8
+ "bin": {
9
+ "mcp-adsb": "bin/cli.js"
10
+ },
8
11
  "keywords": ["mcp", "mcp-server", "model-context-protocol", "pipeworx", "adsb"],
9
12
  "license": "MIT",
10
13
  "repository": {
11
14
  "type": "git",
12
- "url": "https://github.com/pipeworx-io/mcp-adsb"
15
+ "url": "git+https://github.com/pipeworx-io/mcp-adsb.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-46af700d0f46e1ad0dc5da4044230feae36fa4b2bf0ce5479c38c732cab2277f",
30
+ "sourceCommit": "60f04b68c347e970c6be94a53439d1364061fc06"
19
31
  }
20
32
  }
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/adsb",
4
4
  "title": "Adsb",
5
5
  "description": "adsb.lol MCP — live aircraft tracking via community ADS-B.",
6
- "version": "0.1.0",
6
+ "version": "0.1.1",
7
7
  "websiteUrl": "https://pipeworx.io/packs/adsb",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-adsb",
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,704 @@ interface McpToolExport {
16
24
  provider?: string;
17
25
  }
18
26
 
27
+ /**
28
+ * The class routing tokens, and the two safe ways to wrap a message carrying one.
29
+ *
30
+ * A pack signals an error's class with a leading token — `user_error:`,
31
+ * `upstream_down:`, `upstream_throttled:`, `not_found:`, `blocked_host:`. The
32
+ * gateway's classifier anchors on `^`, and `stripClassPrefix` (which hides the
33
+ * token from the caller) anchors on `^` too. So the convention has one failure
34
+ * mode, and it is silent: a catch block that wraps the message —
35
+ * `` `${slug}/${tool}: ${message}` `` — pushes the token off position 0. The
36
+ * error then books as `error` ("Pipeworx has a defect") instead of as the
37
+ * caller mistake it is, AND the raw token leaks into what the caller reads.
38
+ *
39
+ * Nothing about that fails loudly. The call still returns, the message still
40
+ * reads plausibly, and the misclassification only shows up as a pack sitting on
41
+ * the Problem Tools list for a bug it does not have. Found live in
42
+ * `medicaid-intelligence` on 2026-08-21; the same wrapper template is copied
43
+ * across 18 DMV packs, none of which emit a token *yet*.
44
+ *
45
+ * `scripts/check-error-class-prefix.mjs` is the gate that keeps this honest —
46
+ * it fails any pack that both emits a token and wraps a caught message without
47
+ * using one of the helpers below.
48
+ */
49
+
50
+ /**
51
+ * The canonical token set. `workers/gateway/src/error-class.ts` carries its own
52
+ * copy on the read side (it is deliberately importable without pulling a pack
53
+ * in); the gate asserts the two agree, because this list has already drifted
54
+ * twice — `not_found:` and `blocked_host:` were honoured by the classifier and
55
+ * not stripped, so both went out to callers verbatim for months.
56
+ */
57
+ const CLASS_TOKENS = [
58
+ 'upstream_down',
59
+ 'upstream_throttled',
60
+ 'user_error',
61
+ 'not_found',
62
+ 'blocked_host',
63
+ // `blocked_url:` is emitted at position 0 from five sites in ssrf.ts
64
+ // (`assertPublicHttpUrl`, and every redirect hop in `safeFetch`) and was in
65
+ // NEITHER reader — so it went to callers verbatim for its whole life. Caught
66
+ // 2026-08-21 by a live n8n call, which answered a private instance_url with
67
+ // "…host). blocked_url: refusing to fetch non-public or non-https URL".
68
+ // Exactly the drift the gate now blocks.
69
+ 'blocked_url',
70
+ // `auth_required:` joins the list 2026-08-29 (fleet #638). It exists for the
71
+ // same reason `user_error:` does: a bare 401/403 in an upstream body matches
72
+ // the `upstream_throttled` heuristic below before anything auth-specific, so
73
+ // a pack that needs to say "this is a credential problem, not a rate limit"
74
+ // has no wording-based route — only the explicit-prefix escape hatch works.
75
+ // tiingo and open-sanctions both reached for it on their own, on the
76
+ // (reasonable, but wrong at the time) assumption that any snake_case class
77
+ // already meant something to the gateway. Neither shipped a leak from
78
+ // MIS-CLASSIFICATION — the `error` field was already correct — the leak was
79
+ // the literal token riding along in `message`, unstripped, because this list
80
+ // didn't know the token either reader was seeing.
81
+ 'auth_required',
82
+ ] as const;
83
+
84
+ const CLASS_PREFIX_RE =
85
+ /^(?:upstream_down|upstream_throttled|user_error|not_found|blocked_host|blocked_url|auth_required)\s*:\s*/;
86
+
87
+ /**
88
+ * Split a caught message into its leading routing token (possibly empty) and
89
+ * the human-readable body, so a wrapper can put the token back on the front.
90
+ *
91
+ * const { token, body } = splitClassPrefix(message);
92
+ * return { error: `${token}my-pack/${name}: ${body}` };
93
+ *
94
+ * The `${token}` must be the FIRST thing in the template — that is the whole
95
+ * point, and it is what the gate checks.
96
+ */
97
+ function splitClassPrefix(message: string): { token: string; body: string } {
98
+ const token = message.match(CLASS_PREFIX_RE)?.[0] ?? '';
99
+ return { token, body: message.slice(token.length) };
100
+ }
101
+
102
+ /**
103
+ * Drop a leading routing token from a message that is about to become a
104
+ * FRAGMENT of a larger one — a per-mirror failure joined into "all providers
105
+ * failed (...)", say. Hoisting is wrong there: the fragment never reaches
106
+ * position 0, so the token cannot route anything and would only leak. The outer
107
+ * message declares its own class.
108
+ */
109
+ function dropClassPrefix(message: string): string {
110
+ return message.replace(CLASS_PREFIX_RE, '');
111
+ }
112
+
113
+
114
+ /**
115
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
116
+ *
117
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
118
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
119
+ * covered the majority and structurally could not cover the rest: the rest
120
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
121
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
122
+ *
123
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
124
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
125
+ *
126
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
127
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
128
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
129
+ * our own Supabase for fleet. There is no third party anywhere in either call.
130
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
131
+ * class that means "the source is unreachable and there is nothing for us to
132
+ * fix", which is why the problem-tools triage skips it.
133
+ *
134
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
135
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
136
+ * one site today, so it would work today. It would also rot the first time
137
+ * somebody rewords a label — silently, and in the direction of hiding our own
138
+ * outage, which is worse than the bug being fixed. Every prose rule in
139
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
140
+ * #584); that history is most of that file's comment budget.
141
+ *
142
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
143
+ * hostname is a fact about the call, not a guess about its prose. Two
144
+ * consequences that a pack-level flag could not give us, and the reason the
145
+ * flag was rejected:
146
+ *
147
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
148
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
149
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
150
+ * either pack would relabel a real third-party outage as ours — inventing
151
+ * work, which is the same class of error in the opposite direction.
152
+ * - It covers every future internal pack for free, instead of one declared
153
+ * slug at a time.
154
+ *
155
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
156
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
157
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
158
+ * this module — so changing the wording changes both sides in the same edit and
159
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
160
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
161
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
162
+ * from its own classifier three times and needed a CI gate to hold them
163
+ * together.
164
+ *
165
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
166
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
167
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
168
+ * availability failure" is decided from the actual status code, never re-derived
169
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
170
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
171
+ */
172
+
173
+ /**
174
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
175
+ *
176
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
177
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
178
+ * and different fixes. Here there is only one story to tell — an origin we run
179
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
180
+ * value is decoration; #724 is what happens when a class holds several
181
+ * situations, and inventing sub-values ahead of a reason to act on them
182
+ * differently is the same mistake with the sign flipped.
183
+ *
184
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
185
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
186
+ * hint paths, which only care whether retrying or a sibling tool might work —
187
+ * and it might. Nothing a caller sees or is charged changes here.
188
+ *
189
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
190
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
191
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
192
+ * worked on the write side and was invisible for weeks.
193
+ */
194
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
195
+
196
+ /**
197
+ * The token that carries "this origin is ours" from the call site to the
198
+ * classifier.
199
+ *
200
+ * Appended to the error message rather than attached to the Error object,
201
+ * because the object does not survive the trip: 275 packs return `{ error:
202
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
203
+ * and the fleet pack rebuilds its error from a captured status + body across a
204
+ * retry loop. A property on an Error would be dropped by every one of those
205
+ * paths and the class would work in tests and vanish in production.
206
+ *
207
+ * WORDING IS LOAD-BEARING, same rule as labelAge's note in authority.ts. This
208
+ * string is appended to a pack's thrown Error message (shared/src/http.ts),
209
+ * and a thrown Error's message is exactly what the gateway hands back to the
210
+ * caller as `content[0].text` when nothing rewrites it (workers/gateway/src
211
+ * catches the throw and sets `rawResult.message = stripClassPrefix(error)`,
212
+ * which does not touch this suffix) — so the original wording,
213
+ * " [pipeworx-hosted origin — our own service, not a third party]", was not a
214
+ * theoretical leak: it shipped live on pipeworx-catalog's 522s, 7 times in 6
215
+ * hours on 2026-09-02 (see tests/golden-internal-service.test.ts), verbatim
216
+ * naming Pipeworx as the host. check:hosting-claims never caught it because it
217
+ * did not scan shared/ at all (task #2009). Reworded to describe the
218
+ * OBSERVATION (the origin did not answer) without a claim about who runs it —
219
+ * the identical fix labelAge got: drop the possessive, keep the fact.
220
+ */
221
+ const INTERNAL_ORIGIN_MARKER = ' [origin did not respond — retry before concluding the named source is down]';
222
+
223
+ /**
224
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
225
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
226
+ *
227
+ * Matching the shape rather than listing the ref keeps this correct when we add
228
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
229
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
230
+ * own status page and emphatically not our database. Verified 2026-09-02 by
231
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
232
+ * only real project ref anywhere in the tree is ours, the rest are doc
233
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
234
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
235
+ * by construction.
236
+ */
237
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
238
+
239
+ /**
240
+ * Is this a host WE run?
241
+ *
242
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
243
+ * hosted on workers.dev, so the suffix says where something runs and not who
244
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
245
+ * hostname or to our Supabase project, both of which are ownership facts.
246
+ *
247
+ * `workers/gateway/src/provenance.ts`'s `OUR_HOSTS` answers the same
248
+ * question and DOES include `workers.dev` — a documented divergence
249
+ * (task #2051), not a bug to converge. That list decides what a response may
250
+ * cite as a data SOURCE, where a false negative (citing our own worker as an
251
+ * external source) is the hosting-disclosure leak this whole file exists to
252
+ * prevent, so it errs broad. This one decides who gets BLAMED for a 5xx in
253
+ * outage metrics read by on-call, where a false positive (crediting our own
254
+ * infra with a third party's outage) hides the real failure, so it errs
255
+ * narrow. Same suffix, opposite direction, because they are never called for
256
+ * the same reason.
257
+ *
258
+ * Returns false on anything unparseable rather than throwing — this runs inside
259
+ * an error path, and an error path that can itself throw turns a diagnosable
260
+ * failure into a mystery.
261
+ */
262
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
263
+ if (!url) return false;
264
+ let host: string;
265
+ try {
266
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
267
+ } catch {
268
+ return false;
269
+ }
270
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
271
+ return SUPABASE_PROJECT_HOST.test(host);
272
+ }
273
+
274
+ /**
275
+ * Append the marker when this failure was OUR origin failing to answer.
276
+ *
277
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
278
+ * where there is no response at all, and "the origin did not answer" is the
279
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
280
+ * registry for a slug that does not exist is the caller's argument, not our
281
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
282
+ *
283
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
284
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
285
+ */
286
+ function markInternalOrigin(
287
+ message: string,
288
+ url: string | URL | undefined | null,
289
+ status?: number,
290
+ ): string {
291
+ if (status !== undefined && status < 500) return message;
292
+ if (!isPipeworxOrigin(url)) return message;
293
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
294
+ return message + INTERNAL_ORIGIN_MARKER;
295
+ }
296
+
297
+ /**
298
+ * Which blob4 value a failure from our own web services books as, or undefined
299
+ * if this is not one.
300
+ *
301
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
302
+ * from our own Supabase is a strictly more specific statement about the same
303
+ * row (which of our services, and why), and the two cannot disagree about
304
+ * whether the failure is ours.
305
+ */
306
+ function internalHostMetricsClass(error: string): string | undefined {
307
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
308
+ }
309
+
310
+
311
+ /**
312
+ * One place to turn a failed `fetch` into an error a caller can act on.
313
+ *
314
+ * Nearly every pack was written the same way:
315
+ *
316
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
317
+ *
318
+ * which discards the response body — and the body is usually where the upstream
319
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
320
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
321
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
322
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
323
+ *
324
+ * It also hides bugs one level down. Two of the first three packs audited had a
325
+ * second defect that only existed because of this line: unsplash's rate-limit
326
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
327
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
328
+ * parsing dead code for every non-200.
329
+ *
330
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
331
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
332
+ * `error` tier is what the daily problem-tools list is built from — it means
333
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
334
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
335
+ * values into something TED rejected, and that bug was found only because it sat
336
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
337
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
338
+ * for the 481 that say nothing at all.
339
+ */
340
+
341
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
342
+ * short enough that an HTML page or a stack trace can't swamp the error. */
343
+
344
+ const MAX_DETAIL = 300;
345
+
346
+ /**
347
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
348
+ *
349
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
350
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
351
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
352
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
353
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
354
+ * fast, actionable error instead of holding the connection, and long enough
355
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
356
+ */
357
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
358
+
359
+ /**
360
+ * Read the body of a failed response and fold it into a throwable Error.
361
+ *
362
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
363
+ * change rather than a drop-in:
364
+ *
365
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
366
+ *
367
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
368
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
369
+ * something new from inside the error path.
370
+ */
371
+ async function httpError(res: Response, name: string): Promise<Error> {
372
+ return new Error(await httpErrorMessage(res, name));
373
+ }
374
+
375
+ /** The message text without constructing an Error — for packs that need to wrap
376
+ * it in their own envelope or add an explicit classification prefix. */
377
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
378
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
379
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
380
+ // about the call rather than a guess from the `name` the pack passed in —
381
+ // reword that label freely, the class does not move. See
382
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
383
+ // this touches 481 packs' error text and changes none of it.
384
+ return markInternalOrigin(
385
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
386
+ res.url,
387
+ res.status,
388
+ );
389
+ }
390
+
391
+ /**
392
+ * Just the upstream's own explanation — no name, no status.
393
+ *
394
+ * For a pack that has already said both in its own sentence. epo-ops reads
395
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
396
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
397
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
398
+ * actually said ("Not enough characters before truncation character") nowhere
399
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
400
+ * can fall back to its own wording.
401
+ */
402
+ async function upstreamDetail(res: Response): Promise<string> {
403
+ return readDetail(res);
404
+ }
405
+
406
+ /**
407
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
408
+ *
409
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
410
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
411
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
412
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
413
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
414
+ *
415
+ * That string is the problem. It names no upstream, carries no status, and
416
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
417
+ * means "we have a defect", and the caller is told nothing they can act on.
418
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
419
+ * status-code health check we own reported it green (7889a845). A zero-length
420
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
421
+ * uk-gazette (83% of external calls) and census.
422
+ *
423
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
424
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
425
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
426
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
427
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
428
+ * a statement of fact rather than a guess, and it keeps these out of the
429
+ * problem-tools list where they crowd out real defects.
430
+ *
431
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
432
+ *
433
+ * Call it only after the `!res.ok` check — on a failed response you want
434
+ * `httpError`, which mines the body for the upstream's own explanation.
435
+ */
436
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
437
+ let raw: string;
438
+ try {
439
+ raw = await res.text();
440
+ } catch {
441
+ throw new Error(
442
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
443
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
444
+ );
445
+ }
446
+
447
+ const type = res.headers.get('content-type') ?? 'no content-type';
448
+
449
+ if (!raw.trim()) {
450
+ throw new Error(
451
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
452
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
453
+ );
454
+ }
455
+
456
+ // Checked before parsing rather than in the catch, because knowing it is
457
+ // markup is what turns "we failed to parse something" into "they served a
458
+ // web page" — the second is diagnosable, the first is not.
459
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
460
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
461
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
462
+ // The summary, not the source. Pasting the first 120 characters of a web
463
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
464
+ // this branch exists to describe (fleet #712).
465
+ throw new Error(
466
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
467
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
468
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
469
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
470
+ );
471
+ }
472
+
473
+ try {
474
+ return JSON.parse(raw) as T;
475
+ } catch {
476
+ throw new Error(
477
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
478
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
479
+ );
480
+ }
481
+ }
482
+
483
+ /**
484
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
485
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
486
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
487
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
488
+ * existed — every unguarded call carries the same risk, just unconfirmed.
489
+ *
490
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
491
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
492
+ * an `upstream_down:` error that names the upstream and the bound rather than
493
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
494
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
495
+ * argument a caller passes can make an upstream hang, so it is always the
496
+ * upstream's fault, and marking it that way keeps a slow API off the
497
+ * problem-tools list where it would crowd out our own defects.
498
+ *
499
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
500
+ *
501
+ * const res = await fetchWithTimeout(url, init, 'Some API');
502
+ *
503
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
504
+ * with a known-slower upstream; the label should be the same short name you'd
505
+ * pass to `httpError`/`httpErrorMessage` for that call.
506
+ */
507
+ async function fetchWithTimeout(
508
+ url: string | URL,
509
+ init: RequestInit = {},
510
+ name: string,
511
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
512
+ ): Promise<Response> {
513
+ try {
514
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
515
+ } catch (err) {
516
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
517
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
518
+ // "appears to be degraded" is an inference about the vendor that we have
519
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
520
+ // a timeout from a Worker can equally mean OUR egress is blocked.
521
+ //
522
+ // Measured today (2026-09-01, fleet #1047): every call to
523
+ // mainnet.base.org failed from the x402 facilitator while the identical
524
+ // request from a laptop returned 200. Base was entirely healthy; the
525
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
526
+ // there it would have blamed Base by name, and the next person would have
527
+ // waited for a vendor outage to clear that did not exist.
528
+ // A timeout has no status to test — there is no response at all — so
529
+ // `markInternalOrigin` is called without one: an origin we run that never
530
+ // answered is an availability failure by definition. This is the half of
531
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
532
+ throw new Error(
533
+ markInternalOrigin(
534
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
535
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
536
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
537
+ `from elsewhere before concluding ${name} is down.`,
538
+ url,
539
+ ),
540
+ );
541
+ }
542
+ throw err;
543
+ }
544
+ }
545
+
546
+ function detailSuffix(detail: string): string {
547
+ return detail ? ` — ${detail}` : '';
548
+ }
549
+
550
+ async function readDetail(res: Response): Promise<string> {
551
+ let raw: string;
552
+ try {
553
+ raw = await res.text();
554
+ } catch {
555
+ // Body already consumed, or the connection died mid-read. The status alone
556
+ // is still worth throwing — never let the error path throw its own error.
557
+ return '';
558
+ }
559
+ return summarizeErrorBody(raw);
560
+ }
561
+
562
+ /**
563
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
564
+ * that never contains markup.
565
+ *
566
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
567
+ * that markup crowds out the status. That was half right. Dropping it loses the
568
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
569
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
570
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
571
+ * verbatim, across 11 packs, and in every one of them the useful content —
572
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
573
+ * buried in markup the agent had to parse out of a string (fleet #712).
574
+ *
575
+ * So: extract the meaning, discard the markup. The output is passed through
576
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
577
+ * assert mechanically that no caller-facing message can contain `<?xml`,
578
+ * `<!DOCTYPE` or `<html`.
579
+ */
580
+ function summarizeErrorBody(raw: string): string {
581
+ if (!raw || !raw.trim()) return '';
582
+
583
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
584
+
585
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
586
+ // redirect) says what it is in its <title>, and almost nowhere else.
587
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
588
+ const title = htmlTitle(raw);
589
+ return title
590
+ ? `${title} (upstream returned an HTML error page, not an API response)`
591
+ : 'upstream returned an HTML error page, not an API response';
592
+ }
593
+
594
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
595
+ // human sentence sits in a child element whose tag name says what it is.
596
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
597
+ const fault = xmlFaultText(raw);
598
+ return fault
599
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
600
+ : 'upstream returned an XML error document with no readable message';
601
+ }
602
+
603
+ // Most JSON error bodies bury one human sentence among ids and echoed request
604
+ // params. Prefer that sentence; fall back to the whole body when the shape is
605
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
606
+ // guess wrong and show nothing.
607
+ const fromJson = messageFromJson(raw);
608
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
609
+ }
610
+
611
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
612
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
613
+ function htmlTitle(raw: string): string | null {
614
+ const head = raw.slice(0, 4000);
615
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
616
+ const m = re.exec(head);
617
+ const text = m ? stripMarkup(m[1]) : '';
618
+ if (text) return text.slice(0, 160);
619
+ }
620
+ return null;
621
+ }
622
+
623
+ /** Tag names that carry the explanation in an XML fault document, namespace
624
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
625
+ const XML_FAULT_TAG_RE =
626
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
627
+
628
+ function xmlFaultText(raw: string): string | null {
629
+ const head = raw.slice(0, 8000);
630
+ const tagged = XML_FAULT_TAG_RE.exec(head);
631
+ if (tagged && tagged[1].trim()) return tagged[1];
632
+
633
+ // Nothing conventionally named — take the longest text node instead. A fault
634
+ // document with one sentence in an oddly named element is still readable;
635
+ // returning nothing at all is not.
636
+ let best = '';
637
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
638
+ const text = m[1].trim();
639
+ if (text.length > best.length) best = text;
640
+ }
641
+ return best || null;
642
+ }
643
+
644
+ /**
645
+ * Remove every tag and stray angle bracket, then collapse whitespace.
646
+ *
647
+ * Applied to everything on the way out, including the JSON and plain-text
648
+ * paths, because an upstream is free to embed markup in a JSON string field —
649
+ * and a leak is a leak regardless of which branch produced it.
650
+ */
651
+ function stripMarkup(s: string): string {
652
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
653
+ }
654
+
655
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
656
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
657
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
658
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
659
+ function decodeEntities(s: string): string {
660
+ return s
661
+ .replace(/&(?:amp|#0*38);/gi, '&')
662
+ .replace(/&(?:lt|#0*60);/gi, '<')
663
+ .replace(/&(?:gt|#0*62);/gi, '>')
664
+ .replace(/&(?:quot|#0*34);/gi, '"')
665
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
666
+ .replace(/&nbsp;/gi, ' ');
667
+ }
668
+
669
+ /** The conventional "what went wrong" field, under any of the names upstreams
670
+ * actually use. Checked in order; first non-empty string wins. */
671
+ const MESSAGE_KEYS = [
672
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
673
+ 'description', 'error_description', 'reason', 'title', 'fault',
674
+ ];
675
+
676
+ function messageFromJson(raw: string): string | null {
677
+ let parsed: unknown;
678
+ try {
679
+ parsed = JSON.parse(raw);
680
+ } catch {
681
+ return null;
682
+ }
683
+ return pickMessage(parsed, 0);
684
+ }
685
+
686
+ function pickMessage(node: unknown, depth: number): string | null {
687
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
688
+ // shapes that account for nearly all of them, without walking a large payload.
689
+ if (depth > 2 || node == null) return null;
690
+
691
+ if (typeof node === 'string') return node.trim() || null;
692
+
693
+ if (Array.isArray(node)) {
694
+ for (const item of node) {
695
+ const found = pickMessage(item, depth + 1);
696
+ if (found) return found;
697
+ }
698
+ return null;
699
+ }
700
+
701
+ if (typeof node !== 'object') return null;
702
+ const obj = node as Record<string, unknown>;
703
+
704
+ for (const key of MESSAGE_KEYS) {
705
+ const v = obj[key];
706
+ if (typeof v === 'string' && v.trim()) return v.trim();
707
+ }
708
+ // `{error: …}` where error is itself an object or a string — the single most
709
+ // common wrapper, so it is worth descending into by name rather than scanning
710
+ // every key and risking picking up an echoed request parameter.
711
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
712
+ if (key in obj) {
713
+ const found = pickMessage(obj[key], depth + 1);
714
+ if (found) return found;
715
+ }
716
+ }
717
+ return null;
718
+ }
719
+
720
+ /** Errors are read in a single line of log output; newlines and runs of
721
+ * whitespace make a multi-line body unreadable there. */
722
+ function collapse(s: string): string {
723
+ return s.replace(/\s+/g, ' ').trim();
724
+ }
19
725
  /**
20
726
  * adsb.lol MCP — live aircraft tracking via community ADS-B.
21
727
  *
@@ -25,6 +731,14 @@ interface McpToolExport {
25
731
  */
26
732
 
27
733
 
734
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
735
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
736
+ // until its own execution budget kills the request (minutes, not seconds).
737
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
738
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
739
+ return fetchWithTimeout(url, init ?? {}, 'adsb.lol');
740
+ }
741
+
28
742
  const BASE = 'https://api.adsb.lol/v2';
29
743
  const UA = 'pipeworx/1.0 (+https://pipeworx.io)';
30
744
 
@@ -83,7 +797,7 @@ const mapAc = (a: Record<string, unknown>) => ({
83
797
  lat: a.lat,
84
798
  lon: a.lon,
85
799
  alt_baro_ft: a.alt_baro,
86
- ground_speed_kt: a.gs,
800
+ ground_speed_kt: a.gs ?? null,
87
801
  track_deg: a.track,
88
802
  vert_rate_fpm: a.baro_rate,
89
803
  squawk: a.squawk,
@@ -100,13 +814,101 @@ interface AdsbResponse {
100
814
  message?: string;
101
815
  }
102
816
 
817
+ /**
818
+ * Mirrors serving the same readsb payload. adsb.lol alone took this pack down on
819
+ * 2026-07-25 (three of four tools failing on 429/5xx), so a single upstream is
820
+ * not enough. adsb.fi uses a different path layout for the same queries, hence
821
+ * the per-mirror rewrite.
822
+ */
823
+ const ADSB_MIRRORS: { name: string; url: (path: string) => string | null }[] = [
824
+ { name: 'adsb.lol', url: (p) => `https://api.adsb.lol/v2${p}` },
825
+ {
826
+ name: 'airplanes.live',
827
+ url: (p) => {
828
+ const base = 'https://api.airplanes.live/v2';
829
+ // Radius search is /point/<lat>/<lon>/<dist> here, not /lat/../lon/../dist/..
830
+ const m = p.match(/^\/lat\/([^/]+)\/lon\/([^/]+)\/dist\/(.+)$/);
831
+ if (m) return `${base}/point/${m[1]}/${m[2]}/${m[3]}`;
832
+ return `${base}${p}`;
833
+ },
834
+ },
835
+ {
836
+ name: 'adsb.fi',
837
+ url: (p) => {
838
+ const base = 'https://opendata.adsb.fi/api/v2';
839
+ // /hex/<h> -> /icao/<h>; /lat/../lon/../dist/.. and /callsign/.. and /mil match.
840
+ const m = p.match(/^\/hex\/(.+)$/);
841
+ if (m) return `${base}/icao/${m[1]}`;
842
+ if (/^\/(lat|callsign|mil)/.test(p)) return `${base}${p}`;
843
+ return null;
844
+ },
845
+ },
846
+ ];
847
+
103
848
  async function adsbGet(path: string): Promise<AdsbResponse> {
104
- const res = await fetch(`${BASE}${path}`, { headers: { Accept: 'application/json', 'User-Agent': UA } });
105
- if (!res.ok) {
106
- const message = await res.text().catch(() => '');
107
- return { error: res.status, message };
849
+ // The free ADSB tiers 429 under load. Try each mirror (one retry apiece on
850
+ // 429), and never leak the raw nginx HTML error page — return a clean message
851
+ // the caller (and the golden classifier) reads as an upstream throttle rather
852
+ // than a pack bug.
853
+ const problems: string[] = [];
854
+ let lastEmpty: AdsbResponse | undefined;
855
+ for (const mirror of ADSB_MIRRORS) {
856
+ const url = mirror.url(path);
857
+ if (!url) continue;
858
+ let res: Response | undefined;
859
+ for (let attempt = 0; attempt < 2; attempt++) {
860
+ try {
861
+ res = await pwFetch(url, { headers: { Accept: 'application/json', 'User-Agent': UA } });
862
+ } catch (e) {
863
+ problems.push(`${mirror.name}:${dropClassPrefix(String(e)).slice(0, 40)}`);
864
+ res = undefined;
865
+ break;
866
+ }
867
+ if (res.status !== 429) break;
868
+ if (attempt === 0) await new Promise((r) => setTimeout(r, 1200));
869
+ }
870
+ if (!res) continue;
871
+ if (res.status === 429) {
872
+ problems.push(`${mirror.name}:429`);
873
+ continue;
874
+ }
875
+ if (!res.ok) {
876
+ problems.push(`${mirror.name}:${res.status}`);
877
+ continue;
878
+ }
879
+ try {
880
+ const json = (await res.json()) as AdsbResponse & { aircraft?: unknown[] };
881
+ // adsb.fi returns the array under `aircraft`; normalise to `ac`.
882
+ if (!('ac' in json) && Array.isArray(json.aircraft)) {
883
+ (json as { ac?: unknown[] }).ac = json.aircraft;
884
+ }
885
+ // A mirror under load answers HTTP 200 with an EMPTY list instead of 429 —
886
+ // a silent throttle. Verified 2026-08-09: adsb.lol returned total:0 for
887
+ // LAX while airplanes.live returned 218 aircraft for the same point in the
888
+ // same instant. Trusting that answer reports "no aircraft near Heathrow",
889
+ // which is never true and reads as fact. So an empty list is a REASON TO
890
+ // ASK THE NEXT MIRROR, not an answer — but only the last word counts: if
891
+ // every mirror agrees the sky is empty, the empty result stands.
892
+ const ac = (json as { ac?: unknown[] }).ac;
893
+ if (Array.isArray(ac) && ac.length === 0) {
894
+ problems.push(`${mirror.name}:empty-200`);
895
+ lastEmpty = json;
896
+ continue;
897
+ }
898
+ return json;
899
+ } catch (e) {
900
+ problems.push(`${mirror.name}:bad-json`);
901
+ }
108
902
  }
109
- return res.json();
903
+ // Every mirror answered empty — that is a real "nothing in this airspace".
904
+ if (lastEmpty) return lastEmpty;
905
+ const throttled = problems.some((p) => p.endsWith(':429'));
906
+ return {
907
+ error: throttled ? 429 : 502,
908
+ message: throttled
909
+ ? `ADSB upstream rate-limit — all endpoints throttled (${problems.join(', ')}). Free-tier throttle; retry shortly.`
910
+ : `ADSB upstream unavailable across all endpoints (${problems.join(', ')}).`,
911
+ };
110
912
  }
111
913
 
112
914
  function reqStr(args: Record<string, unknown>, key: string, example: string): string {
package/src/server.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Stdio MCP server entry point for @pipeworx/mcp-adsb.
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-adsb', version: '0.1.1' },
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
  }