@cliwant/mcp-sam-gov 1.0.0 → 1.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/dist/server.js CHANGED
@@ -44,6 +44,9 @@ import * as nih from "./nih.js";
44
44
  import * as nsf from "./nsf.js";
45
45
  import * as clinicaltrials from "./clinicaltrials.js";
46
46
  import * as census from "./census.js";
47
+ import * as censusEconomic from "./census-economic.js";
48
+ import * as fred from "./fred.js";
49
+ import * as gsaPerdiem from "./gsa-perdiem.js";
47
50
  import * as fema from "./fema.js";
48
51
  import * as fdic from "./fdic.js";
49
52
  import * as bls from "./bls.js";
@@ -54,6 +57,7 @@ import * as cms from "./cms.js";
54
57
  import * as fac from "./fac.js";
55
58
  import * as usitc from "./usitc.js";
56
59
  import { fetchAttachmentText } from "./attachments.js";
60
+ import * as keys from "./keys.js";
57
61
  import { toToolError, ToolErrorCarrier, errorFromResponse } from "./errors.js";
58
62
  import { buildMeta, isMetaBundle, withMeta, } from "./meta.js";
59
63
  import { pathToFileURL, fileURLToPath } from "node:url";
@@ -61,7 +65,7 @@ import { realpathSync } from "node:fs";
61
65
  const SERVER_NAME = "mcp-sam-gov";
62
66
  // Kept in lockstep with package.json / manifest.json / server.json.
63
67
  // Keep in sync with package.json "version" (asserted at release; see CHANGELOG).
64
- const SERVER_VERSION = "1.0.0";
68
+ const SERVER_VERSION = "1.2.0";
65
69
  // ─── Tool input schemas (Zod) ────────────────────────────────────
66
70
  const SamSearchInput = z.object({
67
71
  query: z.string().optional().describe("Free-text title query"),
@@ -2789,6 +2793,120 @@ const CensusGeographiesByCoordinatesInput = z
2789
2793
  message: "latitude (or its alias y) is required.",
2790
2794
  path: ["latitude"],
2791
2795
  });
