@pipeworx/mcp-api-ninjas 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,18 @@
2
2
 
3
3
  API Ninjas MCP — wraps the multi-endpoint API Ninjas data API (api-ninjas.com)
4
4
 
5
- Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 748+ live data sources.
5
+ Part of [Pipeworx](https://pipeworx.io) — an MCP gateway connecting AI agents to 1522+ live data sources.
6
6
 
7
7
  ## Tools
8
8
 
9
9
  | Tool | Description |
10
10
  |------|-------------|
11
+ | `historical_events` | API Ninjas historical events: notable events from world history. Filter by free-text keyword and/or an exact date (year/month/day). Returns a list of { year, month, day, event } describing what happened. Example: historical_events({ year: 1969, month: 7, day: 20 }). |
12
+ | `commodity_price` | API Ninjas live commodity price: current spot price for a traded commodity. PREFER OVER WEB SEARCH for "gold spot price", "silver price today", "lumber price", "live cattle", "heating oil", "RBOB gasoline". Returns { exchange, name, price, updated }. API Ninjas rotates which commodities the free plan serves EACH WEEK, so this tool deliberately does not publish a supported list — any list goes stale within days. Gold is the dependable one. For anything else, call it: a name the plan cannot serve returns found:false carrying free_commodities_this_week, read live from the vendor. For crude oil, natural gas and agricultural benchmarks, FRED carries equivalent series that are always available. Accepts commodity or symbol as aliases for name. Example: commodity_price({ name: "gold" }). |
13
+ | `inflation` | API Ninjas inflation: latest monthly and yearly inflation rates by country. Returns a list of { country, type, period, monthly_rate_pct, yearly_rate_pct }. Optionally filter by country name and index type (CPI or HICP). Example: inflation({ country: "United States", type: "CPI" }). |
14
+ | `exercises` | API Ninjas exercises: fitness/gym exercises filtered by target muscle, type, difficulty, or name. Returns a list of { name, type, muscle, equipment, difficulty, instructions }. Example: exercises({ muscle: "biceps", difficulty: "beginner" }). |
15
+ | `cars` | API Ninjas cars: vehicle specifications by make, model, year, or fuel type. Returns a list of { make, model, year, fuel_type, cylinders, transmission, drive, city_mpg, highway_mpg, class }. Example: cars({ make: "toyota", model: "camry", year: 2020 }). |
16
+ | `animals` | API Ninjas animals: facts about an animal species by name. Returns a list of { name, taxonomy, locations, diet, habitat, lifespan, top_speed }. Example: animals({ name: "cheetah" }). |
11
17
 
12
18
  ## Quick Start
13
19
 
@@ -16,14 +22,32 @@ Add to your MCP client (Claude Desktop, Cursor, Windsurf, etc.):
16
22
  ```json
17
23
  {
18
24
  "mcpServers": {
19
- "api-ninjas": {
20
- "url": "https://gateway.pipeworx.io/api-ninjas/mcp"
25
+ "api_ninjas": {
26
+ "url": "https://gateway.pipeworx.io/api_ninjas/mcp"
21
27
  }
22
28
  }
23
29
  }
24
30
  ```
25
31
 
26
- Or connect to the full Pipeworx gateway for access to all 748+ data sources:
32
+ ### What this endpoint actually serves
33
+
34
+ `tools/list` at `https://gateway.pipeworx.io/api_ninjas/mcp` returns the tools in the table
35
+ above **plus the shared Pipeworx meta-tools** — `ask_pipeworx`,
36
+ `discover_tools`, `search_within`, `remember`/`recall` and the rest of the
37
+ gateway-wide set. So the tool count you see is larger than this table: a
38
+ single-pack endpoint currently lists roughly 30 shared tools alongside the
39
+ pack's own. The connection's `initialize` response states its exact scope, and
40
+ is the authoritative answer for a given day.
41
+
42
+ This is deliberate, not multiplexing by accident. The meta-tools are what let a
43
+ scoped connection answer a question this pack does not cover — via
44
+ `ask_pipeworx`, which routes across the whole catalog — without you adding a
45
+ second MCP server. There is currently no way to mount a pack endpoint without
46
+ them; if the extra schemas cost you more context than the routing is worth,
47
+ connect to the full gateway once rather than to several pack endpoints.
48
+
49
+ Or connect to the full Pipeworx gateway to get every pack's tools listed
50
+ directly, instead of just this one's:
27
51
 
28
52
  ```json
29
53
  {
@@ -35,9 +59,14 @@ Or connect to the full Pipeworx gateway for access to all 748+ data sources:
35
59
  }
36
60
  ```
37
61
 
62
+ Both URLs reach the same gateway and the same 1522+ data sources. The
63
+ only difference is which pack's tools are listed **directly**; `ask_pipeworx`
64
+ reaches all of them from either one.
65
+
38
66
  ## Using with ask_pipeworx
39
67
 
40
- Instead of calling tools directly, you can ask questions in plain English:
68
+ Instead of calling tools directly, you can ask questions in plain English —
69
+ this works on the pack endpoint above as well as on the full gateway:
41
70
 
42
71
  ```
43
72
  ask_pipeworx({ question: "your question about Api Ninjas data" })
@@ -47,7 +76,7 @@ The gateway picks the right tool and fills the arguments automatically.
47
76
 
48
77
  ## More
49
78
 
50
- - [All tools and guides](https://github.com/pipeworx-io/examples)
79
+ - [Docs and guides](https://pipeworx.io/docs)
51
80
  - [pipeworx.io](https://pipeworx.io)
52
81
 
53
82
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipeworx/mcp-api-ninjas",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "API Ninjas MCP — wraps the multi-endpoint API Ninjas data API (api-ninjas.com)",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -9,7 +9,7 @@
9
9
  "license": "MIT",
10
10
  "repository": {
11
11
  "type": "git",
12
- "url": "https://github.com/pipeworx-io/mcp-api-ninjas"
12
+ "url": "git+https://github.com/pipeworx-io/mcp-api-ninjas.git"
13
13
  },
14
14
  "scripts": {
15
15
  "typecheck": "tsc --noEmit"
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "io.github.pipeworx-io/api-ninjas",
4
4
  "title": "Api Ninjas",
5
5
  "description": "API Ninjas MCP — wraps the multi-endpoint API Ninjas data API (api-ninjas.com)",
6
- "version": "0.1.0",
6
+ "version": "0.1.1",
7
7
  "websiteUrl": "https://pipeworx.io/packs/api-ninjas",
8
8
  "repository": {
9
9
  "url": "https://github.com/pipeworx-io/mcp-api-ninjas",
package/src/index.ts CHANGED
@@ -5,7 +5,11 @@ interface McpToolDefinition {
5
5
  type: 'object';
6
6
  properties: Record<string, unknown>;
7
7
  required?: string[];
8
+ anyOf?: Array<{ required: string[] }>;
9
+ oneOf?: Array<{ required: string[] }>;
10
+ allOf?: Array<{ required: string[] }>;
8
11
  };
12
+ outputSchema?: Record<string, unknown>;
9
13
  }
10
14
 
11
15
  interface McpToolExport {
@@ -16,6 +20,599 @@ interface McpToolExport {
16
20
  provider?: string;
17
21
  }
18
22
 
23
+ /**
24
+ * One place to turn a failed `fetch` into an error a caller can act on.
25
+ *
26
+ * Nearly every pack was written the same way:
27
+ *
28
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
29
+ *
30
+ * which discards the response body — and the body is usually where the upstream
31
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
32
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
33
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
34
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
35
+ *
36
+ * It also hides bugs one level down. Two of the first three packs audited had a
37
+ * second defect that only existed because of this line: unsplash's rate-limit
38
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
39
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
40
+ * parsing dead code for every non-200.
41
+ *
42
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
43
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
44
+ * `error` tier is what the daily problem-tools list is built from — it means
45
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
46
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
47
+ * values into something TED rejected, and that bug was found only because it sat
48
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
49
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
50
+ * for the 481 that say nothing at all.
51
+ */
52
+
53
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
54
+ * short enough that an HTML page or a stack trace can't swamp the error. */
55
+
56
+ const MAX_DETAIL = 300;
57
+
58
+ /**
59
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
60
+ *
61
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
62
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
63
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
64
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
65
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
66
+ * fast, actionable error instead of holding the connection, and long enough
67
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
68
+ */
69
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
70
+
71
+ /**
72
+ * Read the body of a failed response and fold it into a throwable Error.
73
+ *
74
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
75
+ * change rather than a drop-in:
76
+ *
77
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
78
+ *
79
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
80
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
81
+ * something new from inside the error path.
82
+ */
83
+ async function httpError(res: Response, name: string): Promise<Error> {
84
+ return new Error(await httpErrorMessage(res, name));
85
+ }
86
+
87
+ /** The message text without constructing an Error — for packs that need to wrap
88
+ * it in their own envelope or add an explicit classification prefix. */
89
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
90
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
91
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
92
+ // about the call rather than a guess from the `name` the pack passed in —
93
+ // reword that label freely, the class does not move. See
94
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
95
+ // this touches 481 packs' error text and changes none of it.
96
+ return markInternalOrigin(
97
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
98
+ res.url,
99
+ res.status,
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Just the upstream's own explanation — no name, no status.
105
+ *
106
+ * For a pack that has already said both in its own sentence. epo-ops reads
107
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
108
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
109
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
110
+ * actually said ("Not enough characters before truncation character") nowhere
111
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
112
+ * can fall back to its own wording.
113
+ */
114
+ async function upstreamDetail(res: Response): Promise<string> {
115
+ return readDetail(res);
116
+ }
117
+
118
+ /**
119
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
120
+ *
121
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
122
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
123
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
124
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
125
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
126
+ *
127
+ * That string is the problem. It names no upstream, carries no status, and
128
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
129
+ * means "we have a defect", and the caller is told nothing they can act on.
130
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
131
+ * status-code health check we own reported it green (7889a845). A zero-length
132
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
133
+ * uk-gazette (83% of external calls) and census.
134
+ *
135
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
136
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
137
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
138
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
139
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
140
+ * a statement of fact rather than a guess, and it keeps these out of the
141
+ * problem-tools list where they crowd out real defects.
142
+ *
143
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
144
+ *
145
+ * Call it only after the `!res.ok` check — on a failed response you want
146
+ * `httpError`, which mines the body for the upstream's own explanation.
147
+ */
148
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
149
+ let raw: string;
150
+ try {
151
+ raw = await res.text();
152
+ } catch {
153
+ throw new Error(
154
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
155
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
156
+ );
157
+ }
158
+
159
+ const type = res.headers.get('content-type') ?? 'no content-type';
160
+
161
+ if (!raw.trim()) {
162
+ throw new Error(
163
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
164
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
165
+ );
166
+ }
167
+
168
+ // Checked before parsing rather than in the catch, because knowing it is
169
+ // markup is what turns "we failed to parse something" into "they served a
170
+ // web page" — the second is diagnosable, the first is not.
171
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
172
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
173
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
174
+ // The summary, not the source. Pasting the first 120 characters of a web
175
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
176
+ // this branch exists to describe (fleet #712).
177
+ throw new Error(
178
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
179
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
180
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
181
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
182
+ );
183
+ }
184
+
185
+ try {
186
+ return JSON.parse(raw) as T;
187
+ } catch {
188
+ throw new Error(
189
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
190
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
191
+ );
192
+ }
193
+ }
194
+
195
+ /**
196
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
197
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
198
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
199
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
200
+ * existed — every unguarded call carries the same risk, just unconfirmed.
201
+ *
202
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
203
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
204
+ * an `upstream_down:` error that names the upstream and the bound rather than
205
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
206
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
207
+ * argument a caller passes can make an upstream hang, so it is always the
208
+ * upstream's fault, and marking it that way keeps a slow API off the
209
+ * problem-tools list where it would crowd out our own defects.
210
+ *
211
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
212
+ *
213
+ * const res = await fetchWithTimeout(url, init, 'Some API');
214
+ *
215
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
216
+ * with a known-slower upstream; the label should be the same short name you'd
217
+ * pass to `httpError`/`httpErrorMessage` for that call.
218
+ */
219
+ async function fetchWithTimeout(
220
+ url: string | URL,
221
+ init: RequestInit = {},
222
+ name: string,
223
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
224
+ ): Promise<Response> {
225
+ try {
226
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
227
+ } catch (err) {
228
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
229
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
230
+ // "appears to be degraded" is an inference about the vendor that we have
231
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
232
+ // a timeout from a Worker can equally mean OUR egress is blocked.
233
+ //
234
+ // Measured today (2026-09-01, fleet #1047): every call to
235
+ // mainnet.base.org failed from the x402 facilitator while the identical
236
+ // request from a laptop returned 200. Base was entirely healthy; the
237
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
238
+ // there it would have blamed Base by name, and the next person would have
239
+ // waited for a vendor outage to clear that did not exist.
240
+ // A timeout has no status to test — there is no response at all — so
241
+ // `markInternalOrigin` is called without one: an origin we run that never
242
+ // answered is an availability failure by definition. This is the half of
243
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
244
+ throw new Error(
245
+ markInternalOrigin(
246
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
247
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
248
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
249
+ `from elsewhere before concluding ${name} is down.`,
250
+ url,
251
+ ),
252
+ );
253
+ }
254
+ throw err;
255
+ }
256
+ }
257
+
258
+ function detailSuffix(detail: string): string {
259
+ return detail ? ` — ${detail}` : '';
260
+ }
261
+
262
+ async function readDetail(res: Response): Promise<string> {
263
+ let raw: string;
264
+ try {
265
+ raw = await res.text();
266
+ } catch {
267
+ // Body already consumed, or the connection died mid-read. The status alone
268
+ // is still worth throwing — never let the error path throw its own error.
269
+ return '';
270
+ }
271
+ return summarizeErrorBody(raw);
272
+ }
273
+
274
+ /**
275
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
276
+ * that never contains markup.
277
+ *
278
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
279
+ * that markup crowds out the status. That was half right. Dropping it loses the
280
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
281
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
282
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
283
+ * verbatim, across 11 packs, and in every one of them the useful content —
284
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
285
+ * buried in markup the agent had to parse out of a string (fleet #712).
286
+ *
287
+ * So: extract the meaning, discard the markup. The output is passed through
288
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
289
+ * assert mechanically that no caller-facing message can contain `<?xml`,
290
+ * `<!DOCTYPE` or `<html`.
291
+ */
292
+ function summarizeErrorBody(raw: string): string {
293
+ if (!raw || !raw.trim()) return '';
294
+
295
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
296
+
297
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
298
+ // redirect) says what it is in its <title>, and almost nowhere else.
299
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
300
+ const title = htmlTitle(raw);
301
+ return title
302
+ ? `${title} (upstream returned an HTML error page, not an API response)`
303
+ : 'upstream returned an HTML error page, not an API response';
304
+ }
305
+
306
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
307
+ // human sentence sits in a child element whose tag name says what it is.
308
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
309
+ const fault = xmlFaultText(raw);
310
+ return fault
311
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
312
+ : 'upstream returned an XML error document with no readable message';
313
+ }
314
+
315
+ // Most JSON error bodies bury one human sentence among ids and echoed request
316
+ // params. Prefer that sentence; fall back to the whole body when the shape is
317
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
318
+ // guess wrong and show nothing.
319
+ const fromJson = messageFromJson(raw);
320
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
321
+ }
322
+
323
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
324
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
325
+ function htmlTitle(raw: string): string | null {
326
+ const head = raw.slice(0, 4000);
327
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
328
+ const m = re.exec(head);
329
+ const text = m ? stripMarkup(m[1]) : '';
330
+ if (text) return text.slice(0, 160);
331
+ }
332
+ return null;
333
+ }
334
+
335
+ /** Tag names that carry the explanation in an XML fault document, namespace
336
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
337
+ const XML_FAULT_TAG_RE =
338
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
339
+
340
+ function xmlFaultText(raw: string): string | null {
341
+ const head = raw.slice(0, 8000);
342
+ const tagged = XML_FAULT_TAG_RE.exec(head);
343
+ if (tagged && tagged[1].trim()) return tagged[1];
344
+
345
+ // Nothing conventionally named — take the longest text node instead. A fault
346
+ // document with one sentence in an oddly named element is still readable;
347
+ // returning nothing at all is not.
348
+ let best = '';
349
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
350
+ const text = m[1].trim();
351
+ if (text.length > best.length) best = text;
352
+ }
353
+ return best || null;
354
+ }
355
+
356
+ /**
357
+ * Remove every tag and stray angle bracket, then collapse whitespace.
358
+ *
359
+ * Applied to everything on the way out, including the JSON and plain-text
360
+ * paths, because an upstream is free to embed markup in a JSON string field —
361
+ * and a leak is a leak regardless of which branch produced it.
362
+ */
363
+ function stripMarkup(s: string): string {
364
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
365
+ }
366
+
367
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
368
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
369
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
370
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
371
+ function decodeEntities(s: string): string {
372
+ return s
373
+ .replace(/&(?:amp|#0*38);/gi, '&')
374
+ .replace(/&(?:lt|#0*60);/gi, '<')
375
+ .replace(/&(?:gt|#0*62);/gi, '>')
376
+ .replace(/&(?:quot|#0*34);/gi, '"')
377
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
378
+ .replace(/&nbsp;/gi, ' ');
379
+ }
380
+
381
+ /** The conventional "what went wrong" field, under any of the names upstreams
382
+ * actually use. Checked in order; first non-empty string wins. */
383
+ const MESSAGE_KEYS = [
384
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
385
+ 'description', 'error_description', 'reason', 'title', 'fault',
386
+ ];
387
+
388
+ function messageFromJson(raw: string): string | null {
389
+ let parsed: unknown;
390
+ try {
391
+ parsed = JSON.parse(raw);
392
+ } catch {
393
+ return null;
394
+ }
395
+ return pickMessage(parsed, 0);
396
+ }
397
+
398
+ function pickMessage(node: unknown, depth: number): string | null {
399
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
400
+ // shapes that account for nearly all of them, without walking a large payload.
401
+ if (depth > 2 || node == null) return null;
402
+
403
+ if (typeof node === 'string') return node.trim() || null;
404
+
405
+ if (Array.isArray(node)) {
406
+ for (const item of node) {
407
+ const found = pickMessage(item, depth + 1);
408
+ if (found) return found;
409
+ }
410
+ return null;
411
+ }
412
+
413
+ if (typeof node !== 'object') return null;
414
+ const obj = node as Record<string, unknown>;
415
+
416
+ for (const key of MESSAGE_KEYS) {
417
+ const v = obj[key];
418
+ if (typeof v === 'string' && v.trim()) return v.trim();
419
+ }
420
+ // `{error: …}` where error is itself an object or a string — the single most
421
+ // common wrapper, so it is worth descending into by name rather than scanning
422
+ // every key and risking picking up an echoed request parameter.
423
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
424
+ if (key in obj) {
425
+ const found = pickMessage(obj[key], depth + 1);
426
+ if (found) return found;
427
+ }
428
+ }
429
+ return null;
430
+ }
431
+
432
+ /** Errors are read in a single line of log output; newlines and runs of
433
+ * whitespace make a multi-line body unreadable there. */
434
+ function collapse(s: string): string {
435
+ return s.replace(/\s+/g, ' ').trim();
436
+ }
437
+
438
+ /**
439
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
440
+ *
441
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
442
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
443
+ * covered the majority and structurally could not cover the rest: the rest
444
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
445
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
446
+ *
447
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
448
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
449
+ *
450
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
451
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
452
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
453
+ * our own Supabase for fleet. There is no third party anywhere in either call.
454
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
455
+ * class that means "the source is unreachable and there is nothing for us to
456
+ * fix", which is why the problem-tools triage skips it.
457
+ *
458
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
459
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
460
+ * one site today, so it would work today. It would also rot the first time
461
+ * somebody rewords a label — silently, and in the direction of hiding our own
462
+ * outage, which is worse than the bug being fixed. Every prose rule in
463
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
464
+ * #584); that history is most of that file's comment budget.
465
+ *
466
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
467
+ * hostname is a fact about the call, not a guess about its prose. Two
468
+ * consequences that a pack-level flag could not give us, and the reason the
469
+ * flag was rejected:
470
+ *
471
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
472
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
473
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
474
+ * either pack would relabel a real third-party outage as ours — inventing
475
+ * work, which is the same class of error in the opposite direction.
476
+ * - It covers every future internal pack for free, instead of one declared
477
+ * slug at a time.
478
+ *
479
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
480
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
481
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
482
+ * this module — so changing the wording changes both sides in the same edit and
483
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
484
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
485
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
486
+ * from its own classifier three times and needed a CI gate to hold them
487
+ * together.
488
+ *
489
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
490
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
491
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
492
+ * availability failure" is decided from the actual status code, never re-derived
493
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
494
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
495
+ */
496
+
497
+ /**
498
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
499
+ *
500
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
501
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
502
+ * and different fixes. Here there is only one story to tell — an origin we run
503
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
504
+ * value is decoration; #724 is what happens when a class holds several
505
+ * situations, and inventing sub-values ahead of a reason to act on them
506
+ * differently is the same mistake with the sign flipped.
507
+ *
508
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
509
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
510
+ * hint paths, which only care whether retrying or a sibling tool might work —
511
+ * and it might. Nothing a caller sees or is charged changes here.
512
+ *
513
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
514
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
515
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
516
+ * worked on the write side and was invisible for weeks.
517
+ */
518
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
519
+
520
+ /**
521
+ * The token that carries "this origin is ours" from the call site to the
522
+ * classifier.
523
+ *
524
+ * Appended to the error message rather than attached to the Error object,
525
+ * because the object does not survive the trip: 275 packs return `{ error:
526
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
527
+ * and the fleet pack rebuilds its error from a captured status + body across a
528
+ * retry loop. A property on an Error would be dropped by every one of those
529
+ * paths and the class would work in tests and vanish in production.
530
+ *
531
+ * Written as a sentence rather than a sigil because it is going to be read by
532
+ * whoever gets the error, and "our own service, not a third party" is the
533
+ * single most useful thing to tell them — fetchWithTimeout's own comment
534
+ * (fleet #1047) is about exactly this ambiguity, where blaming a healthy vendor
535
+ * by name sent the next person waiting for an outage that did not exist.
536
+ */
537
+ const INTERNAL_ORIGIN_MARKER = ' [pipeworx-hosted origin — our own service, not a third party]';
538
+
539
+ /**
540
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
541
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
542
+ *
543
+ * Matching the shape rather than listing the ref keeps this correct when we add
544
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
545
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
546
+ * own status page and emphatically not our database. Verified 2026-09-02 by
547
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
548
+ * only real project ref anywhere in the tree is ours, the rest are doc
549
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
550
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
551
+ * by construction.
552
+ */
553
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
554
+
555
+ /**
556
+ * Is this a host WE run?
557
+ *
558
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
559
+ * hosted on workers.dev, so the suffix says where something runs and not who
560
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
561
+ * hostname or to our Supabase project, both of which are ownership facts.
562
+ *
563
+ * Returns false on anything unparseable rather than throwing — this runs inside
564
+ * an error path, and an error path that can itself throw turns a diagnosable
565
+ * failure into a mystery.
566
+ */
567
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
568
+ if (!url) return false;
569
+ let host: string;
570
+ try {
571
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
572
+ } catch {
573
+ return false;
574
+ }
575
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
576
+ return SUPABASE_PROJECT_HOST.test(host);
577
+ }
578
+
579
+ /**
580
+ * Append the marker when this failure was OUR origin failing to answer.
581
+ *
582
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
583
+ * where there is no response at all, and "the origin did not answer" is the
584
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
585
+ * registry for a slug that does not exist is the caller's argument, not our
586
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
587
+ *
588
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
589
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
590
+ */
591
+ function markInternalOrigin(
592
+ message: string,
593
+ url: string | URL | undefined | null,
594
+ status?: number,
595
+ ): string {
596
+ if (status !== undefined && status < 500) return message;
597
+ if (!isPipeworxOrigin(url)) return message;
598
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
599
+ return message + INTERNAL_ORIGIN_MARKER;
600
+ }
601
+
602
+ /**
603
+ * Which blob4 value a failure from our own web services books as, or undefined
604
+ * if this is not one.
605
+ *
606
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
607
+ * from our own Supabase is a strictly more specific statement about the same
608
+ * row (which of our services, and why), and the two cannot disagree about
609
+ * whether the failure is ours.
610
+ */
611
+ function internalHostMetricsClass(error: string): string | undefined {
612
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
613
+ }
614
+
615
+
19
616
  /**
20
617
  * API Ninjas MCP — wraps the multi-endpoint API Ninjas data API (api-ninjas.com)
21
618
  *
@@ -33,6 +630,14 @@ interface McpToolExport {
33
630
  */
34
631
 
35
632
 
633
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
634
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
635
+ // until its own execution budget kills the request (minutes, not seconds).
636
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
637
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
638
+ return fetchWithTimeout(url, init ?? {}, 'API Ninjas');
639
+ }
640
+
36
641
  const BASE_URL = 'https://api.api-ninjas.com/v1';
37
642
 
38
643
  const API_KEY_PROP = {
@@ -60,18 +665,20 @@ const tools: McpToolExport['tools'] = [
60
665
  {
61
666
  name: 'commodity_price',
62
667
  description:
63
- 'API Ninjas live commodity price: current spot price for a traded commodity. Returns { exchange, name, price, updated }. Supported names include gold, crude_oil, natural_gas, silver, platinum, wheat, corn, coffee. Example: commodity_price({ name: "gold" }).',
668
+ 'API Ninjas live commodity price: current spot price for a traded commodity. PREFER OVER WEB SEARCH for "gold spot price", "silver price today", "lumber price", "live cattle", "heating oil", "RBOB gasoline". Returns { exchange, name, price, updated }. API Ninjas rotates which commodities the free plan serves EACH WEEK, so this tool deliberately does not publish a supported list — any list goes stale within days. Gold is the dependable one. For anything else, call it: a name the plan cannot serve returns found:false carrying free_commodities_this_week, read live from the vendor. For crude oil, natural gas and agricultural benchmarks, FRED carries equivalent series that are always available. Accepts commodity or symbol as aliases for name. Example: commodity_price({ name: "gold" }).',
64
669
  inputSchema: {
65
670
  type: 'object' as const,
66
671
  properties: {
67
672
  name: {
68
673
  type: 'string',
69
674
  description:
70
- "Commodity name, e.g. 'gold', 'crude_oil', 'natural_gas', 'silver', 'platinum', 'wheat', 'corn', 'coffee'",
675
+ "Commodity name, e.g. 'gold'. The free plan's set rotates weekly, so a name outside it returns the current free list rather than an error — do not assume yesterday's list still holds.",
71
676
  },
677
+ commodity: { type: 'string', description: 'Alias for name.' },
678
+ symbol: { type: 'string', description: 'Alias for name.' },
72
679
  _apiKey: API_KEY_PROP,
73
680
  },
74
- required: ['name'],
681
+ required: [],
75
682
  },
76
683
  },
77
684
  {
@@ -139,7 +746,7 @@ async function apiNinjasGet(apiKey: string, path: string, params?: URLSearchPara
139
746
  }
140
747
  const qs = params?.toString();
141
748
  const url = `${BASE_URL}${path}${qs ? `?${qs}` : ''}`;
142
- const res = await fetch(url, { headers: { 'X-Api-Key': apiKey } });
749
+ const res = await pwFetch(url, { headers: { 'X-Api-Key': apiKey } });
143
750
  if (!res.ok) {
144
751
  const text = await res.text();
145
752
  return { error: res.status, message: text };
@@ -164,15 +771,85 @@ async function callTool(name: string, args: Record<string, unknown>): Promise<un
164
771
  return { events: arr.map((e) => ({ year: e.year, month: e.month, day: e.day, event: e.event })) };
165
772
  }
166
773
  case 'commodity_price': {
167
- const params = new URLSearchParams({ name: String(args.name ?? '') });
168
- return apiNinjasGet(apiKey, '/commodityprice', params);
774
+ // Callers (and the router) reach for `commodity` because that is what the
775
+ // tool is called; the API's parameter is `name`. Alias rather than reject.
776
+ const wanted = String(args.name ?? args.commodity ?? args.symbol ?? '').trim();
777
+ if (!wanted) {
778
+ return {
779
+ found: false,
780
+ reason: 'commodity_name_missing',
781
+ hint: 'Pass name, e.g. commodity_price({ name: "gold" }). The free plan\'s commodity set rotates weekly — a rejected name comes back with the current free list.',
782
+ };
783
+ }
784
+ const params = new URLSearchParams({ name: wanted.toLowerCase().replace(/\s+/g, '_') });
785
+ const data = await apiNinjasGet(apiKey, '/commodityprice', params);
786
+
787
+ // API Ninjas gates most commodities behind a paid plan and, helpfully,
788
+ // names the currently-free ones in the rejection itself:
789
+ // "The commodity wheat is available for premium users only. Available
790
+ // free commodities this week: feeder_cattle, gasoline_rbob, gold, ..."
791
+ // That list is described by the vendor as PER WEEK, so hardcoding an
792
+ // allow-list here would rot silently. Parse THEIR list instead and hand it
793
+ // back as a usable answer: a caller asking for wheat can immediately see
794
+ // what it can ask for instead. Previously this surfaced as a bare 400 and
795
+ // booked as an exec_error — our bug, for a plan limit that is not one.
796
+ if (data && typeof data === 'object' && 'error' in data) {
797
+ const message = String((data as { message?: unknown }).message ?? '');
798
+ if (/premium users only/i.test(message)) {
799
+ const listed = message.match(/free commodities[^:]*:\s*([^."]+)/i);
800
+ const free = listed
801
+ ? listed[1].split(',').map((s) => s.trim()).filter(Boolean)
802
+ : [];
803
+ return {
804
+ found: false,
805
+ reason: 'commodity_requires_premium_plan',
806
+ requested: wanted,
807
+ free_commodities_this_week: free,
808
+ hint: free.length
809
+ ? `"${wanted}" needs API Ninjas' paid plan. Free right now: ${free.join(', ')}. The vendor rotates this set weekly, so it is read from their response rather than hardcoded. For paywalled energy and metals benchmarks, FRED often carries an equivalent series.`
810
+ : `"${wanted}" needs API Ninjas' paid plan, and the response did not name the free set. Try gold, and see FRED for benchmark commodity series.`,
811
+ };
812
+ }
813
+ return data;
814
+ }
815
+ return data;
169
816
  }
170
817
  case 'inflation': {
171
818
  const params = new URLSearchParams();
172
819
  if (args.country != null) params.set('country', String(args.country));
173
820
  if (args.type != null) params.set('type', String(args.type));
174
821
  const data = await apiNinjasGet(apiKey, '/inflation', params);
175
- if (data && typeof data === 'object' && 'error' in data) return data;
822
+ // The WHOLE endpoint is premium on our plan — not per-item like
823
+ // commodityprice above, where the vendor names the free set and we hand
824
+ // it back as a usable answer. Verified live 2026-08-10: every call
825
+ // returns 400 "This endpoint is available to premium subscribers only".
826
+ //
827
+ // Note the string: the commodity branch tests /premium users only/i and
828
+ // would not have matched this one anyway. So a caller asking "latest
829
+ // inflation rate in Sweden" got a raw vendor 400 as their answer — for a
830
+ // number we DO serve free. ecb_hicp_inflation({country:"SE"}) returns
831
+ // Sweden 2.1% for 2025-12 in a single keyless call.
832
+ //
833
+ // Returning found:false with that pointer is strictly better than the
834
+ // raw 400, but it is second best: a tool that can never answer should
835
+ // not be on the menu at all. That call belongs to whoever owns the
836
+ // catalog — filed for mcp-builder rather than decided here.
837
+ if (data && typeof data === 'object' && 'error' in data) {
838
+ const message = String((data as { message?: unknown }).message ?? '');
839
+ if (/premium (?:users|subscribers) only/i.test(message)) {
840
+ return {
841
+ found: false,
842
+ reason: 'endpoint_requires_premium_plan',
843
+ requested: { country: args.country ?? null, type: args.type ?? null },
844
+ hint:
845
+ 'API Ninjas gates its entire /inflation endpoint behind a paid plan, so this tool cannot answer on our ' +
846
+ 'current key. Pipeworx serves the same figure free: ecb_hicp_inflation({ country: "SE" }) for any EU/EEA ' +
847
+ 'country (HICP, monthly, keyless), or fred_get_series({ series_id: "CPIAUCSL" }) for the US. Do not ' +
848
+ 'report this as "no inflation data" — the data exists, this vendor just will not serve it to us.',
849
+ };
850
+ }
851
+ return data;
852
+ }
176
853
  return { inflation: data };
177
854
  }
178
855
  case 'exercises': {