@pipeworx/mcp-meetup 0.1.0 → 0.2.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 DELETED
@@ -1,1274 +0,0 @@
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
- * Place name -> coordinates, ranked so the answer is the city the asker meant.
29
- *
30
- * Extracted 2026-08-04 after the SAME defect was found in four packs in three
31
- * days (weather, open-meteo, openaq, openchargemap). Every one of them called
32
- * Open-Meteo's geocoder with `count=1` (or took `results[0]`) under a comment
33
- * asserting the upstream ranks by relevance and population. **That comment is
34
- * false.** Open-Meteo returns exact-name matches in no useful order, so a
35
- * 3,218-person Romanian village named Roma outranks Rome.
36
- *
37
- * Two things make this correct, and the second is the one that surprises people:
38
- *
39
- * 1. RANK BY POPULATION, with a feature-code boost to break ties when the
40
- * population field is thin or zero.
41
- * 2. RETRY IN OTHER LANGUAGES. Sorting alone is NOT enough. Verified live:
42
- * for `name=Roma&language=en`, Rome is ABSENT from the result set entirely
43
- * (the two Roma/IT rows are population 87 and 33), so a population sort
44
- * moves the answer from Roma, Romania to Roma, LESOTHO — still wrong.
45
- * `language=it` returns Roma, IT at 2,318,895. Endonyms live under the
46
- * local language, so when the English answer looks like nowhere we widen.
47
- *
48
- * The extra requests only happen when the first answer looks weak, so the
49
- * common case ("Chicago") still costs exactly one call.
50
- */
51
-
52
- const GEOCODE_URL = 'https://geocoding-api.open-meteo.com/v1/search';
53
-
54
- /** Languages tried when the English answer looks like nowhere. Ordered by how
55
- * often a major world city hides behind its endonym (Roma, München, Köln,
56
- * Sevilla, Lisboa). */
57
- const EXONYM_LANGS = ['it', 'es', 'de', 'fr', 'pt'] as const;
58
-
59
- /** Population is the primary signal. These only lift real administrative places
60
- * above same-named villages when population data is thin or zero.
61
- * PPLC = national capital, PPLA = first-order admin seat, and so on.
62
- *
63
- * Fleet #111 (2026-08-06): these were 50x too big — PPLA's flat +1,000,000
64
- * outweighed San Francisco CA's real 811K-person lead over San Francisco,
65
- * Morazan, El Salvador (pop 16,152), so the department capital won on
66
- * feature-code alone. Scaled down so the boost can still break a genuine
67
- * thin/zero-population tie (a real capital vs an unrelated small hamlet)
68
- * but can never overturn a population gap in the tens-of-thousands or up —
69
- * which is every case that actually distinguishes a major city from a
70
- * same-named foreign administrative seat. */
71
- const FEATURE_BOOST: Record<string, number> = {
72
- PPLC: 100_000, PPLA: 20_000, PPLA2: 4_000, PPLA3: 800,
73
- };
74
-
75
- interface GeoHit {
76
- name?: string;
77
- admin1?: string;
78
- country?: string;
79
- country_code?: string;
80
- latitude: number;
81
- longitude: number;
82
- population?: number;
83
- feature_code?: string;
84
- }
85
-
86
- interface ResolvedPlace {
87
- name: string;
88
- admin1: string | null;
89
- /** Full country name (e.g. "United States") as Open-Meteo returns it —
90
- * added migrating mcps/weather onto this module, which surfaces the full
91
- * name in tool output and keys a US-vs-not check off it (fleet #74). */
92
- country: string | null;
93
- country_code: string | null;
94
- latitude: number;
95
- longitude: number;
96
- population: number | null;
97
- /** What we searched to find it — surfaced so a caller can SEE that "Roma"
98
- * was resolved via Italian, rather than wonder why it worked. */
99
- matched_language: string;
100
- }
101
-
102
- function geoScore(r: GeoHit): number {
103
- return (r.population ?? 0) + (FEATURE_BOOST[r.feature_code ?? ''] ?? 0);
104
- }
105
-
106
- function bestOf(results: GeoHit[]): GeoHit | undefined {
107
- return results.length ? results.reduce((a, b) => (geoScore(b) > geoScore(a) ? b : a)) : undefined;
108
- }
109
-
110
- /**
111
- * "No real city found here."
112
- *
113
- * Deliberately reads RAW population, not geoScore. The feature boost exists to
114
- * break ties during ranking; letting it feed this decision made a 3,218-person
115
- * PPLA2 town in Romania look strong enough to suppress the very fan-out that
116
- * finds Rome. Boost ranks; population decides whether to keep looking.
117
- */
118
- function looksWeak(hit: GeoHit | undefined): boolean {
119
- return !hit || (hit.population ?? 0) < 50_000;
120
- }
121
-
122
- async function search(name: string, language: string, count: number): Promise<GeoHit[]> {
123
- const url = `${GEOCODE_URL}?name=${encodeURIComponent(name)}&count=${count}&language=${language}&format=json`;
124
- const res = await fetch(url, { headers: { Accept: 'application/json' } });
125
- if (!res.ok) throw new Error(`Geocoding service error (HTTP ${res.status}) resolving "${name}".`);
126
- const data = (await res.json()) as { results?: GeoHit[] };
127
- return (data.results ?? []).filter(
128
- (r) => typeof r?.latitude === 'number' && typeof r?.longitude === 'number',
129
- );
130
- }
131
-
132
- function toResolved(hit: GeoHit, fallbackName: string, lang: string): ResolvedPlace {
133
- return {
134
- name: hit.name ?? fallbackName,
135
- admin1: hit.admin1 ?? null,
136
- country: hit.country ?? null,
137
- country_code: hit.country_code ?? null,
138
- latitude: hit.latitude,
139
- longitude: hit.longitude,
140
- population: typeof hit.population === 'number' ? hit.population : null,
141
- matched_language: lang,
142
- };
143
- }
144
-
145
- /**
146
- * Resolve one place name to the most plausible real city.
147
- *
148
- * `language` is the caller's preferred language; other languages are only tried
149
- * when the best hit so far looks weak.
150
- */
151
- async function resolvePlace(
152
- name: string,
153
- opts: { language?: string; count?: number } = {},
154
- ): Promise<ResolvedPlace | null> {
155
- const lang = opts.language ?? 'en';
156
- // At least 10 candidates: with count=1 there is nothing to rank, which is how
157
- // every instance of this bug shipped.
158
- const count = Math.max(10, opts.count ?? 10);
159
-
160
- const seen = new Map<string, string>(); // hit key -> language it came from
161
- const key = (h: GeoHit) => `${h.latitude},${h.longitude}`;
162
- let pool: GeoHit[] = [];
163
- const absorb = (hits: GeoHit[], viaLang: string) => {
164
- for (const h of hits) if (!seen.has(key(h))) { seen.set(key(h), viaLang); pool.push(h); }
165
- };
166
-
167
- absorb(await search(name, lang, count), lang);
168
- if (!pool.length && lang !== 'en') absorb(await search(name, 'en', count), 'en');
169
-
170
- if (looksWeak(bestOf(pool))) {
171
- for (const alt of EXONYM_LANGS) {
172
- if (alt === lang) continue;
173
- absorb(await search(name, alt, count), alt);
174
- if (!looksWeak(bestOf(pool))) break;
175
- }
176
- }
177
-
178
- let hit = bestOf(pool);
179
- // Open-Meteo matches on the bare place name and returns nothing for
180
- // "City, ST" / "City, State" — but routers routinely produce exactly that
181
- // ("Des Moines, IA"). Retry with the city part before giving up.
182
- if (!hit && name.includes(',')) {
183
- const city = name.split(',')[0]!.trim();
184
- if (city && city.toLowerCase() !== name.toLowerCase()) {
185
- const retry = await search(city, 'en', count);
186
- absorb(retry, 'en');
187
- hit = bestOf(retry);
188
- }
189
- }
190
- return hit ? toResolved(hit, name, seen.get(key(hit)) ?? lang) : null;
191
- }
192
-
193
- /**
194
- * Ranked RAW hits, best first — for packs that must keep the upstream's own
195
- * response shape (open-meteo's `geocode` returns Open-Meteo objects verbatim,
196
- * and normalising them would be a breaking change for its callers).
197
- *
198
- * Same two-part algorithm as resolvePlace: rank by population+boost, and widen
199
- * across endonym languages only when the best hit still looks weak.
200
- */
201
- async function rankedPlaceHits(
202
- name: string,
203
- opts: { language?: string; count?: number } = {},
204
- ): Promise<GeoHit[]> {
205
- const lang = opts.language ?? 'en';
206
- const count = Math.max(10, opts.count ?? 10);
207
- const seen = new Set<string>();
208
- const pool: GeoHit[] = [];
209
- const key = (h: GeoHit) => `${h.latitude},${h.longitude}`;
210
- const absorb = (hits: GeoHit[]) => {
211
- for (const h of hits) if (!seen.has(key(h))) { seen.add(key(h)); pool.push(h); }
212
- };
213
-
214
- absorb(await search(name, lang, count));
215
- if (!pool.length && lang !== 'en') absorb(await search(name, 'en', count));
216
- if (looksWeak(bestOf(pool))) {
217
- for (const alt of EXONYM_LANGS) {
218
- if (alt === lang) continue;
219
- absorb(await search(name, alt, count));
220
- if (!looksWeak(bestOf(pool))) break;
221
- }
222
- }
223
- if (!pool.length && name.includes(',')) {
224
- const city = name.split(',')[0]!.trim();
225
- if (city && city.toLowerCase() !== name.toLowerCase()) absorb(await search(city, 'en', count));
226
- }
227
- return pool.sort((a, b) => geoScore(b) - geoScore(a));
228
- }
229
-
230
- /** Ranked candidates, best first — for packs that offer alternatives. */
231
- async function resolvePlaceCandidates(
232
- name: string,
233
- opts: { language?: string; count?: number; limit?: number } = {},
234
- ): Promise<ResolvedPlace[]> {
235
- const best = await resolvePlace(name, opts);
236
- if (!best) return [];
237
- const lang = best.matched_language;
238
- const hits = await search(name, lang, Math.max(10, opts.count ?? 10));
239
- const ranked = [...hits].sort((a, b) => geoScore(b) - geoScore(a));
240
- const out = ranked.map((h) => toResolved(h, name, lang));
241
- // Guarantee the chosen answer leads, even if it came from a different
242
- // language pass than the one we just re-queried.
243
- if (!out.length || out[0]!.latitude !== best.latitude || out[0]!.longitude !== best.longitude) {
244
- out.unshift(best);
245
- }
246
- return out.slice(0, opts.limit ?? 5);
247
- }
248
-
249
-
250
- /**
251
- * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
252
- *
253
- * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
254
- * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
255
- * covered the majority and structurally could not cover the rest: the rest
256
- * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
257
- * the 24h to 2026-09-02T15:00Z (fleet #1096):
258
- *
259
- * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
260
- * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
261
- *
262
- * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
263
- * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
264
- * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
265
- * our own Supabase for fleet. There is no third party anywhere in either call.
266
- * Same defect as #1089: our own outage filed under `upstream_down`, the one
267
- * class that means "the source is unreachable and there is nothing for us to
268
- * fix", which is why the problem-tools triage skips it.
269
- *
270
- * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
271
- * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
272
- * one site today, so it would work today. It would also rot the first time
273
- * somebody rewords a label — silently, and in the direction of hiding our own
274
- * outage, which is worse than the bug being fixed. Every prose rule in
275
- * error-class.ts has needed widening as packs invented new wording (#409/#450/
276
- * #584); that history is most of that file's comment budget.
277
- *
278
- * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
279
- * hostname is a fact about the call, not a guess about its prose. Two
280
- * consequences that a pack-level flag could not give us, and the reason the
281
- * flag was rejected:
282
- *
283
- * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
284
- * Supabase AND to genuine third parties; `court-listener` holds our cache
285
- * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
286
- * either pack would relabel a real third-party outage as ours — inventing
287
- * work, which is the same class of error in the opposite direction.
288
- * - It covers every future internal pack for free, instead of one declared
289
- * slug at a time.
290
- *
291
- * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
292
- * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
293
- * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
294
- * this module — so changing the wording changes both sides in the same edit and
295
- * cannot desynchronise them. The pack's own label (`fleet db error:`,
296
- * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
297
- * unaffected. That is the property `stripClassPrefix` lacked when it drifted
298
- * from its own classifier three times and needed a CI gate to hold them
299
- * together.
300
- *
301
- * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
302
- * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
303
- * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
304
- * availability failure" is decided from the actual status code, never re-derived
305
- * by scraping a number out of a sentence. A 404 from our own registry for a slug
306
- * that does not exist is a caller's bad argument and is deliberately NOT marked.
307
- */
308
-
309
- /**
310
- * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
311
- *
312
- * ONE value, not three, unlike `internal_db_*`. That split existed because a
313
- * slow query, an exhausted pool and an unknown SQLSTATE have different owners
314
- * and different fixes. Here there is only one story to tell — an origin we run
315
- * did not answer the edge — and one owner. A bucket with no distinct owner per
316
- * value is decoration; #724 is what happens when a class holds several
317
- * situations, and inventing sub-values ahead of a reason to act on them
318
- * differently is the same mistake with the sign flipped.
319
- *
320
- * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
321
- * values. `classifyToolError` still answers `upstream_down` for the retry and
322
- * hint paths, which only care whether retrying or a sibling tool might work —
323
- * and it might. Nothing a caller sees or is charged changes here.
324
- *
325
- * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
326
- * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
327
- * lands on no dashboard — fleet #721 is the warning, where the #719 split
328
- * worked on the write side and was invisible for weeks.
329
- */
330
- const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
331
-
332
- /**
333
- * The token that carries "this origin is ours" from the call site to the
334
- * classifier.
335
- *
336
- * Appended to the error message rather than attached to the Error object,
337
- * because the object does not survive the trip: 275 packs return `{ error:
338
- * string }` instead of throwing, the gateway reads `observedError` as a string,
339
- * and the fleet pack rebuilds its error from a captured status + body across a
340
- * retry loop. A property on an Error would be dropped by every one of those
341
- * paths and the class would work in tests and vanish in production.
342
- *
343
- * WORDING IS LOAD-BEARING, same rule as labelAge's note in authority.ts. This
344
- * string is appended to a pack's thrown Error message (shared/src/http.ts),
345
- * and a thrown Error's message is exactly what the gateway hands back to the
346
- * caller as `content[0].text` when nothing rewrites it (workers/gateway/src
347
- * catches the throw and sets `rawResult.message = stripClassPrefix(error)`,
348
- * which does not touch this suffix) — so the original wording,
349
- * " [pipeworx-hosted origin — our own service, not a third party]", was not a
350
- * theoretical leak: it shipped live on pipeworx-catalog's 522s, 7 times in 6
351
- * hours on 2026-09-02 (see tests/golden-internal-service.test.ts), verbatim
352
- * naming Pipeworx as the host. check:hosting-claims never caught it because it
353
- * did not scan shared/ at all (task #2009). Reworded to describe the
354
- * OBSERVATION (the origin did not answer) without a claim about who runs it —
355
- * the identical fix labelAge got: drop the possessive, keep the fact.
356
- */
357
- const INTERNAL_ORIGIN_MARKER = ' [origin did not respond — retry before concluding the named source is down]';
358
-
359
- /**
360
- * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
361
- * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
362
- *
363
- * Matching the shape rather than listing the ref keeps this correct when we add
364
- * a project — `supabaseEnv` on a pack entry already points some packs at a
365
- * second one — while still excluding `status.supabase.co`, which is Supabase's
366
- * own status page and emphatically not our database. Verified 2026-09-02 by
367
- * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
368
- * only real project ref anywhere in the tree is ours, the rest are doc
369
- * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
370
- * finding internal-db-class.ts relies on for the PostgREST envelope being ours
371
- * by construction.
372
- */
373
- const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
374
-
375
- /**
376
- * Is this a host WE run?
377
- *
378
- * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
379
- * hosted on workers.dev, so the suffix says where something runs and not who
380
- * owns it. Every internal call we actually make goes to a `pipeworx.io`
381
- * hostname or to our Supabase project, both of which are ownership facts.
382
- *
383
- * `workers/gateway/src/provenance.ts`'s `OUR_HOSTS` answers the same
384
- * question and DOES include `workers.dev` — a documented divergence
385
- * (task #2051), not a bug to converge. That list decides what a response may
386
- * cite as a data SOURCE, where a false negative (citing our own worker as an
387
- * external source) is the hosting-disclosure leak this whole file exists to
388
- * prevent, so it errs broad. This one decides who gets BLAMED for a 5xx in
389
- * outage metrics read by on-call, where a false positive (crediting our own
390
- * infra with a third party's outage) hides the real failure, so it errs
391
- * narrow. Same suffix, opposite direction, because they are never called for
392
- * the same reason.
393
- *
394
- * Returns false on anything unparseable rather than throwing — this runs inside
395
- * an error path, and an error path that can itself throw turns a diagnosable
396
- * failure into a mystery.
397
- */
398
- function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
399
- if (!url) return false;
400
- let host: string;
401
- try {
402
- host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
403
- } catch {
404
- return false;
405
- }
406
- if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
407
- return SUPABASE_PROJECT_HOST.test(host);
408
- }
409
-
410
- /**
411
- * Append the marker when this failure was OUR origin failing to answer.
412
- *
413
- * `status` is the HTTP status when there is one, and omitted for a timeout —
414
- * where there is no response at all, and "the origin did not answer" is the
415
- * whole observation. Statuses below 500 are left alone: a 404 from our own
416
- * registry for a slug that does not exist is the caller's argument, not our
417
- * outage, and marking it would put ordinary 404s on the incident dashboard.
418
- *
419
- * Idempotent, so a message that is wrapped and re-marked on the way up (the
420
- * fleet pack's retry loop re-throws through two layers) carries the marker once.
421
- */
422
- function markInternalOrigin(
423
- message: string,
424
- url: string | URL | undefined | null,
425
- status?: number,
426
- ): string {
427
- if (status !== undefined && status < 500) return message;
428
- if (!isPipeworxOrigin(url)) return message;
429
- if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
430
- return message + INTERNAL_ORIGIN_MARKER;
431
- }
432
-
433
- /**
434
- * Which blob4 value a failure from our own web services books as, or undefined
435
- * if this is not one.
436
- *
437
- * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
438
- * from our own Supabase is a strictly more specific statement about the same
439
- * row (which of our services, and why), and the two cannot disagree about
440
- * whether the failure is ours.
441
- */
442
- function internalHostMetricsClass(error: string): string | undefined {
443
- return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
444
- }
445
-
446
-
447
- /**
448
- * One place to turn a failed `fetch` into an error a caller can act on.
449
- *
450
- * Nearly every pack was written the same way:
451
- *
452
- * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
453
- *
454
- * which discards the response body — and the body is usually where the upstream
455
- * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
456
- * out of range", "unknown taxonomy id"). The caller gets a number, cannot
457
- * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
458
- * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
459
- *
460
- * It also hides bugs one level down. Two of the first three packs audited had a
461
- * second defect that only existed because of this line: unsplash's rate-limit
462
- * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
463
- * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
464
- * parsing dead code for every non-200.
465
- *
466
- * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
467
- * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
468
- * `error` tier is what the daily problem-tools list is built from — it means
469
- * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
470
- * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
471
- * values into something TED rejected, and that bug was found only because it sat
472
- * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
473
- * A pack that KNOWS which it is should keep saying so explicitly; this helper is
474
- * for the 481 that say nothing at all.
475
- */
476
-
477
- /** Longest upstream explanation we'll pass through. Enough for a real message,
478
- * short enough that an HTML page or a stack trace can't swamp the error. */
479
-
480
- const MAX_DETAIL = 300;
481
-
482
- /**
483
- * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
484
- *
485
- * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
486
- * a degraded upstream that doesn't error, it just never answers, and a Worker
487
- * sits in `await fetch()` until ITS OWN execution budget kills the request —
488
- * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
489
- * MINUTE hangs before this existed). 25s is short enough that a caller gets a
490
- * fast, actionable error instead of holding the connection, and long enough
491
- * that it doesn't false-trip on a merely-slow-but-alive upstream.
492
- */
493
- const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
494
-
495
- /**
496
- * Read the body of a failed response and fold it into a throwable Error.
497
- *
498
- * Usage — note the `await`, which is the one thing that makes this a mechanical
499
- * change rather than a drop-in:
500
- *
501
- * if (!res.ok) throw await httpError(res, 'Unsplash');
502
- *
503
- * Safe to call on any non-ok response: a body that is missing, empty, unreadable
504
- * or HTML degrades to exactly the old `Name: 404` string rather than throwing
505
- * something new from inside the error path.
506
- */
507
- async function httpError(res: Response, name: string): Promise<Error> {
508
- return new Error(await httpErrorMessage(res, name));
509
- }
510
-
511
- /** The message text without constructing an Error — for packs that need to wrap
512
- * it in their own envelope or add an explicit classification prefix. */
513
- async function httpErrorMessage(res: Response, name: string): Promise<string> {
514
- // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
515
- // the URL the fetch actually resolved to (after redirects), so this is a fact
516
- // about the call rather than a guess from the `name` the pack passed in —
517
- // reword that label freely, the class does not move. See
518
- // internal-host-class.ts; no-op for every third-party upstream, which is why
519
- // this touches 481 packs' error text and changes none of it.
520
- return markInternalOrigin(
521
- `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
522
- res.url,
523
- res.status,
524
- );
525
- }
526
-
527
- /**
528
- * Just the upstream's own explanation — no name, no status.
529
- *
530
- * For a pack that has already said both in its own sentence. epo-ops reads
531
- * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
532
- * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
533
- * dropped: the upstream named twice, the status twice, and the one thing EPO
534
- * actually said ("Not enough characters before truncation character") nowhere
535
- * (fleet #712). Returns '' when the body carries nothing readable, so a caller
536
- * can fall back to its own wording.
537
- */
538
- async function upstreamDetail(res: Response): Promise<string> {
539
- return readDetail(res);
540
- }
541
-
542
- /**
543
- * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
544
- *
545
- * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
546
- * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
547
- * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
548
- * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
549
- * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
550
- *
551
- * That string is the problem. It names no upstream, carries no status, and
552
- * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
553
- * means "we have a defect", and the caller is told nothing they can act on.
554
- * data.govt.nz sat dead behind an Imperva challenge this way and every
555
- * status-code health check we own reported it green (7889a845). A zero-length
556
- * body has the same shape: `Unexpected end of JSON input`, seen this week on
557
- * uk-gazette (83% of external calls) and census.
558
- *
559
- * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
560
- * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
561
- * query we built wrong — so blanket-classifying it would hide our own bugs.
562
- * There is no such ambiguity here: **no argument a caller can pass makes a JSON
563
- * API return an HTML page.** It is always the upstream, so `upstream_down:` is
564
- * a statement of fact rather than a guess, and it keeps these out of the
565
- * problem-tools list where they crowd out real defects.
566
- *
567
- * const data = await parseJson<Feed>(res, 'UK Gazette');
568
- *
569
- * Call it only after the `!res.ok` check — on a failed response you want
570
- * `httpError`, which mines the body for the upstream's own explanation.
571
- */
572
- async function parseJson<T>(res: Response, name: string): Promise<T> {
573
- let raw: string;
574
- try {
575
- raw = await res.text();
576
- } catch {
577
- throw new Error(
578
- `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
579
- 'The connection most likely dropped mid-response; retrying is reasonable.',
580
- );
581
- }
582
-
583
- const type = res.headers.get('content-type') ?? 'no content-type';
584
-
585
- if (!raw.trim()) {
586
- throw new Error(
587
- `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
588
- 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
589
- );
590
- }
591
-
592
- // Checked before parsing rather than in the catch, because knowing it is
593
- // markup is what turns "we failed to parse something" into "they served a
594
- // web page" — the second is diagnosable, the first is not.
595
- const head = raw.slice(0, 200).trimStart().toLowerCase();
596
- if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
597
- const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
598
- // The summary, not the source. Pasting the first 120 characters of a web
599
- // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
600
- // this branch exists to describe (fleet #712).
601
- throw new Error(
602
- `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
603
- 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
604
- `so status-code health checks read it as fine. No argument change will get past it. ` +
605
- `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
606
- );
607
- }
608
-
609
- try {
610
- return JSON.parse(raw) as T;
611
- } catch {
612
- throw new Error(
613
- `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
614
- `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
615
- );
616
- }
617
- }
618
-
619
- /**
620
- * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
621
- * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
622
- * `fetch()` with NO timeout guard anywhere in the file. Two of those
623
- * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
624
- * existed — every unguarded call carries the same risk, just unconfirmed.
625
- *
626
- * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
627
- * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
628
- * an `upstream_down:` error that names the upstream and the bound rather than
629
- * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
630
- * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
631
- * argument a caller passes can make an upstream hang, so it is always the
632
- * upstream's fault, and marking it that way keeps a slow API off the
633
- * problem-tools list where it would crowd out our own defects.
634
- *
635
- * Usage — a mechanical swap for a bare `fetch(url, init)`:
636
- *
637
- * const res = await fetchWithTimeout(url, init, 'Some API');
638
- *
639
- * Pass `timeoutMs` as a fourth argument to override the default for a pack
640
- * with a known-slower upstream; the label should be the same short name you'd
641
- * pass to `httpError`/`httpErrorMessage` for that call.
642
- */
643
- async function fetchWithTimeout(
644
- url: string | URL,
645
- init: RequestInit = {},
646
- name: string,
647
- timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
648
- ): Promise<Response> {
649
- try {
650
- return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
651
- } catch (err) {
652
- if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
653
- // States the OBSERVATION (no response in N seconds), not a diagnosis.
654
- // "appears to be degraded" is an inference about the vendor that we have
655
- // not checked, and it is wrong in a way that misdirects whoever reads it:
656
- // a timeout from a Worker can equally mean OUR egress is blocked.
657
- //
658
- // Measured today (2026-09-01, fleet #1047): every call to
659
- // mainnet.base.org failed from the x402 facilitator while the identical
660
- // request from a laptop returned 200. Base was entirely healthy; the
661
- // public RPC refuses Cloudflare Worker egress. Had this message fired
662
- // there it would have blamed Base by name, and the next person would have
663
- // waited for a vendor outage to clear that did not exist.
664
- // A timeout has no status to test — there is no response at all — so
665
- // `markInternalOrigin` is called without one: an origin we run that never
666
- // answered is an availability failure by definition. This is the half of
667
- // fleet #1096 with neither a SQLSTATE nor a status code to key on.
668
- throw new Error(
669
- markInternalOrigin(
670
- `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
671
- `That can be ${name} being slow or down, or this environment being unable to reach it ` +
672
- `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
673
- `from elsewhere before concluding ${name} is down.`,
674
- url,
675
- ),
676
- );
677
- }
678
- // Fleet #2382. Everything that isn't a timeout/abort here is a genuine
679
- // NETWORK-LEVEL failure — DNS resolution, connection refused, TLS handshake,
680
- // Cloudflare's own "Network connection lost." — meaning `fetch()` itself
681
- // threw and no HTTP response of any kind was ever received. Until this fix
682
- // that raw exception was rethrown VERBATIM: a bare `TypeError: fetch failed`
683
- // (or the Workers-runtime equivalent) names no upstream, carries no class
684
- // token, and reads exactly like a defect in OUR code — because it says
685
- // nothing about the call at all. It landed in `error`, the tier that means
686
- // "Pipeworx has a defect", for every one of the (at the time of writing)
687
- // ~470 packs that call this helper directly with no wrapper of their own.
688
- //
689
- // `dexscreener` hit this independently (fleet #1579) and fixed it with a
690
- // bespoke per-pack try/catch around `fetchWithTimeout`. That fix is correct
691
- // but only covers one pack; every other caller of this shared helper still
692
- // leaked the raw exception. Moving the same fix HERE — the one place that
693
- // already carries the timeout case — covers every pack that uses
694
- // `fetchWithTimeout` without a wrapper, for free, and without widening
695
- // `classifyToolError`'s regex list: the fix is giving the message a proper
696
- // `upstream_down:` token at the point the two facts (no response was ever
697
- // received, and which host we were trying to reach) are actually in hand,
698
- // not teaching the classifier to guess from prose after the fact.
699
- //
700
- // Safe on the same grounds as the timeout branch above: no argument a
701
- // caller passes can make `fetch()` itself throw a connection-level error,
702
- // so this is always an availability failure, never a caller mistake. Same
703
- // `markInternalOrigin` treatment — an origin we run that never answered is
704
- // still ours, not a third party's outage.
705
- const raw = err instanceof Error ? err.message : String(err);
706
- throw new Error(
707
- markInternalOrigin(
708
- `upstream_down: could not reach ${name} at all (${raw.slice(0, 160)}). ` +
709
- `No request reached ${name}, so this says NOTHING about whether the arguments you passed ` +
710
- 'are valid — do not re-check them on the strength of this error. Retry shortly.',
711
- url,
712
- ),
713
- );
714
- }
715
- }
716
-
717
- function detailSuffix(detail: string): string {
718
- return detail ? ` — ${detail}` : '';
719
- }
720
-
721
- async function readDetail(res: Response): Promise<string> {
722
- let raw: string;
723
- try {
724
- raw = await res.text();
725
- } catch {
726
- // Body already consumed, or the connection died mid-read. The status alone
727
- // is still worth throwing — never let the error path throw its own error.
728
- return '';
729
- }
730
- return summarizeErrorBody(raw);
731
- }
732
-
733
- /**
734
- * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
735
- * that never contains markup.
736
- *
737
- * This used to just drop an HTML or XML body on the floor, on the reasoning
738
- * that markup crowds out the status. That was half right. Dropping it loses the
739
- * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
740
- * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
741
- * measured 13 of 291 caller-facing error rows carrying a raw page or document
742
- * verbatim, across 11 packs, and in every one of them the useful content —
743
- * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
744
- * buried in markup the agent had to parse out of a string (fleet #712).
745
- *
746
- * So: extract the meaning, discard the markup. The output is passed through
747
- * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
748
- * assert mechanically that no caller-facing message can contain `<?xml`,
749
- * `<!DOCTYPE` or `<html`.
750
- */
751
- function summarizeErrorBody(raw: string): string {
752
- if (!raw || !raw.trim()) return '';
753
-
754
- const head = raw.slice(0, 400).trimStart().toLowerCase();
755
-
756
- // An HTML error page (Cloudflare interstitial, nginx default, a login
757
- // redirect) says what it is in its <title>, and almost nowhere else.
758
- if (head.startsWith('<!doctype') || head.startsWith('<html')) {
759
- const title = htmlTitle(raw);
760
- return title
761
- ? `${title} (upstream returned an HTML error page, not an API response)`
762
- : 'upstream returned an HTML error page, not an API response';
763
- }
764
-
765
- // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
766
- // human sentence sits in a child element whose tag name says what it is.
767
- if (head.startsWith('<?xml') || head.startsWith('<')) {
768
- const fault = xmlFaultText(raw);
769
- return fault
770
- ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
771
- : 'upstream returned an XML error document with no readable message';
772
- }
773
-
774
- // Most JSON error bodies bury one human sentence among ids and echoed request
775
- // params. Prefer that sentence; fall back to the whole body when the shape is
776
- // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
777
- // guess wrong and show nothing.
778
- const fromJson = messageFromJson(raw);
779
- return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
780
- }
781
-
782
- /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
783
- * bot wall, a 502 and an "Access Denied" all state what happened. */
784
- function htmlTitle(raw: string): string | null {
785
- const head = raw.slice(0, 4000);
786
- for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
787
- const m = re.exec(head);
788
- const text = m ? stripMarkup(m[1]) : '';
789
- if (text) return text.slice(0, 160);
790
- }
791
- return null;
792
- }
793
-
794
- /** Tag names that carry the explanation in an XML fault document, namespace
795
- * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
796
- const XML_FAULT_TAG_RE =
797
- /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
798
-
799
- function xmlFaultText(raw: string): string | null {
800
- const head = raw.slice(0, 8000);
801
- const tagged = XML_FAULT_TAG_RE.exec(head);
802
- if (tagged && tagged[1].trim()) return tagged[1];
803
-
804
- // Nothing conventionally named — take the longest text node instead. A fault
805
- // document with one sentence in an oddly named element is still readable;
806
- // returning nothing at all is not.
807
- let best = '';
808
- for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
809
- const text = m[1].trim();
810
- if (text.length > best.length) best = text;
811
- }
812
- return best || null;
813
- }
814
-
815
- /**
816
- * Remove every tag and stray angle bracket, then collapse whitespace.
817
- *
818
- * Applied to everything on the way out, including the JSON and plain-text
819
- * paths, because an upstream is free to embed markup in a JSON string field —
820
- * and a leak is a leak regardless of which branch produced it.
821
- */
822
- function stripMarkup(s: string): string {
823
- return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
824
- }
825
-
826
- /** The handful of entities that show up in error-page titles. Decoded AFTER
827
- * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
828
- * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
829
- * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
830
- function decodeEntities(s: string): string {
831
- return s
832
- .replace(/&(?:amp|#0*38);/gi, '&')
833
- .replace(/&(?:lt|#0*60);/gi, '<')
834
- .replace(/&(?:gt|#0*62);/gi, '>')
835
- .replace(/&(?:quot|#0*34);/gi, '"')
836
- .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
837
- .replace(/&nbsp;/gi, ' ');
838
- }
839
-
840
- /** The conventional "what went wrong" field, under any of the names upstreams
841
- * actually use. Checked in order; first non-empty string wins. */
842
- const MESSAGE_KEYS = [
843
- 'message', 'error_message', 'errorMessage', 'detail', 'details',
844
- 'description', 'error_description', 'reason', 'title', 'fault',
845
- ];
846
-
847
- function messageFromJson(raw: string): string | null {
848
- let parsed: unknown;
849
- try {
850
- parsed = JSON.parse(raw);
851
- } catch {
852
- return null;
853
- }
854
- return pickMessage(parsed, 0);
855
- }
856
-
857
- function pickMessage(node: unknown, depth: number): string | null {
858
- // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
859
- // shapes that account for nearly all of them, without walking a large payload.
860
- if (depth > 2 || node == null) return null;
861
-
862
- if (typeof node === 'string') return node.trim() || null;
863
-
864
- if (Array.isArray(node)) {
865
- for (const item of node) {
866
- const found = pickMessage(item, depth + 1);
867
- if (found) return found;
868
- }
869
- return null;
870
- }
871
-
872
- if (typeof node !== 'object') return null;
873
- const obj = node as Record<string, unknown>;
874
-
875
- for (const key of MESSAGE_KEYS) {
876
- const v = obj[key];
877
- if (typeof v === 'string' && v.trim()) return v.trim();
878
- }
879
- // `{error: …}` where error is itself an object or a string — the single most
880
- // common wrapper, so it is worth descending into by name rather than scanning
881
- // every key and risking picking up an echoed request parameter.
882
- for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
883
- if (key in obj) {
884
- const found = pickMessage(obj[key], depth + 1);
885
- if (found) return found;
886
- }
887
- }
888
- return null;
889
- }
890
-
891
- /** Errors are read in a single line of log output; newlines and runs of
892
- * whitespace make a multi-line body unreadable there. */
893
- function collapse(s: string): string {
894
- return s.replace(/\s+/g, ' ').trim();
895
- }
896
- /**
897
- * Meetup MCP — wraps Meetup's public GraphQL API (api.meetup.com, free, no auth)
898
- *
899
- * Tools:
900
- * - meetup_search_events: Search upcoming events near a city or coordinates
901
- * - meetup_event: Get full details for one event by ID
902
- * - meetup_group: Get details for one group by its urlname
903
- * - meetup_group_events: List a group's upcoming (or past) events
904
- *
905
- * Privacy: these tools return event/group metadata only. They never request or
906
- * return attendee/RSVP lists, member lists, or any other personal contact data —
907
- * none of the queries below select Meetup's rsvps/memberships/hostRsvps/organizer
908
- * fields, which is deliberate, not an oversight.
909
- */
910
-
911
-
912
- // Bound every fetch() in this pack to a fixed timeout — an upstream that
913
- // degrades without erroring would otherwise hold the Worker in `await fetch()`
914
- // until its own execution budget kills the request (minutes, not seconds).
915
- // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
916
- const UA = 'pipeworx-mcp/1.0 (+https://pipeworx.io)';
917
-
918
- async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
919
- const headers = { 'User-Agent': UA, ...(init?.headers ?? {}) };
920
- return fetchWithTimeout(url, { ...init, headers }, 'Meetup');
921
- }
922
-
923
- const GRAPHQL_URL = 'https://api.meetup.com/gql-ext';
924
-
925
- // ── GraphQL plumbing ────────────────────────────────────────────────────
926
-
927
- type GqlResponse<T> = { data?: T; errors?: Array<{ message: string }> };
928
-
929
- async function gqlPost<T>(query: string): Promise<T> {
930
- const res = await pwFetch(GRAPHQL_URL, {
931
- method: 'POST',
932
- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
933
- body: JSON.stringify({ query }),
934
- });
935
- if (!res.ok) throw await httpError(res, 'Meetup API error');
936
-
937
- const body = (await res.json()) as GqlResponse<T>;
938
- if (body.errors?.length) {
939
- throw new Error(`Meetup API error: ${body.errors.map((e) => e.message).join('; ')}`);
940
- }
941
- if (body.data === undefined) {
942
- throw new Error('Meetup API error: response carried no data');
943
- }
944
- return body.data;
945
- }
946
-
947
- /** Escape a string for inlining into a GraphQL document (this API has no
948
- * variables endpoint exposed the way we call it, so queries are built as
949
- * literal strings — escape quotes/backslashes/newlines so a title or query
950
- * containing them can't break the document). */
951
- function gqlString(s: string): string {
952
- return JSON.stringify(s);
953
- }
954
-
955
- // ── API response shapes (only the fields we select) ─────────────────────
956
-
957
- type ApiGroupSummary = { name: string; urlname?: string } | null;
958
-
959
- type ApiVenue = {
960
- name: string | null;
961
- address: string | null;
962
- city: string | null;
963
- state: string | null;
964
- country: string | null;
965
- lat: number | null;
966
- lon: number | null;
967
- } | null;
968
-
969
- type ApiEventNode = {
970
- id: string;
971
- title: string;
972
- description?: string | null;
973
- dateTime: string | null;
974
- endTime: string | null;
975
- eventUrl: string;
976
- status: string;
977
- eventType: string;
978
- group: ApiGroupSummary;
979
- venue?: ApiVenue;
980
- };
981
-
982
- type ApiEventSearchResult = {
983
- eventSearch: { totalCount: number; edges: Array<{ node: ApiEventNode }> };
984
- };
985
-
986
- type ApiEventResult = { event: ApiEventNode | null };
987
-
988
- type ApiGroup = {
989
- id: string;
990
- name: string;
991
- urlname: string;
992
- description: string | null;
993
- city: string | null;
994
- state: string | null;
995
- country: string | null;
996
- lat: number | null;
997
- lon: number | null;
998
- timezone: string | null;
999
- link: string | null;
1000
- foundedDate: string | null;
1001
- topicCategory: { name: string; urlkey: string } | null;
1002
- };
1003
-
1004
- type ApiGroupResult = { groupByUrlname: ApiGroup | null };
1005
-
1006
- type ApiGroupEventsResult = {
1007
- groupByUrlname: {
1008
- name: string;
1009
- urlname: string;
1010
- events: { totalCount: number; edges: Array<{ node: ApiEventNode }> };
1011
- } | null;
1012
- };
1013
-
1014
- // ── Formatters ────────────────────────────────────────────────────────
1015
-
1016
- function formatEventSummary(n: ApiEventNode) {
1017
- return {
1018
- id: n.id,
1019
- title: n.title,
1020
- date_time: n.dateTime,
1021
- end_time: n.endTime,
1022
- event_url: n.eventUrl,
1023
- status: n.status,
1024
- event_type: n.eventType,
1025
- group: n.group ? { name: n.group.name, urlname: n.group.urlname ?? null } : null,
1026
- };
1027
- }
1028
-
1029
- function formatEventFull(n: ApiEventNode) {
1030
- return {
1031
- id: n.id,
1032
- title: n.title,
1033
- description: n.description ?? null,
1034
- date_time: n.dateTime,
1035
- end_time: n.endTime,
1036
- event_url: n.eventUrl,
1037
- status: n.status,
1038
- event_type: n.eventType,
1039
- group: n.group ? { name: n.group.name, urlname: n.group.urlname ?? null } : null,
1040
- venue: n.venue
1041
- ? {
1042
- name: n.venue.name,
1043
- address: n.venue.address,
1044
- city: n.venue.city,
1045
- state: n.venue.state,
1046
- country: n.venue.country,
1047
- lat: n.venue.lat,
1048
- lon: n.venue.lon,
1049
- }
1050
- : null,
1051
- };
1052
- }
1053
-
1054
- function formatGroup(g: ApiGroup) {
1055
- return {
1056
- id: g.id,
1057
- name: g.name,
1058
- urlname: g.urlname,
1059
- description: g.description,
1060
- city: g.city,
1061
- state: g.state,
1062
- country: g.country,
1063
- lat: g.lat,
1064
- lon: g.lon,
1065
- timezone: g.timezone,
1066
- link: g.link,
1067
- founded_date: g.foundedDate,
1068
- topic_category: g.topicCategory ? { name: g.topicCategory.name, urlkey: g.topicCategory.urlkey } : null,
1069
- };
1070
- }
1071
-
1072
- // ── Tool definitions ──────────────────────────────────────────────────
1073
-
1074
- const tools: McpToolExport['tools'] = [
1075
- {
1076
- name: 'meetup_search_events',
1077
- description:
1078
- "Search Meetup for upcoming public events by keyword, near a city or a lat/lon point. Returns each event's title, time, URL, status and hosting group — never attendee or RSVP lists. Provide either `city` (geocoded automatically) or `lat`+`lon`.",
1079
- inputSchema: {
1080
- type: 'object',
1081
- properties: {
1082
- query: { type: 'string', description: 'Keyword to search for, e.g. "music" or "python".' },
1083
- city: {
1084
- type: 'string',
1085
- description: 'City or place name to search near, e.g. "San Francisco, CA". Geocoded automatically. Omit if you pass lat/lon directly.',
1086
- },
1087
- lat: { type: 'number', description: 'Latitude of the search center, in decimal degrees. Use instead of `city`.' },
1088
- lon: { type: 'number', description: 'Longitude of the search center, in decimal degrees. Use instead of `city`.' },
1089
- radius: { type: 'number', description: 'Search radius in miles around the center point. Defaults to 25.' },
1090
- limit: { type: 'number', description: 'Maximum number of events to return (1-50). Defaults to 10.' },
1091
- },
1092
- required: ['query'],
1093
- },
1094
- },
1095
- {
1096
- name: 'meetup_event',
1097
- description:
1098
- 'Get full details for one Meetup event by its numeric ID (the trailing number in a meetup.com event URL, e.g. "316887506"). Returns title, description, time, venue and hosting group — never attendee or RSVP lists.',
1099
- inputSchema: {
1100
- type: 'object',
1101
- properties: {
1102
- event_id: { type: 'string', description: 'The event\'s numeric Meetup ID, e.g. "316887506".' },
1103
- },
1104
- required: ['event_id'],
1105
- },
1106
- },
1107
- {
1108
- name: 'meetup_group',
1109
- description:
1110
- 'Get details for one Meetup group by its urlname (the slug in meetup.com/<urlname>, e.g. "sfpython"). Returns name, description, location, topic category and founding date — never a member list.',
1111
- inputSchema: {
1112
- type: 'object',
1113
- properties: {
1114
- urlname: { type: 'string', description: 'The group\'s urlname, e.g. "sfpython" (from meetup.com/sfpython).' },
1115
- },
1116
- required: ['urlname'],
1117
- },
1118
- },
1119
- {
1120
- name: 'meetup_group_events',
1121
- description:
1122
- "List a Meetup group's events by the group's urlname. Returns upcoming events by default, or past events with `include_past`. Never returns RSVP or attendee lists.",
1123
- inputSchema: {
1124
- type: 'object',
1125
- properties: {
1126
- urlname: { type: 'string', description: 'The group\'s urlname, e.g. "sfpython" (from meetup.com/sfpython).' },
1127
- limit: { type: 'number', description: 'Maximum number of events to return (1-50). Defaults to 10.' },
1128
- include_past: {
1129
- type: 'boolean',
1130
- description: 'When true, list the group\'s past events instead of its upcoming ones. Defaults to false.',
1131
- },
1132
- },
1133
- required: ['urlname'],
1134
- },
1135
- },
1136
- ];
1137
-
1138
- async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
1139
- switch (name) {
1140
- case 'meetup_search_events':
1141
- return searchEvents(
1142
- args.query as string,
1143
- args.city as string | undefined,
1144
- args.lat as number | undefined,
1145
- args.lon as number | undefined,
1146
- (args.radius as number | undefined) ?? 25,
1147
- (args.limit as number | undefined) ?? 10,
1148
- );
1149
- case 'meetup_event':
1150
- return getEvent(args.event_id as string);
1151
- case 'meetup_group':
1152
- return getGroup(args.urlname as string);
1153
- case 'meetup_group_events':
1154
- return getGroupEvents(
1155
- args.urlname as string,
1156
- (args.limit as number | undefined) ?? 10,
1157
- Boolean(args.include_past),
1158
- );
1159
- default:
1160
- throw new Error(`Unknown tool: ${name}`);
1161
- }
1162
- }
1163
-
1164
- const EVENT_FIELDS = `
1165
- id
1166
- title
1167
- description
1168
- dateTime
1169
- endTime
1170
- eventUrl
1171
- status
1172
- eventType
1173
- group { name urlname }
1174
- venue { name address city state country lat lon }
1175
- `;
1176
-
1177
- const EVENT_SUMMARY_FIELDS = `
1178
- id
1179
- title
1180
- dateTime
1181
- endTime
1182
- eventUrl
1183
- status
1184
- eventType
1185
- group { name urlname }
1186
- `;
1187
-
1188
- async function resolveCoordinates(
1189
- city: string | undefined,
1190
- lat: number | undefined,
1191
- lon: number | undefined,
1192
- ): Promise<{ lat: number; lon: number; resolved_place?: string }> {
1193
- if (typeof lat === 'number' && typeof lon === 'number') return { lat, lon };
1194
- if (!city) {
1195
- throw new Error('Provide either `city` or both `lat` and `lon` to search near a location.');
1196
- }
1197
- const hit = await resolvePlace(city);
1198
- if (!hit) throw new Error(`Could not resolve "${city}" to a location. Try a more specific city name, or pass lat/lon directly.`);
1199
- const parts = [hit.name, hit.admin1, hit.country].filter(Boolean);
1200
- return { lat: hit.latitude, lon: hit.longitude, resolved_place: parts.join(', ') };
1201
- }
1202
-
1203
- async function searchEvents(
1204
- query: string,
1205
- city: string | undefined,
1206
- lat: number | undefined,
1207
- lon: number | undefined,
1208
- radius: number,
1209
- limit: number,
1210
- ) {
1211
- if (!query) throw new Error('`query` is required.');
1212
- const first = Math.max(1, Math.min(50, limit));
1213
- const { lat: rLat, lon: rLon, resolved_place } = await resolveCoordinates(city, lat, lon);
1214
-
1215
- const q = `query {
1216
- eventSearch(filter: { query: ${gqlString(query)}, lat: ${rLat}, lon: ${rLon}, radius: ${radius} }, first: ${first}) {
1217
- totalCount
1218
- edges { node { ${EVENT_SUMMARY_FIELDS} } }
1219
- }
1220
- }`;
1221
- const data = await gqlPost<ApiEventSearchResult>(q);
1222
- return {
1223
- query,
1224
- center: { lat: rLat, lon: rLon, radius_miles: radius, ...(resolved_place ? { resolved_place } : {}) },
1225
- total_count: data.eventSearch.totalCount,
1226
- events: data.eventSearch.edges.map((e) => formatEventSummary(e.node)),
1227
- };
1228
- }
1229
-
1230
- async function getEvent(eventId: string) {
1231
- if (!eventId) throw new Error('`event_id` is required.');
1232
- const q = `query { event(id: ${gqlString(eventId)}) { ${EVENT_FIELDS} } }`;
1233
- const data = await gqlPost<ApiEventResult>(q);
1234
- if (!data.event) throw new Error(`No Meetup event found with id "${eventId}".`);
1235
- return formatEventFull(data.event);
1236
- }
1237
-
1238
- async function getGroup(urlname: string) {
1239
- if (!urlname) throw new Error('`urlname` is required.');
1240
- const q = `query {
1241
- groupByUrlname(urlname: ${gqlString(urlname)}) {
1242
- id name urlname description city state country lat lon timezone link foundedDate
1243
- topicCategory { name urlkey }
1244
- }
1245
- }`;
1246
- const data = await gqlPost<ApiGroupResult>(q);
1247
- if (!data.groupByUrlname) throw new Error(`No Meetup group found with urlname "${urlname}".`);
1248
- return formatGroup(data.groupByUrlname);
1249
- }
1250
-
1251
- async function getGroupEvents(urlname: string, limit: number, includePast: boolean) {
1252
- if (!urlname) throw new Error('`urlname` is required.');
1253
- const first = Math.max(1, Math.min(50, limit));
1254
- const statusFilter = includePast ? ', status: PAST' : '';
1255
- const q = `query {
1256
- groupByUrlname(urlname: ${gqlString(urlname)}) {
1257
- name
1258
- urlname
1259
- events(first: ${first}${statusFilter}) {
1260
- totalCount
1261
- edges { node { ${EVENT_SUMMARY_FIELDS} } }
1262
- }
1263
- }
1264
- }`;
1265
- const data = await gqlPost<ApiGroupEventsResult>(q);
1266
- if (!data.groupByUrlname) throw new Error(`No Meetup group found with urlname "${urlname}".`);
1267
- return {
1268
- group: { name: data.groupByUrlname.name, urlname: data.groupByUrlname.urlname },
1269
- total_count: data.groupByUrlname.events.totalCount,
1270
- events: data.groupByUrlname.events.edges.map((e) => formatEventSummary(e.node)),
1271
- };
1272
- }
1273
-
1274
- export default { tools, callTool, meter: { credits: 2 } } satisfies McpToolExport;