2796
+ // ─── US Census County Business Patterns (CBP) — the FIRST key-required source ──
2797
+ const CensusBusinessPatternsInput = z.object({
2798
+ naics: z
2799
+ .string()
2800
+ .regex(/^\d{2,6}$/)
2801
+ .optional()
2802
+ .describe("A NAICS-2017 code (2–6 digits), e.g. '5415' (Computer Systems Design & Related Services) or '54' (Professional/Scientific/Technical). Omit to aggregate across all sectors. Validated ^\\d{2,6}$."),
2803
+ geography: z
2804
+ .enum(["us", "state", "county"])
2805
+ .optional()
2806
+ .describe("The geography level (default 'us'). 'state' returns one row per state (or a single state when `state` is given); 'county' returns every county in a state and REQUIRES `state`."),
2807
+ state: z
2808
+ .string()
2809
+ .regex(/^\d{2}$/)
2810
+ .optional()
2811
+ .describe("A 2-digit state FIPS code, e.g. '06' (California), '48' (Texas). Optional filter for geography='state'; REQUIRED for geography='county' (the CBP `in=state:` predicate). Validated ^\\d{2}$."),
2812
+ year: z
2813
+ .string()
2814
+ .regex(/^\d{4}$/)
2815
+ .optional()
2816
+ .describe("The CBP data year (default '2022', the latest confirmed vintage). Validated ^\\d{4}$ (it rides in the request path)."),
2817
+ limit: z
2818
+ .number()
2819
+ .int()
2820
+ .min(0)
2821
+ .optional()
2822
+ .describe("OPTIONAL client-side top-N cap on the returned rows. CBP has NO server-side pagination, so this slices AFTER the full set is fetched and DISCLOSES the omission (totalAvailable stays the full count). Omit to return every matching row."),
2823
+ });
2824
+ // ─── FRED (Federal Reserve Economic Data) — the SECOND key-required source ──
2825
+ // ADR-0048. Macro context (GDP/CPI/rates/unemployment/PPI). REQUIRES a free
2826
+ // FRED_API_KEY; without it both tools throw an honest config error (the other 112
2827
+ // tools stay keyless). The key rides &api_key= ONLY. Missing observations ('.') → null.
2828
+ const FredSearchSeriesInput = z.object({
2829
+ query: z
2830
+ .string()
2831
+ .min(1)
2832
+ .describe("The FRED search_text — free-text terms to discover economic series, e.g. 'unemployment rate', 'CPI', 'GDP', '10-year treasury'. Required."),
2833
+ limit: z
2834
+ .number()
2835
+ .int()
2836
+ .min(1)
2837
+ .max(1000)
2838
+ .optional()
2839
+ .describe("Max series to return (default 25, max 1000). Offset-paginated."),
2840
+ offset: z
2841
+ .number()
2842
+ .int()
2843
+ .min(0)
2844
+ .optional()
2845
+ .describe("Row offset for pagination (default 0). Page with _meta.pagination.nextOffset."),
2846
+ });
2847
+ const FredSeriesObservationsInput = z.object({
2848
+ seriesId: z
2849
+ .string()
2850
+ .regex(/^[A-Za-z0-9._-]+$/)
2851
+ .describe("A FRED series id, e.g. 'GDP', 'CPIAUCSL' (CPI), 'UNRATE' (unemployment), 'DGS10' (10-yr Treasury), 'PPIACO' (PPI). Discover ids with fred_search_series. Validated ^[A-Za-z0-9._-]+$. Required."),
2852
+ startDate: z
2853
+ .string()
2854
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
2855
+ .optional()
2856
+ .describe("Earliest observation date (YYYY-MM-DD). Maps to FRED observation_start."),
2857
+ endDate: z
2858
+ .string()
2859
+ .regex(/^\d{4}-\d{2}-\d{2}$/)
2860
+ .optional()
2861
+ .describe("Latest observation date (YYYY-MM-DD). Maps to FRED observation_end."),
2862
+ limit: z
2863
+ .number()
2864
+ .int()
2865
+ .min(1)
2866
+ .max(100000)
2867
+ .optional()
2868
+ .describe("Max observations to return (default 100, max 100000). Offset-paginated."),
2869
+ offset: z
2870
+ .number()
2871
+ .int()
2872
+ .min(0)
2873
+ .optional()
2874
+ .describe("Row offset for pagination (default 0). Page with _meta.pagination.nextOffset."),
2875
+ sortOrder: z
2876
+ .enum(["asc", "desc"])
2877
+ .optional()
2878
+ .describe("Observation date order: 'asc' (oldest first, FRED default) or 'desc' (newest first)."),
2879
+ });
2880
+ // ─── GSA Federal Travel Per-Diem (api.gsa.gov) — travel-cost lane ──
2881
+ // ADR-0050. Lodging + M&IE reimbursement ceilings by city/state OR zip for a year.
2882
+ // KEYLESS by default via the shared DEMO_KEY (datagovKey.ts seam); DATA_GOV_API_KEY
2883
+ // lifts the rate. EITHER (city+state) OR zip — both/neither ⇒ invalid_input, 0 fetch.
2884
+ const GsaPerdiemRatesInput = z
2885
+ .object({
2886
+ city: z
2887
+ .string()
2888
+ .regex(/^[A-Za-z .'\-]{1,60}$/)
2889
+ .optional()
2890
+ .describe("The city name (e.g. 'Washington', 'San Francisco'). Requires `state`. Validated ^[A-Za-z .'\\-]{1,60}$. Use EITHER (city + state) OR zip — not both."),
2891
+ state: z
2892
+ .string()
2893
+ .regex(/^[A-Za-z]{2}$/)
2894
+ .optional()
2895
+ .describe("The 2-letter state/territory code (e.g. 'DC', 'CA'). Required with `city`. Validated ^[A-Za-z]{2}$."),
2896
+ zip: z
2897
+ .string()
2898
+ .regex(/^\d{5}$/)
2899
+ .optional()
2900
+ .describe("A 5-digit ZIP code (e.g. '20001'). The alternative lookup mode to city+state. Validated ^\\d{5}$. Use EITHER zip OR (city + state) — not both."),
2901
+ year: z
2902
+ .string()
2903
+ .regex(/^\d{4}$/)
2904
+ .optional()
2905
+ .describe("The per-diem fiscal year (default '2025'). Validated ^\\d{4}$ (it rides in the request path)."),
2906
+ })
2907
+ .describe("Look up GSA per-diem rates by EITHER (city + state) OR zip. Supplying both, or neither, ⇒ invalid_input.");
2908
+ // api_key_status takes no input — it is a pure status query over process.env.
2909
+ const ApiKeyStatusInput = z.object({});
2792
2910
  // Build a ToolDef whose `handler` is type-checked against the schema's inferred
2793
2911
  // input `I` at the call site (e.g. `input.searchText` is known-present). The
2794
2912
  // `I` binding is erased to `any` in the ToolDef[] array, so entries without a
@@ -4049,9 +4167,72 @@ export const TOOLS = [
4049
4167
  inputSchema: CensusGeographiesByCoordinatesInput,
4050
4168
  handler: (input) => census.geographiesByCoordinates(input),
4051
4169
  }),
4170
+ // ━━━ US Census County Business Patterns — market sizing (1) ━━━ ADR-0047
4171
+ // ★The server's FIRST KEY-REQUIRED source: the Census Data API removed its
4172
+ // keyless tier, so WITHOUT a CENSUS_API_KEY this tool throws an honest
4173
+ // invalid_input config error (the other 111 tools stay keyless). NAICS×geography
4174
+ // establishments / employment / annual payroll — the demand-side market-sizing
4175
+ // lane. Census negative suppression sentinels (-999999999 …) map to null (never
4176
+ // a negative number / never 0). The 2D-array body is parsed by header name.
4177
+ defineTool({
4178
+ name: "census_business_patterns",
4179
+ description: "Market sizing by NAICS × geography — establishments, employment, and annual payroll from the US Census County Business Patterns (CBP) API (api.census.gov/data/{year}/cbp). ★REQUIRES a free CENSUS_API_KEY: the Census Data API has NO keyless tier, so without the key this tool THROWS an honest config error (get one at https://api.census.gov/data/key_signup.html; Census and FRED are the only key-required sources — every other tool is keyless). Input: optional `naics` (2–6 digit NAICS-2017, e.g. '5415'; omit to aggregate all sectors), `geography` (us|state|county, default us; county REQUIRES `state`), `state` (2-digit FIPS, e.g. '06'), `year` (default '2022'), optional `limit` (client-side top-N; CBP has no server pagination). Returns { rows:[{ name, geoId, naicsCode, naicsLabel, establishments, employees, annualPayrollUsd, state }] } + honest _meta. HONESTY: establishments/employees are integer counts and annualPayrollUsd is annual US dollars (×1000 from the source's $1,000-unit PAYANN); Census SUPPRESSED/withheld cells (large negative sentinels like -999999999) map to null — NEVER a negative number and NEVER 0 (a genuine 0 stays 0); geoId/naicsCode/state are STRINGS (leading zeros survive). CBP returns the COMPLETE geography set for the filter (no pagination) ⇒ totalAvailable = the row count, complete:true. A missing/invalid key ⇒ invalid_input (a 302 to the Missing-Key page); a header-only body ⇒ honest empty (returned:0); a 5xx ⇒ THROWS; a 200 non-JSON ⇒ schema_drift. The key rides ONLY in the &key= query param — never logged or echoed.",
4180
+ inputSchema: CensusBusinessPatternsInput,
4181
+ handler: (input) => censusEconomic.businessPatterns(input),
4182
+ }),
4183
+ // ━━━ FRED (Federal Reserve Economic Data) — macro context (2) ━━━ ADR-0048
4184
+ // ★The server's SECOND KEY-REQUIRED source: FRED has NO keyless tier, so WITHOUT
4185
+ // a FRED_API_KEY both tools throw an honest invalid_input config error (the other
4186
+ // 112 tools stay keyless). GDP/CPI/rates/unemployment/PPI — the macro backdrop for
4187
+ // bid escalation / market timing. A missing observation ('.') maps to null (never 0).
4188
+ defineTool({
4189
+ name: "fred_search_series",
4190
+ description: "Discover FRED economic series (GDP, CPI, interest rates, unemployment, PPI…) by free-text search (FRED /fred/series/search; api.stlouisfed.org). ★REQUIRES a free FRED_API_KEY: FRED has NO keyless tier, so without the key this tool THROWS an honest config error (get one at https://fred.stlouisfed.org/docs/api/api_key.html; this and fred_series_observations are the key-required macro tools — the other 112 tools stay keyless). Input: `query` (the search_text, required, e.g. 'unemployment rate' / 'CPI' / '10-year treasury'), optional `limit` (default 25, max 1000), `offset`. Returns { series:[{ id, title, frequency, frequencyShort, units, seasonalAdjustment, observationStart, observationEnd, lastUpdated, popularity }] } + honest _meta. Feed `id` into fred_series_observations for the time series. HONESTY: totalAvailable is FRED's EXACT reported `count` (offset pagination via hasMore/nextOffset — never fabricated); every scalar is null-never-empty-string; a genuine no-match ⇒ honest empty (returned:0); a 400 (bad/missing key) ⇒ invalid_input CARRYING FRED's error_message; a 5xx ⇒ THROWS; a 200 non-JSON / non-array `seriess` ⇒ schema_drift. The key rides ONLY in the &api_key= query param — never logged or echoed.",
4191
+ inputSchema: FredSearchSeriesInput,
4192
+ handler: (input) => fred.searchSeries(input),
4193
+ }),
4194
+ defineTool({
4195
+ name: "fred_series_observations",
4196
+ description: "Fetch a FRED series' time series of date/value observations (FRED /fred/series/observations; api.stlouisfed.org). ★REQUIRES a free FRED_API_KEY (FRED has NO keyless tier — without it this tool THROWS an honest config error; get one at https://fred.stlouisfed.org/docs/api/api_key.html). Input: `seriesId` (required, e.g. 'GDP', 'CPIAUCSL', 'UNRATE', 'DGS10', 'PPIACO'; discover with fred_search_series), optional `startDate`/`endDate` (YYYY-MM-DD), `limit` (default 100, max 100000), `offset`, `sortOrder` (asc|desc). Returns { observations:[{ date, value }] } + honest _meta. ★MISSING-VALUE HONESTY (the crux): FRED encodes a missing observation as the literal '.', which maps to value:null (missing) — NEVER 0; a genuine reported 0 is preserved as 0. HONESTY: totalAvailable is FRED's EXACT `count` (offset pagination via hasMore/nextOffset — never fabricated); a 400 (bad seriesId / missing key) ⇒ invalid_input CARRYING FRED's error_message (never a fake empty); a genuine empty ⇒ honest empty; a 5xx ⇒ THROWS; a 200 non-JSON / non-array `observations` ⇒ schema_drift. seriesId is charclass-validated (^[A-Za-z0-9._-]+$) and dates are YYYY-MM-DD; the key rides ONLY in the &api_key= query param.",
4197
+ inputSchema: FredSeriesObservationsInput,
4198
+ handler: (input) => fred.seriesObservations(input),
4199
+ }),
4200
+ // ━━━ GSA Federal Travel Per-Diem (api.gsa.gov) — travel-cost lane (1) ━━━ ADR-0050
4201
+ // The lodging + M&IE reimbursement ceilings the federal government pays for official
4202
+ // travel, by city/state OR zip for a year. SAME host (api.gsa.gov) + SAME api.data.gov
4203
+ // key seam (datagovKey.ts, X-Api-Key header) as datagov_search_datasets — KEYLESS by
4204
+ // default via the shared DEMO_KEY, keylessMode:false. EITHER (city+state) OR zip; both
4205
+ // or neither ⇒ invalid_input, 0 fetch. `value` (monthly lodging) / `meals` are null-
4206
+ // never-0; standardRate/isOconus are STRING booleans coerced to real booleans.
4207
+ defineTool({
4208
+ name: "gsa_perdiem_rates",
4209
+ description: "Look up GSA Federal Travel PER-DIEM rates — the max lodging + Meals & Incidental Expenses (M&IE) reimbursement ceilings for official U.S. government travel (api.gsa.gov /travel/perdiem/v2, keyed — DATA_GOV_API_KEY or the shared DEMO_KEY). Input: EITHER `city` (e.g. 'Washington') + `state` (2-letter, e.g. 'DC') OR `zip` (5-digit) — supplying BOTH, or NEITHER, ⇒ invalid_input with 0 fetch; optional `year` (default '2025'). Returns { rates:[{ city, county, state, zip, year, isOconus, standardRate, mealsUsd, monthlyLodgingUsd:[{ month (1-12), monthName, lodgingUsd }] }] } + honest _meta. HONESTY: lodgingUsd (the API's monthly `value`) is the MAX nightly lodging ceiling for that month — it VARIES SEASONALLY (hence a per-month array), and mealsUsd is the daily M&IE ceiling; both are integer US dollars, null-when-withheld (NEVER 0 — a genuine 0 is preserved). standardRate/isOconus are booleans coerced from the API's string 'true'/'false' (an unrecognized value ⇒ null, never a fabricated false); the months array is preserved AS-IS (never padded to 12). The API returns the COMPLETE rate set (no pagination) ⇒ totalAvailable = the row count, complete:true. A genuine no-match (rates:[]/rate:[]) ⇒ honest empty (returned:0); the API's `errors` field non-null ⇒ invalid_input carrying the message (never a fake empty); a 429 (DEMO_KEY ~10 req/hr, hit quickly) ⇒ rate_limited THROWS; a 5xx/timeout ⇒ upstream_unavailable THROWS; a 200 non-JSON ⇒ schema_drift. DEMO_KEY ~10 req/hr shared ceiling — set DATA_GOV_API_KEY (free at api.data.gov/signup) for 1000/hr. The key rides ONLY in the X-Api-Key header (never the URL/_meta).",
4210
+ inputSchema: GsaPerdiemRatesInput,
4211
+ handler: (input) => gsaPerdiem.perdiemRates(input),
4212
+ }),
4213
+ // ━━━ Self-service key discovery (1) ━━━
4214
+ // KEYLESS. A local status query — reads process.env (+ any .env auto-loaded at
4215
+ // startup) and reports, per key, whether it is set (a BOOLEAN — the key VALUE is
4216
+ // NEVER read into the output). Makes the 2-required + 5-optional key situation
4217
+ // discoverable without reading source or docs.
4218
+ defineTool({
4219
+ name: "api_key_status",
4220
+ description: "List every API key this server can use, whether each is REQUIRED or OPTIONAL, the free signup URL + what it unlocks, and whether it is CURRENTLY configured — a boolean only; the key VALUE is NEVER shown. KEYLESS (no input). Most sources are keyless; only Census (census_business_patterns) and FRED (2 tools) REQUIRE a key (they throw without one), the other 5 keys are OPTIONAL (raise a rate limit or unlock one filter). Keys can be set as host env vars OR in a `.env` file in the server's working directory (auto-loaded at startup; real env wins over .env). Returns { keys:[{ envVar, sources[], required, signupUrl, unlocks, note, currentlySet }], requiredMissing:[envVars], optionalMissing:[envVars], allKeysFree:true }. This tool tells you the CONFIG state; to verify a key actually WORKS, call that source's own tool. Getting a key (creating the account at the signup URL) is your step — the server automates discovery + configuration, not signup.",
4221
+ inputSchema: ApiKeyStatusInput,
4222
+ handler: async () => keys.apiKeyStatus(),
4223
+ }),
4052
4224
  ];
