@cliwant/mcp-sam-gov 1.2.0 → 1.4.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.
Files changed (91) hide show
  1. package/README.ja.md +22 -9
  2. package/README.ko.md +22 -9
  3. package/README.md +70 -12
  4. package/dist/bea.d.ts +105 -0
  5. package/dist/bea.d.ts.map +1 -0
  6. package/dist/bea.js +303 -0
  7. package/dist/bea.js.map +1 -0
  8. package/dist/census-economic.d.ts +1 -1
  9. package/dist/census-economic.d.ts.map +1 -1
  10. package/dist/census-economic.js +12 -6
  11. package/dist/census-economic.js.map +1 -1
  12. package/dist/cms-facility.d.ts +112 -0
  13. package/dist/cms-facility.d.ts.map +1 -0
  14. package/dist/cms-facility.js +311 -0
  15. package/dist/cms-facility.js.map +1 -0
  16. package/dist/cms-hospital.d.ts +105 -0
  17. package/dist/cms-hospital.d.ts.map +1 -0
  18. package/dist/cms-hospital.js +290 -0
  19. package/dist/cms-hospital.js.map +1 -0
  20. package/dist/cms-supplier.d.ts +133 -0
  21. package/dist/cms-supplier.d.ts.map +1 -0
  22. package/dist/cms-supplier.js +414 -0
  23. package/dist/cms-supplier.js.map +1 -0
  24. package/dist/cms-utilization.d.ts +113 -0
  25. package/dist/cms-utilization.d.ts.map +1 -0
  26. package/dist/cms-utilization.js +328 -0
  27. package/dist/cms-utilization.js.map +1 -0
  28. package/dist/courtlistener.d.ts +115 -0
  29. package/dist/courtlistener.d.ts.map +1 -0
  30. package/dist/courtlistener.js +398 -0
  31. package/dist/courtlistener.js.map +1 -0
  32. package/dist/cpsc.d.ts +81 -0
  33. package/dist/cpsc.d.ts.map +1 -0
  34. package/dist/cpsc.js +283 -0
  35. package/dist/cpsc.js.map +1 -0
  36. package/dist/dol.d.ts +118 -0
  37. package/dist/dol.d.ts.map +1 -0
  38. package/dist/dol.js +421 -0
  39. package/dist/dol.js.map +1 -0
  40. package/dist/epa-envirofacts.d.ts +97 -0
  41. package/dist/epa-envirofacts.d.ts.map +1 -0
  42. package/dist/epa-envirofacts.js +292 -0
  43. package/dist/epa-envirofacts.js.map +1 -0
  44. package/dist/fred.d.ts +1 -1
  45. package/dist/fred.js +1 -1
  46. package/dist/keys.d.ts +11 -8
  47. package/dist/keys.d.ts.map +1 -1
  48. package/dist/keys.js +55 -8
  49. package/dist/keys.js.map +1 -1
  50. package/dist/lda.d.ts +105 -0
  51. package/dist/lda.d.ts.map +1 -0
  52. package/dist/lda.js +317 -0
  53. package/dist/lda.js.map +1 -0
  54. package/dist/nhtsa.d.ts +91 -0
  55. package/dist/nhtsa.d.ts.map +1 -0
  56. package/dist/nhtsa.js +263 -0
  57. package/dist/nhtsa.js.map +1 -0
  58. package/dist/nonprofit.d.ts +116 -0
  59. package/dist/nonprofit.d.ts.map +1 -0
  60. package/dist/nonprofit.js +342 -0
  61. package/dist/nonprofit.js.map +1 -0
  62. package/dist/openfda-device.d.ts +85 -0
  63. package/dist/openfda-device.d.ts.map +1 -0
  64. package/dist/openfda-device.js +277 -0
  65. package/dist/openfda-device.js.map +1 -0
  66. package/dist/openfda.d.ts +133 -0
  67. package/dist/openfda.d.ts.map +1 -0
  68. package/dist/openfda.js +402 -0
  69. package/dist/openfda.js.map +1 -0
  70. package/dist/server.d.ts.map +1 -1
  71. package/dist/server.js +872 -6
  72. package/dist/server.js.map +1 -1
  73. package/package.json +2 -1
  74. package/src/bea.ts +372 -0
  75. package/src/census-economic.ts +12 -6
  76. package/src/cms-facility.ts +379 -0
  77. package/src/cms-hospital.ts +344 -0
  78. package/src/cms-supplier.ts +527 -0
  79. package/src/cms-utilization.ts +389 -0
  80. package/src/courtlistener.ts +465 -0
  81. package/src/cpsc.ts +333 -0
  82. package/src/dol.ts +515 -0
  83. package/src/epa-envirofacts.ts +342 -0
  84. package/src/fred.ts +1 -1
  85. package/src/keys.ts +60 -8
  86. package/src/lda.ts +385 -0
  87. package/src/nhtsa.ts +352 -0
  88. package/src/nonprofit.ts +460 -0
  89. package/src/openfda-device.ts +356 -0
  90. package/src/openfda.ts +495 -0
  91. package/src/server.ts +995 -6
