@cyanheads/usaspending-mcp-server 0.7.0 → 0.7.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 (112) hide show
  1. package/AGENTS.md +8 -5
  2. package/CLAUDE.md +8 -5
  3. package/README.md +48 -27
  4. package/changelog/0.7.x/0.7.1.md +26 -0
  5. package/changelog/0.7.x/0.7.2.md +33 -0
  6. package/changelog/template.md +10 -3
  7. package/dist/config/server-config.d.ts +13 -0
  8. package/dist/config/server-config.d.ts.map +1 -1
  9. package/dist/config/server-config.js +24 -0
  10. package/dist/config/server-config.js.map +1 -1
  11. package/dist/index.js +2 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts +14 -2
  14. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts.map +1 -1
  15. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js +136 -40
  16. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js.map +1 -1
  17. package/dist/mcp-server/tools/definitions/count-limit.d.ts +69 -0
  18. package/dist/mcp-server/tools/definitions/count-limit.d.ts.map +1 -0
  19. package/dist/mcp-server/tools/definitions/count-limit.js +87 -0
  20. package/dist/mcp-server/tools/definitions/count-limit.js.map +1 -0
  21. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts +16 -1
  22. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts.map +1 -1
  23. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js +107 -37
  24. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js.map +1 -1
  25. package/dist/mcp-server/tools/definitions/filters.d.ts +63 -1
  26. package/dist/mcp-server/tools/definitions/filters.d.ts.map +1 -1
  27. package/dist/mcp-server/tools/definitions/filters.js +116 -1
  28. package/dist/mcp-server/tools/definitions/filters.js.map +1 -1
  29. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts +7 -0
  30. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-agency.tool.js +94 -50
  32. package/dist/mcp-server/tools/definitions/get-agency.tool.js.map +1 -1
  33. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.d.ts +5 -0
  34. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.d.ts.map +1 -1
  35. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js +15 -12
  36. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js.map +1 -1
  37. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.d.ts +5 -0
  38. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.d.ts.map +1 -1
  39. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js +14 -11
  40. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js.map +1 -1
  41. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts +5 -0
  42. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js +17 -11
  44. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts +30 -0
  46. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts.map +1 -1
  47. package/dist/mcp-server/tools/definitions/get-award.tool.js +110 -2
  48. package/dist/mcp-server/tools/definitions/get-award.tool.js.map +1 -1
  49. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.d.ts +5 -0
  50. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.d.ts.map +1 -1
  51. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js +18 -11
  52. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js.map +1 -1
  53. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.d.ts +16 -1
  54. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.d.ts.map +1 -1
  55. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js +29 -19
  56. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts +40 -1
  58. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts.map +1 -1
  59. package/dist/mcp-server/tools/definitions/get-recipient.tool.js +185 -5
  60. package/dist/mcp-server/tools/definitions/get-recipient.tool.js.map +1 -1
  61. package/dist/mcp-server/tools/definitions/index.d.ts +327 -6
  62. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  63. package/dist/mcp-server/tools/definitions/list-agencies.tool.d.ts.map +1 -1
  64. package/dist/mcp-server/tools/definitions/list-agencies.tool.js +3 -5
  65. package/dist/mcp-server/tools/definitions/list-agencies.tool.js.map +1 -1
  66. package/dist/mcp-server/tools/definitions/locations.d.ts +20 -9
  67. package/dist/mcp-server/tools/definitions/locations.d.ts.map +1 -1
  68. package/dist/mcp-server/tools/definitions/locations.js +106 -84
  69. package/dist/mcp-server/tools/definitions/locations.js.map +1 -1
  70. package/dist/mcp-server/tools/definitions/pagination.d.ts +9 -8
  71. package/dist/mcp-server/tools/definitions/pagination.d.ts.map +1 -1
  72. package/dist/mcp-server/tools/definitions/pagination.js +9 -8
  73. package/dist/mcp-server/tools/definitions/pagination.js.map +1 -1
  74. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts +50 -3
  75. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts.map +1 -1
  76. package/dist/mcp-server/tools/definitions/search-awards.tool.js +199 -70
  77. package/dist/mcp-server/tools/definitions/search-awards.tool.js.map +1 -1
  78. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.d.ts +5 -0
  79. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.d.ts.map +1 -1
  80. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js +18 -16
  81. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js.map +1 -1
  82. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts +5 -0
  83. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts.map +1 -1
  84. package/dist/mcp-server/tools/definitions/search-recipients.tool.js +13 -13
  85. package/dist/mcp-server/tools/definitions/search-recipients.tool.js.map +1 -1
  86. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts +47 -0
  87. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts.map +1 -1
  88. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js +124 -33
  89. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js.map +1 -1
  90. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts +39 -0
  91. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts.map +1 -1
  92. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js +74 -17
  93. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js.map +1 -1
  94. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts +41 -0
  95. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts.map +1 -1
  96. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js +87 -11
  97. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js.map +1 -1
  98. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts +42 -0
  99. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts.map +1 -0
  100. package/dist/mcp-server/tools/definitions/unavailable-sections.js +63 -0
  101. package/dist/mcp-server/tools/definitions/unavailable-sections.js.map +1 -0
  102. package/dist/services/usaspending/types.d.ts +102 -5
  103. package/dist/services/usaspending/types.d.ts.map +1 -1
  104. package/dist/services/usaspending/types.js +5 -1
  105. package/dist/services/usaspending/types.js.map +1 -1
  106. package/dist/services/usaspending/usaspending-service.d.ts +73 -6
  107. package/dist/services/usaspending/usaspending-service.d.ts.map +1 -1
  108. package/dist/services/usaspending/usaspending-service.js +206 -20
  109. package/dist/services/usaspending/usaspending-service.js.map +1 -1
  110. package/package.json +7 -7
  111. package/server.json +3 -3
  112. package/skills/usaspending-guide/SKILL.md +9 -5