4053
4225
  // ─── Server bootstrap ────────────────────────────────────────────
4054
4226
  async function main() {
4227
+ // Auto-load API keys from a `.env` in the working directory BEFORE anything
4228
+ // reads process.env (tools read env at call time; SamGovClient below reads
4229
+ // SAM_GOV_API_KEY immediately). Real env wins over .env (precedence); no .env
4230
+ // present ⇒ zero change ⇒ byte-identical startup. We log only the COUNT — never
4231
+ // which keys or their values.
4232
+ const loadedFromEnvFile = keys.loadDotEnv();
4233
+ if (loadedFromEnvFile > 0) {
4234
+ console.error(`[mcp-sam-gov] loaded ${loadedFromEnvFile} key(s) from .env`);
4235
+ }
4055
4236
  const sam = new SamGovClient({
4056
4237
  apiKey: process.env.SAM_GOV_API_KEY?.trim() || undefined,
4057
4238
  logger: {
@@ -4166,6 +4347,9 @@ function synthesizeDefaultMeta(toolName, sam) {
4166
4347
  else if (toolName.startsWith("fpds_")) {
4167
4348
  source = "www.fpds.gov ezSearch ATOM (FPDS-NG, keyless)";
4168
4349
  }
4350
+ else if (toolName === "api_key_status") {
4351
+ source = "local (process.env + .env)";
4352
+ }
4169
4353
  else {
4170
4354
  source = "unknown";
4171
4355
  }