@pipeworx/mcp-newswire-com 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/src/index.ts ADDED
@@ -0,0 +1,1111 @@
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
+ * RSS / Atom item parsing, shared across every pack and worker that reads a
29
+ * feed.
30
+ *
31
+ * Ported from `workers/press-intel/src/feed.ts`, which was itself ported from
32
+ * the working parser in `mcps/us-news-feeds/src/index.ts` — the
33
+ * regex-over-XML shape is deliberate (no DOM in Workers, and every feed in
34
+ * the wild is malformed in some small way that a strict parser would
35
+ * reject). press-intel's version is the hardened one: it was built against
36
+ * 85 live feeds and adds two things the pack-local copies were missing.
37
+ * Moved here 2026-09-21 (fleet #2285) so the press-release wire packs reuse
38
+ * it instead of re-copy-pasting a third parser — a capability proven against
39
+ * 85 feeds belongs in one place, not one worker.
40
+ *
41
+ * 1. `<media:credit role="author">`. ZDNET carries a byline on 20 of 20 items
42
+ * in that tag and nothing else. The original probe scored ZDNET
43
+ * `byline_pct: 0` and filed it as needing an article-page fetch — the feed
44
+ * was fine, the parser was looking in three places out of five.
45
+ *
46
+ * 2. `newestItemAt`. A feed can answer 200 with well-formed XML and still be
47
+ * abandoned: WSJ Tech's registered feed (feeds.a.dj.com) returns 20 valid
48
+ * items whose newest is dated 2025-01-27. HTTP status cannot see that,
49
+ * which is why every caller should record the newest item date per poll
50
+ * and flag a feed stale rather than trusting a green 200. This is exactly
51
+ * the trap a keyless press-release wire hits too: a 200 with well-formed
52
+ * XML and a stale newest item looks identical to a live one at the
53
+ * transport layer.
54
+ */
55
+
56
+ interface FeedItem {
57
+ title: string;
58
+ link: string;
59
+ publishedAt?: string;
60
+ excerpt?: string;
61
+ /** RAW byline string, exactly as the feed emitted it. Never normalised here. */
62
+ rawByline?: string;
63
+ guid?: string;
64
+ categories?: string[];
65
+ }
66
+
67
+ interface ParsedFeed {
68
+ items: FeedItem[];
69
+ /** ISO date of the newest item that carried a parseable date, or null. */
70
+ newestItemAt: string | null;
71
+ /** How many items carried any byline at all — the per-poll byline coverage. */
72
+ withByline: number;
73
+ }
74
+
75
+ const AUTHOR_TAGS = ['dc:creator', 'media:credit', 'itunes:author', 'dc:contributor'];
76
+
77
+ function parseFeed(xml: string): ParsedFeed {
78
+ const items: FeedItem[] = [];
79
+ const blocks = xml.match(/<(item|entry)[\s>][\s\S]*?<\/\1>/gi) ?? [];
80
+ let newest: number | null = null;
81
+ let withByline = 0;
82
+
83
+ for (const b of blocks) {
84
+ const link = extractLink(b);
85
+ const publishedRaw = tag(b, 'pubDate') || tag(b, 'published') || tag(b, 'updated') || tag(b, 'dc:date');
86
+ const ts = publishedRaw ? Date.parse(publishedRaw) : NaN;
87
+ if (Number.isFinite(ts) && (newest === null || ts > newest)) newest = ts;
88
+ const rawByline = feedByline(b);
89
+ if (rawByline) withByline++;
90
+ items.push({
91
+ title: clean(tag(b, 'title')),
92
+ link,
93
+ publishedAt: Number.isFinite(ts) ? new Date(ts).toISOString() : undefined,
94
+ excerpt: clean(tag(b, 'description') || tag(b, 'summary') || tag(b, 'content:encoded') || tag(b, 'content'))
95
+ .slice(0, EXCERPT_MAX) || undefined,
96
+ rawByline: rawByline || undefined,
97
+ guid: tag(b, 'guid') || tag(b, 'id') || link || undefined,
98
+ categories: cats(b),
99
+ });
100
+ }
101
+
102
+ return {
103
+ items,
104
+ newestItemAt: newest === null ? null : new Date(newest).toISOString(),
105
+ withByline,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Excerpt cap.
111
+ *
112
+ * `docs/journalist-db-plan.md` draws a rights boundary: URL + metadata + our own
113
+ * summary + a SHORT excerpt, no full-text retention. Several feeds put the
114
+ * entire article in `<content:encoded>` (The Register does), so without a
115
+ * hard cut here "store the excerpt" quietly becomes "mirror the publisher's
116
+ * archive" — of publishers we intend to pitch, or in the wire case, of
117
+ * publishers whose own release text this is.
118
+ */
119
+ const EXCERPT_MAX = 400;
120
+
121
+ function feedByline(b: string): string {
122
+ for (const t of AUTHOR_TAGS) {
123
+ const v = clean(tag(b, t));
124
+ if (v) return v;
125
+ }
126
+ return clean(authorName(b));
127
+ }
128
+
129
+ function extractLink(b: string): string {
130
+ const rss = b.match(/<link>([\s\S]*?)<\/link>/i);
131
+ if (rss && rss[1].trim()) return clean(rss[1]);
132
+ const alt =
133
+ b.match(/<link[^>]*rel=["']alternate["'][^>]*href=["']([^"']+)["']/i) ||
134
+ b.match(/<link[^>]*href=["']([^"']+)["']/i);
135
+ return alt ? decodeXml(alt[1].trim()) : '';
136
+ }
137
+
138
+ function authorName(b: string): string {
139
+ const a = b.match(/<author[\s>]([\s\S]*?)<\/author>/i);
140
+ if (!a) return '';
141
+ const name = a[1].match(/<name>([\s\S]*?)<\/name>/i);
142
+ if (name) return name[1];
143
+ // RSS 2.0 <author> is an email address, optionally "a@b.com (Real Name)".
144
+ const emailWithName = a[1].match(/\(([^)]{2,80})\)/);
145
+ if (emailWithName) return emailWithName[1];
146
+ return /@/.test(a[1]) ? '' : a[1];
147
+ }
148
+
149
+ function cats(b: string): string[] | undefined {
150
+ const list: string[] = [];
151
+ for (const m of b.matchAll(/<category[^>]*?(?:term=["']([^"']+)["'][^>]*)?>([\s\S]*?)<\/category>/gi)) {
152
+ const v = clean(m[1] || m[2]);
153
+ if (v) list.push(v);
154
+ }
155
+ for (const m of b.matchAll(/<category[^>]*term=["']([^"']+)["'][^>]*\/>/gi)) list.push(decodeXml(m[1]));
156
+ return list.length ? [...new Set(list)].slice(0, 10) : undefined;
157
+ }
158
+
159
+ function tag(xml: string, name: string): string {
160
+ const esc = name.replace(':', '\\:');
161
+ const m = xml.match(new RegExp(`<${esc}[^>]*>([\\s\\S]*?)<\\/${esc}>`, 'i'));
162
+ return m ? unwrap(m[1]) : '';
163
+ }
164
+
165
+ function unwrap(s: string): string {
166
+ const m = s.trim().match(/^<!\[CDATA\[([\s\S]*?)\]\]>$/);
167
+ return (m ? m[1] : s).trim();
168
+ }
169
+
170
+ function decodeXml(s: string): string {
171
+ return s
172
+ .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
173
+ .replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
174
+ .replace(/&quot;/g, '"')
175
+ .replace(/&apos;/g, "'")
176
+ .replace(/&lt;/g, '<')
177
+ .replace(/&gt;/g, '>')
178
+ .replace(/&amp;/g, '&');
179
+ }
180
+
181
+ function clean(s: unknown): string {
182
+ if (typeof s !== 'string') return '';
183
+ return decodeXml(
184
+ s.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/<\/?[a-zA-Z][^>]*>/g, ' '),
185
+ )
186
+ .replace(/&nbsp;/g, ' ')
187
+ .replace(/\s+/g, ' ')
188
+ .trim();
189
+ }
190
+
191
+ /**
192
+ * Split feed XML into raw `<item>`/`<entry>` blocks, in document order — the
193
+ * same blocks {@link parseFeed} iterates internally.
194
+ *
195
+ * Exposed so a caller can read a VENDOR-SPECIFIC field {@link parseFeed} does
196
+ * not know about — GlobeNewswire's `dc:contributor` issuer name, PRNewswire's
197
+ * `prn:industry` list — by zipping this array against `parseFeed(xml).items`;
198
+ * both walk the same blocks in the same order, so index N in one is index N
199
+ * in the other. Added for the press-release wire packs (fleet #2285): those
200
+ * feeds carry the issuer in a tag `parseFeed`'s generic byline heuristic
201
+ * would mis-attribute (PRNewswire's `<media:credit>` names the WIRE, "PR
202
+ * Newswire", not the issuer).
203
+ */
204
+ function feedItemBlocks(xml: string): string[] {
205
+ return xml.match(/<(item|entry)[\s>][\s\S]*?<\/\1>/gi) ?? [];
206
+ }
207
+
208
+ /**
209
+ * Read one XML tag's text out of a raw item/entry block (CDATA-unwrapped,
210
+ * entity-decoded). Exposed alongside {@link feedItemBlocks} for the same
211
+ * reason.
212
+ */
213
+ function feedTag(block: string, name: string): string {
214
+ return tag(block, name);
215
+ }
216
+
217
+ /**
218
+ * Like {@link feedTag}, but returns every occurrence — for a tag a feed
219
+ * repeats per item (PRNewswire's `<prn:industry>`, one element per industry
220
+ * assigned to the release).
221
+ */
222
+ function feedTagAll(block: string, name: string): string[] {
223
+ const esc = name.replace(':', '\\:');
224
+ const re = new RegExp(`<${esc}[^>]*>([\\s\\S]*?)<\\/${esc}>`, 'gi');
225
+ const out: string[] = [];
226
+ for (const m of block.matchAll(re)) {
227
+ const v = clean(unwrap(m[1]));
228
+ if (v) out.push(v);
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * Canonical URL for dedupe.
235
+ *
236
+ * Strips tracking noise and the per-feed `?mod=` / `utm_*` suffixes that make
237
+ * the same article arrive as two rows from a section feed and a topic feed.
238
+ * Deliberately keeps the path and any non-tracking query, because several
239
+ * sources address articles by query string alone.
240
+ */
241
+ function canonicalUrl(raw: string): string | null {
242
+ const t = (raw || '').trim();
243
+ if (!/^https?:\/\//i.test(t)) return null;
244
+ let u: URL;
245
+ try { u = new URL(t); } catch { return null; }
246
+ u.hash = '';
247
+ u.protocol = 'https:';
248
+ u.hostname = u.hostname.toLowerCase().replace(/^www\./, '');
249
+ const drop: string[] = [];
250
+ u.searchParams.forEach((_v, k) => {
251
+ if (/^(utm_|ic|mod$|cmp$|cmpid$|src$|source$|ref$|fbclid$|gclid$|guccounter$|amp$|guce_)/i.test(k)) drop.push(k);
252
+ });
253
+ for (const k of drop) u.searchParams.delete(k);
254
+ let s = u.toString();
255
+ if (s.endsWith('?')) s = s.slice(0, -1);
256
+ // Trailing-slash variants are the single most common duplicate shape.
257
+ if (s.endsWith('/') && !u.search) s = s.slice(0, -1);
258
+ return s.slice(0, 1500);
259
+ }
260
+
261
+
262
+ /**
263
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
264
+ *
265
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
266
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
267
+ * covered the majority and structurally could not cover the rest: the rest
268
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
269
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
270
+ *
271
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
272
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
273
+ *
274
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
275
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
276
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
277
+ * our own Supabase for fleet. There is no third party anywhere in either call.
278
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
279
+ * class that means "the source is unreachable and there is nothing for us to
280
+ * fix", which is why the problem-tools triage skips it.
281
+ *
282
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
283
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
284
+ * one site today, so it would work today. It would also rot the first time
285
+ * somebody rewords a label — silently, and in the direction of hiding our own
286
+ * outage, which is worse than the bug being fixed. Every prose rule in
287
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
288
+ * #584); that history is most of that file's comment budget.
289
+ *
290
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
291
+ * hostname is a fact about the call, not a guess about its prose. Two
292
+ * consequences that a pack-level flag could not give us, and the reason the
293
+ * flag was rejected:
294
+ *
295
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
296
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
297
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
298
+ * either pack would relabel a real third-party outage as ours — inventing
299
+ * work, which is the same class of error in the opposite direction.
300
+ * - It covers every future internal pack for free, instead of one declared
301
+ * slug at a time.
302
+ *
303
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
304
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
305
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
306
+ * this module — so changing the wording changes both sides in the same edit and
307
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
308
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
309
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
310
+ * from its own classifier three times and needed a CI gate to hold them
311
+ * together.
312
+ *
313
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
314
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
315
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
316
+ * availability failure" is decided from the actual status code, never re-derived
317
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
318
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
319
+ */
320
+
321
+ /**
322
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
323
+ *
324
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
325
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
326
+ * and different fixes. Here there is only one story to tell — an origin we run
327
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
328
+ * value is decoration; #724 is what happens when a class holds several
329
+ * situations, and inventing sub-values ahead of a reason to act on them
330
+ * differently is the same mistake with the sign flipped.
331
+ *
332
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
333
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
334
+ * hint paths, which only care whether retrying or a sibling tool might work —
335
+ * and it might. Nothing a caller sees or is charged changes here.
336
+ *
337
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
338
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
339
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
340
+ * worked on the write side and was invisible for weeks.
341
+ */
342
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
343
+
344
+ /**
345
+ * The token that carries "this origin is ours" from the call site to the
346
+ * classifier.
347
+ *
348
+ * Appended to the error message rather than attached to the Error object,
349
+ * because the object does not survive the trip: 275 packs return `{ error:
350
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
351
+ * and the fleet pack rebuilds its error from a captured status + body across a
352
+ * retry loop. A property on an Error would be dropped by every one of those
353
+ * paths and the class would work in tests and vanish in production.
354
+ *
355
+ * WORDING IS LOAD-BEARING, same rule as labelAge's note in authority.ts. This
356
+ * string is appended to a pack's thrown Error message (shared/src/http.ts),
357
+ * and a thrown Error's message is exactly what the gateway hands back to the
358
+ * caller as `content[0].text` when nothing rewrites it (workers/gateway/src
359
+ * catches the throw and sets `rawResult.message = stripClassPrefix(error)`,
360
+ * which does not touch this suffix) — so the original wording,
361
+ * " [pipeworx-hosted origin — our own service, not a third party]", was not a
362
+ * theoretical leak: it shipped live on pipeworx-catalog's 522s, 7 times in 6
363
+ * hours on 2026-09-02 (see tests/golden-internal-service.test.ts), verbatim
364
+ * naming Pipeworx as the host. check:hosting-claims never caught it because it
365
+ * did not scan shared/ at all (task #2009). Reworded to describe the
366
+ * OBSERVATION (the origin did not answer) without a claim about who runs it —
367
+ * the identical fix labelAge got: drop the possessive, keep the fact.
368
+ */
369
+ const INTERNAL_ORIGIN_MARKER = ' [origin did not respond — retry before concluding the named source is down]';
370
+
371
+ /**
372
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
373
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
374
+ *
375
+ * Matching the shape rather than listing the ref keeps this correct when we add
376
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
377
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
378
+ * own status page and emphatically not our database. Verified 2026-09-02 by
379
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
380
+ * only real project ref anywhere in the tree is ours, the rest are doc
381
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
382
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
383
+ * by construction.
384
+ */
385
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
386
+
387
+ /**
388
+ * Is this a host WE run?
389
+ *
390
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
391
+ * hosted on workers.dev, so the suffix says where something runs and not who
392
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
393
+ * hostname or to our Supabase project, both of which are ownership facts.
394
+ *
395
+ * `workers/gateway/src/provenance.ts`'s `OUR_HOSTS` answers the same
396
+ * question and DOES include `workers.dev` — a documented divergence
397
+ * (task #2051), not a bug to converge. That list decides what a response may
398
+ * cite as a data SOURCE, where a false negative (citing our own worker as an
399
+ * external source) is the hosting-disclosure leak this whole file exists to
400
+ * prevent, so it errs broad. This one decides who gets BLAMED for a 5xx in
401
+ * outage metrics read by on-call, where a false positive (crediting our own
402
+ * infra with a third party's outage) hides the real failure, so it errs
403
+ * narrow. Same suffix, opposite direction, because they are never called for
404
+ * the same reason.
405
+ *
406
+ * Returns false on anything unparseable rather than throwing — this runs inside
407
+ * an error path, and an error path that can itself throw turns a diagnosable
408
+ * failure into a mystery.
409
+ */
410
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
411
+ if (!url) return false;
412
+ let host: string;
413
+ try {
414
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
415
+ } catch {
416
+ return false;
417
+ }
418
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
419
+ return SUPABASE_PROJECT_HOST.test(host);
420
+ }
421
+
422
+ /**
423
+ * Append the marker when this failure was OUR origin failing to answer.
424
+ *
425
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
426
+ * where there is no response at all, and "the origin did not answer" is the
427
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
428
+ * registry for a slug that does not exist is the caller's argument, not our
429
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
430
+ *
431
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
432
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
433
+ */
434
+ function markInternalOrigin(
435
+ message: string,
436
+ url: string | URL | undefined | null,
437
+ status?: number,
438
+ ): string {
439
+ if (status !== undefined && status < 500) return message;
440
+ if (!isPipeworxOrigin(url)) return message;
441
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
442
+ return message + INTERNAL_ORIGIN_MARKER;
443
+ }
444
+
445
+ /**
446
+ * Which blob4 value a failure from our own web services books as, or undefined
447
+ * if this is not one.
448
+ *
449
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
450
+ * from our own Supabase is a strictly more specific statement about the same
451
+ * row (which of our services, and why), and the two cannot disagree about
452
+ * whether the failure is ours.
453
+ */
454
+ function internalHostMetricsClass(error: string): string | undefined {
455
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
456
+ }
457
+
458
+
459
+ /**
460
+ * One place to turn a failed `fetch` into an error a caller can act on.
461
+ *
462
+ * Nearly every pack was written the same way:
463
+ *
464
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
465
+ *
466
+ * which discards the response body — and the body is usually where the upstream
467
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
468
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
469
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
470
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
471
+ *
472
+ * It also hides bugs one level down. Two of the first three packs audited had a
473
+ * second defect that only existed because of this line: unsplash's rate-limit
474
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
475
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
476
+ * parsing dead code for every non-200.
477
+ *
478
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
479
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
480
+ * `error` tier is what the daily problem-tools list is built from — it means
481
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
482
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
483
+ * values into something TED rejected, and that bug was found only because it sat
484
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
485
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
486
+ * for the 481 that say nothing at all.
487
+ */
488
+
489
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
490
+ * short enough that an HTML page or a stack trace can't swamp the error. */
491
+
492
+ const MAX_DETAIL = 300;
493
+
494
+ /**
495
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
496
+ *
497
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
498
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
499
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
500
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
501
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
502
+ * fast, actionable error instead of holding the connection, and long enough
503
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
504
+ */
505
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
506
+
507
+ /**
508
+ * Read the body of a failed response and fold it into a throwable Error.
509
+ *
510
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
511
+ * change rather than a drop-in:
512
+ *
513
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
514
+ *
515
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
516
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
517
+ * something new from inside the error path.
518
+ */
519
+ async function httpError(res: Response, name: string): Promise<Error> {
520
+ return new Error(await httpErrorMessage(res, name));
521
+ }
522
+
523
+ /** The message text without constructing an Error — for packs that need to wrap
524
+ * it in their own envelope or add an explicit classification prefix. */
525
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
526
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
527
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
528
+ // about the call rather than a guess from the `name` the pack passed in —
529
+ // reword that label freely, the class does not move. See
530
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
531
+ // this touches 481 packs' error text and changes none of it.
532
+ return markInternalOrigin(
533
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
534
+ res.url,
535
+ res.status,
536
+ );
537
+ }
538
+
539
+ /**
540
+ * Just the upstream's own explanation — no name, no status.
541
+ *
542
+ * For a pack that has already said both in its own sentence. epo-ops reads
543
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
544
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
545
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
546
+ * actually said ("Not enough characters before truncation character") nowhere
547
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
548
+ * can fall back to its own wording.
549
+ */
550
+ async function upstreamDetail(res: Response): Promise<string> {
551
+ return readDetail(res);
552
+ }
553
+
554
+ /**
555
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
556
+ *
557
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
558
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
559
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
560
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
561
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
562
+ *
563
+ * That string is the problem. It names no upstream, carries no status, and
564
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
565
+ * means "we have a defect", and the caller is told nothing they can act on.
566
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
567
+ * status-code health check we own reported it green (7889a845). A zero-length
568
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
569
+ * uk-gazette (83% of external calls) and census.
570
+ *
571
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
572
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
573
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
574
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
575
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
576
+ * a statement of fact rather than a guess, and it keeps these out of the
577
+ * problem-tools list where they crowd out real defects.
578
+ *
579
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
580
+ *
581
+ * Call it only after the `!res.ok` check — on a failed response you want
582
+ * `httpError`, which mines the body for the upstream's own explanation.
583
+ */
584
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
585
+ let raw: string;
586
+ try {
587
+ raw = await res.text();
588
+ } catch {
589
+ throw new Error(
590
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
591
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
592
+ );
593
+ }
594
+
595
+ const type = res.headers.get('content-type') ?? 'no content-type';
596
+
597
+ if (!raw.trim()) {
598
+ throw new Error(
599
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
600
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
601
+ );
602
+ }
603
+
604
+ // Checked before parsing rather than in the catch, because knowing it is
605
+ // markup is what turns "we failed to parse something" into "they served a
606
+ // web page" — the second is diagnosable, the first is not.
607
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
608
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
609
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
610
+ // The summary, not the source. Pasting the first 120 characters of a web
611
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
612
+ // this branch exists to describe (fleet #712).
613
+ throw new Error(
614
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
615
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
616
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
617
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
618
+ );
619
+ }
620
+
621
+ try {
622
+ return JSON.parse(raw) as T;
623
+ } catch {
624
+ throw new Error(
625
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
626
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
627
+ );
628
+ }
629
+ }
630
+
631
+ /**
632
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
633
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
634
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
635
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
636
+ * existed — every unguarded call carries the same risk, just unconfirmed.
637
+ *
638
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
639
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
640
+ * an `upstream_down:` error that names the upstream and the bound rather than
641
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
642
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
643
+ * argument a caller passes can make an upstream hang, so it is always the
644
+ * upstream's fault, and marking it that way keeps a slow API off the
645
+ * problem-tools list where it would crowd out our own defects.
646
+ *
647
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
648
+ *
649
+ * const res = await fetchWithTimeout(url, init, 'Some API');
650
+ *
651
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
652
+ * with a known-slower upstream; the label should be the same short name you'd
653
+ * pass to `httpError`/`httpErrorMessage` for that call.
654
+ */
655
+ async function fetchWithTimeout(
656
+ url: string | URL,
657
+ init: RequestInit = {},
658
+ name: string,
659
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
660
+ ): Promise<Response> {
661
+ try {
662
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
663
+ } catch (err) {
664
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
665
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
666
+ // "appears to be degraded" is an inference about the vendor that we have
667
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
668
+ // a timeout from a Worker can equally mean OUR egress is blocked.
669
+ //
670
+ // Measured today (2026-09-01, fleet #1047): every call to
671
+ // mainnet.base.org failed from the x402 facilitator while the identical
672
+ // request from a laptop returned 200. Base was entirely healthy; the
673
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
674
+ // there it would have blamed Base by name, and the next person would have
675
+ // waited for a vendor outage to clear that did not exist.
676
+ // A timeout has no status to test — there is no response at all — so
677
+ // `markInternalOrigin` is called without one: an origin we run that never
678
+ // answered is an availability failure by definition. This is the half of
679
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
680
+ throw new Error(
681
+ markInternalOrigin(
682
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
683
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
684
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
685
+ `from elsewhere before concluding ${name} is down.`,
686
+ url,
687
+ ),
688
+ );
689
+ }
690
+ throw err;
691
+ }
692
+ }
693
+
694
+ function detailSuffix(detail: string): string {
695
+ return detail ? ` — ${detail}` : '';
696
+ }
697
+
698
+ async function readDetail(res: Response): Promise<string> {
699
+ let raw: string;
700
+ try {
701
+ raw = await res.text();
702
+ } catch {
703
+ // Body already consumed, or the connection died mid-read. The status alone
704
+ // is still worth throwing — never let the error path throw its own error.
705
+ return '';
706
+ }
707
+ return summarizeErrorBody(raw);
708
+ }
709
+
710
+ /**
711
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
712
+ * that never contains markup.
713
+ *
714
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
715
+ * that markup crowds out the status. That was half right. Dropping it loses the
716
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
717
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
718
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
719
+ * verbatim, across 11 packs, and in every one of them the useful content —
720
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
721
+ * buried in markup the agent had to parse out of a string (fleet #712).
722
+ *
723
+ * So: extract the meaning, discard the markup. The output is passed through
724
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
725
+ * assert mechanically that no caller-facing message can contain `<?xml`,
726
+ * `<!DOCTYPE` or `<html`.
727
+ */
728
+ function summarizeErrorBody(raw: string): string {
729
+ if (!raw || !raw.trim()) return '';
730
+
731
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
732
+
733
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
734
+ // redirect) says what it is in its <title>, and almost nowhere else.
735
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
736
+ const title = htmlTitle(raw);
737
+ return title
738
+ ? `${title} (upstream returned an HTML error page, not an API response)`
739
+ : 'upstream returned an HTML error page, not an API response';
740
+ }
741
+
742
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
743
+ // human sentence sits in a child element whose tag name says what it is.
744
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
745
+ const fault = xmlFaultText(raw);
746
+ return fault
747
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
748
+ : 'upstream returned an XML error document with no readable message';
749
+ }
750
+
751
+ // Most JSON error bodies bury one human sentence among ids and echoed request
752
+ // params. Prefer that sentence; fall back to the whole body when the shape is
753
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
754
+ // guess wrong and show nothing.
755
+ const fromJson = messageFromJson(raw);
756
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
757
+ }
758
+
759
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
760
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
761
+ function htmlTitle(raw: string): string | null {
762
+ const head = raw.slice(0, 4000);
763
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
764
+ const m = re.exec(head);
765
+ const text = m ? stripMarkup(m[1]) : '';
766
+ if (text) return text.slice(0, 160);
767
+ }
768
+ return null;
769
+ }
770
+
771
+ /** Tag names that carry the explanation in an XML fault document, namespace
772
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
773
+ const XML_FAULT_TAG_RE =
774
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
775
+
776
+ function xmlFaultText(raw: string): string | null {
777
+ const head = raw.slice(0, 8000);
778
+ const tagged = XML_FAULT_TAG_RE.exec(head);
779
+ if (tagged && tagged[1].trim()) return tagged[1];
780
+
781
+ // Nothing conventionally named — take the longest text node instead. A fault
782
+ // document with one sentence in an oddly named element is still readable;
783
+ // returning nothing at all is not.
784
+ let best = '';
785
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
786
+ const text = m[1].trim();
787
+ if (text.length > best.length) best = text;
788
+ }
789
+ return best || null;
790
+ }
791
+
792
+ /**
793
+ * Remove every tag and stray angle bracket, then collapse whitespace.
794
+ *
795
+ * Applied to everything on the way out, including the JSON and plain-text
796
+ * paths, because an upstream is free to embed markup in a JSON string field —
797
+ * and a leak is a leak regardless of which branch produced it.
798
+ */
799
+ function stripMarkup(s: string): string {
800
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
801
+ }
802
+
803
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
804
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
805
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
806
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
807
+ function decodeEntities(s: string): string {
808
+ return s
809
+ .replace(/&(?:amp|#0*38);/gi, '&')
810
+ .replace(/&(?:lt|#0*60);/gi, '<')
811
+ .replace(/&(?:gt|#0*62);/gi, '>')
812
+ .replace(/&(?:quot|#0*34);/gi, '"')
813
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
814
+ .replace(/&nbsp;/gi, ' ');
815
+ }
816
+
817
+ /** The conventional "what went wrong" field, under any of the names upstreams
818
+ * actually use. Checked in order; first non-empty string wins. */
819
+ const MESSAGE_KEYS = [
820
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
821
+ 'description', 'error_description', 'reason', 'title', 'fault',
822
+ ];
823
+
824
+ function messageFromJson(raw: string): string | null {
825
+ let parsed: unknown;
826
+ try {
827
+ parsed = JSON.parse(raw);
828
+ } catch {
829
+ return null;
830
+ }
831
+ return pickMessage(parsed, 0);
832
+ }
833
+
834
+ function pickMessage(node: unknown, depth: number): string | null {
835
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
836
+ // shapes that account for nearly all of them, without walking a large payload.
837
+ if (depth > 2 || node == null) return null;
838
+
839
+ if (typeof node === 'string') return node.trim() || null;
840
+
841
+ if (Array.isArray(node)) {
842
+ for (const item of node) {
843
+ const found = pickMessage(item, depth + 1);
844
+ if (found) return found;
845
+ }
846
+ return null;
847
+ }
848
+
849
+ if (typeof node !== 'object') return null;
850
+ const obj = node as Record<string, unknown>;
851
+
852
+ for (const key of MESSAGE_KEYS) {
853
+ const v = obj[key];
854
+ if (typeof v === 'string' && v.trim()) return v.trim();
855
+ }
856
+ // `{error: …}` where error is itself an object or a string — the single most
857
+ // common wrapper, so it is worth descending into by name rather than scanning
858
+ // every key and risking picking up an echoed request parameter.
859
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
860
+ if (key in obj) {
861
+ const found = pickMessage(obj[key], depth + 1);
862
+ if (found) return found;
863
+ }
864
+ }
865
+ return null;
866
+ }
867
+
868
+ /** Errors are read in a single line of log output; newlines and runs of
869
+ * whitespace make a multi-line body unreadable there. */
870
+ function collapse(s: string): string {
871
+ return s.replace(/\s+/g, ' ').trim();
872
+ }
873
+ /**
874
+ * Newswire.com MCP — press releases from Newswire's public newsroom feed.
875
+ *
876
+ * Sourced from newswire.com's own RSS feed, keyless, no account, no
877
+ * clickthrough terms (probed live 2026-09-22, HTTP 200, ~39 KB, 50 items,
878
+ * with our own User-Agent). newswire.com's robots.txt disallows only the
879
+ * per-tag feeds (`/newsroom/rss/tag/`) and asks for `Crawl-delay: 5`; the
880
+ * gateway's per-(tool,args) result cache keeps our polling far below that.
881
+ *
882
+ * WHAT NEWSWIRE.COM IS, and why it matters for ACCESS Newswire: Newswire
883
+ * (newswire.com) is an Issuer Direct property, as is ACCESS Newswire (the
884
+ * former ACCESSWIRE). Measured 2026-09-22: 12 of the 20 releases on ACCESS
885
+ * Newswire's own newsroom landing page appeared verbatim in this feed. ACCESS
886
+ * Newswire itself serves every feed path (`/users/rss`, `/rss`, `/rss.xml`,
887
+ * its sitemap index) and every article page behind a Cloudflare managed
888
+ * challenge (HTTP 403, `cf-mitigated: challenge`, "Just a moment..."), and
889
+ * its only open feeds (`/feed/rss2`, `/feed/atom`) are its corporate BLOG,
890
+ * not the wire (fleet #2286). So this feed is the closest keyless,
891
+ * machine-readable surface to that wire that exists — partial, not a mirror.
892
+ *
893
+ * COVERAGE, STATED HONESTLY: this pack reads ONE feed — `/newsroom/rss`, the
894
+ * newsroom's "Press Releases" channel (channel link co.newswire.com). It
895
+ * holds the 50 most recent releases (measured: 50 items spanning roughly a
896
+ * day) and is NOT an archive — every call re-fetches this same rolling
897
+ * window, so `search_releases` only searches what is currently in it and
898
+ * `get_release` can miss a release that has already scrolled off. The
899
+ * /feeds page lists ~650 per-beat feeds (`/newsroom/rss/beat/<slug>`), but
900
+ * every one probed returned a bare nginx 404 and the two "custom" feeds it
901
+ * lists return HTTP 410 Gone, so this pack does not enumerate them.
902
+ *
903
+ * ITEM SHAPE: title, link, guid, description (the release's own sub-headline,
904
+ * as HTML), pubDate. There is NO issuer field on this feed — the company
905
+ * name is only in the headline or sub-headline — so `issuer` is null on
906
+ * every row here, deliberately, rather than a guess parsed out of the
907
+ * headline. Search matches headline + excerpt.
908
+ *
909
+ * (`shared/src/feed-parse.ts`, fleet #2285). `newestItemAt` on every
910
+ * response is how a caller tells a quiet wire from a dead one.
911
+ */
912
+
913
+
914
+ const SOURCE = 'Newswire.com';
915
+ const FEED_URL = 'https://www.newswire.com/newsroom/rss';
916
+ const UA = 'pipeworx-mcp/1.0 (+https://pipeworx.io)';
917
+ const COVERAGE_NOTE =
918
+ "This is Newswire.com's public newsroom feed — the 50 most recent releases across every category (typically " +
919
+ 'about a day of volume). Newswire.com is an Issuer Direct wire, sibling to ACCESS Newswire, and carries a ' +
920
+ 'large share of the same releases. Every call re-fetches this same rolling window live; it is not an archive.';
921
+ const MAX_LIMIT = 50;
922
+
923
+ /**
924
+ * newswire.com RATE-LIMITS, and it is easy to trip: the pack's own live test
925
+ * suite (five feed fetches inside ~2 seconds) got HTTP 429 on the fifth
926
+ * (2026-09-22). robots.txt asks for `Crawl-delay: 5`. The gateway's result
927
+ * cache is keyed per (tool, args), so a burst of DISTINCT searches would
928
+ * re-fetch the feed once per query and hit the same wall in production. So:
929
+ *
930
+ * - one feed fetch per isolate per FEED_TTL_MS, whatever the arguments
931
+ * (module-scope memo; populated lazily at request time, never at module
932
+ * load — see reference-workers-runtime for why the latter is a trap);
933
+ * - a 429 is NOT retried (retrying a rate limit is how you extend it), and
934
+ * if a previous copy exists it is served with `stale_after_429: true`
935
+ * rather than failing the caller for a limit we caused;
936
+ * - other non-2xx are retried up to 3 attempts, as in the sibling packs.
937
+ */
938
+ const FEED_TTL_MS = 60_000;
939
+ let memo: { xml: string; at: number } | null = null;
940
+
941
+ async function nwFetch(): Promise<{ xml: string; via: string; stale_after_429?: true }> {
942
+ if (memo && Date.now() - memo.at < FEED_TTL_MS) return { xml: memo.xml, via: FEED_URL };
943
+ let res: Response | null = null;
944
+ for (let attempt = 0; attempt < 3; attempt++) {
945
+ res = await fetchWithTimeout(FEED_URL, { headers: { 'User-Agent': UA, Accept: 'application/rss+xml, application/xml, text/xml, */*' } }, SOURCE);
946
+ if (res.ok || res.status === 429) break;
947
+ }
948
+ if (res && res.status === 429) {
949
+ if (memo) return { xml: memo.xml, via: FEED_URL, stale_after_429: true };
950
+ throw new Error(
951
+ `upstream_down: ${SOURCE} answered HTTP 429 (rate limited) for its RSS feed. newswire.com asks for a 5-second ` +
952
+ 'crawl delay; wait a minute and retry — this pack caches the feed for 60s per instance to stay under it.',
953
+ );
954
+ }
955
+ if (!res || !res.ok) throw new Error(`upstream_down: ${SOURCE} answered HTTP ${res?.status} for its RSS feed (after 3 attempts).`);
956
+ const xml = await res.text();
957
+ if (!/<item[\s>]/i.test(xml)) {
958
+ throw new Error(
959
+ `upstream_down: ${SOURCE} answered HTTP ${res.status} with no <item> elements (${xml.length} bytes) — ` +
960
+ 'the feed may be temporarily empty or its shape has changed.',
961
+ );
962
+ }
963
+ memo = { xml, at: Date.now() };
964
+ return { xml, via: FEED_URL };
965
+ }
966
+
967
+ interface Release {
968
+ headline: string;
969
+ /** Always null: this feed carries no issuer field (see header). */
970
+ issuer: null;
971
+ url: string;
972
+ canonical_url: string | null;
973
+ published_at?: string;
974
+ excerpt?: string;
975
+ }
976
+
977
+ function toReleases(xml: string): { releases: Release[]; newestItemAt: string | null } {
978
+ const parsed = parseFeed(xml);
979
+ const releases: Release[] = parsed.items.map((item) => ({
980
+ headline: item.title,
981
+ issuer: null,
982
+ url: item.link,
983
+ canonical_url: canonicalUrl(item.link),
984
+ published_at: item.publishedAt,
985
+ // The description is the sub-headline as entity-escaped HTML
986
+ // (&lt;p&gt;&lt;i&gt;&lt;strong&gt;…); parseFeed decodes the entities but
987
+ // the tags survive, so strip them here.
988
+ excerpt: item.excerpt ? item.excerpt.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim() || undefined : undefined,
989
+ }));
990
+ return { releases, newestItemAt: parsed.newestItemAt };
991
+ }
992
+
993
+ const tools: McpToolExport['tools'] = [
994
+ {
995
+ name: 'newswire_com_latest_releases',
996
+ description:
997
+ "Latest press releases from Newswire.com's public newsroom RSS feed (source: newswire.com, an Issuer Direct " +
998
+ 'wire that shares many releases with ACCESS Newswire). Returns headline, published time and sub-headline ' +
999
+ "excerpt for each release, newest first. Covers the 50 most recent releases — not Newswire.com's full archive.",
1000
+ inputSchema: {
1001
+ type: 'object' as const,
1002
+ properties: {
1003
+ since_hours: { type: 'number', description: 'Only return releases published within the last N hours (optional).' },
1004
+ limit: { type: 'number', description: `Max releases to return, 1-${MAX_LIMIT} (default 20).` },
1005
+ },
1006
+ },
1007
+ },
1008
+ {
1009
+ name: 'newswire_com_search_releases',
1010
+ description:
1011
+ "Keyword/company search over Newswire.com's current newsroom feed (source: newswire.com). Matches against " +
1012
+ 'headline and sub-headline excerpt. Searches only the live rolling 50-item window each call — not a ' +
1013
+ 'historical archive.',
1014
+ inputSchema: {
1015
+ type: 'object' as const,
1016
+ properties: {
1017
+ query: { type: 'string', description: 'Company name or keyword to match.' },
1018
+ limit: { type: 'number', description: `Max matches to return, 1-${MAX_LIMIT} (default 20).` },
1019
+ },
1020
+ required: ['query'],
1021
+ },
1022
+ },
1023
+ {
1024
+ name: 'newswire_com_get_release',
1025
+ description:
1026
+ 'Fetch one specific Newswire.com release by its URL (source: newswire.com), as returned by ' +
1027
+ 'newswire_com_latest_releases or newswire_com_search_releases. Re-fetches the live feed each call — a ' +
1028
+ 'release that has scrolled off the current 50-item window will not be found.',
1029
+ inputSchema: {
1030
+ type: 'object' as const,
1031
+ properties: {
1032
+ url: { type: 'string', description: 'The release URL (from a prior newswire_com tool call).' },
1033
+ },
1034
+ required: ['url'],
1035
+ },
1036
+ },
1037
+ ];
1038
+
1039
+ async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
1040
+ switch (name) {
1041
+ case 'newswire_com_latest_releases': {
1042
+ const { xml, via, stale_after_429 } = await nwFetch();
1043
+ const { releases, newestItemAt } = toReleases(xml);
1044
+ let out = releases;
1045
+ const sinceHours = numArg(args.since_hours);
1046
+ if (sinceHours != null) {
1047
+ const cutoff = Date.now() - sinceHours * 3_600_000;
1048
+ out = out.filter((r) => r.published_at && Date.parse(r.published_at) >= cutoff);
1049
+ }
1050
+ const limit = clamp(numArg(args.limit) ?? 20, 1, MAX_LIMIT);
1051
+ return {
1052
+ source: SOURCE,
1053
+ feed_url: via,
1054
+ coverage: COVERAGE_NOTE,
1055
+ newest_item_at: newestItemAt,
1056
+ ...(stale_after_429 ? { stale_after_429 } : {}),
1057
+ count: Math.min(out.length, limit),
1058
+ total_in_window: releases.length,
1059
+ releases: out.slice(0, limit),
1060
+ };
1061
+ }
1062
+ case 'newswire_com_search_releases': {
1063
+ const query = String(args.query ?? '').trim();
1064
+ if (!query) throw new Error('user_error: Pass a non-empty `query` (company name or keyword).');
1065
+ const { xml, stale_after_429 } = await nwFetch();
1066
+ const { releases, newestItemAt } = toReleases(xml);
1067
+ const q = query.toLowerCase();
1068
+ const matches = releases.filter((r) => r.headline.toLowerCase().includes(q) || (r.excerpt ?? '').toLowerCase().includes(q));
1069
+ const limit = clamp(numArg(args.limit) ?? 20, 1, MAX_LIMIT);
1070
+ return {
1071
+ source: SOURCE,
1072
+ coverage: COVERAGE_NOTE,
1073
+ newest_item_at: newestItemAt,
1074
+ ...(stale_after_429 ? { stale_after_429 } : {}),
1075
+ query,
1076
+ scanned: releases.length,
1077
+ count: Math.min(matches.length, limit),
1078
+ releases: matches.slice(0, limit),
1079
+ };
1080
+ }
1081
+ case 'newswire_com_get_release': {
1082
+ const url = String(args.url ?? '').trim();
1083
+ if (!url) throw new Error('user_error: Pass the release `url` from a prior newswire_com tool call.');
1084
+ const target = canonicalUrl(url) ?? url;
1085
+ const { xml, stale_after_429 } = await nwFetch();
1086
+ const { releases, newestItemAt } = toReleases(xml);
1087
+ const hit = releases.find((r) => r.canonical_url === target || r.url === url);
1088
+ if (!hit) {
1089
+ throw new Error(
1090
+ "user_error: Not found in the current feed window (Newswire.com's newsroom feed keeps the last 50 " +
1091
+ 'releases). This tool re-fetches the live feed on every call; a release scrolls off within about a day ' +
1092
+ 'at typical wire volume. Call newswire_com_latest_releases or newswire_com_search_releases first to get ' +
1093
+ 'a URL still in the window.',
1094
+ );
1095
+ }
1096
+ return { source: SOURCE, coverage: COVERAGE_NOTE, newest_item_at: newestItemAt, ...(stale_after_429 ? { stale_after_429 } : {}), release: hit };
1097
+ }
1098
+ default:
1099
+ throw new Error(`Unknown tool: ${name}`);
1100
+ }
1101
+ }
1102
+
1103
+ function numArg(v: unknown): number | null {
1104
+ const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN;
1105
+ return Number.isFinite(n) ? n : null;
1106
+ }
1107
+ function clamp(n: number, lo: number, hi: number): number {
1108
+ return Math.max(lo, Math.min(hi, Math.round(n)));
1109
+ }
1110
+
1111
+ export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;