@@ -1,21 +1,26 @@
1
1
  /**
2
2
  * @fileoverview Tool to search federal awards by keyword, recipient, agency, award type,
3
- * NAICS, Assistance Listing, PSC, or DEF code, location, or date range.
3
+ * NAICS, Assistance Listing, PSC, or DEF code, place of performance or recipient
4
+ * location, or date range.
4
5
  * @module mcp-server/tools/definitions/search-awards.tool
5
6
  */
6
7
  import { tool, z } from '@cyanheads/mcp-ts-core';
7
8
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
8
9
  import { escapeMarkdownInline } from '@cyanheads/mcp-ts-core/utils';
9
- import { getUSASpendingService } from '../../../services/usaspending/usaspending-service.js';
10
+ import { getUSASpendingService, } from '../../../services/usaspending/usaspending-service.js';
11
+ import { countLimit, LimitClampSchema, limitClampTrailer } from './count-limit.js';
10
12
  import { ANALYTICS_DATE_FIELDS, blankableIsoDate, filledBoundNotice, floorViolationMessage, invertedRangeMessage, optionalIsoDate, resolveDateRange, } from './dates.js';
11
- import { ASSISTANCE_AWARD_TYPE_CODES, AWARD_TYPE_CODES, applyCodeFilters, awardingAgencyFilters, CODE_FILTER_FIELDS, codeFilterEcho, describeCodeFilters, normalizeCodeFilters, PROCUREMENT_AWARD_TYPE_CODES, } from './filters.js';
13
+ import { ASSISTANCE_AWARD_TYPE_CODES, AWARD_TYPE_CODES, applyCodeFilters, applyLocationFilters, awardingAgencyFilters, CODE_FILTER_FIELDS, codeFilterEcho, describeCodeFilters, describeLocationFilters, LOCATION_FILTER_FIELDS, locationFilterEcho, normalizeCodeFilters, normalizeEffectiveFilters, PROCUREMENT_AWARD_TYPE_CODES, resolveLocationFilters, } from './filters.js';
12
14
  import { formatCurrency } from './formatting.js';
13
- import { describeLocation, LocationFilterSchema, resolveLocation } from './locations.js';
14
- import { resolveHasNext } from './pagination.js';
15
+ import { LocationFilterSchema, resolveLocation } from './locations.js';
16
+ import { emptyPageNotice, resolveHasNext } from './pagination.js';
17
+ import { renderUnavailableSections, settleSection, unavailableNotice, unavailableSectionSchema, } from './unavailable-sections.js';
15
18
  /** Award search default fields — covers summary + chaining IDs. */
