@pipeworx/mcp-meps 0.1.0
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 +21 -0
- package/README.md +180 -0
- package/bin/cli.js +17 -0
- package/package.json +27 -0
- package/server.json +18 -0
- package/src/conditions.ts +108 -0
- package/src/index.ts +998 -0
- package/src/server.ts +45 -0
- package/tsconfig.json +16 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,998 @@
|
|
|
1
|
+
interface McpToolDefinition {
|
|
2
|
+
name: string;
|
|
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;
|
|
8
|
+
inputSchema: {
|
|
9
|
+
type: 'object';
|
|
10
|
+
properties: Record<string, unknown>;
|
|
11
|
+
required?: string[];
|
|
12
|
+
anyOf?: Array<{ required: string[] }>;
|
|
13
|
+
oneOf?: Array<{ required: string[] }>;
|
|
14
|
+
allOf?: Array<{ required: string[] }>;
|
|
15
|
+
};
|
|
16
|
+
outputSchema?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface McpToolExport {
|
|
20
|
+
tools: McpToolDefinition[];
|
|
21
|
+
callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
|
|
22
|
+
meter?: { credits: number };
|
|
23
|
+
cost?: Record<string, unknown>;
|
|
24
|
+
provider?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One place to turn a failed `fetch` into an error a caller can act on.
|
|
29
|
+
*
|
|
30
|
+
* Nearly every pack was written the same way:
|
|
31
|
+
*
|
|
32
|
+
* if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
|
|
33
|
+
*
|
|
34
|
+
* which discards the response body — and the body is usually where the upstream
|
|
35
|
+
* says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
|
|
36
|
+
* out of range", "unknown taxonomy id"). The caller gets a number, cannot
|
|
37
|
+
* self-correct, and retries the same broken call. A 2026-07-31 sweep found this
|
|
38
|
+
* shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
|
|
39
|
+
*
|
|
40
|
+
* It also hides bugs one level down. Two of the first three packs audited had a
|
|
41
|
+
* second defect that only existed because of this line: unsplash's rate-limit
|
|
42
|
+
* branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
|
|
43
|
+
* `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
|
|
44
|
+
* parsing dead code for every non-200.
|
|
45
|
+
*
|
|
46
|
+
* DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
|
|
47
|
+
* `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
|
|
48
|
+
* `error` tier is what the daily problem-tools list is built from — it means
|
|
49
|
+
* "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
|
|
50
|
+
* argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
|
|
51
|
+
* values into something TED rejected, and that bug was found only because it sat
|
|
52
|
+
* in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
|
|
53
|
+
* A pack that KNOWS which it is should keep saying so explicitly; this helper is
|
|
54
|
+
* for the 481 that say nothing at all.
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
/** Longest upstream explanation we'll pass through. Enough for a real message,
|
|
58
|
+
* short enough that an HTML page or a stack trace can't swamp the error. */
|
|
59
|
+
|
|
60
|
+
const MAX_DETAIL = 300;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Default bound for `fetchWithTimeout` when a pack doesn't state its own.
|
|
64
|
+
*
|
|
65
|
+
* 25s mirrors the number `epo-ops` landed on after measuring the real failure:
|
|
66
|
+
* a degraded upstream that doesn't error, it just never answers, and a Worker
|
|
67
|
+
* sits in `await fetch()` until ITS OWN execution budget kills the request —
|
|
68
|
+
* which can take minutes, not seconds (epo_ops_search_patents measured 4-8
|
|
69
|
+
* MINUTE hangs before this existed). 25s is short enough that a caller gets a
|
|
70
|
+
* fast, actionable error instead of holding the connection, and long enough
|
|
71
|
+
* that it doesn't false-trip on a merely-slow-but-alive upstream.
|
|
72
|
+
*/
|
|
73
|
+
const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Read the body of a failed response and fold it into a throwable Error.
|
|
77
|
+
*
|
|
78
|
+
* Usage — note the `await`, which is the one thing that makes this a mechanical
|
|
79
|
+
* change rather than a drop-in:
|
|
80
|
+
*
|
|
81
|
+
* if (!res.ok) throw await httpError(res, 'Unsplash');
|
|
82
|
+
*
|
|
83
|
+
* Safe to call on any non-ok response: a body that is missing, empty, unreadable
|
|
84
|
+
* or HTML degrades to exactly the old `Name: 404` string rather than throwing
|
|
85
|
+
* something new from inside the error path.
|
|
86
|
+
*/
|
|
87
|
+
async function httpError(res: Response, name: string): Promise<Error> {
|
|
88
|
+
return new Error(await httpErrorMessage(res, name));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The message text without constructing an Error — for packs that need to wrap
|
|
92
|
+
* it in their own envelope or add an explicit classification prefix. */
|
|
93
|
+
async function httpErrorMessage(res: Response, name: string): Promise<string> {
|
|
94
|
+
// The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
|
|
95
|
+
// the URL the fetch actually resolved to (after redirects), so this is a fact
|
|
96
|
+
// about the call rather than a guess from the `name` the pack passed in —
|
|
97
|
+
// reword that label freely, the class does not move. See
|
|
98
|
+
// internal-host-class.ts; no-op for every third-party upstream, which is why
|
|
99
|
+
// this touches 481 packs' error text and changes none of it.
|
|
100
|
+
return markInternalOrigin(
|
|
101
|
+
`${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
|
|
102
|
+
res.url,
|
|
103
|
+
res.status,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Just the upstream's own explanation — no name, no status.
|
|
109
|
+
*
|
|
110
|
+
* For a pack that has already said both in its own sentence. epo-ops reads
|
|
111
|
+
* `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
|
|
112
|
+
* which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
|
|
113
|
+
* dropped: the upstream named twice, the status twice, and the one thing EPO
|
|
114
|
+
* actually said ("Not enough characters before truncation character") nowhere
|
|
115
|
+
* (fleet #712). Returns '' when the body carries nothing readable, so a caller
|
|
116
|
+
* can fall back to its own wording.
|
|
117
|
+
*/
|
|
118
|
+
async function upstreamDetail(res: Response): Promise<string> {
|
|
119
|
+
return readDetail(res);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
|
|
124
|
+
*
|
|
125
|
+
* `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
|
|
126
|
+
* of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
|
|
127
|
+
* page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
|
|
128
|
+
* error page are all 200s, so `res.ok` is true, and `res.json()` then throws
|
|
129
|
+
* `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
|
|
130
|
+
*
|
|
131
|
+
* That string is the problem. It names no upstream, carries no status, and
|
|
132
|
+
* reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
|
|
133
|
+
* means "we have a defect", and the caller is told nothing they can act on.
|
|
134
|
+
* data.govt.nz sat dead behind an Imperva challenge this way and every
|
|
135
|
+
* status-code health check we own reported it green (7889a845). A zero-length
|
|
136
|
+
* body has the same shape: `Unexpected end of JSON input`, seen this week on
|
|
137
|
+
* uk-gazette (83% of external calls) and census.
|
|
138
|
+
*
|
|
139
|
+
* UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
|
|
140
|
+
* A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
|
|
141
|
+
* query we built wrong — so blanket-classifying it would hide our own bugs.
|
|
142
|
+
* There is no such ambiguity here: **no argument a caller can pass makes a JSON
|
|
143
|
+
* API return an HTML page.** It is always the upstream, so `upstream_down:` is
|
|
144
|
+
* a statement of fact rather than a guess, and it keeps these out of the
|
|
145
|
+
* problem-tools list where they crowd out real defects.
|
|
146
|
+
*
|
|
147
|
+
* const data = await parseJson<Feed>(res, 'UK Gazette');
|
|
148
|
+
*
|
|
149
|
+
* Call it only after the `!res.ok` check — on a failed response you want
|
|
150
|
+
* `httpError`, which mines the body for the upstream's own explanation.
|
|
151
|
+
*/
|
|
152
|
+
async function parseJson<T>(res: Response, name: string): Promise<T> {
|
|
153
|
+
let raw: string;
|
|
154
|
+
try {
|
|
155
|
+
raw = await res.text();
|
|
156
|
+
} catch {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
|
|
159
|
+
'The connection most likely dropped mid-response; retrying is reasonable.',
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const type = res.headers.get('content-type') ?? 'no content-type';
|
|
164
|
+
|
|
165
|
+
if (!raw.trim()) {
|
|
166
|
+
throw new Error(
|
|
167
|
+
`upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
|
|
168
|
+
'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Checked before parsing rather than in the catch, because knowing it is
|
|
173
|
+
// markup is what turns "we failed to parse something" into "they served a
|
|
174
|
+
// web page" — the second is diagnosable, the first is not.
|
|
175
|
+
const head = raw.slice(0, 200).trimStart().toLowerCase();
|
|
176
|
+
if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
|
|
177
|
+
const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
|
|
178
|
+
// The summary, not the source. Pasting the first 120 characters of a web
|
|
179
|
+
// page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
|
|
180
|
+
// this branch exists to describe (fleet #712).
|
|
181
|
+
throw new Error(
|
|
182
|
+
`upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
|
|
183
|
+
'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
|
|
184
|
+
`so status-code health checks read it as fine. No argument change will get past it. ` +
|
|
185
|
+
`The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
try {
|
|
190
|
+
return JSON.parse(raw) as T;
|
|
191
|
+
} catch {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
|
|
194
|
+
`It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
|
|
201
|
+
* audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
|
|
202
|
+
* `fetch()` with NO timeout guard anywhere in the file. Two of those
|
|
203
|
+
* (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
|
|
204
|
+
* existed — every unguarded call carries the same risk, just unconfirmed.
|
|
205
|
+
*
|
|
206
|
+
* Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
|
|
207
|
+
* bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
|
|
208
|
+
* an `upstream_down:` error that names the upstream and the bound rather than
|
|
209
|
+
* letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
|
|
210
|
+
* `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
|
|
211
|
+
* argument a caller passes can make an upstream hang, so it is always the
|
|
212
|
+
* upstream's fault, and marking it that way keeps a slow API off the
|
|
213
|
+
* problem-tools list where it would crowd out our own defects.
|
|
214
|
+
*
|
|
215
|
+
* Usage — a mechanical swap for a bare `fetch(url, init)`:
|
|
216
|
+
*
|
|
217
|
+
* const res = await fetchWithTimeout(url, init, 'Some API');
|
|
218
|
+
*
|
|
219
|
+
* Pass `timeoutMs` as a fourth argument to override the default for a pack
|
|
220
|
+
* with a known-slower upstream; the label should be the same short name you'd
|
|
221
|
+
* pass to `httpError`/`httpErrorMessage` for that call.
|
|
222
|
+
*/
|
|
223
|
+
async function fetchWithTimeout(
|
|
224
|
+
url: string | URL,
|
|
225
|
+
init: RequestInit = {},
|
|
226
|
+
name: string,
|
|
227
|
+
timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
|
|
228
|
+
): Promise<Response> {
|
|
229
|
+
try {
|
|
230
|
+
return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
231
|
+
} catch (err) {
|
|
232
|
+
if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
|
|
233
|
+
// States the OBSERVATION (no response in N seconds), not a diagnosis.
|
|
234
|
+
// "appears to be degraded" is an inference about the vendor that we have
|
|
235
|
+
// not checked, and it is wrong in a way that misdirects whoever reads it:
|
|
236
|
+
// a timeout from a Worker can equally mean OUR egress is blocked.
|
|
237
|
+
//
|
|
238
|
+
// Measured today (2026-09-01, fleet #1047): every call to
|
|
239
|
+
// mainnet.base.org failed from the x402 facilitator while the identical
|
|
240
|
+
// request from a laptop returned 200. Base was entirely healthy; the
|
|
241
|
+
// public RPC refuses Cloudflare Worker egress. Had this message fired
|
|
242
|
+
// there it would have blamed Base by name, and the next person would have
|
|
243
|
+
// waited for a vendor outage to clear that did not exist.
|
|
244
|
+
// A timeout has no status to test — there is no response at all — so
|
|
245
|
+
// `markInternalOrigin` is called without one: an origin we run that never
|
|
246
|
+
// answered is an availability failure by definition. This is the half of
|
|
247
|
+
// fleet #1096 with neither a SQLSTATE nor a status code to key on.
|
|
248
|
+
throw new Error(
|
|
249
|
+
markInternalOrigin(
|
|
250
|
+
`upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
|
|
251
|
+
`That can be ${name} being slow or down, or this environment being unable to reach it ` +
|
|
252
|
+
`(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
|
|
253
|
+
`from elsewhere before concluding ${name} is down.`,
|
|
254
|
+
url,
|
|
255
|
+
),
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
throw err;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function detailSuffix(detail: string): string {
|
|
263
|
+
return detail ? ` — ${detail}` : '';
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function readDetail(res: Response): Promise<string> {
|
|
267
|
+
let raw: string;
|
|
268
|
+
try {
|
|
269
|
+
raw = await res.text();
|
|
270
|
+
} catch {
|
|
271
|
+
// Body already consumed, or the connection died mid-read. The status alone
|
|
272
|
+
// is still worth throwing — never let the error path throw its own error.
|
|
273
|
+
return '';
|
|
274
|
+
}
|
|
275
|
+
return summarizeErrorBody(raw);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
|
|
280
|
+
* that never contains markup.
|
|
281
|
+
*
|
|
282
|
+
* This used to just drop an HTML or XML body on the floor, on the reasoning
|
|
283
|
+
* that markup crowds out the status. That was half right. Dropping it loses the
|
|
284
|
+
* one sentence a caller could have acted on: an `Access Denied` title, an SDMX
|
|
285
|
+
* `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
|
|
286
|
+
* measured 13 of 291 caller-facing error rows carrying a raw page or document
|
|
287
|
+
* verbatim, across 11 packs, and in every one of them the useful content —
|
|
288
|
+
* "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
|
|
289
|
+
* buried in markup the agent had to parse out of a string (fleet #712).
|
|
290
|
+
*
|
|
291
|
+
* So: extract the meaning, discard the markup. The output is passed through
|
|
292
|
+
* `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
|
|
293
|
+
* assert mechanically that no caller-facing message can contain `<?xml`,
|
|
294
|
+
* `<!DOCTYPE` or `<html`.
|
|
295
|
+
*/
|
|
296
|
+
function summarizeErrorBody(raw: string): string {
|
|
297
|
+
if (!raw || !raw.trim()) return '';
|
|
298
|
+
|
|
299
|
+
const head = raw.slice(0, 400).trimStart().toLowerCase();
|
|
300
|
+
|
|
301
|
+
// An HTML error page (Cloudflare interstitial, nginx default, a login
|
|
302
|
+
// redirect) says what it is in its <title>, and almost nowhere else.
|
|
303
|
+
if (head.startsWith('<!doctype') || head.startsWith('<html')) {
|
|
304
|
+
const title = htmlTitle(raw);
|
|
305
|
+
return title
|
|
306
|
+
? `${title} (upstream returned an HTML error page, not an API response)`
|
|
307
|
+
: 'upstream returned an HTML error page, not an API response';
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
|
|
311
|
+
// human sentence sits in a child element whose tag name says what it is.
|
|
312
|
+
if (head.startsWith('<?xml') || head.startsWith('<')) {
|
|
313
|
+
const fault = xmlFaultText(raw);
|
|
314
|
+
return fault
|
|
315
|
+
? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
|
|
316
|
+
: 'upstream returned an XML error document with no readable message';
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Most JSON error bodies bury one human sentence among ids and echoed request
|
|
320
|
+
// params. Prefer that sentence; fall back to the whole body when the shape is
|
|
321
|
+
// unfamiliar, since an unfamiliar shape is exactly when we can least afford to
|
|
322
|
+
// guess wrong and show nothing.
|
|
323
|
+
const fromJson = messageFromJson(raw);
|
|
324
|
+
return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
|
|
328
|
+
* bot wall, a 502 and an "Access Denied" all state what happened. */
|
|
329
|
+
function htmlTitle(raw: string): string | null {
|
|
330
|
+
const head = raw.slice(0, 4000);
|
|
331
|
+
for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
|
|
332
|
+
const m = re.exec(head);
|
|
333
|
+
const text = m ? stripMarkup(m[1]) : '';
|
|
334
|
+
if (text) return text.slice(0, 160);
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Tag names that carry the explanation in an XML fault document, namespace
|
|
340
|
+
* prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
|
|
341
|
+
const XML_FAULT_TAG_RE =
|
|
342
|
+
/<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
|
|
343
|
+
|
|
344
|
+
function xmlFaultText(raw: string): string | null {
|
|
345
|
+
const head = raw.slice(0, 8000);
|
|
346
|
+
const tagged = XML_FAULT_TAG_RE.exec(head);
|
|
347
|
+
if (tagged && tagged[1].trim()) return tagged[1];
|
|
348
|
+
|
|
349
|
+
// Nothing conventionally named — take the longest text node instead. A fault
|
|
350
|
+
// document with one sentence in an oddly named element is still readable;
|
|
351
|
+
// returning nothing at all is not.
|
|
352
|
+
let best = '';
|
|
353
|
+
for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
|
|
354
|
+
const text = m[1].trim();
|
|
355
|
+
if (text.length > best.length) best = text;
|
|
356
|
+
}
|
|
357
|
+
return best || null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Remove every tag and stray angle bracket, then collapse whitespace.
|
|
362
|
+
*
|
|
363
|
+
* Applied to everything on the way out, including the JSON and plain-text
|
|
364
|
+
* paths, because an upstream is free to embed markup in a JSON string field —
|
|
365
|
+
* and a leak is a leak regardless of which branch produced it.
|
|
366
|
+
*/
|
|
367
|
+
function stripMarkup(s: string): string {
|
|
368
|
+
return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** The handful of entities that show up in error-page titles. Decoded AFTER
|
|
372
|
+
* tags are stripped and BEFORE the angle-bracket sweep, so `<script>`
|
|
373
|
+
* in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
|
|
374
|
+
* page renders as `500 Internal Server Error < EMBL-EBI` otherwise. */
|
|
375
|
+
function decodeEntities(s: string): string {
|
|
376
|
+
return s
|
|
377
|
+
.replace(/&(?:amp|#0*38);/gi, '&')
|
|
378
|
+
.replace(/&(?:lt|#0*60);/gi, '<')
|
|
379
|
+
.replace(/&(?:gt|#0*62);/gi, '>')
|
|
380
|
+
.replace(/&(?:quot|#0*34);/gi, '"')
|
|
381
|
+
.replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
|
|
382
|
+
.replace(/ /gi, ' ');
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The conventional "what went wrong" field, under any of the names upstreams
|
|
386
|
+
* actually use. Checked in order; first non-empty string wins. */
|
|
387
|
+
const MESSAGE_KEYS = [
|
|
388
|
+
'message', 'error_message', 'errorMessage', 'detail', 'details',
|
|
389
|
+
'description', 'error_description', 'reason', 'title', 'fault',
|
|
390
|
+
];
|
|
391
|
+
|
|
392
|
+
function messageFromJson(raw: string): string | null {
|
|
393
|
+
let parsed: unknown;
|
|
394
|
+
try {
|
|
395
|
+
parsed = JSON.parse(raw);
|
|
396
|
+
} catch {
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
return pickMessage(parsed, 0);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function pickMessage(node: unknown, depth: number): string | null {
|
|
403
|
+
// Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
|
|
404
|
+
// shapes that account for nearly all of them, without walking a large payload.
|
|
405
|
+
if (depth > 2 || node == null) return null;
|
|
406
|
+
|
|
407
|
+
if (typeof node === 'string') return node.trim() || null;
|
|
408
|
+
|
|
409
|
+
if (Array.isArray(node)) {
|
|
410
|
+
for (const item of node) {
|
|
411
|
+
const found = pickMessage(item, depth + 1);
|
|
412
|
+
if (found) return found;
|
|
413
|
+
}
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (typeof node !== 'object') return null;
|
|
418
|
+
const obj = node as Record<string, unknown>;
|
|
419
|
+
|
|
420
|
+
for (const key of MESSAGE_KEYS) {
|
|
421
|
+
const v = obj[key];
|
|
422
|
+
if (typeof v === 'string' && v.trim()) return v.trim();
|
|
423
|
+
}
|
|
424
|
+
// `{error: …}` where error is itself an object or a string — the single most
|
|
425
|
+
// common wrapper, so it is worth descending into by name rather than scanning
|
|
426
|
+
// every key and risking picking up an echoed request parameter.
|
|
427
|
+
for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
|
|
428
|
+
if (key in obj) {
|
|
429
|
+
const found = pickMessage(obj[key], depth + 1);
|
|
430
|
+
if (found) return found;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Errors are read in a single line of log output; newlines and runs of
|
|
437
|
+
* whitespace make a multi-line body unreadable there. */
|
|
438
|
+
function collapse(s: string): string {
|
|
439
|
+
return s.replace(/\s+/g, ' ').trim();
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
|
|
444
|
+
*
|
|
445
|
+
* fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
|
|
446
|
+
* keying on the SQLSTATE inside PostgREST's four-key error envelope. That
|
|
447
|
+
* covered the majority and structurally could not cover the rest: the rest
|
|
448
|
+
* never reach Postgres, so they carry no SQLSTATE. What was left, measured over
|
|
449
|
+
* the 24h to 2026-09-02T15:00Z (fleet #1096):
|
|
450
|
+
*
|
|
451
|
+
* 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
|
|
452
|
+
* 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
|
|
453
|
+
*
|
|
454
|
+
* 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
|
|
455
|
+
* in both of those rows the origin is ours — `gateway.pipeworx.io` for the
|
|
456
|
+
* catalog pack (it self-fetches when the gateway hasn't injected a manifest),
|
|
457
|
+
* our own Supabase for fleet. There is no third party anywhere in either call.
|
|
458
|
+
* Same defect as #1089: our own outage filed under `upstream_down`, the one
|
|
459
|
+
* class that means "the source is unreachable and there is nothing for us to
|
|
460
|
+
* fix", which is why the problem-tools triage skips it.
|
|
461
|
+
*
|
|
462
|
+
* WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
|
|
463
|
+
* `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
|
|
464
|
+
* one site today, so it would work today. It would also rot the first time
|
|
465
|
+
* somebody rewords a label — silently, and in the direction of hiding our own
|
|
466
|
+
* outage, which is worse than the bug being fixed. Every prose rule in
|
|
467
|
+
* error-class.ts has needed widening as packs invented new wording (#409/#450/
|
|
468
|
+
* #584); that history is most of that file's comment budget.
|
|
469
|
+
*
|
|
470
|
+
* WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
|
|
471
|
+
* hostname is a fact about the call, not a guess about its prose. Two
|
|
472
|
+
* consequences that a pack-level flag could not give us, and the reason the
|
|
473
|
+
* flag was rejected:
|
|
474
|
+
*
|
|
475
|
+
* - It describes the CALL, not the pack. `govcon-intel` fans out to our own
|
|
476
|
+
* Supabase AND to genuine third parties; `court-listener` holds our cache
|
|
477
|
+
* in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
|
|
478
|
+
* either pack would relabel a real third-party outage as ours — inventing
|
|
479
|
+
* work, which is the same class of error in the opposite direction.
|
|
480
|
+
* - It covers every future internal pack for free, instead of one declared
|
|
481
|
+
* slug at a time.
|
|
482
|
+
*
|
|
483
|
+
* WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
|
|
484
|
+
* separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
|
|
485
|
+
* reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
|
|
486
|
+
* this module — so changing the wording changes both sides in the same edit and
|
|
487
|
+
* cannot desynchronise them. The pack's own label (`fleet db error:`,
|
|
488
|
+
* `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
|
|
489
|
+
* unaffected. That is the property `stripClassPrefix` lacked when it drifted
|
|
490
|
+
* from its own classifier three times and needed a CI gate to hold them
|
|
491
|
+
* together.
|
|
492
|
+
*
|
|
493
|
+
* WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
|
|
494
|
+
* hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
|
|
495
|
+
* branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
|
|
496
|
+
* availability failure" is decided from the actual status code, never re-derived
|
|
497
|
+
* by scraping a number out of a sentence. A 404 from our own registry for a slug
|
|
498
|
+
* that does not exist is a caller's bad argument and is deliberately NOT marked.
|
|
499
|
+
*/
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
|
|
503
|
+
*
|
|
504
|
+
* ONE value, not three, unlike `internal_db_*`. That split existed because a
|
|
505
|
+
* slow query, an exhausted pool and an unknown SQLSTATE have different owners
|
|
506
|
+
* and different fixes. Here there is only one story to tell — an origin we run
|
|
507
|
+
* did not answer the edge — and one owner. A bucket with no distinct owner per
|
|
508
|
+
* value is decoration; #724 is what happens when a class holds several
|
|
509
|
+
* situations, and inventing sub-values ahead of a reason to act on them
|
|
510
|
+
* differently is the same mistake with the sign flipped.
|
|
511
|
+
*
|
|
512
|
+
* METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
|
|
513
|
+
* values. `classifyToolError` still answers `upstream_down` for the retry and
|
|
514
|
+
* hint paths, which only care whether retrying or a sibling tool might work —
|
|
515
|
+
* and it might. Nothing a caller sees or is charged changes here.
|
|
516
|
+
*
|
|
517
|
+
* READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
|
|
518
|
+
* ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
|
|
519
|
+
* lands on no dashboard — fleet #721 is the warning, where the #719 split
|
|
520
|
+
* worked on the write side and was invisible for weeks.
|
|
521
|
+
*/
|
|
522
|
+
const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* The token that carries "this origin is ours" from the call site to the
|
|
526
|
+
* classifier.
|
|
527
|
+
*
|
|
528
|
+
* Appended to the error message rather than attached to the Error object,
|
|
529
|
+
* because the object does not survive the trip: 275 packs return `{ error:
|
|
530
|
+
* string }` instead of throwing, the gateway reads `observedError` as a string,
|
|
531
|
+
* and the fleet pack rebuilds its error from a captured status + body across a
|
|
532
|
+
* retry loop. A property on an Error would be dropped by every one of those
|
|
533
|
+
* paths and the class would work in tests and vanish in production.
|
|
534
|
+
*
|
|
535
|
+
* Written as a sentence rather than a sigil because it is going to be read by
|
|
536
|
+
* whoever gets the error, and "our own service, not a third party" is the
|
|
537
|
+
* single most useful thing to tell them — fetchWithTimeout's own comment
|
|
538
|
+
* (fleet #1047) is about exactly this ambiguity, where blaming a healthy vendor
|
|
539
|
+
* by name sent the next person waiting for an outage that did not exist.
|
|
540
|
+
*/
|
|
541
|
+
const INTERNAL_ORIGIN_MARKER = ' [pipeworx-hosted origin — our own service, not a third party]';
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
|
|
545
|
+
* exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
|
|
546
|
+
*
|
|
547
|
+
* Matching the shape rather than listing the ref keeps this correct when we add
|
|
548
|
+
* a project — `supabaseEnv` on a pack entry already points some packs at a
|
|
549
|
+
* second one — while still excluding `status.supabase.co`, which is Supabase's
|
|
550
|
+
* own status page and emphatically not our database. Verified 2026-09-02 by
|
|
551
|
+
* `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
|
|
552
|
+
* only real project ref anywhere in the tree is ours, the rest are doc
|
|
553
|
+
* placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
|
|
554
|
+
* finding internal-db-class.ts relies on for the PostgREST envelope being ours
|
|
555
|
+
* by construction.
|
|
556
|
+
*/
|
|
557
|
+
const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Is this a host WE run?
|
|
561
|
+
*
|
|
562
|
+
* Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
|
|
563
|
+
* hosted on workers.dev, so the suffix says where something runs and not who
|
|
564
|
+
* owns it. Every internal call we actually make goes to a `pipeworx.io`
|
|
565
|
+
* hostname or to our Supabase project, both of which are ownership facts.
|
|
566
|
+
*
|
|
567
|
+
* Returns false on anything unparseable rather than throwing — this runs inside
|
|
568
|
+
* an error path, and an error path that can itself throw turns a diagnosable
|
|
569
|
+
* failure into a mystery.
|
|
570
|
+
*/
|
|
571
|
+
function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
|
|
572
|
+
if (!url) return false;
|
|
573
|
+
let host: string;
|
|
574
|
+
try {
|
|
575
|
+
host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
|
|
576
|
+
} catch {
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
|
|
580
|
+
return SUPABASE_PROJECT_HOST.test(host);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Append the marker when this failure was OUR origin failing to answer.
|
|
585
|
+
*
|
|
586
|
+
* `status` is the HTTP status when there is one, and omitted for a timeout —
|
|
587
|
+
* where there is no response at all, and "the origin did not answer" is the
|
|
588
|
+
* whole observation. Statuses below 500 are left alone: a 404 from our own
|
|
589
|
+
* registry for a slug that does not exist is the caller's argument, not our
|
|
590
|
+
* outage, and marking it would put ordinary 404s on the incident dashboard.
|
|
591
|
+
*
|
|
592
|
+
* Idempotent, so a message that is wrapped and re-marked on the way up (the
|
|
593
|
+
* fleet pack's retry loop re-throws through two layers) carries the marker once.
|
|
594
|
+
*/
|
|
595
|
+
function markInternalOrigin(
|
|
596
|
+
message: string,
|
|
597
|
+
url: string | URL | undefined | null,
|
|
598
|
+
status?: number,
|
|
599
|
+
): string {
|
|
600
|
+
if (status !== undefined && status < 500) return message;
|
|
601
|
+
if (!isPipeworxOrigin(url)) return message;
|
|
602
|
+
if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
|
|
603
|
+
return message + INTERNAL_ORIGIN_MARKER;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Which blob4 value a failure from our own web services books as, or undefined
|
|
608
|
+
* if this is not one.
|
|
609
|
+
*
|
|
610
|
+
* Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
|
|
611
|
+
* from our own Supabase is a strictly more specific statement about the same
|
|
612
|
+
* row (which of our services, and why), and the two cannot disagree about
|
|
613
|
+
* whether the failure is ours.
|
|
614
|
+
*/
|
|
615
|
+
function internalHostMetricsClass(error: string): string | undefined {
|
|
616
|
+
return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* MEPS — what Americans actually take, and what for.
|
|
620
|
+
*
|
|
621
|
+
* AHRQ's Medical Expenditure Panel Survey is a survey of the whole US civilian
|
|
622
|
+
* non-institutionalized population: every payer, every age, insured and not.
|
|
623
|
+
* It is the only source in this catalog that links a prescription to the
|
|
624
|
+
* CONDITION it was written for.
|
|
625
|
+
*
|
|
626
|
+
* These are SURVEY ESTIMATES. Each respondent stands in for ~18,000 Americans,
|
|
627
|
+
* so a cell backed by three people yields a confident-looking "55,000 people".
|
|
628
|
+
* Every row therefore carries `sample_persons`, and anything under AHRQ's own
|
|
629
|
+
* floor of 60 is marked unreliable rather than dressed up or silently dropped.
|
|
630
|
+
*/
|
|
631
|
+
import { resolveConditionCodes } from './conditions.js';
|
|
632
|
+
|
|
633
|
+
const UA = 'pipeworx/1.0 (+https://pipeworx.io)';
|
|
634
|
+
|
|
635
|
+
/** AHRQ's reliability floor for a MEPS estimate. */
|
|
636
|
+
const RELIABLE_PERSONS = 60;
|
|
637
|
+
/** Default sample floor for a returned row: AHRQ's own publication bar, so the
|
|
638
|
+
* default answer contains nothing AHRQ would decline to publish (Bruce,
|
|
639
|
+
* 2026-09-09). It was briefly 30, which returned more of the tail — every row
|
|
640
|
+
* reported its sample either way, but a caller who does not read
|
|
641
|
+
* `sample_persons` was being handed estimates AHRQ would suppress. A caller
|
|
642
|
+
* who genuinely wants the tail asks for it with `min_sample` and gets rows
|
|
643
|
+
* marked reliable:false. */
|
|
644
|
+
const DEFAULT_MIN_PERSONS = RELIABLE_PERSONS;
|
|
645
|
+
|
|
646
|
+
const tools: McpToolExport['tools'] = [
|
|
647
|
+
{
|
|
648
|
+
name: 'meps_drugs_for_condition',
|
|
649
|
+
description:
|
|
650
|
+
'Which prescription drugs Americans actually take for a given medical condition, with a national estimate of how many people take each one. Covers the whole US population — every payer, every age, commercial and uninsured included, not just Medicare or Medicaid. Ask with a plain condition name like "depression", "high cholesterol", "type 2 diabetes" or "asthma". Returns drugs ranked by estimated people treated, each with the survey sample behind it.',
|
|
651
|
+
inputSchema: {
|
|
652
|
+
type: 'object',
|
|
653
|
+
properties: {
|
|
654
|
+
condition: { type: 'string', description: 'Condition in plain words ("depression", "high blood pressure"), or a CCSR category code like MBD002.' },
|
|
655
|
+
year: { type: 'number', description: 'Survey year. Defaults to the most recent loaded.' },
|
|
656
|
+
min_sample: { type: 'number', description: `Minimum survey respondents behind a row, default ${DEFAULT_MIN_PERSONS} — AHRQ's own reliability floor. Lower it to see less-common drugs, which come back marked reliable:false because AHRQ would not publish them.` },
|
|
657
|
+
limit: { type: 'number', description: 'Max drugs, default 20, max 100.' },
|
|
658
|
+
},
|
|
659
|
+
required: ['condition'],
|
|
660
|
+
},
|
|
661
|
+
},
|
|
662
|
+
{
|
|
663
|
+
name: 'meps_conditions_for_drug',
|
|
664
|
+
description:
|
|
665
|
+
'What a drug is actually being prescribed for in the US population, ranked by estimated people. Answers off-label and multi-use questions that a label or an approval database cannot: what gabapentin, metformin or amitriptyline are really used to treat in practice. Give a generic drug name.',
|
|
666
|
+
inputSchema: {
|
|
667
|
+
type: 'object',
|
|
668
|
+
properties: {
|
|
669
|
+
drug: { type: 'string', description: 'Generic drug name, e.g. "gabapentin", "metformin".' },
|
|
670
|
+
year: { type: 'number', description: 'Survey year. Defaults to the most recent loaded.' },
|
|
671
|
+
min_sample: { type: 'number', description: `Minimum survey respondents behind a row, default ${DEFAULT_MIN_PERSONS}.` },
|
|
672
|
+
limit: { type: 'number', description: 'Max conditions, default 20, max 100.' },
|
|
673
|
+
},
|
|
674
|
+
required: ['drug'],
|
|
675
|
+
},
|
|
676
|
+
},
|
|
677
|
+
{
|
|
678
|
+
name: 'meps_drug_use',
|
|
679
|
+
description:
|
|
680
|
+
'National prescription volume and spending for one drug: how many Americans filled it, how many fills, total spend across all payers and how much patients paid out of pocket. Population-wide rather than a single programme, so it answers how widely used a medicine is in the US and what share of its cost falls on patients.',
|
|
681
|
+
inputSchema: {
|
|
682
|
+
type: 'object',
|
|
683
|
+
properties: {
|
|
684
|
+
drug: { type: 'string', description: 'Generic drug name, e.g. "atorvastatin".' },
|
|
685
|
+
year: { type: 'number', description: 'Survey year. Defaults to the most recent loaded.' },
|
|
686
|
+
},
|
|
687
|
+
required: ['drug'],
|
|
688
|
+
},
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
name: 'meps_top_drugs',
|
|
692
|
+
description:
|
|
693
|
+
'The most-used prescription drugs in the United States, ranked by estimated number of people who filled them, with total and out-of-pocket spending. Answers what the most commonly taken medications in America are for a given year.',
|
|
694
|
+
inputSchema: {
|
|
695
|
+
type: 'object',
|
|
696
|
+
properties: {
|
|
697
|
+
year: { type: 'number', description: 'Survey year. Defaults to the most recent loaded.' },
|
|
698
|
+
order_by: { type: 'string', enum: ['people', 'fills', 'spending'], description: 'Ranking measure, default people.' },
|
|
699
|
+
limit: { type: 'number', description: 'Max drugs, default 25, max 100.' },
|
|
700
|
+
},
|
|
701
|
+
},
|
|
702
|
+
},
|
|
703
|
+
];
|
|
704
|
+
|
|
705
|
+
// ---- helpers ---------------------------------------------------------------
|
|
706
|
+
|
|
707
|
+
const clamp = (v: unknown, def: number, max: number) => {
|
|
708
|
+
const n = typeof v === 'number' ? v : Number(v);
|
|
709
|
+
return Number.isFinite(n) ? Math.min(max, Math.max(1, Math.floor(n))) : def;
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
/** The gateway injects Supabase credentials into `args` (injectSupabase). */
|
|
713
|
+
async function pg(args: Record<string, unknown>, path: string): Promise<any[]> {
|
|
714
|
+
const url = (args._supabaseUrl as string | undefined)?.trim();
|
|
715
|
+
const key = (args._supabaseKey as string | undefined)?.trim();
|
|
716
|
+
if (!url || !key) throw new Error('backing-store credentials not injected');
|
|
717
|
+
// Bounded: an unbounded fetch to a degraded backing store does not error, it
|
|
718
|
+
// holds the Worker until its own budget kills the request minutes later.
|
|
719
|
+
const res = await fetchWithTimeout(
|
|
720
|
+
`${url}/rest/v1/${path}`,
|
|
721
|
+
{ headers: { apikey: key, Authorization: `Bearer ${key}`, Accept: 'application/json', 'User-Agent': UA } },
|
|
722
|
+
'MEPS backing store',
|
|
723
|
+
);
|
|
724
|
+
// httpError summarises the body rather than forwarding it: a backing-store
|
|
725
|
+
// error page pasted into a caller-facing message is how a whole HTML document
|
|
726
|
+
// ends up inside a JSON field.
|
|
727
|
+
if (!res.ok) throw await httpError(res, 'MEPS backing store');
|
|
728
|
+
return res.json();
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** Newest year with a COMPLETED load. Reading max(year) from the data instead
|
|
732
|
+
* would happily return a year whose ingest died halfway. */
|
|
733
|
+
async function latestYear(args: Record<string, unknown>): Promise<number | null> {
|
|
734
|
+
const rows = await pg(args, 'meps_ingest_runs?status=eq.ok&select=year&order=year.desc&limit=1');
|
|
735
|
+
return rows[0]?.year ?? null;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
async function resolveYear(args: Record<string, unknown>): Promise<{ year: number | null; requested?: number }> {
|
|
739
|
+
const asked = typeof args.year === 'number' ? args.year : undefined;
|
|
740
|
+
if (asked) {
|
|
741
|
+
const rows = await pg(args, `meps_ingest_runs?status=eq.ok&year=eq.${asked}&select=year&limit=1`);
|
|
742
|
+
if (rows.length) return { year: asked, requested: asked };
|
|
743
|
+
return { year: await latestYear(args), requested: asked };
|
|
744
|
+
}
|
|
745
|
+
return { year: await latestYear(args) };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** MEPS reports a therapeutic CLASS in place of a product name when naming the
|
|
749
|
+
* product would identify a respondent — "INTERLEUKIN INHIBITORS" rather than a
|
|
750
|
+
* specific biologic. 49 of 554 names in 2024 are classes and they carry 31.9%
|
|
751
|
+
* of all spending, so a spending ranking is mostly classes at the top. Said
|
|
752
|
+
* plainly in the response, because a caller reading "INTERLEUKIN INHIBITORS is
|
|
753
|
+
* the top drug by spending" has been misled by our vocabulary, not theirs. */
|
|
754
|
+
const CLASS_NAME_NOTE =
|
|
755
|
+
'Some names are therapeutic CLASSES, not products — MEPS substitutes the class ' +
|
|
756
|
+
'("INTERLEUKIN INHIBITORS", "ANTINEOPLASTICS") where naming the drug would identify a ' +
|
|
757
|
+
'respondent. In 2024 that is 49 of 554 names but 32% of all spending, so class rows ' +
|
|
758
|
+
'dominate any ranking by cost. Treat a plural or category-sounding name as a class.';
|
|
759
|
+
|
|
760
|
+
const num = (v: unknown) => (v === null || v === undefined ? null : Math.round(Number(v)));
|
|
761
|
+
const esc = (v: string) => encodeURIComponent(`*${v.replace(/[*,()]/g, ' ').trim()}*`);
|
|
762
|
+
|
|
763
|
+
/** The shared caveat. Repeated on every response on purpose: a weighted survey
|
|
764
|
+
* number read without it is indistinguishable from a census count. */
|
|
765
|
+
function basis(year: number, coverage?: number | null) {
|
|
766
|
+
return {
|
|
767
|
+
source: 'AHRQ Medical Expenditure Panel Survey (MEPS), household component',
|
|
768
|
+
year,
|
|
769
|
+
population: 'US civilian non-institutionalized population, all payers',
|
|
770
|
+
estimate_basis:
|
|
771
|
+
`Weighted survey estimates, not counts. sample_persons is the number of real respondents behind each row; rows below ${RELIABLE_PERSONS} respondents are marked reliable:false, which is AHRQ's own floor.`,
|
|
772
|
+
...(coverage != null
|
|
773
|
+
? {
|
|
774
|
+
condition_link_coverage:
|
|
775
|
+
`${(coverage * 100).toFixed(1)}% of prescription fills in this year are linked to a condition; the rest are not attributed to any diagnosis, so condition totals are a subset of all prescribing.`,
|
|
776
|
+
}
|
|
777
|
+
: {}),
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
async function coverageFor(args: Record<string, unknown>, year: number): Promise<number | null> {
|
|
782
|
+
const rows = await pg(args, `meps_ingest_runs?status=eq.ok&year=eq.${year}&select=condition_link_coverage&order=finished_at.desc&limit=1`);
|
|
783
|
+
return rows[0]?.condition_link_coverage ?? null;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async function labelsFor(args: Record<string, unknown>, codes: string[]): Promise<Record<string, string>> {
|
|
787
|
+
if (!codes.length) return {};
|
|
788
|
+
const rows = await pg(args, `meps_ccsr_category?ccsr=in.(${codes.join(',')})&select=ccsr,label`);
|
|
789
|
+
return Object.fromEntries(rows.map((r: any) => [r.ccsr, r.label]));
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// ---- tools -----------------------------------------------------------------
|
|
793
|
+
|
|
794
|
+
async function drugsForCondition(args: Record<string, unknown>) {
|
|
795
|
+
const raw = typeof args.condition === 'string' ? args.condition.trim() : '';
|
|
796
|
+
if (!raw) return { found: false, reason: 'no_condition', hint: 'Give a condition, e.g. "depression" or a CCSR code like MBD002.' };
|
|
797
|
+
|
|
798
|
+
const { year, requested } = await resolveYear(args);
|
|
799
|
+
if (!year) return { found: false, reason: 'no_data_loaded', hint: 'No MEPS year has finished loading yet.' };
|
|
800
|
+
|
|
801
|
+
let codes = resolveConditionCodes(raw);
|
|
802
|
+
let matchedBy: 'code' | 'synonym' | 'label' = codes ? (/^[A-Z]{3}\d{3}$/.test(raw.toUpperCase()) ? 'code' : 'synonym') : 'label';
|
|
803
|
+
if (!codes) {
|
|
804
|
+
const hits = await pg(args, `meps_ccsr_category?label=ilike.${esc(raw)}&select=ccsr,label&limit=6`);
|
|
805
|
+
if (!hits.length) {
|
|
806
|
+
return {
|
|
807
|
+
found: false,
|
|
808
|
+
reason: 'unknown_condition',
|
|
809
|
+
hint: `No MEPS condition category matches "${raw}". Try a broader word ("diabetes", "asthma", "depression"), or a CCSR code like END010.`,
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
codes = hits.map((h: any) => h.ccsr);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const minSample = clamp(args.min_sample, DEFAULT_MIN_PERSONS, 100000);
|
|
816
|
+
const limit = clamp(args.limit, 20, 100);
|
|
817
|
+
const rows = await pg(
|
|
818
|
+
args,
|
|
819
|
+
`meps_rx_condition_drug?year=eq.${year}&ccsr=in.(${codes.join(',')})&persons_unweighted=gte.${minSample}` +
|
|
820
|
+
`&select=ccsr,drug,persons_unweighted,fills_unweighted,persons_weighted,fills_weighted,reliable` +
|
|
821
|
+
`&order=persons_weighted.desc&limit=${limit}`
|
|
822
|
+
);
|
|
823
|
+
|
|
824
|
+
const [labels, coverage] = await Promise.all([labelsFor(args, codes), coverageFor(args, year)]);
|
|
825
|
+
|
|
826
|
+
if (!rows.length) {
|
|
827
|
+
// Distinguish "nothing meets the bar" from "nothing at all" — they call for
|
|
828
|
+
// different next moves, and collapsing them reads as absence of the drug.
|
|
829
|
+
const anyRows = await pg(args, `meps_rx_condition_drug?year=eq.${year}&ccsr=in.(${codes.join(',')})&select=drug&limit=1`);
|
|
830
|
+
return {
|
|
831
|
+
found: false,
|
|
832
|
+
reason: anyRows.length ? 'below_min_sample' : 'no_match',
|
|
833
|
+
hint: anyRows.length
|
|
834
|
+
? `Rows exist for ${codes.join(', ')} in ${year} but none has ${minSample}+ respondents behind it. Lower min_sample to see them, treating the estimates as weak.`
|
|
835
|
+
: `MEPS ${year} records no prescriptions linked to ${codes.join(', ')}. Fewer than half of fills carry a condition link at all, so this can mean "not captured" rather than "not prescribed".`,
|
|
836
|
+
matched_conditions: codes.map((c) => ({ ccsr: c, label: labels[c] ?? c })),
|
|
837
|
+
...basis(year, coverage),
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
return {
|
|
842
|
+
found: true,
|
|
843
|
+
count: rows.length,
|
|
844
|
+
matched_by: matchedBy,
|
|
845
|
+
matched_conditions: codes.map((c) => ({ ccsr: c, label: labels[c] ?? c })),
|
|
846
|
+
...(requested && requested !== year ? { note_year: `MEPS ${requested} is not loaded; answering for ${year}.` } : {}),
|
|
847
|
+
drugs: rows.map((r: any) => ({
|
|
848
|
+
drug: r.drug,
|
|
849
|
+
condition: labels[r.ccsr] ?? r.ccsr,
|
|
850
|
+
ccsr: r.ccsr,
|
|
851
|
+
people_estimate: num(r.persons_weighted),
|
|
852
|
+
fills_estimate: num(r.fills_weighted),
|
|
853
|
+
sample_persons: r.persons_unweighted,
|
|
854
|
+
reliable: r.reliable,
|
|
855
|
+
})),
|
|
856
|
+
...basis(year, coverage),
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
async function conditionsForDrug(args: Record<string, unknown>) {
|
|
861
|
+
const drug = typeof args.drug === 'string' ? args.drug.trim().toUpperCase() : '';
|
|
862
|
+
if (!drug) return { found: false, reason: 'no_drug', hint: 'Give a generic drug name, e.g. "gabapentin".' };
|
|
863
|
+
|
|
864
|
+
const { year, requested } = await resolveYear(args);
|
|
865
|
+
if (!year) return { found: false, reason: 'no_data_loaded', hint: 'No MEPS year has finished loading yet.' };
|
|
866
|
+
|
|
867
|
+
const minSample = clamp(args.min_sample, DEFAULT_MIN_PERSONS, 100000);
|
|
868
|
+
const limit = clamp(args.limit, 20, 100);
|
|
869
|
+
const rows = await pg(
|
|
870
|
+
args,
|
|
871
|
+
`meps_rx_condition_drug?year=eq.${year}&drug=ilike.${esc(drug)}&persons_unweighted=gte.${minSample}` +
|
|
872
|
+
`&select=ccsr,drug,persons_unweighted,persons_weighted,fills_weighted,reliable&order=persons_weighted.desc&limit=${limit}`
|
|
873
|
+
);
|
|
874
|
+
const coverage = await coverageFor(args, year);
|
|
875
|
+
|
|
876
|
+
if (!rows.length) {
|
|
877
|
+
const known = await pg(args, `meps_rx_drug?year=eq.${year}&drug=ilike.${esc(drug)}&select=drug,persons_unweighted&limit=3`);
|
|
878
|
+
return {
|
|
879
|
+
found: false,
|
|
880
|
+
reason: known.length ? 'no_condition_link' : 'unknown_drug',
|
|
881
|
+
hint: known.length
|
|
882
|
+
? `"${known[0].drug}" is in MEPS ${year} but no condition it was prescribed for clears ${minSample} respondents. Fewer than half of fills carry a condition link at all.`
|
|
883
|
+
: `No drug matching "${drug}" in MEPS ${year}. MEPS records cleaned GENERIC names, so try "atorvastatin" rather than "Lipitor".`,
|
|
884
|
+
...basis(year, coverage),
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
const labels = await labelsFor(args, [...new Set(rows.map((r: any) => r.ccsr))]);
|
|
889
|
+
return {
|
|
890
|
+
found: true,
|
|
891
|
+
drug: rows[0].drug,
|
|
892
|
+
count: rows.length,
|
|
893
|
+
...(requested && requested !== year ? { note_year: `MEPS ${requested} is not loaded; answering for ${year}.` } : {}),
|
|
894
|
+
conditions: rows.map((r: any) => ({
|
|
895
|
+
condition: labels[r.ccsr] ?? r.ccsr,
|
|
896
|
+
ccsr: r.ccsr,
|
|
897
|
+
people_estimate: num(r.persons_weighted),
|
|
898
|
+
fills_estimate: num(r.fills_weighted),
|
|
899
|
+
sample_persons: r.persons_unweighted,
|
|
900
|
+
reliable: r.reliable,
|
|
901
|
+
})),
|
|
902
|
+
...basis(year, coverage),
|
|
903
|
+
note: 'A single fill can be linked to more than one condition, so these do not sum to the drug total in meps_drug_use.',
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
async function drugUse(args: Record<string, unknown>) {
|
|
908
|
+
const drug = typeof args.drug === 'string' ? args.drug.trim().toUpperCase() : '';
|
|
909
|
+
if (!drug) return { found: false, reason: 'no_drug', hint: 'Give a generic drug name, e.g. "atorvastatin".' };
|
|
910
|
+
|
|
911
|
+
const { year, requested } = await resolveYear(args);
|
|
912
|
+
if (!year) return { found: false, reason: 'no_data_loaded', hint: 'No MEPS year has finished loading yet.' };
|
|
913
|
+
|
|
914
|
+
const rows = await pg(
|
|
915
|
+
args,
|
|
916
|
+
`meps_rx_drug?year=eq.${year}&drug=ilike.${esc(drug)}&select=*&order=persons_weighted.desc&limit=5`
|
|
917
|
+
);
|
|
918
|
+
if (!rows.length) {
|
|
919
|
+
return {
|
|
920
|
+
found: false,
|
|
921
|
+
reason: 'unknown_drug',
|
|
922
|
+
hint: `No drug matching "${drug}" in MEPS ${year}. MEPS records cleaned GENERIC names, so try "atorvastatin" rather than "Lipitor".`,
|
|
923
|
+
...basis(year),
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
const r = rows[0];
|
|
928
|
+
const total = Number(r.total_expenditure);
|
|
929
|
+
const oop = Number(r.oop_expenditure);
|
|
930
|
+
return {
|
|
931
|
+
found: true,
|
|
932
|
+
drug: r.drug,
|
|
933
|
+
...(requested && requested !== year ? { note_year: `MEPS ${requested} is not loaded; answering for ${year}.` } : {}),
|
|
934
|
+
people_estimate: num(r.persons_weighted),
|
|
935
|
+
fills_estimate: num(r.fills_weighted),
|
|
936
|
+
sample_persons: r.persons_unweighted,
|
|
937
|
+
reliable: r.reliable,
|
|
938
|
+
total_spending_usd: num(total),
|
|
939
|
+
out_of_pocket_usd: num(oop),
|
|
940
|
+
out_of_pocket_share: Number.isFinite(total) && total > 0 ? Number((oop / total).toFixed(3)) : null,
|
|
941
|
+
...(rows.length > 1 ? { other_matches: rows.slice(1).map((x: any) => x.drug) } : {}),
|
|
942
|
+
...basis(year),
|
|
943
|
+
note: CLASS_NAME_NOTE,
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
async function topDrugs(args: Record<string, unknown>) {
|
|
948
|
+
const { year, requested } = await resolveYear(args);
|
|
949
|
+
if (!year) return { found: false, reason: 'no_data_loaded', hint: 'No MEPS year has finished loading yet.' };
|
|
950
|
+
|
|
951
|
+
const orderArg = typeof args.order_by === 'string' ? args.order_by.toLowerCase() : 'people';
|
|
952
|
+
const ORDER: Record<string, string> = {
|
|
953
|
+
people: 'persons_weighted',
|
|
954
|
+
fills: 'fills_weighted',
|
|
955
|
+
spending: 'total_expenditure',
|
|
956
|
+
};
|
|
957
|
+
const col = ORDER[orderArg];
|
|
958
|
+
if (!col) {
|
|
959
|
+
return { found: false, reason: 'unknown_order_by', hint: `order_by must be one of: ${Object.keys(ORDER).join(', ')}.` };
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const limit = clamp(args.limit, 25, 100);
|
|
963
|
+
const rows = await pg(
|
|
964
|
+
args,
|
|
965
|
+
`meps_rx_drug?year=eq.${year}&select=drug,persons_unweighted,persons_weighted,fills_weighted,total_expenditure,oop_expenditure,reliable&order=${col}.desc&limit=${limit}`
|
|
966
|
+
);
|
|
967
|
+
if (!rows.length) return { found: false, reason: 'no_match', hint: `No drug rows for MEPS ${year}.`, ...basis(year) };
|
|
968
|
+
|
|
969
|
+
return {
|
|
970
|
+
found: true,
|
|
971
|
+
count: rows.length,
|
|
972
|
+
ranked_by: orderArg,
|
|
973
|
+
...(requested && requested !== year ? { note_year: `MEPS ${requested} is not loaded; answering for ${year}.` } : {}),
|
|
974
|
+
drugs: rows.map((r: any) => ({
|
|
975
|
+
drug: r.drug,
|
|
976
|
+
people_estimate: num(r.persons_weighted),
|
|
977
|
+
fills_estimate: num(r.fills_weighted),
|
|
978
|
+
total_spending_usd: num(r.total_expenditure),
|
|
979
|
+
out_of_pocket_usd: num(r.oop_expenditure),
|
|
980
|
+
sample_persons: r.persons_unweighted,
|
|
981
|
+
reliable: r.reliable,
|
|
982
|
+
})),
|
|
983
|
+
...basis(year),
|
|
984
|
+
note: CLASS_NAME_NOTE,
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
const callTool: McpToolExport['callTool'] = async (name, args) => {
|
|
989
|
+
switch (name) {
|
|
990
|
+
case 'meps_drugs_for_condition': return drugsForCondition(args);
|
|
991
|
+
case 'meps_conditions_for_drug': return conditionsForDrug(args);
|
|
992
|
+
case 'meps_drug_use': return drugUse(args);
|
|
993
|
+
case 'meps_top_drugs': return topDrugs(args);
|
|
994
|
+
default: return { error: `unknown tool: ${name}` };
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
|
|
998
|
+
export default { tools, callTool } satisfies McpToolExport;
|