@cliwant/mcp-sam-gov 0.3.0 → 1.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.
Files changed (243) hide show
  1. package/LICENSE +21 -21
  2. package/README.ja.md +49 -16
  3. package/README.ko.md +49 -16
  4. package/README.md +255 -64
  5. package/dist/attachments.d.ts +63 -0
  6. package/dist/attachments.d.ts.map +1 -0
  7. package/dist/attachments.js +576 -0
  8. package/dist/attachments.js.map +1 -0
  9. package/dist/bls.d.ts +267 -0
  10. package/dist/bls.d.ts.map +1 -0
  11. package/dist/bls.js +1549 -0
  12. package/dist/bls.js.map +1 -0
  13. package/dist/cache.d.ts +2 -0
  14. package/dist/cache.d.ts.map +1 -1
  15. package/dist/cache.js +4 -0
  16. package/dist/cache.js.map +1 -1
  17. package/dist/census-economic.d.ts +93 -0
  18. package/dist/census-economic.d.ts.map +1 -0
  19. package/dist/census-economic.js +355 -0
  20. package/dist/census-economic.js.map +1 -0
  21. package/dist/census.d.ts +182 -0
  22. package/dist/census.d.ts.map +1 -0
  23. package/dist/census.js +576 -0
  24. package/dist/census.js.map +1 -0
  25. package/dist/ckan.d.ts +141 -0
  26. package/dist/ckan.d.ts.map +1 -0
  27. package/dist/ckan.js +393 -0
  28. package/dist/ckan.js.map +1 -0
  29. package/dist/clinicaltrials.d.ts +180 -0
  30. package/dist/clinicaltrials.d.ts.map +1 -0
  31. package/dist/clinicaltrials.js +730 -0
  32. package/dist/clinicaltrials.js.map +1 -0
  33. package/dist/cms.d.ts +140 -0
  34. package/dist/cms.d.ts.map +1 -0
  35. package/dist/cms.js +482 -0
  36. package/dist/cms.js.map +1 -0
  37. package/dist/coerce.d.ts +32 -0
  38. package/dist/coerce.d.ts.map +1 -0
  39. package/dist/coerce.js +50 -0
  40. package/dist/coerce.js.map +1 -0
  41. package/dist/datagov-catalog.d.ts +84 -0
  42. package/dist/datagov-catalog.d.ts.map +1 -0
  43. package/dist/datagov-catalog.js +233 -0
  44. package/dist/datagov-catalog.js.map +1 -0
  45. package/dist/datagov.d.ts +146 -0
  46. package/dist/datagov.d.ts.map +1 -0
  47. package/dist/datagov.js +689 -0
  48. package/dist/datagov.js.map +1 -0
  49. package/dist/datagovKey.d.ts +36 -0
  50. package/dist/datagovKey.d.ts.map +1 -0
  51. package/dist/datagovKey.js +60 -0
  52. package/dist/datagovKey.js.map +1 -0
  53. package/dist/datasource.d.ts +313 -0
  54. package/dist/datasource.d.ts.map +1 -0
  55. package/dist/datasource.js +551 -0
  56. package/dist/datasource.js.map +1 -0
  57. package/dist/disclosure.d.ts +55 -0
  58. package/dist/disclosure.d.ts.map +1 -0
  59. package/dist/disclosure.js +57 -0
  60. package/dist/disclosure.js.map +1 -0
  61. package/dist/ecfr.d.ts +4 -2
  62. package/dist/ecfr.d.ts.map +1 -1
  63. package/dist/ecfr.js +74 -1
  64. package/dist/ecfr.js.map +1 -1
  65. package/dist/echo.d.ts +143 -0
  66. package/dist/echo.d.ts.map +1 -0
  67. package/dist/echo.js +424 -0
  68. package/dist/echo.js.map +1 -0
  69. package/dist/edgar.d.ts +377 -0
  70. package/dist/edgar.d.ts.map +1 -0
  71. package/dist/edgar.js +2418 -0
  72. package/dist/edgar.js.map +1 -0
  73. package/dist/errors.d.ts +26 -0
  74. package/dist/errors.d.ts.map +1 -1
  75. package/dist/errors.js +69 -1
  76. package/dist/errors.js.map +1 -1
  77. package/dist/fac.d.ts +180 -0
  78. package/dist/fac.d.ts.map +1 -0
  79. package/dist/fac.js +416 -0
  80. package/dist/fac.js.map +1 -0
  81. package/dist/far.d.ts +170 -0
  82. package/dist/far.d.ts.map +1 -0
  83. package/dist/far.js +804 -0
  84. package/dist/far.js.map +1 -0
  85. package/dist/fdic.d.ts +599 -0
  86. package/dist/fdic.d.ts.map +1 -0
  87. package/dist/fdic.js +1624 -0
  88. package/dist/fdic.js.map +1 -0
  89. package/dist/federal-register.d.ts +139 -2
  90. package/dist/federal-register.d.ts.map +1 -1
  91. package/dist/federal-register.js +419 -3
  92. package/dist/federal-register.js.map +1 -1
  93. package/dist/fema.d.ts +181 -0
  94. package/dist/fema.d.ts.map +1 -0
  95. package/dist/fema.js +436 -0
  96. package/dist/fema.js.map +1 -0
  97. package/dist/fpds.d.ts +108 -0
  98. package/dist/fpds.d.ts.map +1 -0
  99. package/dist/fpds.js +519 -0
  100. package/dist/fpds.js.map +1 -0
  101. package/dist/fred.d.ts +108 -0
  102. package/dist/fred.d.ts.map +1 -0
  103. package/dist/fred.js +373 -0
  104. package/dist/fred.js.map +1 -0
  105. package/dist/gao.d.ts +64 -0
  106. package/dist/gao.d.ts.map +1 -0
  107. package/dist/gao.js +640 -0
  108. package/dist/gao.js.map +1 -0
  109. package/dist/govinfo.d.ts +111 -0
  110. package/dist/govinfo.d.ts.map +1 -0
  111. package/dist/govinfo.js +422 -0
  112. package/dist/govinfo.js.map +1 -0
  113. package/dist/grants.d.ts +27 -4
  114. package/dist/grants.d.ts.map +1 -1
  115. package/dist/grants.js +111 -6
  116. package/dist/grants.js.map +1 -1
  117. package/dist/gsa-csv.d.ts +249 -0
  118. package/dist/gsa-csv.d.ts.map +1 -0
  119. package/dist/gsa-csv.js +784 -0
  120. package/dist/gsa-csv.js.map +1 -0
  121. package/dist/integrity.d.ts +212 -0
  122. package/dist/integrity.d.ts.map +1 -0
  123. package/dist/integrity.js +707 -0
  124. package/dist/integrity.js.map +1 -0
  125. package/dist/keys.d.ts +83 -0
  126. package/dist/keys.d.ts.map +1 -0
  127. package/dist/keys.js +173 -0
  128. package/dist/keys.js.map +1 -0
  129. package/dist/meta.d.ts +165 -0
  130. package/dist/meta.d.ts.map +1 -0
  131. package/dist/meta.js +162 -0
  132. package/dist/meta.js.map +1 -0
  133. package/dist/nih.d.ts +117 -0
  134. package/dist/nih.d.ts.map +1 -0
  135. package/dist/nih.js +291 -0
  136. package/dist/nih.js.map +1 -0
  137. package/dist/nppes.d.ts +157 -0
  138. package/dist/nppes.d.ts.map +1 -0
  139. package/dist/nppes.js +648 -0
  140. package/dist/nppes.js.map +1 -0
  141. package/dist/nsf.d.ts +176 -0
  142. package/dist/nsf.d.ts.map +1 -0
  143. package/dist/nsf.js +554 -0
  144. package/dist/nsf.js.map +1 -0
  145. package/dist/nvd.d.ts +176 -0
  146. package/dist/nvd.d.ts.map +1 -0
  147. package/dist/nvd.js +912 -0
  148. package/dist/nvd.js.map +1 -0
  149. package/dist/ofac.d.ts +205 -0
  150. package/dist/ofac.d.ts.map +1 -0
  151. package/dist/ofac.js +919 -0
  152. package/dist/ofac.js.map +1 -0
  153. package/dist/pricing.d.ts +110 -0
  154. package/dist/pricing.d.ts.map +1 -0
  155. package/dist/pricing.js +843 -0
  156. package/dist/pricing.js.map +1 -0
  157. package/dist/sam-gov/client.d.ts +60 -2
  158. package/dist/sam-gov/client.d.ts.map +1 -1
  159. package/dist/sam-gov/client.js +320 -54
  160. package/dist/sam-gov/client.js.map +1 -1
  161. package/dist/sam-gov/index.d.ts +1 -1
  162. package/dist/sam-gov/index.d.ts.map +1 -1
  163. package/dist/sam-gov/index.js +1 -1
  164. package/dist/sam-gov/index.js.map +1 -1
  165. package/dist/sam-gov/types.d.ts +24 -0
  166. package/dist/sam-gov/types.d.ts.map +1 -1
  167. package/dist/sba.d.ts +72 -0
  168. package/dist/sba.d.ts.map +1 -0
  169. package/dist/sba.js +281 -0
  170. package/dist/sba.js.map +1 -0
  171. package/dist/server.d.ts +14 -2
  172. package/dist/server.d.ts.map +1 -1
  173. package/dist/server.js +4032 -297
  174. package/dist/server.js.map +1 -1
  175. package/dist/snapshot.d.ts +115 -0
  176. package/dist/snapshot.d.ts.map +1 -0
  177. package/dist/snapshot.js +175 -0
  178. package/dist/snapshot.js.map +1 -0
  179. package/dist/socrata.d.ts +157 -0
  180. package/dist/socrata.d.ts.map +1 -0
  181. package/dist/socrata.js +448 -0
  182. package/dist/socrata.js.map +1 -0
  183. package/dist/treasury.d.ts +143 -0
  184. package/dist/treasury.d.ts.map +1 -0
  185. package/dist/treasury.js +436 -0
  186. package/dist/treasury.js.map +1 -0
  187. package/dist/usaspending.d.ts +260 -65
  188. package/dist/usaspending.d.ts.map +1 -1
  189. package/dist/usaspending.js +1629 -201
  190. package/dist/usaspending.js.map +1 -1
  191. package/dist/usitc.d.ts +142 -0
  192. package/dist/usitc.d.ts.map +1 -0
  193. package/dist/usitc.js +339 -0
  194. package/dist/usitc.js.map +1 -0
  195. package/package.json +24 -2
  196. package/src/attachments.ts +652 -0
  197. package/src/bls.ts +1943 -0
  198. package/src/cache.ts +5 -0
  199. package/src/census-economic.ts +425 -0
  200. package/src/census.ts +735 -0
  201. package/src/ckan.ts +495 -0
  202. package/src/clinicaltrials.ts +923 -0
  203. package/src/cms.ts +634 -0
  204. package/src/coerce.ts +47 -0
  205. package/src/datagov-catalog.ts +296 -0
  206. package/src/datagov.ts +907 -0
  207. package/src/datagovKey.ts +68 -0
  208. package/src/datasource.ts +721 -0
  209. package/src/disclosure.ts +61 -0
  210. package/src/ecfr.ts +98 -1
  211. package/src/echo.ts +496 -0
  212. package/src/edgar.ts +3014 -0
  213. package/src/errors.ts +84 -1
  214. package/src/fac.ts +529 -0
  215. package/src/far.ts +1007 -0
  216. package/src/fdic.ts +2052 -0
  217. package/src/federal-register.ts +512 -3
  218. package/src/fema.ts +541 -0
  219. package/src/fpds.ts +620 -0
  220. package/src/fred.ts +464 -0
  221. package/src/gao.ts +744 -0
  222. package/src/govinfo.ts +497 -0
  223. package/src/grants.ts +139 -7
  224. package/src/gsa-csv.ts +992 -0
  225. package/src/integrity.ts +928 -0
  226. package/src/keys.ts +216 -0
  227. package/src/meta.ts +292 -0
  228. package/src/nih.ts +375 -0
  229. package/src/nppes.ts +834 -0
  230. package/src/nsf.ts +706 -0
  231. package/src/nvd.ts +1124 -0
  232. package/src/ofac.ts +1166 -0
  233. package/src/pricing.ts +1075 -0
  234. package/src/sam-gov/client.ts +345 -63
  235. package/src/sam-gov/index.ts +5 -1
  236. package/src/sam-gov/types.ts +22 -0
  237. package/src/sba.ts +357 -0
  238. package/src/server.ts +4717 -328
  239. package/src/snapshot.ts +223 -0
  240. package/src/socrata.ts +532 -0
  241. package/src/treasury.ts +575 -0
  242. package/src/usaspending.ts +1946 -214
  243. package/src/usitc.ts +420 -0