16
19
  const AWARD_SEARCH_FIELDS = [
17
20
  'Award ID',
18
21
  'Recipient Name',
22
+ 'recipient_id',
23
+ 'Recipient UEI',
19
24
  'Award Amount',
20
25
  'Total Outlays',
21
26
  'Awarding Agency',
@@ -60,7 +65,8 @@ const LOAN_SORTS = [
60
65
  * partition its mixed-group 422 lists, F-codes and -1 included — and the sorts
61
66
  * each group's field mapping allows; upstream answers any other sort with a 400.
62
67
  * IDVs have no End Date; loans have no amount or date fields of the contract
63
- * kind and sort by their own. Labels follow USAspending's type names.
68
+ * kind and sort by their own. Labels follow USAspending's type names. The keys
69
+ * are the buckets `search/spending_by_award_count/` reports, one per group.
64
70
  */
65
71
  const AWARD_TYPE_GROUPS = {
66
72
  contracts: { label: 'contracts', codes: AWARD_TYPE_CODES.contracts, sorts: CONTRACT_SORTS },
@@ -83,7 +89,8 @@ const AWARD_TYPE_GROUPS = {
83
89
  * include one outside them — upstream's own 422 then decides, unguessed.
84
90
  */
85
91
  function resolveAwardTypeGroup(codes) {
86
- const groups = new Set(codes.map((code) => Object.values(AWARD_TYPE_GROUPS).find((g) => g.codes.includes(code))));
92
+ const names = Object.keys(AWARD_TYPE_GROUPS);
93
+ const groups = new Set(codes.map((code) => names.find((name) => AWARD_TYPE_GROUPS[name].codes.includes(code))));
87
94
  const [only] = groups;
88
95
  return groups.size === 1 ? only : undefined;
89
96
  }
@@ -107,15 +114,43 @@ const MAX_PAGE_OFFSET = 50_000;
107
114
  * the cursor must capture it before crossing this line.
108
115
  */
109
116
  const CURSOR_WINDOW_OFFSET = 10_000;
117
+ /**
118
+ * How long the count request may run, measured from the start of the call: about
119
+ * 2.5× the slowest cold count measured (an 18-year all-contracts filter); warm
120
+ * repeats answer in well under a second. Past it the request is aborted and the
121
+ * total reported unavailable, so a slow count never holds the answer longer.
122
+ */
123
+ const COUNT_DEADLINE_MS = 10_000;
124
+ /** search/spending_by_award/ answers a limit above 100 with a 422. */
125
+ const LIMIT = countLimit({ tool: 'usaspending_search_awards', default: 10, cap: 100 });
126
+ const UnavailableSectionSchema = unavailableSectionSchema(['total'], 'total: page_metadata.total and totalCount, from the count request.');
127
+ /** Paging guidance before the 10,000-result offset where the cursor pair stops. */
128
+ const CURSOR_GUIDANCE = `More results may remain — request the next page, or chain last_record_sort_value + last_record_unique_id from page_metadata to page past the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number limit. The cursor pair stops being returned once page × limit reaches ${CURSOR_WINDOW_OFFSET.toLocaleString()}, so capture it before then; a short or empty page marks the true end.`;
129
+ /**
130
+ * Paging guidance for a page-number page with rows past it and a known total.
131
+ * The cursor guidance is kept only for matches page numbers cannot reach.
132
+ */
133
+ function knownTotalGuidance(page, limit, total) {
134
+ const parts = [
135
+ `${total.toLocaleString()} awards match; this page ends at result ${(page * limit).toLocaleString()}.`,
136
+ (page + 1) * limit <= MAX_PAGE_OFFSET
137
+ ? `Request page ${page + 1} for more.`
138
+ : `The next page would pass the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number window.`,
139
+ ];
140
+ if (total > MAX_PAGE_OFFSET) {
141
+ parts.push(`${(total - MAX_PAGE_OFFSET).toLocaleString()} of them lie past the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number window: reach them with last_record_sort_value + last_record_unique_id from page_metadata, returned only while page × limit stays under ${CURSOR_WINDOW_OFFSET.toLocaleString()}, so capture the pair before then — or narrow the filters.`);
142
+ }
143
+ return parts.join(' ');
144
+ }
110
145
  export const searchAwardsTool = tool('usaspending_search_awards', {
111
146
  title: 'Search Federal Awards',
112
- description: 'Search federal awards by keyword, recipient, agency, award type, NAICS code, assistance listing (CFDA) number, PSC, DEF code, location, or date range. Returns ranked award summaries including recipient names, amounts, awarding agencies, and generated award IDs for use with usaspending_get_award; loan rows carry loan value, subsidy cost, and issue date in place of award amount and dates. Award types: A/B/C/D = contracts, IDV_A–IDV_E = IDVs, 02/03/04/05/F001/F002 = grants, 06/10/F006/F007 = direct payments, 07/08/F003/F004 = loans, 09/11/-1/F005/F008/F009/F010 = other assistance. Dates must be ISO 8601 (YYYY-MM-DD). Earliest data: 2007-10-01 via search API. DoD contracts have a 90-day publication lag.',
147
+ description: 'Search federal awards by keyword, recipient, agency, award type, NAICS code, assistance listing (CFDA) number, PSC, DEF code, location, or date range. Location filters by place of performance (location_filter, or filters.place_of_performance_location, which overrides it) or by where the recipient is based (filters.recipient_location). Returns ranked award summaries including recipient names, amounts, awarding agencies, and generated award IDs for use with usaspending_get_award; loan rows carry loan value, subsidy cost, and issue date in place of award amount and dates. Rows carry the recipient_id that opens usaspending_get_recipient, and the recipient UEI, when upstream has them; page_metadata.total counts every match in the selected award-type group. Award types: A/B/C/D = contracts, IDV_A–IDV_E = IDVs, 02/03/04/05/F001/F002 = grants, 06/10/F006/F007 = direct payments, 07/08/F003/F004 = loans, 09/11/-1/F005/F008/F009/F010 = other assistance. Dates must be ISO 8601 (YYYY-MM-DD). Earliest data: 2007-10-01 via search API. DoD contracts have a 90-day publication lag.',
113
148
  annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true },
114
149
  input: z.object({
115
150
  keyword: z
116
151
  .string()
117
152
  .optional()
118
- .describe('Full-text search across award descriptions, recipient names, and place names'),
153
+ .describe('Full-text search across award descriptions, recipient names, and place names; effective keywords need at least three characters without trimming; empty is unset'),
119
154
  award_type_codes: z
120
155
  .array(z.string())
121
156
  .min(1)
@@ -132,7 +167,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
132
167
  naics_codes: z
133
168
  .array(z.string())
134
169
  .optional()
135
- .describe('Filter by NAICS industry codes (e.g., ["541512"]). Use usaspending_autocomplete_filters type=naics to look up codes.'),
170
+ .describe('NAICS codes: canonical 2, 4, or 6 digits; recognized ASCII integer aliases normalize whitespace, plus, leading zeros and digit underscores; unclassified spellings remain provider-validated. Use usaspending_autocomplete_filters type=naics to look up codes.'),
136
171
  ...CODE_FILTER_FIELDS,
137
172
  time_period: z
138
173
  .object({
@@ -158,13 +193,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
158
193
  .optional()
159
194
  .describe('Sort field for results. Loans (07/08/F003/F004) sort by Loan Value, Subsidy Cost, Issued Date, Recipient Name, or Awarding Agency, defaulting to Loan Value. Every other group sorts by Award Amount, Total Outlays, Start Date, End Date, Recipient Name, or Awarding Agency, defaulting to Award Amount — except IDVs, which have no End Date. A sort the group does not support is rejected before the search runs.'),
160
195
  order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),
161
- limit: z
162
- .number()
163
- .int()
164
- .min(1)
165
- .max(100)
166
- .default(10)
167
- .describe('Maximum results per page (1–100)'),
196
+ limit: LIMIT.schema.describe('Awards per page. Default 10, at most 100 per call.'),
168
197
  page: z
169
198
  .number()
170
199
  .int()
@@ -185,7 +214,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
185
214
  keywords: z
186
215
  .array(z.string())
187
216
  .optional()
188
- .describe('Full-text search terms across award descriptions, recipient names, and places'),
217
+ .describe('Full-text search terms across award descriptions, recipient names, and places; effective terms need at least three characters without trimming; nonempty nested values override flat values'),
189
218
  award_type_codes: z
190
219
  .array(z.string())
191
220
  .optional()
@@ -201,8 +230,9 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
201
230
  naics_codes: z
202
231
  .array(z.string())
203
232
  .optional()
204
- .describe('NAICS industry codes to require, e.g., ["541512"]'),
233
+ .describe('NAICS industry codes to require: canonical 2, 4, or 6 digits; recognized ASCII integer aliases normalize; unclassified spellings remain provider-validated; nonempty nested values override flat values'),
205
234
  ...CODE_FILTER_FIELDS,
235
+ ...LOCATION_FILTER_FIELDS,
206
236
  time_period_start: optionalIsoDate('Start date (YYYY-MM-DD); earliest valid 2007-10-01. Given alone, the range runs through today (UTC).'),
207
237
  time_period_end: optionalIsoDate('End date (YYYY-MM-DD). Given alone, the range starts at 2007-10-01, the earliest searchable date.'),
208
238
  })
@@ -223,6 +253,14 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
223
253
  .optional()
224
254
  .describe('Generated unique award ID — pass to usaspending_get_award to fetch full details'),
225
255
  recipient_name: z.string().optional().describe('Name of the award recipient'),
256
+ recipient_id: z
257
+ .string()
258
+ .optional()
259
+ .describe('Recipient hash ID with its level suffix (-C, -R, or -P) — pass to usaspending_get_recipient for the profile. Absent when upstream has none, as on rows aggregated as MULTIPLE RECIPIENTS.'),
260
+ uei: z
261
+ .string()
262
+ .optional()
263
+ .describe('Recipient Unique Entity Identifier. Absent when upstream has none.'),
226
264
  award_amount: z.number().optional().describe('Total award amount in USD'),
227
265
  total_outlays: z.number().optional().describe('Total outlays in USD'),
228
266
  loan_value: z
@@ -263,9 +301,13 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
263
301
  .object({
264
302
  has_next: z
265
303
  .boolean()
266
- .describe(`Whether more results may remain — true on a full page even when the upstream flag reports none, since this endpoint under-reports continuation on a final full page and on every page past a ${CURSOR_WINDOW_OFFSET.toLocaleString()}-result offset. A short or empty page marks the end.`),
304
+ .describe(`Whether more results remain. With total known on page-number paging, true exactly when rows lie past this page. Without it — the count failed, or the page came by cursor — true on any full page, since the upstream flag reads false on every page past a ${CURSOR_WINDOW_OFFSET.toLocaleString()}-result offset; an exactly-full final page then reports one page more than exists. A short or empty page marks the end.`),
267
305
  page: z.number().describe('Current page number'),
268
306
  limit: z.number().describe('Results per page'),
307
+ total: z
308
+ .number()
309
+ .optional()
310
+ .describe('Awards matching the filters in the selected award-type group, across all pages. Absent when the count request failed; unavailable_sections then names it.'),
269
311
  last_record_sort_value: z
270
312
  .string()
271
313
  .optional()
@@ -275,7 +317,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
275
317
  .optional()
276
318
  .describe('Keyset-pagination cursor for the next page — pass back as last_record_unique_id alongside last_record_sort_value. Absent on the same pages that omit last_record_sort_value.'),
277
319
  })
278
- .describe('Pagination metadata. This endpoint does not return a total match count; use has_next and the cursor pair to page.'),
320
+ .describe('Pagination metadata: has_next, the page and limit, the total match count, and the keyset cursor pair.'),
279
321
  }),
280
322
  // Agent-facing search context: applied filters, upstream API notices, and an optional
281
323
  // recovery notice for empty pages. Populated via ctx.enrich() so it reaches both
@@ -284,11 +326,15 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
284
326
  page: z.number().describe('Current page number returned'),
285
327
  has_next: z
286
328
  .boolean()
287
- .describe('Whether more results may remain — set on a full page even when the upstream flag reports none.'),
329
+ .describe('Whether more results remain: exact with a known total on page-number paging, otherwise true on any full page.'),
288
330
  truncated: z
289
331
  .boolean()
290
332
  .optional()
291
- .describe(`True when the upstream reports more results beyond this page (continue via page or the cursor). Absent on a full page the upstream marks as last, including every page past a ${CURSOR_WINDOW_OFFSET.toLocaleString()}-result offset where the upstream stops reporting continuation — has_next still says whether to request another.`),
333
+ .describe(`True when rows are known to lie past this page: page × limit is below the total, or the upstream reports a next page (continue via page or the cursor). Without a total — the count failed, or the page came by cursor — only the upstream flag counts, and it reads false on every page past a ${CURSOR_WINDOW_OFFSET.toLocaleString()}-result offset; has_next still says whether to request another.`),
334
+ totalCount: z
335
+ .number()
336
+ .optional()
337
+ .describe('Awards matching the filters in the selected award-type group, across all pages — the same value as page_metadata.total. Absent when the count request failed.'),
292
338
  shown: z
293
339
  .number()
294
340
  .optional()
@@ -323,6 +369,10 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
323
369
  .string()
324
370
  .optional()
325
371
  .describe('Place of performance location sent, as normalized (e.g. country=USA, state=NM, county=049)'),
372
+ applied_recipient_location: z
373
+ .string()
374
+ .optional()
375
+ .describe('Recipient location sent, as normalized (e.g. country=USA, state=WA)'),
326
376
  applied_time_period_start: z
327
377
  .string()
328
378
  .optional()
@@ -331,10 +381,15 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
331
381
  .string()
332
382
  .optional()
333
383
  .describe('End of the date range sent (YYYY-MM-DD), including a filled-in end'),
384
+ unavailable_sections: z
385
+ .array(UnavailableSectionSchema)
386
+ .optional()
387
+ .describe(`Present when the count request failed, was rejected, or ran past its ${COUNT_DEADLINE_MS / 1000}-second deadline; the awards on the page are unaffected. Absent when the count loaded.`),
388
+ limitClamp: LimitClampSchema,
334
389
  notice: z
335
390
  .string()
336
391
  .optional()
337
- .describe('How to page on when more results may remain, which date bound was filled in when only the other was supplied, and the applied filters on an empty page. This endpoint supplies no total, so an empty page does not establish zero matches. Absent when none applies.'),
392
+ .describe('A reduced limit, how to page on when more results remain, which date bound was filled in when only the other was supplied, why an empty page is empty (nothing matches, the page is past the last match, or — without a total — unknown), and which section failed to load. Absent when none applies.'),
338
393
  },
339
394
  // upstream_messages is an array — supply a markdown renderer so the content[] trailer
340
395
  // shows a bullet list instead of a one-line JSON blob (structuredContent is unaffected).
@@ -342,7 +397,9 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
342
397
  // full escape hatch and never consults a sibling `label`, so an unheaded bullet list
343
398
  // would otherwise sit unattributed between the surrounding `**key:** value` lines.
344
399
  enrichmentTrailer: {
400
+ limitClamp: limitClampTrailer,
345
401
  notice: { render: (notice) => (notice ? `> ${escapeMarkdownInline(notice)}` : '') },
402
+ unavailable_sections: { render: renderUnavailableSections },
346
403
  upstream_messages: {
347
404
  /**
348
405
  * The trailing empty element closes the bullet list with a blank line. The
@@ -356,6 +413,20 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
356
413
  },
357
414
  },
358
415
  errors: [
416
+ {
417
+ reason: 'invalid_keyword',
418
+ code: JsonRpcErrorCode.ValidationError,
419
+ when: 'An effective keyword has fewer than three characters.',
420
+ retryable: false,
421
+ recovery: 'Supply keywords of at least three characters; whitespace is significant.',
422
+ },
423
+ {
424
+ reason: 'invalid_naics_code',
425
+ code: JsonRpcErrorCode.ValidationError,
426
+ when: 'An effective NAICS code is known to be invalid.',
427
+ retryable: false,
428
+ recovery: 'Use a 2, 4, or 6 digit NAICS code from usaspending_autocomplete_filters type=naics.',
429
+ },
359
430
  {
360
431
  reason: 'incomplete_cursor',
361
432
  code: JsonRpcErrorCode.ValidationError,
@@ -424,15 +495,18 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
424
495
  {
425
496
  reason: 'invalid_location',
426
497
  code: JsonRpcErrorCode.ValidationError,
427
- when: 'location_filter names an unknown US state, a county without a state or under an armed-forces code, a county or FIPS-number state under a non-USA country, or parts that place it in different states.',
498
+ when: 'location_filter, filters.place_of_performance_location, or filters.recipient_location names an unknown US state, a county without a state or under an armed-forces code, a county or FIPS-number state under a non-USA country, or parts that place it in different states.',
428
499
  retryable: false,
429
- recovery: "Under country USA (the default) or a US territory code, send location_filter.state as a postal code (NM) or 2-digit FIPS code (35), and location_filter.county as 3 digits with that state or as the 5-digit state + county code (35049). Under another country, send state as that country's own 2-letter subdivision code and no county.",
500
+ recovery: "Under country USA (the default) or a US territory code, send state as a postal code (NM) or 2-digit FIPS code (35), and county as 3 digits with that state or as the 5-digit state + county code (35049). Under another country, send state as that country's own 2-letter subdivision code and no county.",
430
501
  },
431
502
  ],
432
503
  async handler(input, ctx) {
504
+ const countDeadlineAt = Date.now() + COUNT_DEADLINE_MS;
505
+ // Every read below uses the applied limit, never input.limit.
506
+ const { applied: limit, notice: clampNotice } = LIMIT.apply(ctx, 'limit', input.limit);
433
507
  ctx.log.info('usaspending_search_awards', {
434
508
  keyword: input.keyword,
435
- limit: input.limit,
509
+ limit,
436
510
  page: input.page,
437
511
  });
438
512
  const svc = getUSASpendingService();
@@ -446,8 +520,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
446
520
  const usingCursor = hasSortValue && hasUniqueId;
447
521
  // Page-number pagination caps at a 50,000-result offset; fail fast with the cursor
448
522
  // recovery path instead of letting the upstream 422 bubble up unclassified.
449
- if (!usingCursor && input.page * input.limit > MAX_PAGE_OFFSET) {
450
- throw ctx.fail('pagination_limit_exceeded', `Requested page ${input.page} at limit ${input.limit} exceeds this endpoint's ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number window.`);
523
+ if (!usingCursor && input.page * limit > MAX_PAGE_OFFSET) {
524
+ throw ctx.fail('pagination_limit_exceeded', `${clampNotice ? `${clampNotice} ` : ''}Requested page ${input.page} at limit ${limit} exceeds this endpoint's ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number window.`);
451
525
  }
452
526
  /**
453
527
  * Merge the analytics-style `filters` object over the flat inputs (nested wins
@@ -456,7 +530,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
456
530
  * `messages` as unused).
457
531
  */
458
532
  const f = input.filters;
459
- const keywords = f?.keywords && f.keywords.length > 0
533
+ const mergedKeywords = f?.keywords && f.keywords.length > 0
460
534
  ? f.keywords
461
535
  : input.keyword
462
536
  ? [input.keyword]
@@ -466,7 +540,16 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
466
540
  : input.award_type_codes;
467
541
  const agencyName = f?.agency_name || input.agency_name;
468
542
  const recipientName = f?.recipient_name || input.recipient_name;
469
- const naicsCodes = f?.naics_codes && f.naics_codes.length > 0 ? f.naics_codes : input.naics_codes;
543
+ const mergedNaicsCodes = f?.naics_codes && f.naics_codes.length > 0 ? f.naics_codes : input.naics_codes;
544
+ const effective = normalizeEffectiveFilters({
545
+ keywords: mergedKeywords,
546
+ naics_codes: mergedNaicsCodes,
547
+ });
548
+ if ('reason' in effective) {
549
+ throw ctx.fail(effective.reason === 'invalid_keyword' ? 'invalid_keyword' : 'invalid_naics_code', effective.message);
550
+ }
551
+ const keywords = effective.keywords;
552
+ const naicsCodes = effective.naics_codes;
470
553
  // Both input paths (the flat time_period and the nested filters.time_period_*)
471
554
  // merge here, nested winning per bound; a blank reads as absent. A lone bound
472
555
  // is filled to a two-ended range, padded, so a half-blank flat pair is a lone
@@ -516,22 +599,31 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
516
599
  }
517
600
  // Upstream checks the sort against the group's field mapping and answers 400
518
601
  // outside it. Codes spanning groups skip the check: upstream's 422 decides.
519
- const group = resolveAwardTypeGroup(awardTypeCodes);
520
- const isLoan = group === AWARD_TYPE_GROUPS.loans;
602
+ const groupName = resolveAwardTypeGroup(awardTypeCodes);
603
+ const group = groupName ? AWARD_TYPE_GROUPS[groupName] : undefined;
604
+ const isLoan = groupName === 'loans';
521
605
  const sort = input.sort ?? (isLoan ? 'Loan Value' : 'Award Amount');
522
606
  if (group && !group.sorts.includes(sort)) {
523
607
  throw ctx.fail('unsupported_sort', `Sort "${sort}" is not available for ${group.label} (award_type_codes ${awardTypeCodes.join(', ')}). Supported sorts for ${group.label}: ${group.sorts.join(', ')}.`);
524
608
  }
525
609
  /**
526
610
  * Upstream 422s on a missing country or a 5-digit county, and answers an empty
527
- * page for a FIPS-number state or a territory's ISO code, so the location is
528
- * normalized to the one shape it matches, or rejected, before the request.
611
+ * page for a FIPS-number state or a territory's ISO code, so each location is
612
+ * normalized to the one shape it matches, or rejected naming its input path,
613
+ * before the request. A nested place of performance wins over the flat
614
+ * location_filter, which is then neither sent nor checked.
529
615
  */
530
- const resolvedLocation = resolveLocation(input.location_filter);
531
- if (!resolvedLocation.ok) {
532
- throw ctx.fail('invalid_location', resolvedLocation.message);
616
+ const located = resolveLocationFilters(f ?? {});
617
+ if (!located.ok)
618
+ throw ctx.fail('invalid_location', located.message);
619
+ const { locations } = located;
620
+ if (!locations.place_of_performance_location) {
621
+ const flat = resolveLocation(input.location_filter);
622
+ if (!flat.ok)
623
+ throw ctx.fail('invalid_location', flat.message);
624
+ if (flat.location)
625
+ locations.place_of_performance_location = flat.location;
533
626
  }
534
- const location = resolvedLocation.location;
535
627
  const filters = {};
536
628
  if (keywords?.length)
537
629
  filters.keywords = keywords;
@@ -548,14 +640,13 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
548
640
  if (timePeriod) {
549
641
  filters.time_period = [{ start_date: timePeriod.start_date, end_date: timePeriod.end_date }];
550
642
  }
551
- if (location)
552
- filters.place_of_performance_locations = [location];
553
- const data = await svc.searchAwards({
643
+ applyLocationFilters(filters, locations);
644
+ const searchRequest = svc.searchAwards({
554
645
  filters,
555
646
  fields: isLoan ? [...AWARD_SEARCH_FIELDS, ...LOAN_FIELDS] : AWARD_SEARCH_FIELDS,
556
647
  sort,
557
648
  order: input.order,
558
- limit: input.limit,
649
+ limit,
559
650
  // page and cursor are mutually exclusive; omit page when paging by cursor.
560
651
  // Re-test both fields inline so exactOptionalPropertyTypes narrows away `undefined`.
561
652
  ...(input.last_record_sort_value !== undefined && input.last_record_unique_id !== undefined
@@ -565,12 +656,30 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
565
656
  }
566
657
  : { page: input.page }),
567
658
  }, ctx);
659
+ /**
660
+ * The count gets the very `filters` object the search sends, so every filter
661
+ * reaches both, and runs beside the search as a best-effort side read under its
662
+ * own deadline. Codes spanning groups never reach it: upstream's 422 fails the
663
+ * search. Settled up front, so a count that rejects after a failed search is
664
+ * still handled; the search is awaited alone, so its failure surfaces at once.
665
+ */
666
+ const countLeg = Promise.allSettled([
667
+ groupName ? svc.countAwards(filters, ctx, countDeadlineAt) : undefined,
668
+ ]);
669
+ const data = await searchRequest;
670
+ const [countResult] = await countLeg;
671
+ // A failed count leaves the total unknown and is disclosed; a caller abort rethrows.
672
+ const unavailable = [];
673
+ const counts = settleSection(ctx, 'total', countResult, unavailable);
674
+ const total = groupName && counts ? counts[groupName] : undefined;
568
675
  const results = (data.results ?? []).map((r) => ({
569
676
  ...(r['Award ID'] ? { award_id: String(r['Award ID']) } : {}),
570
677
  ...(r.generated_internal_id
571
678
  ? { generated_internal_id: String(r.generated_internal_id) }
572
679
  : {}),
573
680
  ...(r['Recipient Name'] ? { recipient_name: String(r['Recipient Name']) } : {}),
681
+ ...(r.recipient_id ? { recipient_id: r.recipient_id } : {}),
682
+ ...(r['Recipient UEI'] ? { uei: r['Recipient UEI'] } : {}),
574
683
  ...(typeof r['Award Amount'] === 'number' ? { award_amount: r['Award Amount'] } : {}),
575
684
  ...(typeof r['Total Outlays'] === 'number' ? { total_outlays: r['Total Outlays'] } : {}),
576
685
  ...(typeof r['Loan Value'] === 'number' ? { loan_value: r['Loan Value'] } : {}),
@@ -607,10 +716,18 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
607
716
  : {}),
608
717
  }));
609
718
  const pageMeta = data.page_metadata ?? {};
610
- // Past a 10,000-result offset this endpoint keeps returning full pages while
611
- // reporting hasNext: false, so forwarding the flag verbatim ends pagination with
612
- // tens of thousands of matches still behind it. Page fullness is the honest signal.
613
- const hasNext = resolveHasNext(pageMeta.hasNext, results.length, input.limit);
719
+ const page = pageMeta.page ?? input.page;
720
+ /**
721
+ * A known total settles continuation on page-number paging: rows remain exactly
722
+ * when this page ends before the total. Without one — the count failed, or the
723
+ * page came by cursor, whose absolute offset is unknown — page fullness stands
724
+ * in, since past a 10,000-result offset upstream reports hasNext: false on every
725
+ * full page and forwarding the flag would strand the matches behind it.
726
+ */
727
+ const pagedTotal = usingCursor ? undefined : total;
728
+ const hasNext = pagedTotal !== undefined
729
+ ? page * limit < pagedTotal || pageMeta.hasNext === true
730
+ : resolveHasNext(pageMeta.hasNext, results.length, limit);
614
731
  // The keyset cursor is usable only on interior pages. On the final page the upstream
615
732
  // returns last_record_unique_id: null and last_record_sort_value: "None" (a stringified
616
733
  // Python None) — a bare `!== undefined` forwards that null and crashes the z.number()
@@ -621,8 +738,9 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
621
738
  const uniqueCursor = pageMeta.last_record_unique_id;
622
739
  const page_metadata = {
623
740
  has_next: hasNext,
624
- page: pageMeta.page ?? input.page,
625
- limit: input.limit,
741
+ page,
742
+ limit,
743
+ ...(total !== undefined ? { total } : {}),
626
744
  ...(hasNext &&
627
745
  typeof sortCursor === 'string' &&
628
746
  sortCursor !== 'None' &&
@@ -638,7 +756,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
638
756
  ...(agencyName ? { applied_agency_name: agencyName } : {}),
639
757
  ...(naicsCodes?.length ? { applied_naics_codes: naicsCodes.join(', ') } : {}),
640
758
  ...codeFilterEcho(codes),
641
- ...(location ? { applied_location: describeLocation(location) } : {}),
759
+ ...locationFilterEcho(locations),
642
760
  ...(timePeriod
643
761
  ? {
644
762
  applied_time_period_start: timePeriod.start_date,
@@ -646,19 +764,21 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
646
764
  }
647
765
  : {}),
648
766
  });
767
+ if (total !== undefined)
768
+ ctx.enrich.total(total);
649
769
  // enrich.notice is last-wins, and enrich.truncated writes the notice too, so
650
770
  // every notice source joins into one string written at the end.
651
- const notices = [];
771
+ const notices = [clampNotice];
652
772
  /**
653
- * Paging guidance follows has_next, which keeps the page-fullness fallback. The
654
- * truncated/shown/cap disclosure needs evidence that rows exist past this page — the
655
- * upstream hasNext — so an exactly-full final page and every page past the
656
- * CURSOR_WINDOW_OFFSET (where hasNext is always false) carry the notice alone.
773
+ * The truncated/shown/cap disclosure needs evidence that rows exist past this
774
+ * page: the known total, or the upstream hasNext. Without a total, an exactly-full
775
+ * final page and every page past the CURSOR_WINDOW_OFFSET (where hasNext is always
776
+ * false) carry the paging notice alone.
657
777
  */
658
- if (page_metadata.has_next) {
659
- const guidance = `More results may remain — request the next page, or chain last_record_sort_value + last_record_unique_id from page_metadata to page past the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number limit. The cursor pair stops being returned once page × limit reaches ${CURSOR_WINDOW_OFFSET.toLocaleString()}, so capture it before then; a short or empty page marks the true end.`;
660
- if (pageMeta.hasNext) {
661
- ctx.enrich.truncated({ shown: results.length, cap: input.limit, guidance });
778
+ if (hasNext) {
779
+ const guidance = pagedTotal !== undefined ? knownTotalGuidance(page, limit, pagedTotal) : CURSOR_GUIDANCE;
780
+ if (pagedTotal !== undefined || pageMeta.hasNext) {
781
+ ctx.enrich.truncated({ shown: results.length, cap: limit, guidance });
662
782
  }
663
783
  notices.push(guidance);
664
784
  }
@@ -669,15 +789,16 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
669
789
  filterParts.push(`keyword="${keywords.join(', ')}"`);
670
790
  if (agencyName)
671
791
  filterParts.push(`agency="${agencyName}"`);
672
- filterParts.push(...describeCodeFilters(codes));
673
- if (location)
674
- filterParts.push(`location="${describeLocation(location)}"`);
675
- if (awardTypeCodes?.length) {
676
- filterParts.push(`types=${awardTypeCodes.join(',')}`);
677
- }
678
- notices.push(filterParts.length > 0
679
- ? `Page ${page_metadata.page} returned no awards for ${filterParts.join(', ')}. The API does not supply a total match count.`
680
- : `Page ${page_metadata.page} returned no awards. The API does not supply a total match count.`);
792
+ filterParts.push(...describeCodeFilters(codes), ...describeLocationFilters(locations));
793
+ filterParts.push(`types=${awardTypeCodes.join(',')}`);
794
+ const filterText = filterParts.join(', ');
795
+ notices.push(pagedTotal !== undefined
796
+ ? emptyPageNotice(page, limit, pagedTotal, `No awards match ${filterText}.`)
797
+ : `Page ${page} returned no awards for ${filterText}.${total !== undefined ? ` The API reports ${total.toLocaleString()} matching awards across all pages.` : ' The total match count is unavailable, so an empty page does not establish zero matches.'}`);
798
+ }
799
+ if (unavailable.length > 0) {
800
+ ctx.enrich({ unavailable_sections: unavailable });
801
+ notices.push(unavailableNotice(unavailable));
681
802
  }
682
803
  const notice = notices.filter(Boolean).join(' ');
683
804
  if (notice)
@@ -686,7 +807,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
686
807
  },
687
808
  format: (result) => {
688
809
  const lines = ['## Federal Award Search Results'];
689
- lines.push(`\n**Results:** ${result.results.length} | **Page:** ${result.page_metadata.page} | **Per page:** ${result.page_metadata.limit} | **Has next:** ${result.page_metadata.has_next ? 'Yes' : 'No'}`);
810
+ const { total } = result.page_metadata;
811
+ lines.push(`\n**Results:** ${result.results.length} | **Page:** ${result.page_metadata.page}${total !== undefined ? ` | **Total matches:** ${total.toLocaleString()}` : ''} | **Per page:** ${result.page_metadata.limit} | **Has next:** ${result.page_metadata.has_next ? 'Yes' : 'No'}`);
690
812
  for (const r of result.results) {
691
813
  lines.push('');
692
814
  lines.push(`### ${escapeMarkdownInline(r.recipient_name ?? r.award_id ?? r.generated_internal_id ?? 'Unknown')}`);
@@ -694,6 +816,10 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
694
816
  lines.push(`**Award ID:** ${escapeMarkdownInline(r.award_id)}`);
695
817
  if (r.generated_internal_id)
696
818
  lines.push(`**Chain ID (for get_award):** ${escapeMarkdownInline(r.generated_internal_id)}`);
819
+ if (r.recipient_id)
820
+ lines.push(`**Recipient ID (for get_recipient):** ${escapeMarkdownInline(r.recipient_id)}`);
821
+ if (r.uei)
822
+ lines.push(`**UEI:** ${escapeMarkdownInline(r.uei)}`);
697
823
  if (r.agency_slug)
698
824
  lines.push(`**Agency Slug (for get_agency):** ${escapeMarkdownInline(r.agency_slug)}`);
699
825
  if (typeof r.award_amount === 'number')
@@ -734,8 +860,11 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
734
860
  // the MAX_PAGE_OFFSET cap there is no next page to direct to: the handler's own
735
861
  // pagination_limit_exceeded guard rejects it.
736
862
  const nextPage = result.page_metadata.page + 1;
863
+ const beyond = total !== undefined
864
+ ? ` — ${(total - result.page_metadata.page * result.page_metadata.limit).toLocaleString()} matching awards lie past it`
865
+ : '';
737
866
  lines.push(nextPage * result.page_metadata.limit > MAX_PAGE_OFFSET
738
- ? `**No further pages reachable:** this page sits at the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number cap and no keyset cursor was returned, so nothing beyond it can be read. Narrow the filters to bring the result set inside the window.`
867
+ ? `**No further pages reachable:** this page sits at the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number cap and no keyset cursor was returned, so nothing beyond it can be read${beyond}. Narrow the filters to bring the result set inside the window.`
739
868
  : `**Next page:** request page ${nextPage}. No keyset cursor was returned for this page — the endpoint withholds the pair on a final page and on every page past a ${CURSOR_WINDOW_OFFSET.toLocaleString()}-result offset, so continue by page number; a short or empty page marks the true end.`);
740
869
  }
741
870
  }