@@ -0,0 +1,379 @@
1
+ /**
2
+ * cms-facility.ts — CMS "facility directory" across FOUR provider-data datasets
3
+ * (`data.cms.gov`, the provider-data DKAN datastore-query API; ADR-0063). KEYLESS.
4
+ *
5
+ * WHAT IT ADDS: `cms_facility_directory` — a healthcare-facility directory / market
6
+ * lane that generalizes cms_hospital_compare (ADR-0062) BEYOND hospitals: a caller
7
+ * picks a `facilityType` (nursing_home | home_health | hospice | dialysis) and the
8
+ * tool routes to the RIGHT CMS provider-data dataset, returning each facility's
9
+ * name / address / city / state / zip / ownership. The facility-level complement to
10
+ * the utilization and hospital lanes — WHERE these Medicare-certified facilities are.
11
+ *
12
+ * ★THE facilityType → DATASET-ID CONSTANT MAP (the load-bearing SSRF guard): the
13
+ * USER value never enters the URL path. `facilityType` is a Zod ENUM; it indexes a
14
+ * MODULE-CONSTANT map to a VETTED dataset id (e.g. nursing_home → "4pq5-n9py") that
15
+ * is spliced into the path. An unknown facilityType is blocked by the enum
16
+ * (invalid_input) BEFORE any fetch — only one of four compile-time ids can ever
17
+ * reach the path.
18
+ *
19
+ * ★THE ONE-REQUEST COUNT PATTERN (P1 honesty, inherited from cms-hospital): the DKAN
20
+ * datastore-query response is `{ count, results, schema, query }` — `count` is the
21
+ * EXACT per-filter total in the SAME body as the rows. So totalAvailable = the
22
+ * response's top-level `count` (nursing_home ⇒ 14695), NEVER `results.length`.
23
+ *
24
+ * ★FIELD-NAME VARIANCE ACROSS DATASETS (the one genuinely-new complexity vs.
25
+ * cms-hospital) — live-verified 2026-07-15. The facility NAME, ADDRESS, and
26
+ * OWNERSHIP columns are NAMED DIFFERENTLY per dataset, so each is COALESCED over a
27
+ * fixed candidate order (null if none present — NEVER an empty string, NEVER
28
+ * fabricated):
29
+ * name : provider_name → facility_name → legal_business_name
30
+ * address : address → provider_address → address_line_1
31
+ * ownership : ownership_type → type_of_ownership → profit_or_nonprofit
32
+ * (city = citytown, state = state, zip = zip_code are uniform across all four.)
33
+ * Per-dataset verified columns:
34
+ * nursing_home 4pq5-n9py: provider_name / provider_address / ownership_type
35
+ * home_health 6jpm-sxkc: provider_name / address / type_of_ownership
36
+ * hospice yc9t-dgbk: facility_name / address_line_1 / ownership_type
37
+ * dialysis 23ew-n7w9: facility_name / address_line_1 / profit_or_nonprofit
38
+ * ★ADR-0063 said nursing_home's address is `address`; it is actually
39
+ * `provider_address` (probed live) — the coalescing candidate list covers it.
40
+ *
41
+ * ★THE facilityName FILTER COLUMN also varies: the `contains` filter targets the
42
+ * dataset's OWN primary-name column (provider_name for nursing_home/home_health,
43
+ * facility_name for hospice/dialysis) — stored per-type in the constant map.
44
+ *
45
+ * The module writes ZERO fetch/coercion/error/meta code — it REUSES `getJson`
46
+ * (redirect:"error") / `driftError` (datasource.ts), `str` (coerce.ts,
47
+ * null-never-empty-string), and `withMeta`·`buildMeta` (meta.ts, offset pagination
48
+ * + totalAvailable). It MIRRORS cms-hospital.ts's fixed-host SSRF idiom (a single
49
+ * host const + a post-construction hostname/protocol assertion + redirect:"error" +
50
+ * `conditions[i][…]` bracket keys and values carried via URLSearchParams) and its
51
+ * schema_drift catch-ladder (ToolErrorCarrier rethrow FIRST → SyntaxError→driftError
52
+ * → bare rethrow).
53
+ *
54
+ * GET https://data.cms.gov/provider-data/api/1/datastore/query/{datasetId}/0
55
+ * ?limit=&offset=&conditions[0][property]=state&conditions[0][value]=VA&conditions[0][operator]==
56
+ * → { count: 383, results: [ { provider_name, provider_address, … }, … ], schema, query }
57
+ *
58
+ * ★ SSRF: the host is a compile-time literal (`CMS_HOST`); the dataset id is chosen
59
+ * by a Zod-enum key from a MODULE-CONSTANT map (never the user string). Every USER
60
+ * filter VALUE rides as a URLSearchParams VALUE (`conditions[i][value]=…`) — the
61
+ * bracket key AND the value are encoded, so a value can never break out of the
62
+ * path or inject a parameter. state is `^[A-Za-z]{2}$`; facilityName is a bounded
63
+ * free-text charclass; size/offset are coerced to integers. A post-construction
64
+ * hostname/protocol assertion + `redirect:"error"` fail closed on any off-host 3xx.
65
+ *
66
+ * ★ HONESTY (ADR-0063 P1–P5, live-verified 2026-07-15 on data.cms.gov):
67
+ * [P1] totalAvailable = the response's top-level `count` (EXACT per-filter total),
68
+ * NOT the slice length. hasMore = offset+returned < count.
69
+ * [P2] results:[] ⇒ honest empty (returned:0). An invalid facilityType is blocked
70
+ * by the Zod enum (invalid_input). getJson maps a 4xx/5xx via
71
+ * errorFromResponse and THROWS (503 ⇒ upstream_unavailable, 400 ⇒
72
+ * invalid_input, 404 ⇒ not_found); a 200 non-JSON body OR a body missing
73
+ * `count`/`results` ⇒ schema_drift (NEVER a fabricated empty).
74
+ * [P3] name/address/ownership are COALESCED over the candidate order — null if none
75
+ * (NEVER an empty string, NEVER fabricated). String fields via str().
76
+ * [P4] results non-array OR count non-number ⇒ driftError.
77
+ */
78
+
79
+ import { ToolErrorCarrier } from "./errors.js";
80
+ import { getJson, driftError } from "./datasource.js";
81
+ import { str } from "./coerce.js";
82
+ import { withMeta, type MetaBundle, type ResponseMeta } from "./meta.js";
83
+
84
+ // Re-export the shared honesty coercion (single audited copy in ./coerce.js) so a
85
+ // regression fails together across sources. NO local str.
86
+ export { str };
87
+
88
+ // ─── SSRF core: the single fixed host + module-literal endpoint prefix ──
89
+ const CMS_HOST = "data.cms.gov";
90
+ // HOST-only label — surfaces in ToolError.upstreamEndpoint; keyless, so no token
91
+ // can ever appear here.
92
+ const CMS_LABEL = "cms-facility:data.cms.gov";
93
+ const CMS_PATH_PREFIX = "/provider-data/api/1/datastore/query";
94
+ const CMS_PATH_SUFFIX = "/0";
95
+
96
+ // ★THE facilityType → dataset CONSTANT MAP. The USER value is a Zod-enum KEY; only
97
+ // one of these four VETTED dataset ids can ever reach the URL path (the user string
98
+ // never does). `nameColumn` is the dataset's OWN primary-name column — the target of
99
+ // the facilityName `contains` filter, which also varies per dataset. `label` is
100
+ // surfaced to the caller in a _meta note so a consumer never mistakes the source.
101
+ // ★UPDATE IF CMS RE-IDs a dataset: the provider-data datastore keys each dataset by a
102
+ // short slug; CMS has historically kept these stable, but a re-publish could change
103
+ // one — the active id + count are disclosed in _meta.
104
+ type FacilityType = "nursing_home" | "home_health" | "hospice" | "dialysis";
105
+ type DatasetDef = { id: string; nameColumn: string; label: string };
106
+ const FACILITY_DATASETS: Record<FacilityType, DatasetDef> = {
107
+ nursing_home: {
108
+ id: "4pq5-n9py",
109
+ nameColumn: "provider_name",
110
+ label:
111
+ 'CMS "Provider Information" (Nursing Home / Long-Term Care; ~14,695 Medicare/Medicaid-certified nursing homes)',
112
+ },
113
+ home_health: {
114
+ id: "6jpm-sxkc",
115
+ nameColumn: "provider_name",
116
+ label:
117
+ 'CMS "Home Health Care Agencies" (~12,460 Medicare-certified home health agencies)',
118
+ },
119
+ hospice: {
120
+ id: "yc9t-dgbk",
121
+ nameColumn: "facility_name",
122
+ label: 'CMS "Hospice Provider Information" (~6,852 Medicare-certified hospices)',
123
+ },
124
+ dialysis: {
125
+ id: "23ew-n7w9",
126
+ nameColumn: "facility_name",
127
+ label:
128
+ 'CMS "Dialysis Facility" (~7,490 Medicare-certified dialysis facilities)',
129
+ },
130
+ };
131
+
132
+ // The valid enum keys — a belt-and-suspenders re-guard behind the server Zod (a
133
+ // DIRECT handler call bypasses Zod). An unknown key ⇒ invalid_input, 0 fetch.
134
+ const FACILITY_TYPES = Object.keys(FACILITY_DATASETS) as FacilityType[];
135
+
136
+ // ─── Coalescing candidate orders (the field-name variance across datasets) ──
137
+ // Each output field probes these source columns IN ORDER; the first non-null (via
138
+ // str(), which nulls ""/whitespace/"null") wins; null if NONE present. NEVER an
139
+ // empty string, NEVER a fabricated value.
140
+ const NAME_FIELDS = ["provider_name", "facility_name", "legal_business_name"];
141
+ const ADDRESS_FIELDS = ["address", "provider_address", "address_line_1"];
142
+ const OWNERSHIP_FIELDS = ["ownership_type", "type_of_ownership", "profit_or_nonprofit"];
143
+
144
+ // ─── Validation charclasses (SSRF + "verify the input" honesty) ───
145
+ const STATE_RE = /^[A-Za-z]{2}$/; // 2-letter state/territory abbreviation
146
+ // facilityName rides as a URLSearchParams VALUE (encoded), so this bound is a sanity
147
+ // guard, not an SSRF necessity: letters/digits/space and common punctuation only
148
+ // (facility names carry apostrophes, &, /, -, .).
149
+ const FACILITY_NAME_RE = /^[A-Za-z0-9 &.,()/'-]{1,100}$/;
150
+
151
+ const SIZE_MIN = 1;
152
+ const SIZE_MAX = 100;
153
+ const SIZE_DEFAULT = 25;
154
+
155
+ // DKAN condition operators (live-verified). state = exact; name = substring.
156
+ const OP_EQUALS = "=";
157
+ const OP_CONTAINS = "contains";
158
+
159
+ // ─── Honesty notes (ADR-0063 required set) ────────────────────────
160
+ const COALESCE_NOTE =
161
+ "Field names vary across the four CMS provider-data datasets — `name`, `address`, and `ownership` are COALESCED over per-dataset candidate columns (name: provider_name/facility_name/legal_business_name; address: address/provider_address/address_line_1; ownership: ownership_type/type_of_ownership/profit_or_nonprofit). A field absent in the chosen dataset is null (unknown), NEVER an empty string and NEVER fabricated.";
162
+ const FILTER_NOTE =
163
+ "Filters are applied SERVER-SIDE via DKAN conditions (AND-combined): `state` is an EXACT match; `facilityName` is a case-insensitive SUBSTRING (contains) match against the dataset's primary-name column — so a facilityName fragment may match several facilities. totalAvailable is the upstream's EXACT count for this filter set, not the returned-row count.";
164
+
165
+ // ─── Curated facility shape ───────────────────────────────────────
166
+ export type Facility = {
167
+ name: string | null;
168
+ address: string | null;
169
+ city: string | null;
170
+ state: string | null;
171
+ zip: string | null;
172
+ facilityType: FacilityType;
173
+ ownership: string | null;
174
+ };
175
+
176
+ /**
177
+ * Coalesce a row's value over a candidate column order → string | null.
178
+ * Returns the FIRST column whose str() is non-null (str nulls ""/whitespace/"null");
179
+ * null if NONE — NEVER an empty string, NEVER a fabricated value (P3).
180
+ */
181
+ export function coalesceField(
182
+ row: Record<string, unknown>,
183
+ fields: string[],
184
+ ): string | null {
185
+ for (const f of fields) {
186
+ const v = str(row[f]);
187
+ if (v !== null) return v;
188
+ }
189
+ return null;
190
+ }
191
+
192
+ /** Map ONE datastore-query row → the curated facility shape for `facilityType`. */
193
+ function mapFacility(row: unknown, facilityType: FacilityType): Facility {
194
+ const r = (row ?? {}) as Record<string, unknown>;
195
+ return {
196
+ // [P3] name/address/ownership coalesced over candidate columns; null-never-empty.
197
+ name: coalesceField(r, NAME_FIELDS),
198
+ address: coalesceField(r, ADDRESS_FIELDS),
199
+ city: str(r.citytown),
200
+ state: str(r.state),
201
+ zip: str(r.zip_code),
202
+ // Echo the input facilityType (the caller's chosen lane).
203
+ facilityType,
204
+ ownership: coalesceField(r, OWNERSHIP_FIELDS),
205
+ };
206
+ }
207
+
208
+ // ─── SSRF-guarded fetch (fixed host + hostname assertion + redirect:"error") ──
209
+ /**
210
+ * GET one data.cms.gov provider-data JSON resource at a MODULE-BUILT URL. The dataset
211
+ * id is a VETTED value from FACILITY_DATASETS (never the user string); the endpoint
212
+ * path is built from module literals; all user filter VALUES are already carried in
213
+ * the URLSearchParams `query`. Asserts the CONSTRUCTED URL's hostname === the fixed
214
+ * host over https, and sets `redirect:"error"` (an off-host 3xx must NOT be
215
+ * followed). Keyless — no headers.
216
+ */
217
+ async function getCms(datasetId: string, query: URLSearchParams): Promise<unknown> {
218
+ const path = `${CMS_PATH_PREFIX}/${datasetId}${CMS_PATH_SUFFIX}`;
219
+ const url = `https://${CMS_HOST}${path}?${query.toString()}`;
220
+ const built = new URL(url);
221
+ if (built.hostname !== CMS_HOST || built.protocol !== "https:") {
222
+ throw new ToolErrorCarrier({
223
+ kind: "invalid_input",
224
+ message: `Constructed CMS provider-data URL host ${JSON.stringify(built.hostname)} (${built.protocol}) does not match the fixed host ${JSON.stringify(CMS_HOST)} over https — refusing to fetch (SSRF safety).`,
225
+ retryable: false,
226
+ upstreamEndpoint: CMS_LABEL,
227
+ });
228
+ }
229
+ return getJson(built.toString(), { label: CMS_LABEL, redirect: "error" });
230
+ }
231
+
232
+ export type CmsFacilityDirectoryArgs = {
233
+ facilityType?: string;
234
+ state?: string;
235
+ facilityName?: string;
236
+ size?: number;
237
+ offset?: number;
238
+ };
239
+
240
+ /**
241
+ * Fetch CMS provider-data facility rows for a `facilityType` (+ optional state /
242
+ * facility-name fragment) → normalized facility rows + honest `_meta`. The
243
+ * facilityType (a Zod enum) indexes the FACILITY_DATASETS constant map to a vetted
244
+ * dataset id — the user value never enters the path. A SINGLE request: the response's
245
+ * top-level `count` is the EXACT per-filter total (P1 — never the slice length).
246
+ */
247
+ export async function facilityDirectory(
248
+ args: CmsFacilityDirectoryArgs,
249
+ ): Promise<MetaBundle> {
250
+ // ── [SSRF/input] resolve facilityType → the vetted dataset (belt-and-suspenders
251
+ // behind the server Zod enum; a DIRECT handler call bypasses Zod). An unknown/
252
+ // absent facilityType ⇒ invalid_input, 0 fetch. ──
253
+ const ft = args.facilityType;
254
+ if (ft === undefined || !Object.prototype.hasOwnProperty.call(FACILITY_DATASETS, ft)) {
255
+ throw new ToolErrorCarrier({
256
+ kind: "invalid_input",
257
+ retryable: false,
258
+ message: `Invalid or missing facilityType ${JSON.stringify(ft)} — expected one of: ${FACILITY_TYPES.join(", ")}.`,
259
+ upstreamEndpoint: CMS_LABEL,
260
+ });
261
+ }
262
+ const facilityType = ft as FacilityType;
263
+ const dataset = FACILITY_DATASETS[facilityType];
264
+
265
+ // ── Validate + build the DKAN conditions (SSRF: charclass + URLSearchParams
266
+ // value). URLSearchParams encodes both the bracket key and the value. Each
267
+ // condition is an (property, value, operator) triple indexed by position. ──
268
+ const query = new URLSearchParams();
269
+ const filtersApplied: string[] = [`facilityType:${facilityType}`];
270
+ let ci = 0;
271
+ const pushCondition = (property: string, value: string, operator: string) => {
272
+ query.set(`conditions[${ci}][property]`, property);
273
+ query.set(`conditions[${ci}][value]`, value);
274
+ query.set(`conditions[${ci}][operator]`, operator);
275
+ ci += 1;
276
+ };
277
+
278
+ if (args.state !== undefined && args.state !== "") {
279
+ const state = args.state;
280
+ if (!STATE_RE.test(state)) {
281
+ throw new ToolErrorCarrier({
282
+ kind: "invalid_input",
283
+ retryable: false,
284
+ message: `Invalid state ${JSON.stringify(state)} — expected a 2-letter state/territory code (^[A-Za-z]{2}$), e.g. "VA".`,
285
+ upstreamEndpoint: CMS_LABEL,
286
+ });
287
+ }
288
+ pushCondition("state", state.toUpperCase(), OP_EQUALS);
289
+ filtersApplied.push(`state:${state.toUpperCase()}`);
290
+ }
291
+
292
+ if (args.facilityName !== undefined && args.facilityName !== "") {
293
+ const name = args.facilityName;
294
+ if (!FACILITY_NAME_RE.test(name)) {
295
+ throw new ToolErrorCarrier({
296
+ kind: "invalid_input",
297
+ retryable: false,
298
+ message: `Invalid facilityName ${JSON.stringify(name)} — allowed: letters, digits, space, & . , ( ) / ' - (≤100 chars). It is a case-insensitive substring match.`,
299
+ upstreamEndpoint: CMS_LABEL,
300
+ });
301
+ }
302
+ // The name column varies per dataset (provider_name vs facility_name).
303
+ pushCondition(dataset.nameColumn, name, OP_CONTAINS);
304
+ filtersApplied.push(`facilityName~${name}`);
305
+ }
306
+
307
+ // ── Coerce size / offset to bounded integers (belt-and-suspenders behind the
308
+ // server Zod; a DIRECT handler call bypasses Zod). ──
309
+ let size = SIZE_DEFAULT;
310
+ if (typeof args.size === "number" && Number.isFinite(args.size)) {
311
+ size = Math.trunc(args.size);
312
+ if (size < SIZE_MIN) size = SIZE_MIN;
313
+ if (size > SIZE_MAX) size = SIZE_MAX;
314
+ }
315
+ let offset = 0;
316
+ if (
317
+ typeof args.offset === "number" &&
318
+ Number.isFinite(args.offset) &&
319
+ args.offset > 0
320
+ ) {
321
+ offset = Math.trunc(args.offset);
322
+ }
323
+ query.set("limit", String(size));
324
+ query.set("offset", String(offset));
325
+
326
+ // ── The single request. Catch-ladder (cms-hospital shape): preserve the
327
+ // 4xx/5xx/timeout ToolErrorCarrier taxonomy FIRST; reclassify a 200 non-JSON
328
+ // SyntaxError to schema_drift SECOND; bare-rethrow LAST. ──
329
+ let body: unknown;
330
+ try {
331
+ body = await getCms(dataset.id, query);
332
+ } catch (e) {
333
+ if (e instanceof ToolErrorCarrier) throw e;
334
+ if (e instanceof SyntaxError)
335
+ throw driftError(
336
+ CMS_LABEL,
337
+ "CMS provider-data API returned a non-JSON body at HTTP 200 — schema drift (never read as an empty result).",
338
+ );
339
+ throw e;
340
+ }
341
+
342
+ // [P4] the body MUST be an object with a numeric `count` and an array `results`
343
+ // (a non-array results OR a non-number count is drift, never a fabricated empty).
344
+ const b = (body ?? {}) as { count?: unknown; results?: unknown };
345
+ if (
346
+ typeof b.count !== "number" ||
347
+ !Number.isFinite(b.count) ||
348
+ !Array.isArray(b.results)
349
+ ) {
350
+ throw driftError(
351
+ CMS_LABEL,
352
+ "CMS provider-data shape drift — the response must carry a numeric `count` and an array `results` of facility rows.",
353
+ );
354
+ }
355
+
356
+ const totalAvailable = b.count;
357
+ const facilities = (b.results as unknown[]).map((row) => mapFacility(row, facilityType));
358
+ const returned = facilities.length;
359
+
360
+ // ── [P1] pagination. hasMore = offset+returned < total (the EXACT count). ──
361
+ const hasMore = offset + returned < totalAvailable;
362
+ const nextOffset = hasMore ? offset + returned : null;
363
+
364
+ const DATASET_NOTE = `Source dataset: ${dataset.label} — data.cms.gov provider-data datastore "${dataset.id}". A CMS-published snapshot, not a live/real-time feed. Update the dataset id if CMS re-publishes it.`;
365
+
366
+ const meta: Partial<ResponseMeta> = {
367
+ source: `${CMS_HOST} CMS provider-data facility directory — ${facilityType} (keyless)`,
368
+ keylessMode: true,
369
+ returned,
370
+ totalAvailable,
371
+ filtersApplied,
372
+ filtersDropped: [],
373
+ fieldsUnavailable: [],
374
+ pagination: { offset, limit: size, hasMore, nextOffset },
375
+ notes: [DATASET_NOTE, COALESCE_NOTE, FILTER_NOTE],
376
+ };
377
+
378
+ return withMeta({ facilities }, meta);
379
+ }