package/src/keys.ts ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * @cliwant/mcp-sam-gov/keys — API-key discovery + `.env` auto-loading.
3
+ *
4
+ * Why this exists
5
+ * ----------------
6
+ * The server rides 31 federal sources. MOST are fully keyless. But the set of
7
+ * *optional* keys (raise a rate limit, unlock one filter) plus the two *required*
8
+ * keys (Census business-patterns, FRED) has grown to the point where a user — or
9
+ * the AI driving the server — cannot tell, without reading source code:
10
+ * - which env var each source reads,
11
+ * - whether a key is REQUIRED or merely OPTIONAL,
12
+ * - where to get one (free), and
13
+ * - whether it is currently configured.
14
+ *
15
+ * `apiKeyStatus()` answers all four, truthfully, WITHOUT ever revealing a key's
16
+ * value (only a `currentlySet` boolean). `loadDotEnv()` lets a user configure
17
+ * keys ONCE in a `.env` file instead of the host's env block.
18
+ *
19
+ * Grounding: every `envVar` below is the exact string the code reads via
20
+ * `process.env.<NAME>` — DATA_GOV_API_KEY (datagovKey.ts), SAM_GOV_API_KEY
21
+ * (server.ts), BLS_API_KEY (bls.ts), NVD_API_KEY (nvd.ts), SOCRATA_APP_TOKEN
22
+ * (socrata.ts), CENSUS_API_KEY (census-economic.ts), FRED_API_KEY (fred.ts).
23
+ * No invented keys, sources, or signup URLs.
24
+ */
25
+
26
+ import { readFileSync } from "node:fs";
27
+ import { join } from "node:path";
28
+
29
+ /** One registry entry describing a single API key the server can use. */
30
+ export type KeyRegistryEntry = {
31
+ /** The exact `process.env.<NAME>` the code reads. */
32
+ envVar: string;
33
+ /** Human-readable source(s) this key affects. */
34
+ sources: string[];
35
+ /** true ⇒ the source has NO keyless tier (the tool throws without it). */
36
+ required: boolean;
37
+ /** Free signup URL (the user creates the account — this is their step). */
38
+ signupUrl: string;
39
+ /** What setting the key unlocks (higher limit / a filter / a whole tool). */
40
+ unlocks: string;
41
+ /** Extra honesty note (keyless fallback, precedence, scope). */
42
+ note: string;
43
+ };
44
+
45
+ /**
46
+ * The 7 keys the server reads — code-grounded, no inventions.
47
+ *
48
+ * REQUIRED (2): CENSUS_API_KEY, FRED_API_KEY — those sources have no keyless
49
+ * tier, so the tool throws without them. OPTIONAL (5): everything else works
50
+ * keyless; a key only raises a rate limit or unlocks a single filter.
51
+ */
52
+ export const KEY_REGISTRY: readonly KeyRegistryEntry[] = [
53
+ {
54
+ envVar: "DATA_GOV_API_KEY",
55
+ sources: [
56
+ "api.data.gov keyed sources: Regulations.gov, Congress.gov, GovInfo, Federal Audit Clearinghouse (FAC), data.gov catalog",
57
+ ],
58
+ required: false,
59
+ signupUrl: "https://api.data.gov/signup/",
60
+ unlocks:
61
+ "higher rate limits on the api.data.gov keyed sources (lifts the shared DEMO_KEY ~30/hr cap to ~1,000/hr)",
62
+ note: "Keyless by default via the public DEMO_KEY; a key only raises the shared hourly quota. (NPPES, CMS, and Federal Register are keyless on their own hosts and do NOT use this key.)",
63
+ },
64
+ {
65
+ envVar: "SAM_GOV_API_KEY",
66
+ sources: ["SAM.gov opportunities"],
67
+ required: false,
68
+ signupUrl:
69
+ "https://open.gsa.gov/api/get-opportunities-public-api/",
70
+ unlocks:
71
+ "the authenticated v2 opportunity search + the organization-name filter",
72
+ note: "Keyless HAL endpoint works without it; a key enables the keyed v2 path and org-name filtering. Register at sam.gov / api.sam.gov.",
73
+ },
74
+ {
75
+ envVar: "BLS_API_KEY",
76
+ sources: ["Bureau of Labor Statistics (BLS)"],
77
+ required: false,
78
+ signupUrl: "https://data.bls.gov/registrationEngine/",
79
+ unlocks:
80
+ "the BLS v2 tier (~500 queries/day, 50 series/query, ~20-year span) vs keyless v1 (~25 queries/day)",
81
+ note: "Keyless v1 works out of the box; a key upgrades to the higher v2 limits.",
82
+ },
83
+ {
84
+ envVar: "NVD_API_KEY",
85
+ sources: ["NIST NVD (cve_lookup)"],
86
+ required: false,
87
+ signupUrl: "https://nvd.nist.gov/developers/request-an-api-key",
88
+ unlocks: "a higher NVD rate limit",
89
+ note: "Keyless by default; a key lifts the request rate limit.",
90
+ },
91
+ {
92
+ envVar: "SOCRATA_APP_TOKEN",
93
+ sources: ["Socrata (state/city open-data portals)"],
94
+ required: false,
95
+ signupUrl: "https://evergreen.data.socrata.com/signup",
96
+ unlocks: "higher Socrata throttling limits",
97
+ note: "Keyless by default; a token raises the per-host throttle. Any Socrata portal's developer settings issues one.",
98
+ },
99
+ {
100
+ envVar: "CENSUS_API_KEY",
101
+ sources: ["US Census (census_business_patterns)"],
102
+ required: true,
103
+ signupUrl: "https://api.census.gov/data/key_signup.html",
104
+ unlocks:
105
+ "the census_business_patterns tool (there is no keyless tier — it throws without a key)",
106
+ note: "REQUIRED: the Census economic API has no keyless access.",
107
+ },
108
+ {
109
+ envVar: "FRED_API_KEY",
110
+ sources: ["FRED (fred_search_series, fred_series_observations)"],
111
+ required: true,
112
+ signupUrl: "https://fred.stlouisfed.org/docs/api/api_key.html",
113
+ unlocks:
114
+ "the 2 FRED tools (there is no keyless tier — they throw without a key)",
115
+ note: "REQUIRED: the FRED API has no keyless access.",
116
+ },
117
+ ] as const;
118
+
119
+ /** true iff the env var is set to a non-empty (after-trim) string. */
120
+ function isSet(envVar: string): boolean {
121
+ const v = process.env[envVar];
122
+ return typeof v === "string" && v.trim().length > 0;
123
+ }
124
+
125
+ /** Per-key status: the registry entry + a `currentlySet` boolean. NEVER the value. */
126
+ export type KeyStatus = KeyRegistryEntry & { currentlySet: boolean };
127
+
128
+ /** The `apiKeyStatus()` result shape. */
129
+ export type ApiKeyStatusResult = {
130
+ keys: KeyStatus[];
131
+ /** envVars of REQUIRED keys not currently set (empty ⇒ all required keys present). */
132
+ requiredMissing: string[];
133
+ /** envVars of OPTIONAL keys not currently set. */
134
+ optionalMissing: string[];
135
+ /** Every key here is free to obtain. */
136
+ allKeysFree: boolean;
137
+ };
138
+
139
+ /**
140
+ * Report which API keys the server can use and whether each is configured.
141
+ *
142
+ * SECURITY: the returned object carries ONLY a `currentlySet` boolean per key —
143
+ * the key's VALUE is NEVER read into the output. (`isSet` inspects the value to
144
+ * compute the boolean, but the value itself never leaves this function.)
145
+ */
146
+ export function apiKeyStatus(): ApiKeyStatusResult {
147
+ const keys: KeyStatus[] = KEY_REGISTRY.map((k) => ({
148
+ ...k,
149
+ currentlySet: isSet(k.envVar),
150
+ }));
151
+ const requiredMissing = keys
152
+ .filter((k) => k.required && !k.currentlySet)
153
+ .map((k) => k.envVar);
154
+ const optionalMissing = keys
155
+ .filter((k) => !k.required && !k.currentlySet)
156
+ .map((k) => k.envVar);
157
+ return { keys, requiredMissing, optionalMissing, allKeysFree: true };
158
+ }
159
+
160
+ /**
161
+ * MINIMAL, dependency-free `.env` loader.
162
+ *
163
+ * Reads `${cwd||process.cwd()}/.env` if present and sets `process.env[KEY]` for
164
+ * each `KEY=VALUE` line — but ONLY if that key is not already set, so a real
165
+ * environment variable always wins over `.env` (standard precedence). Supports
166
+ * `export KEY=VALUE`, `#` comments, blank lines, and surrounding single/double
167
+ * quotes on the value. NEVER throws: a missing file returns 0 (⇒ byte-identical
168
+ * startup), and a malformed line is skipped rather than fatal.
169
+ *
170
+ * @returns the number of vars newly set into process.env.
171
+ */
172
+ export function loadDotEnv(cwd?: string): number {
173
+ const path = join(cwd ?? process.cwd(), ".env");
174
+ let text: string;
175
+ try {
176
+ text = readFileSync(path, "utf8");
177
+ } catch {
178
+ // Missing / unreadable .env ⇒ zero change. This is the common case and
179
+ // MUST be a no-op so startup is byte-identical when no .env exists.
180
+ return 0;
181
+ }
182
+
183
+ let loaded = 0;
184
+ for (const rawLine of text.split(/\r?\n/)) {
185
+ const line = rawLine.trim();
186
+ if (line.length === 0 || line.startsWith("#")) continue;
187
+
188
+ // Optional `export ` prefix.
189
+ const body = line.startsWith("export ")
190
+ ? line.slice("export ".length).trim()
191
+ : line;
192
+
193
+ const eq = body.indexOf("=");
194
+ if (eq <= 0) continue; // no `=`, or empty key ⇒ skip (malformed).
195
+
196
+ const key = body.slice(0, eq).trim();
197
+ if (!key) continue;
198
+
199
+ let value = body.slice(eq + 1).trim();
200
+ // Strip a single matching pair of surrounding quotes.
201
+ if (
202
+ value.length >= 2 &&
203
+ ((value.startsWith('"') && value.endsWith('"')) ||
204
+ (value.startsWith("'") && value.endsWith("'")))
205
+ ) {
206
+ value = value.slice(1, -1);
207
+ }
208
+
209
+ // Precedence: if the key is already set in the real environment, it wins —
210
+ // we set `process.env[key]` ONLY when it is not already present.
211
+ if (process.env[key] !== undefined) continue;
212
+ process.env[key] = value;
213
+ loaded++;
214
+ }
215
+ return loaded;
216
+ }
package/src/meta.ts ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * @cliwant/mcp-sam-gov/meta — the `_meta` completeness/provenance convention.
3
+ *
4
+ * Why this exists
5
+ * ----------------
6
+ * These tools' outputs are consumed by an AI, not a human who can eyeball
7
+ * a table. For an AI consumer, silently-misleading data is strictly worse
8
+ * than missing data: the AI cannot tell a filtered-but-blank field from a
9
+ * genuinely-empty one, a hard cap from a complete list, or a swallowed
10
+ * error from a real zero — and will state the wrong answer confidently.
11
+ *
12
+ * Every tool's success payload therefore gains a sibling `_meta` object.
13
+ * `data` is UNCHANGED (backward compat): the envelope becomes
14
+ * `{ ok, data, _meta }` where existing consumers reading `ok`/`data.*`
15
+ * are 100% unaffected.
16
+ *
17
+ * See docs/research/02-truthful-outputs-spec.md §2 for the normative spec.
18
+ */
19
+
20
+ /** Two-phase (enrich) tools: rows lost to failed per-record enrichment. */
21
+ export type MetaDegraded = {
22
+ attempted: number;
23
+ succeeded: number;
24
+ failed: number;
25
+ };
26
+
27
+ /** Offset-based pagination descriptor for list/search/aggregate tools. */
28
+ export type MetaPagination = {
29
+ /**
30
+ * The row offset of this page. `number` for offset-paginated tools (unchanged —
31
+ * every existing tool sets an integer). ADR-0010: widened to `number | null` for
32
+ * OPAQUE-CURSOR tools (GovInfo), where no meaningful numeric offset exists — those
33
+ * tools set `offset:null` (the honest "not a numeric offset"; continuation is via
34
+ * `_meta.nextCursor`, not a numeric `nextOffset`). Additive: no existing tool changes.
35
+ */
36
+ offset: number | null;
37
+ limit: number;
38
+ nextOffset: number | null;
39
+ hasMore: boolean;
40
+ };
41
+
42
+ /**
43
+ * The normative `_meta` shape (spec §2.1). Rides alongside `data` in the
44
+ * success envelope so the AI can branch on completeness/provenance
45
+ * deterministically instead of guessing from null fields.
46
+ */
47
+ export type ResponseMeta = {
48
+ /** Human+machine label of the upstream + layer that served THIS response. */
49
+ source: string;
50
+ /** SAM tools: true when no SAM_GOV_API_KEY. Non-SAM tools: always true. */
51
+ keylessMode: boolean;
52
+ /** true iff this response contains the ENTIRE result set for the query. */
53
+ complete: boolean;
54
+ /** true iff a hard cap / top-N limited the rows. */
55
+ truncated: boolean;
56
+ /** Number of primary records in `data`. */
57
+ returned: number;
58
+ /** Upstream's total match count; null when the endpoint doesn't report it. */
59
+ totalAvailable: number | null;
60
+ /**
61
+ * Present (and true) when `totalAvailable` is a KNOWN LOWER BOUND rather than
62
+ * an exact count — i.e. the upstream reported the total as "≥ N" (e.g. SEC
63
+ * EDGAR full-text search returns `hits.total.relation: "gte"` with the value
64
+ * pinned at 10000). The true total is UNKNOWN and ≥ `totalAvailable`. Absent
65
+ * on endpoints that report an exact total (do NOT read absence as `false`
66
+ * meaning "exact" for tools that never set it — it is simply not applicable).
67
+ */
68
+ totalIsLowerBound?: boolean;
69
+ /**
70
+ * Present (and true) when `totalAvailable` (or, for CKAN, the value disclosed
71
+ * in `notes`) is an upstream STATISTICAL ESTIMATE rather than an exact count —
72
+ * i.e. the source reported the total as an approximation that may be ABOVE OR
73
+ * BELOW the true count (CKAN `datastore_search` returns `total_was_estimated:
74
+ * true` for a PostgreSQL `reltuples`-style estimate, live-verified to overshoot
75
+ * — so it is NOT a lower bound, unlike `totalIsLowerBound`). CKAN sets this on
76
+ * the estimated path alongside `totalAvailable:null` (the estimate never drives
77
+ * pagination — ADR-0006 B1) + a disclosing note carrying the estimate value.
78
+ * Absent on endpoints that report an exact total (do NOT read absence as
79
+ * `false` meaning "exact" for tools that never set it — it is not applicable).
80
+ */
81
+ totalIsEstimated?: boolean;
82
+ /**
83
+ * Present when this response comes from an OPAQUE-CURSOR-paginated source
84
+ * (ADR-0010 — GovInfo's `offsetMark`): the opaque continuation token to pass back
85
+ * to fetch the NEXT page (GovInfo: as the `pageMark` argument), or `null` on the
86
+ * last page (no further cursor). It is a source-minted token, NOT derived from any
87
+ * secret and NEVER the raw upstream `nextPage` URL (which embeds pageSize + the
88
+ * api_key). Cursor tools set `nextOffset:null`/`offset:null` (a numeric offset is
89
+ * meaningless for a cursor) and use THIS as the sole continuation surface. Absent
90
+ * on offset-paginated tools (do NOT read absence as "no more" for those). Added as
91
+ * a conditional passthrough exactly like totalIsLowerBound/totalIsEstimated —
92
+ * only surfaced when the tool provides it, so existing tools' `_meta` stays
93
+ * byte-identical and the tools/list snapshot is unaffected (it is a runtime `_meta`
94
+ * field, not part of any tool's input schema).
95
+ */
96
+ nextCursor?: string | null;
97
+ /** Request filters the upstream verifiably honored. */
98
+ filtersApplied: string[];
99
+ /** Request filters sent but NOT honored (results are unfiltered on these). */
100
+ filtersDropped: string[];
101
+ /** Fields null/absent BY LIMITATION (keyless/endpoint), not "no data". */
102
+ fieldsUnavailable: string[];
103
+ /** Two-phase tools only: rows for which per-record detail was fetched. */
104
+ enrichedCount?: number;
105
+ /** Two-phase tools: enrichment accounting (see MetaDegraded). */
106
+ degraded?: MetaDegraded;
107
+ /** Present on list/search/aggregate tools. */
108
+ pagination?: MetaPagination;
109
+ /**
110
+ * P5 PROVENANCE (ADR-0045 B2/M1). The access path that served THIS response:
111
+ * `"live"` (the current, and in Phase 1 the ONLY, path) or `"snapshot"` (a
112
+ * self-hosted cache served when the live upstream was unreachable). Set by the
113
+ * resilience port's provenance-returning primitive, then threaded by the
114
+ * adapter ONLY when NON-live — so a live response OMITS this field entirely and
115
+ * stays byte-identical to pre-P5 output. Surfaced via the guarded
116
+ * `if (partial.dataPath !== undefined)` passthrough below (NO `??` default).
117
+ * Absent ⇒ live; do NOT read absence as any other value. Freshness enum, not a
118
+ * topology label (M2): an independent host serving live data is still `"live"`.
119
+ */
120
+ dataPath?: "live" | "snapshot";
121
+ /**
122
+ * P5 FRESHNESS (ADR-0045 m3). ISO-8601 UTC timestamp of when a NON-live
123
+ * (`snapshot`) body was retrieved from the origin — the as-of instant for
124
+ * deterministic cross-tool freshness comparison. Present ONLY alongside a
125
+ * non-live `dataPath`; absent on a live response (byte-identical). When a
126
+ * snapshot carries a `totalAvailable`, it is qualified as an as-of figure via
127
+ * the existing `totalIsEstimated` flag (m1 forbids a dedicated `totalAsOf`
128
+ * field — the only NEW P5 fields are `dataPath` and `asOf`).
129
+ */
130
+ asOf?: string;
131
+ /** Short, AI-actionable caveats (natural language). */
132
+ notes: string[];
133
+ };
134
+
135
+ /**
136
+ * Build a fully-populated, invariant-consistent ResponseMeta from a partial.
137
+ *
138
+ * Safe defaults (spec §2.1): a tool that supplies nothing gets a truthful,
139
+ * "single-record / known-complete" meta (`complete:true, truncated:false`).
140
+ *
141
+ * The server (or the caller) hands over whatever it knows; this helper fills
142
+ * the rest and then ENFORCES the §2.1 invariants so the flags the AI trusts
143
+ * are internally consistent:
144
+ * - `complete === true` ⟺ NOT truncated AND filtersDropped empty AND
145
+ * (no pagination OR hasMore===false) AND (no degraded OR failed===0).
146
+ * - If totalAvailable is known and returned < totalAvailable ⇒
147
+ * complete:false, truncated:true.
148
+ * - filtersDropped non-empty ⇒ at least one note is present.
149
+ */
150
+ export function buildMeta(partial: Partial<ResponseMeta> = {}): ResponseMeta {
151
+ const source = partial.source ?? "unknown";
152
+ const keylessMode = partial.keylessMode ?? true;
153
+ const returned = partial.returned ?? 0;
154
+ const totalAvailable =
155
+ partial.totalAvailable === undefined ? null : partial.totalAvailable;
156
+ const filtersApplied = partial.filtersApplied ?? [];
157
+ const filtersDropped = partial.filtersDropped ?? [];
158
+ const fieldsUnavailable = partial.fieldsUnavailable ?? [];
159
+ const notes = partial.notes ? [...partial.notes] : [];
160
+ const pagination = partial.pagination;
161
+ const degraded = partial.degraded;
162
+
163
+ // --- Derive truncated -------------------------------------------------
164
+ // A known total that exceeds what we returned proves truncation.
165
+ const totalProvesTruncation =
166
+ totalAvailable !== null && returned < totalAvailable;
167
+ const paginationHasMore = pagination ? pagination.hasMore : false;
168
+ let truncated =
169
+ partial.truncated ?? (totalProvesTruncation || paginationHasMore);
170
+ if (totalProvesTruncation || paginationHasMore) truncated = true;
171
+
172
+ // --- P5 provenance (ADR-0045 B2/M1) -----------------------------------
173
+ // A NON-live response (a snapshot served because the live upstream was
174
+ // unreachable) is honesty-qualified below. For a live/absent dataPath this
175
+ // whole strand is INERT — `nonLiveProvenance` is false, so `complete`, the
176
+ // notes[], and totalIsEstimated are all derived EXACTLY as before P5 (Phase 1:
177
+ // no adapter threads a dataPath ⇒ byte-identical output on every one of the
178
+ // 110 tools).
179
+ const nonLiveProvenance =
180
+ partial.dataPath !== undefined && partial.dataPath !== "live";
181
+
182
+ // --- Derive complete (single source of truth = the §2.1 invariant) ----
183
+ const degradedLoss = degraded ? degraded.failed > 0 : false;
184
+ const derivedComplete =
185
+ !truncated &&
186
+ filtersDropped.length === 0 &&
187
+ !paginationHasMore &&
188
+ !degradedLoss &&
189
+ !totalProvesTruncation &&
190
+ // M1a: `complete` is defined against the LIVE result set (:53), so a snapshot
191
+ // can NEVER claim complete:true — gate the derivation behind a live/absent
192
+ // dataPath. (Inert for live: `!false` === true, no change.)
193
+ !nonLiveProvenance;
194
+ // Honor an explicit complete:false, but never let a caller claim
195
+ // complete:true when the invariant says otherwise.
196
+ const complete =
197
+ partial.complete === false ? false : derivedComplete;
198
+
199
+ // --- Invariant: filtersDropped non-empty ⇒ a note explaining it -------
200
+ if (filtersDropped.length > 0 && notes.length === 0) {
201
+ notes.push(
202
+ `The following requested filters were NOT applied by the upstream and the results are unfiltered on them: ${filtersDropped.join(", ")}. Treat these results as unfiltered on those facets.`,
203
+ );
204
+ }
205
+
206
+ // --- P5 (ADR-0045 M1c/m1): staleness note on a non-live response ------
207
+ // Push into the EXISTING notes[] (m1 killed the separate `stalenessNote`
208
+ // field). Inert for live/absent dataPath. Names the as-of instant when known.
209
+ if (nonLiveProvenance) {
210
+ const asOfPhrase = partial.asOf ? ` (as of ${partial.asOf})` : "";
211
+ notes.push(
212
+ `Live upstream was unreachable — this response is served from a ${partial.dataPath} snapshot${asOfPhrase}. Freshness is NOT guaranteed; treat completeness and totals as of the snapshot time, not live.`,
213
+ );
214
+ }
215
+
216
+ const meta: ResponseMeta = {
217
+ source,
218
+ keylessMode,
219
+ complete,
220
+ truncated,
221
+ returned,
222
+ totalAvailable,
223
+ filtersApplied,
224
+ filtersDropped,
225
+ fieldsUnavailable,
226
+ notes,
227
+ };
228
+ if (partial.enrichedCount !== undefined)
229
+ meta.enrichedCount = partial.enrichedCount;
230
+ if (degraded) meta.degraded = degraded;
231
+ if (pagination) meta.pagination = pagination;
232
+ // Conditional passthrough (like enrichedCount/pagination): only surfaced when
233
+ // the tool provides it, so existing tools' `_meta` output stays byte-identical.
234
+ if (partial.totalIsLowerBound !== undefined)
235
+ meta.totalIsLowerBound = partial.totalIsLowerBound;
236
+ // Conditional passthrough (identical shape to totalIsLowerBound above): only
237
+ // surfaced when the tool provides it (CKAN's estimated-total path), so every
238
+ // existing tool's `_meta` output stays byte-identical. NO new derivation logic.
239
+ if (partial.totalIsEstimated !== undefined)
240
+ meta.totalIsEstimated = partial.totalIsEstimated;
241
+ // Conditional passthrough (IDENTICAL shape to totalIsLowerBound/totalIsEstimated
242
+ // above): only surfaced when the tool provides it (GovInfo's opaque-cursor path),
243
+ // so every existing tool's `_meta` output stays byte-identical. NO new derivation
244
+ // logic — the value (the offsetMark token, or null on the last page) is set by the
245
+ // cursor tool and passed through verbatim.
246
+ if (partial.nextCursor !== undefined) meta.nextCursor = partial.nextCursor;
247
+ // P5 provenance passthrough (ADR-0045 B2) — IDENTICAL guarded idiom to
248
+ // totalIsLowerBound/nextCursor above: surfaced ONLY when the adapter provides
249
+ // it, so every existing (live, dataPath-absent) tool `_meta` stays
250
+ // byte-identical. NO `??` default. In Phase 1 no adapter threads these ⇒ inert.
251
+ if (partial.dataPath !== undefined) meta.dataPath = partial.dataPath;
252
+ if (partial.asOf !== undefined) meta.asOf = partial.asOf;
253
+ // M1b: a snapshot's totalAvailable is an as-of figure, NOT a live exact total —
254
+ // qualify it via the EXISTING totalIsEstimated flag (m1 forbids a new
255
+ // totalAsOf field) so an AI never reads it as a live count. Only when a total
256
+ // is actually present. Inert for live (nonLiveProvenance false).
257
+ if (nonLiveProvenance && totalAvailable !== null) meta.totalIsEstimated = true;
258
+ return meta;
259
+ }
260
+
261
+ /**
262
+ * Branded wrapper a tool handler returns to attach `_meta` to its payload.
263
+ *
264
+ * A handler may return either its raw domain object (server synthesizes a
265
+ * minimal truthful default) OR `withMeta(data, partialMeta)`. The brand lets
266
+ * the server distinguish "handler attached meta" from "domain object that
267
+ * happens to have `data`/`_meta` keys" with zero ambiguity.
268
+ */
269
+ export class MetaBundle<T = unknown> {
270
+ readonly __isMetaBundle = true as const;
271
+ constructor(
272
+ readonly data: T,
273
+ readonly meta: Partial<ResponseMeta>,
274
+ ) {}
275
+ }
276
+
277
+ /** Attach a partial `_meta` to a handler's `data`. Server finalizes it. */
278
+ export function withMeta<T>(
279
+ data: T,
280
+ meta: Partial<ResponseMeta>,
281
+ ): MetaBundle<T> {
282
+ return new MetaBundle(data, meta);
283
+ }
284
+
285
+ /** Type guard: did the handler hand back a MetaBundle? */
286
+ export function isMetaBundle(v: unknown): v is MetaBundle {
287
+ return (
288
+ typeof v === "object" &&
289
+ v !== null &&
290
+ (v as { __isMetaBundle?: unknown }).__isMetaBundle === true
291
+ );
292
+ }