@cyanheads/usaspending-mcp-server 0.4.0 → 0.4.2

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 (80) hide show
  1. package/CLAUDE.md +11 -9
  2. package/Dockerfile +9 -4
  3. package/README.md +10 -6
  4. package/changelog/0.4.x/0.4.1.md +27 -0
  5. package/changelog/0.4.x/0.4.2.md +28 -0
  6. package/changelog/template.md +55 -16
  7. package/dist/config/server-config.d.ts +1 -0
  8. package/dist/config/server-config.d.ts.map +1 -1
  9. package/dist/config/server-config.js +9 -1
  10. package/dist/config/server-config.js.map +1 -1
  11. package/dist/index.js +10 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts +4 -0
  14. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts.map +1 -1
  15. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js +48 -13
  16. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js.map +1 -1
  17. package/dist/mcp-server/tools/definitions/formatting.d.ts +22 -0
  18. package/dist/mcp-server/tools/definitions/formatting.d.ts.map +1 -0
  19. package/dist/mcp-server/tools/definitions/formatting.js +24 -0
  20. package/dist/mcp-server/tools/definitions/formatting.js.map +1 -0
  21. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts.map +1 -1
  22. package/dist/mcp-server/tools/definitions/get-agency.tool.js +10 -6
  23. package/dist/mcp-server/tools/definitions/get-agency.tool.js.map +1 -1
  24. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js +8 -1
  26. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.d.ts.map +1 -1
  28. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js +8 -1
  29. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js.map +1 -1
  30. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js +8 -1
  32. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js.map +1 -1
  33. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-award.tool.js +5 -4
  35. package/dist/mcp-server/tools/definitions/get-award.tool.js.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.d.ts.map +1 -1
  37. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js +8 -1
  38. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js.map +1 -1
  39. package/dist/mcp-server/tools/definitions/get-federal-account.tool.d.ts.map +1 -1
  40. package/dist/mcp-server/tools/definitions/get-federal-account.tool.js +7 -10
  41. package/dist/mcp-server/tools/definitions/get-federal-account.tool.js.map +1 -1
  42. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.d.ts.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js +17 -4
  44. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts.map +1 -1
  46. package/dist/mcp-server/tools/definitions/get-recipient.tool.js +3 -2
  47. package/dist/mcp-server/tools/definitions/get-recipient.tool.js.map +1 -1
  48. package/dist/mcp-server/tools/definitions/index.d.ts +4 -0
  49. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  50. package/dist/mcp-server/tools/definitions/list-agencies.tool.d.ts.map +1 -1
  51. package/dist/mcp-server/tools/definitions/list-agencies.tool.js +4 -5
  52. package/dist/mcp-server/tools/definitions/list-agencies.tool.js.map +1 -1
  53. package/dist/mcp-server/tools/definitions/pagination.d.ts +14 -8
  54. package/dist/mcp-server/tools/definitions/pagination.d.ts.map +1 -1
  55. package/dist/mcp-server/tools/definitions/pagination.js +14 -8
  56. package/dist/mcp-server/tools/definitions/pagination.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts.map +1 -1
  58. package/dist/mcp-server/tools/definitions/search-awards.tool.js +12 -3
  59. package/dist/mcp-server/tools/definitions/search-awards.tool.js.map +1 -1
  60. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.d.ts.map +1 -1
  61. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js +7 -1
  62. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js.map +1 -1
  63. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts.map +1 -1
  64. package/dist/mcp-server/tools/definitions/search-recipients.tool.js +14 -5
  65. package/dist/mcp-server/tools/definitions/search-recipients.tool.js.map +1 -1
  66. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts.map +1 -1
  67. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js +9 -1
  68. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js.map +1 -1
  69. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts.map +1 -1
  70. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js +3 -2
  71. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js.map +1 -1
  72. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts.map +1 -1
  73. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js +8 -7
  74. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js.map +1 -1
  75. package/dist/services/usaspending/usaspending-service.d.ts +34 -0
  76. package/dist/services/usaspending/usaspending-service.d.ts.map +1 -1
  77. package/dist/services/usaspending/usaspending-service.js +83 -34
  78. package/dist/services/usaspending/usaspending-service.js.map +1 -1
  79. package/package.json +8 -8
  80. package/server.json +3 -3
package/CLAUDE.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # Developer Protocol
2
2
 
3
3
  **Server:** usaspending-mcp-server
4
- **Version:** 0.4.0
5
- **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.11.0`
4
+ **Version:** 0.4.2
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.12.3`
6
6
  **Engines:** Bun ≥1.3.0, Node ≥24.0.0
7
- **MCP SDK:** `@modelcontextprotocol/sdk` ^1.29.0
7
+ **MCP SDK:** `@modelcontextprotocol/server` + `@modelcontextprotocol/client` ^2.0.0
8
8
  **Zod:** ^4.4.3
9
9
 
10
10
  > **Read the framework docs first:** `node_modules/@cyanheads/mcp-ts-core/CLAUDE.md` contains the full API reference — builders, Context, error codes, exports, patterns. This file covers server-specific conventions only.
@@ -35,7 +35,7 @@ Tailor suggestions to what's actually missing or stale — don't recite the full
35
35
  - **Logic throws, framework catches.** Tool/resource handlers are pure — throw on failure, no `try/catch`. Plain `Error` is fine; the framework catches, classifies, and formats. Use error factories (`notFound()`, `validationError()`, etc.) when the error code matters.
36
36
  - **Use `ctx.log`** for request-scoped logging. No `console` calls.
37
37
  - **Use `ctx.state`** for tenant-scoped storage. Never access persistence directly.
38
- - **Check `ctx.elicit`** for presence before calling.
38
+ - **Need input the caller didn't supply?** `return ctx.requestInput(...)` and read `ctx.inputs` when the handler is re-entered. Never `await` for user input mid-handler.
39
39
  - **Secrets in env vars only** — never hardcoded.
40
40
  - **Close the loop on issues.** When implementing work tracked by a GitHub issue, comment on the issue with what landed and close it. Do both — a comment without a close leaves stale issues open; a close without a comment leaves no record of what shipped. The comment is for future readers — state the concrete changes, not the conversation that produced them.
41
41
 
@@ -91,7 +91,7 @@ export const itemData = resource('inventory://{itemId}', {
91
91
  params: z.object({ itemId: z.string().describe('Item identifier') }),
92
92
  auth: ['inventory:read'],
93
93
  async handler(params, ctx) {
94
- const item = await ctx.state.get(`item:${params.itemId}`);
94
+ const item = await ctx.state.get(`item/${params.itemId}`);
95
95
  if (!item) throw notFound(`Item ${params.itemId} not found`, { itemId: params.itemId });
96
96
  return item;
97
97
  },
@@ -125,6 +125,7 @@ import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';
125
125
  const ServerConfigSchema = z.object({
126
126
  apiKey: z.string().describe('External API key'),
127
127
  maxResults: z.coerce.number().default(100),
128
+ verboseLogging: z.stringbool().default(false).describe('Enable verbose logging'),
128
129
  });
129
130
 
130
131
  let _config: z.infer<typeof ServerConfigSchema> | undefined;
@@ -132,6 +133,7 @@ export function getServerConfig() {
132
133
  _config ??= parseEnvConfig(ServerConfigSchema, {
133
134
  apiKey: 'MY_API_KEY',
134
135
  maxResults: 'MY_MAX_RESULTS',
136
+ verboseLogging: 'MY_VERBOSE_LOGGING',
135
137
  });
136
138
  return _config;
137
139
  }
@@ -166,13 +168,13 @@ Handlers receive a unified `ctx` object. Key properties:
166
168
 
167
169
  | Property | Description |
168
170
  |:---------|:------------|
169
- | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. |
171
+ | `ctx.log` | Request-scoped logger — `.debug()`, `.info()`, `.notice()`, `.warning()`, `.error()`. Auto-correlates requestId, traceId, tenantId. Dual-sink: Pino **and** `notifications/message` to the client, so treat it as client-visible. |
170
172
  | `ctx.state` | Tenant-scoped KV — `.get(key)`, `.set(key, value, { ttl? })`, `.delete(key)`, `.getMany(keys)`, `.list(prefix, { cursor, limit })`. Accepts any serializable value. |
171
- | `ctx.elicit` | Ask user for structured input — form call `(message, schema)` or `.url(message, url)` for an external link. **Check for presence first:** `if (ctx.elicit) { ... }` |
173
+ | `ctx.requestInput` | Suspend and ask the caller for more input — `return ctx.requestInput({ inputRequests: { key: inputRequired.elicit({ message, requestedSchema }) } })`. Never returns; the handler is re-entered with the answers. Always present. |
174
+ | `ctx.inputs` | Reader over a retried request's responses — `.accepted(key, schema)`, `.view(key)`, `.state()`, `.dropped`. Empty on the first round. |
172
175
  | `ctx.enrich` | Success-path agent context (empty-result notices, query echo, pagination totals) — `ctx.enrich(...)` or `.notice()` / `.total()` / `.echo()` / `.truncated()`. Reaches `structuredContent` and `content[]`; lands only when the definition declares an `enrichment` block (no-op otherwise). |
173
176
  | `ctx.content` | Non-text content blocks — `.image(data, mimeType)`, `.audio(data, mimeType)`, or `ctx.content(block)` for a raw block. Prepended to `content[]` after `format()`; never enters `structuredContent`. |
174
177
  | `ctx.signal` | `AbortSignal` for cancellation. |
175
- | `ctx.progress` | Task progress (present when `task: true`) — `.setTotal(n)`, `.increment()`, `.update(message)`. |
176
178
  | `ctx.requestId` | Unique request ID. |
177
179
  | `ctx.tenantId` | Tenant ID from JWT; `'default'` for stdio or HTTP with auth off. |
178
180
 
@@ -288,7 +290,7 @@ Available skills:
288
290
  | `api-auth` | Auth modes, scopes, JWT/OAuth |
289
291
  | `api-canvas` | DataCanvas: register tabular data, run SQL, export, plus the `spillover()` helper for big result sets — Tier 3 opt-in |
290
292
  | `api-config` | AppConfig, parseConfig, env vars |
291
- | `api-context` | Context interface, logger, state, progress |
293
+ | `api-context` | Context interface, RequestContext, logger, state, multi-round-trip input |
292
294
  | `api-errors` | McpError, JsonRpcErrorCode, error patterns |
293
295
  | `api-linter` | Definition linter rule catalog — invoked by `bun run lint:mcp` and `devcheck` |
294
296
  | `api-mirror` | MirrorService: persistent self-refreshing local mirror (embedded SQLite + FTS5) of a bulk upstream dataset — Tier 3 opt-in |
package/Dockerfile CHANGED
@@ -4,7 +4,7 @@
4
4
  # This stage installs all dependencies (including dev), builds the TypeScript
5
5
  # source code into JavaScript, and prepares the production assets.
6
6
  # ==============================================================================
7
- FROM oven/bun:1.3.14 AS build
7
+ FROM oven/bun:1.4.0 AS build
8
8
 
9
9
  WORKDIR /usr/src/app
10
10
 
@@ -30,7 +30,7 @@ RUN bun run build
30
30
  # application. It uses a slim base image and only includes production
31
31
  # dependencies and build artifacts.
32
32
  # ==============================================================================
33
- FROM oven/bun:1.3.14-slim AS production
33
+ FROM oven/bun:1.4.0-slim AS production
34
34
 
35
35
  WORKDIR /usr/src/app
36
36
 
@@ -51,8 +51,13 @@ COPY package.json bun.lock ./
51
51
 
52
52
  # Install only production dependencies, ignoring any lifecycle scripts (like 'prepare')
53
53
  # that are not needed in the final production image.
54
+ # `--omit=peer` drops the framework's optional peer tiers (test runner, service
55
+ # SDKs, parsers) that Bun would otherwise auto-install. Anything this server
56
+ # actually imports belongs in its own `dependencies`, so nothing needed at
57
+ # runtime is lost. The OTEL step below carries the same flag — without it, that
58
+ # install re-resolves the graph and pulls every optional peer back in.
54
59
  RUN --mount=type=cache,target=/root/.bun/install/cache \
55
- bun install --production --frozen-lockfile --ignore-scripts
60
+ bun install --production --omit=peer --frozen-lockfile --ignore-scripts
56
61
 
57
62
  # Conditionally install OpenTelemetry optional peer dependencies (Tier 3).
58
63
  # These are not bundled by default to keep the base image lean. Enable at build time
@@ -60,7 +65,7 @@ RUN --mount=type=cache,target=/root/.bun/install/cache \
60
65
  ARG OTEL_ENABLED=true
61
66
  RUN --mount=type=cache,target=/root/.bun/install/cache \
62
67
  if [ "$OTEL_ENABLED" = "true" ]; then \
63
- bun add --omit=dev --ignore-scripts @hono/otel \
68
+ bun add --omit=dev --omit=peer --ignore-scripts @hono/otel \
64
69
  @opentelemetry/instrumentation-http \
65
70
  @opentelemetry/exporter-metrics-otlp-http \
66
71
  @opentelemetry/exporter-trace-otlp-http \
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  <div align="center">
9
9
 
10
- [![Version](https://img.shields.io/badge/Version-0.4.0-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/usaspending-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^1.29.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/usaspending-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/usaspending-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.3.14-blueviolet.svg?style=flat-square)](https://bun.sh/)
10
+ [![Version](https://img.shields.io/badge/Version-0.4.2-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/usaspending-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^2.0.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/usaspending-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/usaspending-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.4.0-blueviolet.svg?style=flat-square)](https://bun.sh/)
11
11
 
12
12
  </div>
13
13
 
@@ -95,7 +95,7 @@ List child contracts and orders placed under an IDV (Indefinite Delivery Vehicle
95
95
  List obligation history and modifications for an award.
96
96
 
97
97
  - Each row is one transaction: `action_date`, `federal_action_obligation`, `modification_number`, and description
98
- - Pagination via `limit` and `page`; configurable sort and order
98
+ - Pagination via `limit` and `page`; configurable sort and order. No `total` count is available from this endpoint
99
99
 
100
100
  ---
101
101
 
@@ -105,7 +105,7 @@ List subawards under a prime contract or grant.
105
105
 
106
106
  - Each row covers: subaward number, description, action date, amount, and recipient name
107
107
  - Reveals the supply chain below the prime — who actually performs the work
108
- - Pagination via `limit` and `page`; configurable sort and order
108
+ - Pagination via `limit` and `page`; configurable sort and order. No `total` count is available from this endpoint
109
109
 
110
110
  ---
111
111
 
@@ -171,6 +171,7 @@ Aggregate spending broken down by a single dimension.
171
171
  - `category` enum maps to the right sub-route: `naics`, `psc`, `awarding_agency`, `funding_agency`, `cfda`, or `recipient`
172
172
  - Returns top items with amounts and codes for trend analysis
173
173
  - Accepts the standard award filter object for scoping to a specific agency, time period, or keyword
174
+ - Pagination via `limit` and `page`; no `total` count is available from this endpoint
174
175
 
175
176
  ---
176
177
 
@@ -245,7 +246,8 @@ List all top-tier federal agencies.
245
246
  Discover valid code values for award filter fields.
246
247
 
247
248
  - `type` enum selects the lookup: `naics`, `psc`, `cfda`, `awarding_agency`, or `recipient`
248
- - Returns matching codes and names — use before filtering to find the right code when you only know a description (e.g., "cybersecurity" → NAICS code); `recipient` matches also carry `uei`/`duns`
249
+ - Returns matching codes and names — use before filtering to find the right code when you only know a description (e.g., "software" → NAICS codes); `recipient` matches also carry `uei`/`duns`
250
+ - The `naics` lookup matches official NAICS title text, not colloquial industry language — "software" and "aircraft" resolve, "cybersecurity" and "aircraft maintenance" return nothing. Fall back to the broader industry term the NAICS title would use
249
251
  - Consolidates five autocomplete endpoints into one tool
250
252
  - `limit` accepts 1–500 and is enforced client-side — the `recipient` lookup unions three upstream match buckets (name, UEI, DUNS) and can return up to 3x the requested count, so its results are capped before returning; the other four honor `limit` exactly
251
253
 
@@ -271,7 +273,7 @@ USAspending-specific:
271
273
  Agent-friendly output:
272
274
 
273
275
  - Chaining fields on every response — `generated_internal_id`, `agency_slug`, `recipient_hash`, and `account_code` fields are surfaced explicitly so agents can follow the money without parsing identifiers out of display strings
274
- - Pagination metadata on all list responses — `page_metadata.hasNext`, `page_metadata.page`, and `page_metadata.total` let agents iterate large result sets without guessing
276
+ - Pagination metadata on list responses — `page_metadata.has_next` and `page_metadata.page` let agents iterate large result sets without guessing. `page_metadata.total` is carried wherever the upstream endpoint publishes one; `usaspending_get_award_transactions`, `usaspending_get_award_subawards`, and `usaspending_spending_by_category` sit on endpoints that publish none, so `has_next` is the only continuation signal there
275
277
  - Structured geographic outputs — `shape_code`, `display_name`, `aggregated_amount`, and `per_capita` are typed consistently across state, county, and district views for composable analysis
276
278
 
277
279
  ## Getting started
@@ -393,10 +395,12 @@ All configuration is validated at startup via Zod schemas in `src/config/server-
393
395
  | Variable | Description | Default |
394
396
  |:---------|:------------|:--------|
395
397
  | `USASPENDING_BASE_URL` | Base URL for the USAspending.gov API. | `https://api.usaspending.gov/api/v2/` |
396
- | `USASPENDING_TIMEOUT_MS` | Per-request HTTP timeout in milliseconds. | `30000` |
398
+ | `USASPENDING_TIMEOUT_MS` | HTTP timeout in milliseconds, applied per attempt. | `30000` |
399
+ | `USASPENDING_RETRY_BUDGET_MS` | Wall-clock budget covering every retry attempt of one request, so a slow endpoint cannot re-pay the per-attempt timeout on each retry. Accepts 1000–300000. | `1.5 × USASPENDING_TIMEOUT_MS` |
397
400
  | `MCP_TRANSPORT_TYPE` | Transport: `stdio` or `http`. | `stdio` |
398
401
  | `MCP_HTTP_PORT` | Port for the HTTP server. | `3010` |
399
402
  | `MCP_HTTP_ENDPOINT_PATH` | HTTP endpoint path. | `/mcp` |
403
+ | `MCP_SESSION_MODE` | Session mode: `auto`, `stateful`, or `stateless`; `auto` resolves to `stateful`. Shipped as `stateless` in both `.env.example` and the Dockerfile — this server holds no per-session state. | `auto` |
400
404
  | `MCP_PUBLIC_URL` | Public origin override for TLS-terminating reverse-proxy deployments. | — |
401
405
  | `MCP_AUTH_MODE` | Auth mode: `none`, `jwt`, or `oauth`. | `none` |
402
406
  | `MCP_LOG_LEVEL` | Log level (`debug`, `info`, `warning`, `error`, etc.). | `info` |
@@ -0,0 +1,27 @@
1
+ ---
2
+ summary: "Bounds the service's retry loop under one wall-clock deadline, audits nine paginated tools' hasNext reads against the live API, fixes a currency sign-placement bug and an enrichment-trailer spacing bug, and corrects a misdocumented NAICS autocomplete example."
3
+ breaking: false
4
+ security: false
5
+ ---
6
+
7
+ # 0.4.1 — 2026-07-27
8
+
9
+ ## Added
10
+
11
+ - **`USASPENDING_RETRY_BUDGET_MS`** env var — a wall-clock budget spanning every retry attempt of one request, so a per-attempt timeout is no longer re-paid on each retry. Defaults to 1.5x `USASPENDING_TIMEOUT_MS`. ([#52](https://github.com/cyanheads/usaspending-mcp-server/issues/52))
12
+ - **`formatCurrency()`** in `src/mcp-server/tools/definitions/formatting.ts` — shared currency formatter that places a negative sign outside the `$` (`-$264,436.97`, not `$-264,436.97`); every monetary `format()` site on the server now routes through it.
13
+ - **`resolveHasNext()` unit tests** (`tests/tools/pagination.test.ts`) — direct coverage of its three-boundary contract, previously exercised only incidentally through its two consumer tools.
14
+
15
+ ## Changed
16
+
17
+ - **`USASpendingService`'s retry loop runs under one shared deadline** — `get()` and `post()` now route through a single `request()` primitive; an `AbortController` fires at the budget and composes with the caller's own abort signal. Deadline expiry from either propagation path (an abort mid-fetch, an abort mid-backoff) normalizes to one `Timeout` naming the exhausted budget instead of two incoherent raw errors. ([#52](https://github.com/cyanheads/usaspending-mcp-server/issues/52))
18
+ - **Nine paginated tools' `hasNext` reads verified against the live API** — `usaspending_disaster_spending`, `usaspending_get_agency` (sub-agency list), `usaspending_get_award_federal_accounts`, `usaspending_get_award_subawards`, `usaspending_get_award_transactions`, `usaspending_get_federal_account_breakdown`, `usaspending_search_federal_accounts`, `usaspending_search_recipients`, and `usaspending_spending_by_category` each carry a call-site comment recording the verified verdict and the depth it was checked to. All nine report `hasNext` truthfully at every boundary tested; no pagination guard was added to any of them. ([#54](https://github.com/cyanheads/usaspending-mcp-server/issues/54))
19
+ - **`resolveHasNext()`'s doc comment narrowed** — previously said "several" USAspending endpoints under-report `hasNext`; exactly one, `search/spending_by_award/`, is confirmed to. The comment now also states where the helper should and should not be applied.
20
+ - **`usaspending_get_idv_awards`'s guard comment corrected** — no longer claims a stale `hasNext` was observed on `idvs/awards/`. States what was verified (every constructible boundary, across IDVs with 6 and 16 children), what wasn't (the deep-offset regime, unreachable on that endpoint), and the guard's cost: a wrong `has_next: true` and an extra round trip on an exactly-full final page.
21
+ - **`usaspending_autocomplete_filters` README and design-doc examples corrected** — the NAICS example `"cybersecurity"` (0 upstream matches) is replaced with `"software"`; both docs now note that the `naics` lookup matches official NAICS title text, not colloquial industry language, and that `"aircraft maintenance"` resolves under `psc` rather than `naics`. ([#55](https://github.com/cyanheads/usaspending-mcp-server/issues/55))
22
+
23
+ ## Fixed
24
+
25
+ - **`usaspending_disaster_spending` discloses a saturated recipient total as a ceiling rather than a count** — `disaster/recipient/spending/` reports exactly 10,000 once its reachable result set saturates (verified: a single DEF code reports an honest 3,045, while broader filters land on exactly 10,000 with the last page full and the page after it empty). The recipient dimension now emits `truncated`/`shown`/`cap`/`notice` enrichment fields when the reported total lands on that ceiling. ([#54](https://github.com/cyanheads/usaspending-mcp-server/issues/54))
26
+ - **`usaspending_search_awards`'s `upstream_messages` enrichment trailer no longer runs into the following entry** — the rendered bullet list now closes with a blank line so the next trailer entry (`applied_keyword` and similar) lands on its own line instead of reading as a lazy continuation of the last bullet under a strict markdown renderer.
27
+ - **Negative dollar amounts render with the sign outside the currency symbol** — `-$264,436.97`, not `$-264,436.97` — across every tool's `format()` output. Negative amounts are ordinary in this data: deobligations, downward contract modifications, and negative award-type columns in `usaspending_spending_over_time` all report reductions as negative values.
@@ -0,0 +1,28 @@
1
+ ---
2
+ summary: "Adopts mcp-ts-core ^0.12.3 (SDK v2): tool inputs are now strict, the advertised outputSchema declares the error envelope, protocol revision 2026-07-28 is served everywhere, and session mode is pinned to stateless on every surface."
3
+ breaking: true
4
+ security: false
5
+ ---
6
+
7
+ # 0.4.2 — 2026-08-24
8
+
9
+ ## Added
10
+
11
+ - **Protocol revision `2026-07-28` is served on every HTTP endpoint**, alongside the existing 2025-era revisions — a 2025 client keeps working unchanged.
12
+ - **`tools/list` carries a cache hint** — the tool surface is 18 compiled-in definitions with no dynamic registration or per-caller filtering, so it changes only on redeploy. `cacheHints: { 'tools/list': { ttlMs: 3_600_000, cacheScope: 'public' } }` lets a 2026-era client cache it for an hour; 2025-era clients are unaffected.
13
+
14
+ ## Changed
15
+
16
+ - **Breaking: tool arguments are strict.** Every tool's advertised `inputSchema` now carries `additionalProperties: false`, and an argument key a tool's schema doesn't declare is rejected by name (`Unrecognized key: "..."`) instead of being silently dropped. A call that previously succeeded with an extra or misspelled key — its filter never applied — now fails instead of returning results the caller misread as filtered.
17
+ - **The advertised `outputSchema` declares the error envelope** — success fields are optional and `error` is a declared member. A client that validates `structuredContent` without checking `isError` no longer rejects error results.
18
+ - **`MCP_SESSION_MODE` is explicit `stateless` on every surface that sets it.** `.env.example` previously left the variable commented out, resolving through `auto` to `stateful`, while the Dockerfile already set `stateless` — a container and a source run served different session modes. `.env.example` now ships uncommented with `stateless` and documents all three accepted values (`auto` / `stateful` / `stateless`) and the real default; the README configuration table gains a row for it.
19
+
20
+ ## Fixed
21
+
22
+ - **The production Docker image no longer pulls the framework's optional peer dependencies** (test runner, service SDKs, parsers) — `bun install --production` now passes `--omit=peer`, so only what this server actually imports lands in the image; the OTel install step carries the same flag so it doesn't re-resolve the graph and pull them back in.
23
+
24
+ ## Dependencies
25
+
26
+ - `@cyanheads/mcp-ts-core` `^0.11.0` → `^0.12.3` — nine releases, including the SDK v2 migration in 0.12.0 (`@modelcontextprotocol/sdk` + `@hono/mcp` replaced by `@modelcontextprotocol/server` + `@modelcontextprotocol/client`, `ctx.elicit` replaced by `ctx.requestInput`/`ctx.inputs`, the experimental tasks surface removed).
27
+ - `bun` `1.3.14` → `1.4.0` (`packageManager`, `Dockerfile` base images).
28
+ - `@biomejs/biome` `^2.5.5` → `^2.5.10`, `@types/node` `^26.0.0` → `^26.2.0`, `ignore` `^7.0.5` → `^7.0.6`, `tsc-alias` `^1.8.17` → `^1.9.2`, `vitest` `^4.1.9` → `^4.1.11`.
@@ -4,10 +4,11 @@
4
4
  # to author a new release. Set that file's H1 to `# <version> — YYYY-MM-DD`
5
5
  # with a concrete date.
6
6
 
7
- # Required. One-line GitHub Release-style headline. 350 character cap.
8
- # Default short and scannable. Don't pad, don't stitch unrelated changes with
9
- # semicolons — pick the headline. Quotes required: unquoted YAML treats `: `
10
- # inside the value as a key separator and fails GitHub's strict parser.
7
+ # Required. One-line GitHub Release-style headline. 350 character cap — a
8
+ # ceiling, not a target. Default short and scannable. Don't pad, don't stitch
9
+ # unrelated changes with commas/semicolons into an inventory — pick the
10
+ # headline, like a tag's theme line. Quotes required: unquoted YAML treats
11
+ # `: ` inside the value as a key separator and fails GitHub's strict parser.
11
12
  summary: ""
12
13
 
13
14
  # Set `true` when consumers must change code to upgrade: API removals,
@@ -24,9 +25,10 @@ security: false
24
25
 
25
26
  # Optional free-form notes for maintenance agents processing this release.
26
27
  # Not rendered in CHANGELOG — consumed by agents running `maintenance` on
27
- # downstream servers. Use for adoption instructions that don't fit the
28
- # human-facing sections: new files to create, fields to populate, one-time
29
- # migration steps. Omit the field entirely when there's nothing to say.
28
+ # downstream servers. ADOPTION STEPS ONLY — new files to create, fields to
29
+ # populate, one-time migration steps. Never a second rendering of the body:
30
+ # if a body bullet already says it, name the bullet's symbol instead of
31
+ # re-explaining. Omit the field entirely when there's nothing to say.
30
32
  # agent-notes: |
31
33
  # <instructions for downstream maintenance agents>
32
34
  ---
@@ -41,17 +43,54 @@ security: false
41
43
  each bullet with the symbol or concept name in **bold** so they can skip
42
44
  what's irrelevant and zoom in on what's not.
43
45
 
44
- Tone: terse, fact-dense, not verbose. Default to one sentence per bullet —
45
- name the symbol, state what changed, stop. Use a second sentence only when
46
- it carries weight. If a bullet feels long, it is.
47
-
48
- Cut: mechanism walkthroughs (those belong in JSDoc, CLAUDE.md/AGENTS.md, or the
49
- relevant skill), ceremonial framings ("This release introduces…",
50
- backwards-compat paragraphs), file-by-file test enumerations, internal
51
- implementation notes. Prefer code/symbol names over English re-explanations.
46
+ Tone: terse, fact-dense, not verbose. Bullet shape: **symbol** + what
47
+ changed + at most one consumer-facing caveat. One sentence by default, two
48
+ when the second carries weight — a bullet past ~40 words or three sentences
49
+ is wrong. The depth lives one hop away: the linked issue carries the why,
50
+ the commit diff carries the how. The changelog names what changed and what
51
+ a consumer does about it; a reader who wants mechanism opens the link.
52
+
53
+ Model length on THIS guide, never on the previous entry — entries modeled
54
+ on entries compound.
55
+
56
+ Cut (each has shipped as a wall of text; these are the cruft):
57
+ - History/justification narration — how the bug worked, why the old
58
+ behavior was wrong. One short clause at most; the issue carries the story.
59
+ - Design-rationale defense — "chosen over Y because…", "guarding the
60
+ getter is not enough…". That is the author arguing with a reviewer;
61
+ reviewers read the PR, not the changelog.
62
+ - Defensive unchanged-clauses — "X is unchanged", "byte-identical to
63
+ <prev>". Keep one only where its absence would cause a real misread,
64
+ as a short parenthetical.
65
+ - Edge-case inventories — marker lists, not-flagged lists, escape tables.
66
+ Tests and the issue carry those.
67
+ - Mechanism walkthroughs (JSDoc, CLAUDE.md/AGENTS.md, or the relevant
68
+ skill own those), ceremonial framings ("This release introduces…"),
69
+ backwards-compat paragraphs, file-by-file test enumerations. Prefer
70
+ code/symbol names over English re-explanations.
71
+
72
+ Verified ≠ included: the every-claim-verified-from-the-diff rule bounds
73
+ the TRUTH of what you write, never the AMOUNT.
74
+
75
+ Example — same fact, right size:
76
+
77
+ TOO LONG: **`fetchWithTimeout`'s `timeoutMs` bounds the whole exchange**
78
+ (#341). `fetch` resolves once headers arrive and the deadline was
79
+ cleared as the helper returned, so a peer that answered promptly and
80
+ then stalled the stream held the request open indefinitely. A 2xx
81
+ carrying a body now comes back as a passthrough wrapper that disarms
82
+ the deadline when the body closes, errors, or is cancelled; …
83
+ [+90 more words of mechanism and edge cases]
84
+
85
+ RIGHT: **`fetchWithTimeout`'s `timeoutMs` now bounds the whole
86
+ exchange, not just the headers** (#341). A stalled body aborts with
87
+ the same `Timeout` error; the returned `Response` is a wrapper, so
88
+ identity assertions (`toBe(response)`) no longer hold.
52
89
 
53
90
  Narrative intro: skip by default. Add one short sentence only when the
54
- release theme genuinely needs framing the bullets can't carry.
91
+ release theme genuinely needs framing the bullets can't carry. When many
92
+ bullets share one upgrade consequence, state it ONCE — intro line or
93
+ agent-notes — never per bullet.
55
94
 
56
95
  Sections: Keep a Changelog order — Added, Changed, Deprecated, Removed,
57
96
  Fixed, Security. Include only sections with entries; delete the rest
@@ -6,6 +6,7 @@ import { z } from '@cyanheads/mcp-ts-core';
6
6
  declare const ServerConfigSchema: z.ZodObject<{
7
7
  baseUrl: z.ZodDefault<z.ZodString>;
8
8
  timeoutMs: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
9
+ retryBudgetMs: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
9
10
  }, z.core.$strip>;
10
11
  export type ServerConfig = z.infer<typeof ServerConfigSchema>;
11
12
  export declare function getServerConfig(): ServerConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.d.ts","sourceRoot":"","sources":["../../src/config/server-config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAG3C,QAAA,MAAM,kBAAkB;;;iBAatB,CAAC;AAEH,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAI9D,wBAAgB,eAAe,IAAI,YAAY,CAM9C"}
1
+ {"version":3,"file":"server-config.d.ts","sourceRoot":"","sources":["../../src/config/server-config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAG3C,QAAA,MAAM,kBAAkB;;;;iBAsBtB,CAAC;AAEH,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAI9D,wBAAgB,eAAe,IAAI,YAAY,CAO9C"}
@@ -16,13 +16,21 @@ const ServerConfigSchema = z.object({
16
16
  .min(1000)
17
17
  .max(120_000)
18
18
  .default(30_000)
19
- .describe('HTTP request timeout in milliseconds'),
19
+ .describe('HTTP request timeout in milliseconds, per attempt'),
20
+ retryBudgetMs: z.coerce
21
+ .number()
22
+ .int()
23
+ .min(1000)
24
+ .max(300_000)
25
+ .optional()
26
+ .describe('Wall-clock budget covering every retry attempt of one request. Defaults to 1.5x the per-attempt timeout, which leaves room for one retry rather than four full timeouts plus backoff.'),
20
27
  });
21
28
  let _config;
22
29
  export function getServerConfig() {
23
30
  _config ??= parseEnvConfig(ServerConfigSchema, {
24
31
  baseUrl: 'USASPENDING_BASE_URL',
25
32
  timeoutMs: 'USASPENDING_TIMEOUT_MS',
33
+ retryBudgetMs: 'USASPENDING_RETRY_BUDGET_MS',
26
34
  });
27
35
  return _config;
28
36
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sourceRoot":"","sources":["../../src/config/server-config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IAClC,OAAO,EAAE,CAAC;SACP,MAAM,EAAE;SACR,GAAG,EAAE;SACL,OAAO,CAAC,qCAAqC,CAAC;SAC9C,QAAQ,CAAC,iCAAiC,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM;SAChB,MAAM,EAAE;SACR,GAAG,EAAE;SACL,GAAG,CAAC,IAAI,CAAC;SACT,GAAG,CAAC,OAAO,CAAC;SACZ,OAAO,CAAC,MAAM,CAAC;SACf,QAAQ,CAAC,sCAAsC,CAAC;CACpD,CAAC,CAAC;AAIH,IAAI,OAAiC,CAAC;AAEtC,MAAM,UAAU,eAAe;IAC7B,OAAO,KAAK,cAAc,CAAC,kBAAkB,EAAE;QAC7C,OAAO,EAAE,sBAAsB;QAC/B,SAAS,EAAE,wBAAwB;KACpC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC"}
1
+ {"version":3,"file":"server-config.js","sourceRoot":"","sources":["../../src/config/server-config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IAClC,OAAO,EAAE,CAAC;SACP,MAAM,EAAE;SACR,GAAG,EAAE;SACL,OAAO,CAAC,qCAAqC,CAAC;SAC9C,QAAQ,CAAC,iCAAiC,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM;SAChB,MAAM,EAAE;SACR,GAAG,EAAE;SACL,GAAG,CAAC,IAAI,CAAC;SACT,GAAG,CAAC,OAAO,CAAC;SACZ,OAAO,CAAC,MAAM,CAAC;SACf,QAAQ,CAAC,mDAAmD,CAAC;IAChE,aAAa,EAAE,CAAC,CAAC,MAAM;SACpB,MAAM,EAAE;SACR,GAAG,EAAE;SACL,GAAG,CAAC,IAAI,CAAC;SACT,GAAG,CAAC,OAAO,CAAC;SACZ,QAAQ,EAAE;SACV,QAAQ,CACP,uLAAuL,CACxL;CACJ,CAAC,CAAC;AAIH,IAAI,OAAiC,CAAC;AAEtC,MAAM,UAAU,eAAe;IAC7B,OAAO,KAAK,cAAc,CAAC,kBAAkB,EAAE;QAC7C,OAAO,EAAE,sBAAsB;QAC/B,SAAS,EAAE,wBAAwB;QACnC,aAAa,EAAE,6BAA6B;KAC7C,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/dist/index.js CHANGED
@@ -15,6 +15,16 @@ await createApp({
15
15
  resources: [],
16
16
  prompts: [],
17
17
  landing: { requireAuth: false },
18
+ /**
19
+ * The tool surface is compiled in — 18 static definitions, no dynamic
20
+ * registration, no auth scopes filtering the list per caller — so it changes
21
+ * only on a redeploy and is byte-identical for every client. An hour of
22
+ * client-side caching on `tools/list` is well inside the release cadence.
23
+ * Only 2026-07-28 clients read this; 2025-era responses are unaffected.
24
+ */
25
+ cacheHints: {
26
+ 'tools/list': { ttlMs: 3_600_000, cacheScope: 'public' },
27
+ },
18
28
  instructions: 'USAspending.gov MCP server — federal award, recipient, agency, and spending data from the US Treasury DATA Act platform.\n' +
19
29
  '- Start with usaspending_list_agencies or usaspending_autocomplete_filters to discover agency codes and NAICS/PSC codes\n' +
20
30
  '- Use usaspending_search_awards to find awards, then usaspending_get_award for full details\n' +
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AAEvF,MAAM,SAAS,CAAC;IACd,IAAI,EAAE,wBAAwB;IAC9B,KAAK,EAAE,wBAAwB;IAC/B,KAAK,EAAE,CAAC,GAAG,kBAAkB,CAAC;IAC9B,SAAS,EAAE,EAAE;IACb,OAAO,EAAE,EAAE;IACX,OAAO,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE;IAC/B,YAAY,EACV,4HAA4H;QAC5H,2HAA2H;QAC3H,+FAA+F;QAC/F,sGAAsG;QACtG,kFAAkF;IACpF,KAAK,CAAC,IAAI;QACR,MAAM,YAAY,GAAG,eAAe,EAAE,CAAC;QACvC,sBAAsB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;IAClE,CAAC;CACF,CAAC,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAC7E,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AAEvF,MAAM,SAAS,CAAC;IACd,IAAI,EAAE,wBAAwB;IAC9B,KAAK,EAAE,wBAAwB;IAC/B,KAAK,EAAE,CAAC,GAAG,kBAAkB,CAAC;IAC9B,SAAS,EAAE,EAAE;IACb,OAAO,EAAE,EAAE;IACX,OAAO,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE;IAC/B;;;;;;OAMG;IACH,UAAU,EAAE;QACV,YAAY,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE;KACzD;IACD,YAAY,EACV,4HAA4H;QAC5H,2HAA2H;QAC3H,+FAA+F;QAC/F,sGAAsG;QACtG,kFAAkF;IACpF,KAAK,CAAC,IAAI;QACR,MAAM,YAAY,GAAG,eAAe,EAAE,CAAC;QACvC,sBAAsB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;IAClE,CAAC;CACF,CAAC,CAAC"}
@@ -82,5 +82,9 @@ export declare const disasterSpendingTool: import("@cyanheads/mcp-ts-core").Tool
82
82
  readonly totalCount: z.ZodOptional<z.ZodNumber>;
83
83
  readonly current_page: z.ZodOptional<z.ZodNumber>;
84
84
  readonly has_next_page: z.ZodOptional<z.ZodBoolean>;
85
+ readonly truncated: z.ZodOptional<z.ZodBoolean>;
86
+ readonly shown: z.ZodOptional<z.ZodNumber>;
87
+ readonly cap: z.ZodOptional<z.ZodNumber>;
88
+ readonly notice: z.ZodOptional<z.ZodString>;
85
89
  }>;
86
90
  //# sourceMappingURL=disaster-spending.tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"disaster-spending.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/disaster-spending.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAmB,MAAM,+BAA+B,CAAC;AAKlF,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuY/B,CAAC"}
1
+ {"version":3,"file":"disaster-spending.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/disaster-spending.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAmB,MAAM,+BAA+B,CAAC;AAgBlF,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAia/B,CAAC"}
@@ -6,7 +6,17 @@
6
6
  import { tool, z } from '@cyanheads/mcp-ts-core';
7
7
  import { JsonRpcErrorCode, validationError } from '@cyanheads/mcp-ts-core/errors';
8
8
  import { getUSASpendingService } from '../../../services/usaspending/usaspending-service.js';
9
+ import { formatCurrency } from './formatting.js';
9
10
  import { formatPaginationLine } from './pagination.js';
11
+ /**
12
+ * `disaster/recipient/spending/` reports this number as a ceiling, not a count.
13
+ * Unrelated broad `def_codes` filters all land on exactly 10,000 while a narrow one
14
+ * reports an honest 3,045, and the set is saturated at that point: with all five COVID
15
+ * codes the page at offset 9,900 comes back full with `hasNext: false` and the next page
16
+ * is empty. Rows past the 10,000th are unreachable, and a caller reading the total has no
17
+ * way to tell a cap from a count — hence the disclosure below.
18
+ */
19
+ const RECIPIENT_TOTAL_CEILING = 10_000;
10
20
  export const disasterSpendingTool = tool('usaspending_disaster_spending', {
11
21
  title: 'Disaster and Emergency Spending',
12
22
  description: 'Fetch disaster and emergency supplemental spending (COVID-19, hurricanes, infrastructure law, etc.) broken down by agency, CFDA assistance program, recipient, or geography. Use the dimension parameter to select the breakdown axis: overview (top-level totals), agency, cfda, recipient, or geography. Filter by DEF codes (Disaster/Emergency Funding codes) to isolate a specific emergency appropriation. DEF codes appear in usaspending_get_award account_obligations_by_defc and usaspending_get_agency def_codes fields.',
@@ -51,6 +61,16 @@ export const disasterSpendingTool = tool('usaspending_disaster_spending', {
51
61
  .describe('Total items for paginated dimensions (when available)'),
52
62
  current_page: z.number().optional().describe('Current page (non-overview dimensions)'),
53
63
  has_next_page: z.boolean().optional().describe('Whether there are more pages'),
64
+ truncated: z
65
+ .boolean()
66
+ .optional()
67
+ .describe('True when the upstream capped the reachable result set rather than counting it.'),
68
+ shown: z.number().optional().describe('Number of results returned on this page.'),
69
+ cap: z.number().optional().describe('The result-set ceiling the upstream applied.'),
70
+ notice: z
71
+ .string()
72
+ .optional()
73
+ .describe('Caveat explaining a capped total and how to bring the set under the cap.'),
54
74
  },
55
75
  output: z.object({
56
76
  dimension: z.string().describe('Breakdown dimension returned'),
@@ -270,6 +290,13 @@ export const disasterSpendingTool = tool('usaspending_disaster_spending', {
270
290
  : {}),
271
291
  }));
272
292
  const pageMeta = rawResults.page_metadata ?? {};
293
+ /**
294
+ * Direct read, verified: the agency, cfda, and recipient breakdown endpoints were
295
+ * each paged to the end of a real result set and reported `hasNext` truthfully at
296
+ * every boundary — interior full page, exactly-full final page, and the empty page
297
+ * past it. Routing through `resolveHasNext()` would report a wrong `has_next: true`
298
+ * on any result set whose size is an exact multiple of `limit`.
299
+ */
273
300
  const hasNext = pageMeta.hasNext ?? false;
274
301
  const currentPage = pageMeta.page ?? input.page;
275
302
  if (typeof pageMeta.total === 'number')
@@ -279,6 +306,14 @@ export const disasterSpendingTool = tool('usaspending_disaster_spending', {
279
306
  current_page: currentPage,
280
307
  has_next_page: hasNext,
281
308
  });
309
+ if (input.dimension === 'recipient' && pageMeta.total === RECIPIENT_TOTAL_CEILING) {
310
+ const ceiling = RECIPIENT_TOTAL_CEILING.toLocaleString();
311
+ ctx.enrich.truncated({
312
+ shown: results.length,
313
+ cap: RECIPIENT_TOTAL_CEILING,
314
+ guidance: `The recipient breakdown caps its reachable result set at ${ceiling} and reports that cap as the total, so this total is an upper bound rather than a count — recipients past the ${ceiling}th cannot be paged to. Narrow filters.def_codes to a single code or a smaller set to bring the result set under the cap and get a countable total.`,
315
+ });
316
+ }
282
317
  return {
283
318
  dimension: input.dimension,
284
319
  spending_type: input.spending_type,
@@ -298,23 +333,23 @@ export const disasterSpendingTool = tool('usaspending_disaster_spending', {
298
333
  if (result.overview) {
299
334
  const o = result.overview;
300
335
  if (o.total_budget_authority !== undefined)
301
- lines.push(`**Total Budget Authority:** $${o.total_budget_authority.toLocaleString()}`);
336
+ lines.push(`**Total Budget Authority:** ${formatCurrency(o.total_budget_authority)}`);
302
337
  if (o.total_obligations !== undefined)
303
- lines.push(`**Total Obligations:** $${o.total_obligations.toLocaleString()}`);
338
+ lines.push(`**Total Obligations:** ${formatCurrency(o.total_obligations)}`);
304
339
  if (o.total_outlays !== undefined)
305
- lines.push(`**Total Outlays:** $${o.total_outlays.toLocaleString()}`);
340
+ lines.push(`**Total Outlays:** ${formatCurrency(o.total_outlays)}`);
306
341
  if (o.award_obligations !== undefined)
307
- lines.push(`**Award Obligations:** $${o.award_obligations.toLocaleString()}`);
342
+ lines.push(`**Award Obligations:** ${formatCurrency(o.award_obligations)}`);
308
343
  if (o.award_outlays !== undefined)
309
- lines.push(`**Award Outlays:** $${o.award_outlays.toLocaleString()}`);
344
+ lines.push(`**Award Outlays:** ${formatCurrency(o.award_outlays)}`);
310
345
  if (o.face_value_of_loans !== undefined)
311
- lines.push(`**Face Value of Loans:** $${o.face_value_of_loans.toLocaleString()}`);
346
+ lines.push(`**Face Value of Loans:** ${formatCurrency(o.face_value_of_loans)}`);
312
347
  if (o.unobligated_balance !== undefined)
313
- lines.push(`**Unobligated Balance:** $${o.unobligated_balance.toLocaleString()}`);
348
+ lines.push(`**Unobligated Balance:** ${formatCurrency(o.unobligated_balance)}`);
314
349
  if (o.funding_by_def_code?.length) {
315
350
  lines.push('\n### Funding by DEF Code');
316
351
  for (const f of o.funding_by_def_code) {
317
- const amt = f.amount !== undefined ? `$${f.amount.toLocaleString()}` : 'N/A';
352
+ const amt = f.amount !== undefined ? formatCurrency(f.amount) : 'N/A';
318
353
  lines.push(`- **${f.def_code ?? 'N/A'}** — ${f.label ?? 'N/A'} (${f.public_law ?? 'N/A'}): ${amt}`);
319
354
  }
320
355
  }
@@ -338,12 +373,12 @@ export const disasterSpendingTool = tool('usaspending_disaster_spending', {
338
373
  const id = r.id ?? 'N/A';
339
374
  const code = r.code ?? 'N/A';
340
375
  const shape = r.shape_code ?? 'N/A';
341
- const oblig = r.obligation !== undefined ? `$${r.obligation.toLocaleString()}` : 'N/A';
342
- const outlay = r.outlay !== undefined ? `$${r.outlay.toLocaleString()}` : 'N/A';
343
- const agg = r.aggregated_amount !== undefined ? `$${r.aggregated_amount.toLocaleString()}` : 'N/A';
376
+ const oblig = r.obligation !== undefined ? formatCurrency(r.obligation) : 'N/A';
377
+ const outlay = r.outlay !== undefined ? formatCurrency(r.outlay) : 'N/A';
378
+ const agg = r.aggregated_amount !== undefined ? formatCurrency(r.aggregated_amount) : 'N/A';
344
379
  const population = r.population !== undefined ? r.population.toLocaleString() : 'N/A';
345
- const perCapita = r.per_capita !== undefined ? `$${r.per_capita.toLocaleString()}` : 'N/A';
346
- const loans = r.face_value_of_loan !== undefined ? `$${r.face_value_of_loan.toLocaleString()}` : 'N/A';
380
+ const perCapita = r.per_capita !== undefined ? formatCurrency(r.per_capita) : 'N/A';
381
+ const loans = r.face_value_of_loan !== undefined ? formatCurrency(r.face_value_of_loan) : 'N/A';
347
382
  const awards = r.award_count !== undefined ? String(r.award_count) : 'N/A';
348
383
  lines.push(`| ${label} | ${id} | ${code} | ${shape} | ${oblig} | ${outlay} | ${agg} | ${population} | ${perCapita} | ${loans} | ${awards} |`);
349
384
  }