@cyanheads/usaspending-mcp-server 0.7.1 → 0.7.3

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 (120) hide show
  1. package/AGENTS.md +8 -5
  2. package/CLAUDE.md +8 -5
  3. package/README.md +49 -31
  4. package/changelog/0.7.x/0.7.2.md +33 -0
  5. package/changelog/0.7.x/0.7.3.md +29 -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 +1 -6
  12. package/dist/index.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/agency-filters.d.ts +36 -0
  14. package/dist/mcp-server/tools/definitions/agency-filters.d.ts.map +1 -0
  15. package/dist/mcp-server/tools/definitions/agency-filters.js +123 -0
  16. package/dist/mcp-server/tools/definitions/agency-filters.js.map +1 -0
  17. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts +18 -3
  18. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts.map +1 -1
  19. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js +176 -45
  20. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js.map +1 -1
  21. package/dist/mcp-server/tools/definitions/count-limit.d.ts +69 -0
  22. package/dist/mcp-server/tools/definitions/count-limit.d.ts.map +1 -0
  23. package/dist/mcp-server/tools/definitions/count-limit.js +87 -0
  24. package/dist/mcp-server/tools/definitions/count-limit.js.map +1 -0
  25. package/dist/mcp-server/tools/definitions/dates.d.ts +2 -0
  26. package/dist/mcp-server/tools/definitions/dates.d.ts.map +1 -1
  27. package/dist/mcp-server/tools/definitions/dates.js +2 -0
  28. package/dist/mcp-server/tools/definitions/dates.js.map +1 -1
  29. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts +6 -1
  30. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts.map +1 -1
  31. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js +28 -22
  32. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js.map +1 -1
  33. package/dist/mcp-server/tools/definitions/filters.d.ts +60 -10
  34. package/dist/mcp-server/tools/definitions/filters.d.ts.map +1 -1
  35. package/dist/mcp-server/tools/definitions/filters.js +67 -12
  36. package/dist/mcp-server/tools/definitions/filters.js.map +1 -1
  37. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts +9 -0
  38. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts.map +1 -1
  39. package/dist/mcp-server/tools/definitions/get-agency.tool.js +114 -55
  40. package/dist/mcp-server/tools/definitions/get-agency.tool.js.map +1 -1
  41. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.d.ts +5 -0
  42. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.d.ts.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js +14 -11
  44. package/dist/mcp-server/tools/definitions/get-award-federal-accounts.tool.js.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.d.ts +5 -0
  46. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.d.ts.map +1 -1
  47. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js +14 -11
  48. package/dist/mcp-server/tools/definitions/get-award-subawards.tool.js.map +1 -1
  49. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts +5 -0
  50. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts.map +1 -1
  51. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js +17 -11
  52. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js.map +1 -1
  53. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts +30 -0
  54. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts.map +1 -1
  55. package/dist/mcp-server/tools/definitions/get-award.tool.js +110 -2
  56. package/dist/mcp-server/tools/definitions/get-award.tool.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.d.ts +5 -0
  58. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.d.ts.map +1 -1
  59. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js +18 -11
  60. package/dist/mcp-server/tools/definitions/get-federal-account-breakdown.tool.js.map +1 -1
  61. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.d.ts +5 -0
  62. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.d.ts.map +1 -1
  63. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js +18 -18
  64. package/dist/mcp-server/tools/definitions/get-idv-awards.tool.js.map +1 -1
  65. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts +41 -2
  66. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts.map +1 -1
  67. package/dist/mcp-server/tools/definitions/get-recipient.tool.js +201 -11
  68. package/dist/mcp-server/tools/definitions/get-recipient.tool.js.map +1 -1
  69. package/dist/mcp-server/tools/definitions/index.d.ts +264 -15
  70. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  71. package/dist/mcp-server/tools/definitions/list-agencies.tool.d.ts.map +1 -1
  72. package/dist/mcp-server/tools/definitions/list-agencies.tool.js +2 -4
  73. package/dist/mcp-server/tools/definitions/list-agencies.tool.js.map +1 -1
  74. package/dist/mcp-server/tools/definitions/locations.d.ts +20 -9
  75. package/dist/mcp-server/tools/definitions/locations.d.ts.map +1 -1
  76. package/dist/mcp-server/tools/definitions/locations.js +106 -84
  77. package/dist/mcp-server/tools/definitions/locations.js.map +1 -1
  78. package/dist/mcp-server/tools/definitions/pagination.d.ts +9 -8
  79. package/dist/mcp-server/tools/definitions/pagination.d.ts.map +1 -1
  80. package/dist/mcp-server/tools/definitions/pagination.js +9 -8
  81. package/dist/mcp-server/tools/definitions/pagination.js.map +1 -1
  82. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts +46 -6
  83. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts.map +1 -1
  84. package/dist/mcp-server/tools/definitions/search-awards.tool.js +203 -83
  85. package/dist/mcp-server/tools/definitions/search-awards.tool.js.map +1 -1
  86. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.d.ts +5 -0
  87. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.d.ts.map +1 -1
  88. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js +15 -13
  89. package/dist/mcp-server/tools/definitions/search-federal-accounts.tool.js.map +1 -1
  90. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts +6 -0
  91. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts.map +1 -1
  92. package/dist/mcp-server/tools/definitions/search-recipients.tool.js +19 -17
  93. package/dist/mcp-server/tools/definitions/search-recipients.tool.js.map +1 -1
  94. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts +33 -2
  95. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts.map +1 -1
  96. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js +100 -40
  97. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js.map +1 -1
  98. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts +25 -2
  99. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts.map +1 -1
  100. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js +50 -26
  101. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js.map +1 -1
  102. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts +24 -2
  103. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts.map +1 -1
  104. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js +36 -14
  105. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js.map +1 -1
  106. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts +42 -0
  107. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts.map +1 -0
  108. package/dist/mcp-server/tools/definitions/unavailable-sections.js +63 -0
  109. package/dist/mcp-server/tools/definitions/unavailable-sections.js.map +1 -0
  110. package/dist/services/usaspending/types.d.ts +91 -7
  111. package/dist/services/usaspending/types.d.ts.map +1 -1
  112. package/dist/services/usaspending/types.js +5 -1
  113. package/dist/services/usaspending/types.js.map +1 -1
  114. package/dist/services/usaspending/usaspending-service.d.ts +85 -7
  115. package/dist/services/usaspending/usaspending-service.d.ts.map +1 -1
  116. package/dist/services/usaspending/usaspending-service.js +205 -32
  117. package/dist/services/usaspending/usaspending-service.js.map +1 -1
  118. package/package.json +4 -4
  119. package/server.json +3 -3
  120. package/skills/usaspending-guide/SKILL.md +12 -6
@@ -1,21 +1,27 @@
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 { 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, normalizeEffectiveFilters, PROCUREMENT_AWARD_TYPE_CODES, } from './filters.js';
10
+ import { getUSASpendingService, } from '../../../services/usaspending/usaspending-service.js';
11
+ import { AGENCY_FILTER_ENRICHMENT, AGENCY_FILTER_FIELDS, agencyFilterEcho, applyAgencyFilters, describeAgencyFilters, resolveAgencyFilters, } from './agency-filters.js';
12
+ import { countLimit, LimitClampSchema, limitClampTrailer } from './count-limit.js';
13
+ import { ANALYTICS_DATE_FIELDS, blankableIsoDate, filledBoundNotice, floorViolationMessage, invertedRangeMessage, NO_DATE_FILTER_NOTICE, optionalIsoDate, resolveDateRange, } from './dates.js';
14
+ import { ASSISTANCE_AWARD_TYPE_CODES, AWARD_TYPE_CODES, applyCodeFilters, applyLocationFilters, CODE_FILTER_FIELDS, codeFilterEcho, describeCodeFilters, describeLocationFilters, LOCATION_FILTER_FIELDS, locationFilterEcho, normalizeCodeFilters, normalizeEffectiveFilters, PROCUREMENT_AWARD_TYPE_CODES, resolveLocationFilters, } from './filters.js';
12
15
  import { formatCurrency } from './formatting.js';
13
- import { describeLocation, LocationFilterSchema, resolveLocation } from './locations.js';
14
- import { resolveHasNext } from './pagination.js';
16
+ import { LocationFilterSchema, resolveLocation } from './locations.js';
17
+ import { emptyPageNotice, resolveHasNext } from './pagination.js';
18
+ import { renderUnavailableSections, settleSection, unavailableNotice, unavailableSectionSchema, } from './unavailable-sections.js';
15
19
  /** Award search default fields — covers summary + chaining IDs. */
16
20
  const AWARD_SEARCH_FIELDS = [
17
21
  'Award ID',
18
22
  'Recipient Name',
23
+ 'recipient_id',
24
+ 'Recipient UEI',
19
25
  'Award Amount',
20
26
  'Total Outlays',
21
27
  'Awarding Agency',
@@ -60,7 +66,8 @@ const LOAN_SORTS = [
60
66
  * partition its mixed-group 422 lists, F-codes and -1 included — and the sorts
61
67
  * each group's field mapping allows; upstream answers any other sort with a 400.
62
68
  * 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.
69
+ * kind and sort by their own. Labels follow USAspending's type names. The keys
70
+ * are the buckets `search/spending_by_award_count/` reports, one per group.
64
71
  */
65
72
  const AWARD_TYPE_GROUPS = {
66
73
  contracts: { label: 'contracts', codes: AWARD_TYPE_CODES.contracts, sorts: CONTRACT_SORTS },
@@ -83,7 +90,8 @@ const AWARD_TYPE_GROUPS = {
83
90
  * include one outside them — upstream's own 422 then decides, unguessed.
84
91
  */
85
92
  function resolveAwardTypeGroup(codes) {
86
- const groups = new Set(codes.map((code) => Object.values(AWARD_TYPE_GROUPS).find((g) => g.codes.includes(code))));
93
+ const names = Object.keys(AWARD_TYPE_GROUPS);
94
+ const groups = new Set(codes.map((code) => names.find((name) => AWARD_TYPE_GROUPS[name].codes.includes(code))));
87
95
  const [only] = groups;
88
96
  return groups.size === 1 ? only : undefined;
89
97
  }
@@ -107,9 +115,37 @@ const MAX_PAGE_OFFSET = 50_000;
107
115
  * the cursor must capture it before crossing this line.
108
116
  */
109
117
  const CURSOR_WINDOW_OFFSET = 10_000;
118
+ /**
119
+ * How long the count request may run, measured from the start of the call: about
120
+ * 2.5× the slowest cold count measured (an 18-year all-contracts filter); warm
121
+ * repeats answer in well under a second. Past it the request is aborted and the
122
+ * total reported unavailable, so a slow count never holds the answer longer.
123
+ */
124
+ const COUNT_DEADLINE_MS = 10_000;
125
+ /** search/spending_by_award/ answers a limit above 100 with a 422. */
126
+ const LIMIT = countLimit({ tool: 'usaspending_search_awards', default: 10, cap: 100 });
127
+ const UnavailableSectionSchema = unavailableSectionSchema(['total'], 'total: page_metadata.total and totalCount, from the count request.');
128
+ /** Paging guidance before the 10,000-result offset where the cursor pair stops. */
129
+ 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.`;
130
+ /**
131
+ * Paging guidance for a page-number page with rows past it and a known total.
132
+ * The cursor guidance is kept only for matches page numbers cannot reach.
133
+ */
134
+ function knownTotalGuidance(page, limit, total) {
135
+ const parts = [
136
+ `${total.toLocaleString()} awards match; this page ends at result ${(page * limit).toLocaleString()}.`,
137
+ (page + 1) * limit <= MAX_PAGE_OFFSET
138
+ ? `Request page ${page + 1} for more.`
139
+ : `The next page would pass the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number window.`,
140
+ ];
141
+ if (total > MAX_PAGE_OFFSET) {
142
+ 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.`);
143
+ }
144
+ return parts.join(' ');
145
+ }
110
146
  export const searchAwardsTool = tool('usaspending_search_awards', {
111
147
  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.',
148
+ 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
149
  annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true },
114
150
  input: z.object({
115
151
  keyword: z
@@ -121,10 +157,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
121
157
  .min(1)
122
158
  .default(['A', 'B', 'C', 'D'])
123
159
  .describe('Filter by award type codes. All codes must belong to a single group: A/B/C/D (contracts), IDV_A/IDV_B/IDV_B_A/IDV_B_B/IDV_B_C/IDV_C/IDV_D/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). Defaults to contracts. Mixing groups causes a 422 error. The group decides which sort values apply.'),
124
- agency_name: z
125
- .string()
126
- .optional()
127
- .describe('Awarding top-tier or sub-tier agency name — use the matched name from usaspending_autocomplete_filters type=awarding_agency; use toptier_name to select the whole parent department. A sub-tier name shared by several parents matches under all parents.'),
160
+ ...AGENCY_FILTER_FIELDS,
128
161
  recipient_name: z
129
162
  .string()
130
163
  .optional()
@@ -141,7 +174,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
141
174
  })
142
175
  .strict()
143
176
  .optional()
144
- .describe('Filter awards by date range (action date). Both blank means no date filter; one blank end is filled and named in the notice.'),
177
+ .describe("Filter awards by date range (action date). Omit both bounds or leave both blank to query USAspending's available coverage without a date filter. One blank end is filled and named in the notice."),
145
178
  location_filter: LocationFilterSchema,
146
179
  sort: z
147
180
  .enum([
@@ -158,13 +191,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
158
191
  .optional()
159
192
  .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
193
  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)'),
194
+ limit: LIMIT.schema.describe('Awards per page. Default 10, at most 100 per call.'),
168
195
  page: z
169
196
  .number()
170
197
  .int()
@@ -190,10 +217,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
190
217
  .array(z.string())
191
218
  .optional()
192
219
  .describe('Award type codes; all must belong to one group (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). When non-empty, overrides the top-level award_type_codes and decides which sort values apply; an empty array falls back to the top-level value.'),
193
- agency_name: z
194
- .string()
195
- .optional()
196
- .describe('Awarding top-tier or sub-tier agency name — use the matched name from usaspending_autocomplete_filters type=awarding_agency; use toptier_name to select the whole parent department. A sub-tier name shared by several parents matches under all parents.'),
220
+ ...AGENCY_FILTER_FIELDS,
197
221
  recipient_name: z
198
222
  .string()
199
223
  .optional()
@@ -203,7 +227,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
203
227
  .optional()
204
228
  .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
229
  ...CODE_FILTER_FIELDS,
206
- time_period_start: optionalIsoDate('Start date (YYYY-MM-DD); earliest valid 2007-10-01. Given alone, the range runs through today (UTC).'),
230
+ ...LOCATION_FILTER_FIELDS,
231
+ time_period_start: optionalIsoDate("Start date (YYYY-MM-DD); earliest valid 2007-10-01. Given alone, the range runs through today (UTC). With no effective start or end, the query uses USAspending's available coverage without a date filter."),
207
232
  time_period_end: optionalIsoDate('End date (YYYY-MM-DD). Given alone, the range starts at 2007-10-01, the earliest searchable date.'),
208
233
  })
209
234
  .strict()
@@ -223,6 +248,14 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
223
248
  .optional()
224
249
  .describe('Generated unique award ID — pass to usaspending_get_award to fetch full details'),
225
250
  recipient_name: z.string().optional().describe('Name of the award recipient'),
251
+ recipient_id: z
252
+ .string()
253
+ .optional()
254
+ .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.'),
255
+ uei: z
256
+ .string()
257
+ .optional()
258
+ .describe('Recipient Unique Entity Identifier. Absent when upstream has none.'),
226
259
  award_amount: z.number().optional().describe('Total award amount in USD'),
227
260
  total_outlays: z.number().optional().describe('Total outlays in USD'),
228
261
  loan_value: z
@@ -263,9 +296,13 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
263
296
  .object({
264
297
  has_next: z
265
298
  .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.`),
299
+ .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
300
  page: z.number().describe('Current page number'),
268
301
  limit: z.number().describe('Results per page'),
302
+ total: z
303
+ .number()
304
+ .optional()
305
+ .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
306
  last_record_sort_value: z
270
307
  .string()
271
308
  .optional()
@@ -275,7 +312,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
275
312
  .optional()
276
313
  .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
314
  })
278
- .describe('Pagination metadata. This endpoint does not return a total match count; use has_next and the cursor pair to page.'),
315
+ .describe('Pagination metadata: has_next, the page and limit, the total match count, and the keyset cursor pair.'),
279
316
  }),
280
317
  // Agent-facing search context: applied filters, upstream API notices, and an optional
281
318
  // recovery notice for empty pages. Populated via ctx.enrich() so it reaches both
@@ -284,11 +321,15 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
284
321
  page: z.number().describe('Current page number returned'),
285
322
  has_next: z
286
323
  .boolean()
287
- .describe('Whether more results may remain — set on a full page even when the upstream flag reports none.'),
324
+ .describe('Whether more results remain: exact with a known total on page-number paging, otherwise true on any full page.'),
288
325
  truncated: z
289
326
  .boolean()
290
327
  .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.`),
328
+ .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.`),
329
+ totalCount: z
330
+ .number()
331
+ .optional()
332
+ .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
333
  shown: z
293
334
  .number()
294
335
  .optional()
@@ -302,7 +343,12 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
302
343
  .optional()
303
344
  .describe('Notices the USAspending API returned with this response — e.g. a supplied filter it ignored because this endpoint does not support it. Every successful response also carries a standing advisory that search covers 2007-10-01 onward; that advisory is boilerplate, not a verdict on the dates requested. Present whenever the API returns any messages.'),
304
345
  applied_keyword: z.string().optional().describe('Keyword filter applied to this search'),
305
- applied_agency_name: z.string().optional().describe('Awarding agency name filter applied'),
346
+ applied_recipient_name: z
347
+ .string()
348
+ .optional()
349
+ .describe('Effective recipient name sent upstream'),
350
+ applied_award_type_codes: z.string().describe('Award type codes sent, comma-separated'),
351
+ ...AGENCY_FILTER_ENRICHMENT,
306
352
  applied_naics_codes: z
307
353
  .string()
308
354
  .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, the use of available coverage without a date filter or any filled date bound, active filters on an empty page, and any section that 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
@@ -438,15 +495,17 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
438
495
  {
439
496
  reason: 'invalid_location',
440
497
  code: JsonRpcErrorCode.ValidationError,
441
- 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.',
442
499
  retryable: false,
443
- 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.",
444
501
  },
445
502
  ],
446
503
  async handler(input, ctx) {
504
+ // Every read below uses the applied limit, never input.limit.
505
+ const { applied: limit, notice: clampNotice } = LIMIT.apply(ctx, 'limit', input.limit);
447
506
  ctx.log.info('usaspending_search_awards', {
448
507
  keyword: input.keyword,
449
- limit: input.limit,
508
+ limit,
450
509
  page: input.page,
451
510
  });
452
511
  const svc = getUSASpendingService();
@@ -460,8 +519,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
460
519
  const usingCursor = hasSortValue && hasUniqueId;
461
520
  // Page-number pagination caps at a 50,000-result offset; fail fast with the cursor
462
521
  // recovery path instead of letting the upstream 422 bubble up unclassified.
463
- if (!usingCursor && input.page * input.limit > MAX_PAGE_OFFSET) {
464
- 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.`);
522
+ if (!usingCursor && input.page * limit > MAX_PAGE_OFFSET) {
523
+ 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.`);
465
524
  }
466
525
  /**
467
526
  * Merge the analytics-style `filters` object over the flat inputs (nested wins
@@ -478,7 +537,6 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
478
537
  const awardTypeCodes = f?.award_type_codes?.length
479
538
  ? f.award_type_codes
480
539
  : input.award_type_codes;
481
- const agencyName = f?.agency_name || input.agency_name;
482
540
  const recipientName = f?.recipient_name || input.recipient_name;
483
541
  const mergedNaicsCodes = f?.naics_codes && f.naics_codes.length > 0 ? f.naics_codes : input.naics_codes;
484
542
  const effective = normalizeEffectiveFilters({
@@ -539,29 +597,43 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
539
597
  }
540
598
  // Upstream checks the sort against the group's field mapping and answers 400
541
599
  // outside it. Codes spanning groups skip the check: upstream's 422 decides.
542
- const group = resolveAwardTypeGroup(awardTypeCodes);
543
- const isLoan = group === AWARD_TYPE_GROUPS.loans;
600
+ const groupName = resolveAwardTypeGroup(awardTypeCodes);
601
+ const group = groupName ? AWARD_TYPE_GROUPS[groupName] : undefined;
602
+ const isLoan = groupName === 'loans';
544
603
  const sort = input.sort ?? (isLoan ? 'Loan Value' : 'Award Amount');
545
604
  if (group && !group.sorts.includes(sort)) {
546
605
  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(', ')}.`);
547
606
  }
548
607
  /**
549
608
  * Upstream 422s on a missing country or a 5-digit county, and answers an empty
550
- * page for a FIPS-number state or a territory's ISO code, so the location is
551
- * normalized to the one shape it matches, or rejected, before the request.
609
+ * page for a FIPS-number state or a territory's ISO code, so each location is
610
+ * normalized to the one shape it matches, or rejected naming its input path,
611
+ * before the request. A nested place of performance wins over the flat
612
+ * location_filter, which is then neither sent nor checked.
552
613
  */
553
- const resolvedLocation = resolveLocation(input.location_filter);
554
- if (!resolvedLocation.ok) {
555
- throw ctx.fail('invalid_location', resolvedLocation.message);
614
+ const located = resolveLocationFilters(f ?? {});
615
+ if (!located.ok)
616
+ throw ctx.fail('invalid_location', located.message);
617
+ const { locations } = located;
618
+ if (!locations.place_of_performance_location) {
619
+ const flat = resolveLocation(input.location_filter);
620
+ if (!flat.ok)
621
+ throw ctx.fail('invalid_location', flat.message);
622
+ if (flat.location)
623
+ locations.place_of_performance_location = flat.location;
556
624
  }
557
- const location = resolvedLocation.location;
558
625
  const filters = {};
559
626
  if (keywords?.length)
560
627
  filters.keywords = keywords;
561
628
  filters.award_type_codes = awardTypeCodes;
562
- if (agencyName) {
563
- filters.agencies = awardingAgencyFilters(agencyName);
564
- }
629
+ const names = {
630
+ agency_name: f?.agency_name || input.agency_name,
631
+ funding_agency_name: f?.funding_agency_name || input.funding_agency_name,
632
+ };
633
+ const agencies = names.agency_name || names.funding_agency_name
634
+ ? await resolveAgencyFilters(svc, names, ctx)
635
+ : { names, notices: [] };
636
+ applyAgencyFilters(filters, agencies.names);
565
637
  if (recipientName)
566
638
  filters.recipient_search_text = [recipientName];
567
639
  if (naicsCodes?.length) {
@@ -571,14 +643,14 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
571
643
  if (timePeriod) {
572
644
  filters.time_period = [{ start_date: timePeriod.start_date, end_date: timePeriod.end_date }];
573
645
  }
574
- if (location)
575
- filters.place_of_performance_locations = [location];
576
- const data = await svc.searchAwards({
646
+ applyLocationFilters(filters, locations);
647
+ const countDeadlineAt = Date.now() + COUNT_DEADLINE_MS;
648
+ const searchRequest = svc.searchAwards({
577
649
  filters,
578
650
  fields: isLoan ? [...AWARD_SEARCH_FIELDS, ...LOAN_FIELDS] : AWARD_SEARCH_FIELDS,
579
651
  sort,
580
652
  order: input.order,
581
- limit: input.limit,
653
+ limit,
582
654
  // page and cursor are mutually exclusive; omit page when paging by cursor.
583
655
  // Re-test both fields inline so exactOptionalPropertyTypes narrows away `undefined`.
584
656
  ...(input.last_record_sort_value !== undefined && input.last_record_unique_id !== undefined
@@ -588,12 +660,30 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
588
660
  }
589
661
  : { page: input.page }),
590
662
  }, ctx);
663
+ /**
664
+ * The count gets the very `filters` object the search sends, so every filter
665
+ * reaches both, and runs beside the search as a best-effort side read under its
666
+ * own deadline. Codes spanning groups never reach it: upstream's 422 fails the
667
+ * search. Settled up front, so a count that rejects after a failed search is
668
+ * still handled; the search is awaited alone, so its failure surfaces at once.
669
+ */
670
+ const countLeg = Promise.allSettled([
671
+ groupName ? svc.countAwards(filters, ctx, countDeadlineAt) : undefined,
672
+ ]);
673
+ const data = await searchRequest;
674
+ const [countResult] = await countLeg;
675
+ // A failed count leaves the total unknown and is disclosed; a caller abort rethrows.
676
+ const unavailable = [];
677
+ const counts = settleSection(ctx, 'total', countResult, unavailable);
678
+ const total = groupName && counts ? counts[groupName] : undefined;
591
679
  const results = (data.results ?? []).map((r) => ({
592
680
  ...(r['Award ID'] ? { award_id: String(r['Award ID']) } : {}),
593
681
  ...(r.generated_internal_id
594
682
  ? { generated_internal_id: String(r.generated_internal_id) }
595
683
  : {}),
596
684
  ...(r['Recipient Name'] ? { recipient_name: String(r['Recipient Name']) } : {}),
685
+ ...(r.recipient_id ? { recipient_id: r.recipient_id } : {}),
686
+ ...(r['Recipient UEI'] ? { uei: r['Recipient UEI'] } : {}),
597
687
  ...(typeof r['Award Amount'] === 'number' ? { award_amount: r['Award Amount'] } : {}),
598
688
  ...(typeof r['Total Outlays'] === 'number' ? { total_outlays: r['Total Outlays'] } : {}),
599
689
  ...(typeof r['Loan Value'] === 'number' ? { loan_value: r['Loan Value'] } : {}),
@@ -630,10 +720,18 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
630
720
  : {}),
631
721
  }));
632
722
  const pageMeta = data.page_metadata ?? {};
633
- // Past a 10,000-result offset this endpoint keeps returning full pages while
634
- // reporting hasNext: false, so forwarding the flag verbatim ends pagination with
635
- // tens of thousands of matches still behind it. Page fullness is the honest signal.
636
- const hasNext = resolveHasNext(pageMeta.hasNext, results.length, input.limit);
723
+ const page = pageMeta.page ?? input.page;
724
+ /**
725
+ * A known total settles continuation on page-number paging: rows remain exactly
726
+ * when this page ends before the total. Without one — the count failed, or the
727
+ * page came by cursor, whose absolute offset is unknown — page fullness stands
728
+ * in, since past a 10,000-result offset upstream reports hasNext: false on every
729
+ * full page and forwarding the flag would strand the matches behind it.
730
+ */
731
+ const pagedTotal = usingCursor ? undefined : total;
732
+ const hasNext = pagedTotal !== undefined
733
+ ? page * limit < pagedTotal || pageMeta.hasNext === true
734
+ : resolveHasNext(pageMeta.hasNext, results.length, limit);
637
735
  // The keyset cursor is usable only on interior pages. On the final page the upstream
638
736
  // returns last_record_unique_id: null and last_record_sort_value: "None" (a stringified
639
737
  // Python None) — a bare `!== undefined` forwards that null and crashes the z.number()
@@ -644,8 +742,9 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
644
742
  const uniqueCursor = pageMeta.last_record_unique_id;
645
743
  const page_metadata = {
646
744
  has_next: hasNext,
647
- page: pageMeta.page ?? input.page,
648
- limit: input.limit,
745
+ page,
746
+ limit,
747
+ ...(total !== undefined ? { total } : {}),
649
748
  ...(hasNext &&
650
749
  typeof sortCursor === 'string' &&
651
750
  sortCursor !== 'None' &&
@@ -658,10 +757,12 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
658
757
  has_next: page_metadata.has_next,
659
758
  ...(data.messages?.length ? { upstream_messages: data.messages } : {}),
660
759
  ...(keywords?.length ? { applied_keyword: keywords.join(', ') } : {}),
661
- ...(agencyName ? { applied_agency_name: agencyName } : {}),
760
+ ...(recipientName ? { applied_recipient_name: recipientName } : {}),
761
+ applied_award_type_codes: awardTypeCodes.join(', '),
762
+ ...agencyFilterEcho(agencies.names),
662
763
  ...(naicsCodes?.length ? { applied_naics_codes: naicsCodes.join(', ') } : {}),
663
764
  ...codeFilterEcho(codes),
664
- ...(location ? { applied_location: describeLocation(location) } : {}),
765
+ ...locationFilterEcho(locations),
665
766
  ...(timePeriod
666
767
  ? {
667
768
  applied_time_period_start: timePeriod.start_date,
@@ -669,38 +770,49 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
669
770
  }
670
771
  : {}),
671
772
  });
773
+ if (total !== undefined)
774
+ ctx.enrich.total(total);
672
775
  // enrich.notice is last-wins, and enrich.truncated writes the notice too, so
673
776
  // every notice source joins into one string written at the end.
674
- const notices = [];
777
+ const notices = [clampNotice, ...agencies.notices];
675
778
  /**
676
- * Paging guidance follows has_next, which keeps the page-fullness fallback. The
677
- * truncated/shown/cap disclosure needs evidence that rows exist past this page — the
678
- * upstream hasNext — so an exactly-full final page and every page past the
679
- * CURSOR_WINDOW_OFFSET (where hasNext is always false) carry the notice alone.
779
+ * The truncated/shown/cap disclosure needs evidence that rows exist past this
780
+ * page: the known total, or the upstream hasNext. Without a total, an exactly-full
781
+ * final page and every page past the CURSOR_WINDOW_OFFSET (where hasNext is always
782
+ * false) carry the paging notice alone.
680
783
  */
681
- if (page_metadata.has_next) {
682
- 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.`;
683
- if (pageMeta.hasNext) {
684
- ctx.enrich.truncated({ shown: results.length, cap: input.limit, guidance });
784
+ if (hasNext) {
785
+ const guidance = pagedTotal !== undefined ? knownTotalGuidance(page, limit, pagedTotal) : CURSOR_GUIDANCE;
786
+ if (pagedTotal !== undefined || pageMeta.hasNext) {
787
+ ctx.enrich.truncated({ shown: results.length, cap: limit, guidance });
685
788
  }
686
789
  notices.push(guidance);
687
790
  }
688
- notices.push(filledBoundNotice(timePeriod, filledFields));
791
+ notices.push(timePeriod ? filledBoundNotice(timePeriod, filledFields) : NO_DATE_FILTER_NOTICE);
689
792
  if (results.length === 0) {
690
793
  const filterParts = [];
794
+ const agencyParts = describeAgencyFilters(agencies.names);
691
795
  if (keywords?.length)
692
796
  filterParts.push(`keyword="${keywords.join(', ')}"`);
693
- if (agencyName)
694
- filterParts.push(`agency="${agencyName}"`);
695
- filterParts.push(...describeCodeFilters(codes));
696
- if (location)
697
- filterParts.push(`location="${describeLocation(location)}"`);
698
- if (awardTypeCodes?.length) {
699
- filterParts.push(`types=${awardTypeCodes.join(',')}`);
797
+ if (recipientName)
798
+ filterParts.push(`recipient_name="${recipientName}"`);
799
+ filterParts.push(...agencyParts);
800
+ filterParts.push(...describeCodeFilters(codes), ...describeLocationFilters(locations));
801
+ filterParts.push(`types=${awardTypeCodes.join(',')}`);
802
+ const filterText = filterParts.join(', ');
803
+ notices.push(pagedTotal !== undefined
804
+ ? emptyPageNotice(page, limit, pagedTotal, `No awards match ${filterText}.`)
805
+ : `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.'}`);
806
+ if (pagedTotal !== undefined && pagedTotal > 0) {
807
+ if (recipientName)
808
+ notices.push(`Recipient filter: recipient_name="${recipientName}".`);
809
+ if (agencyParts.length)
810
+ notices.push(`Agency filters: ${agencyParts.join(', ')}.`);
700
811
  }
701
- notices.push(filterParts.length > 0
702
- ? `Page ${page_metadata.page} returned no awards for ${filterParts.join(', ')}. The API does not supply a total match count.`
703
- : `Page ${page_metadata.page} returned no awards. The API does not supply a total match count.`);
812
+ }
813
+ if (unavailable.length > 0) {
814
+ ctx.enrich({ unavailable_sections: unavailable });
815
+ notices.push(unavailableNotice(unavailable));
704
816
  }
705
817
  const notice = notices.filter(Boolean).join(' ');
706
818
  if (notice)
@@ -709,7 +821,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
709
821
  },
710
822
  format: (result) => {
711
823
  const lines = ['## Federal Award Search Results'];
712
- 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'}`);
824
+ const { total } = result.page_metadata;
825
+ 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'}`);
713
826
  for (const r of result.results) {
714
827
  lines.push('');
715
828
  lines.push(`### ${escapeMarkdownInline(r.recipient_name ?? r.award_id ?? r.generated_internal_id ?? 'Unknown')}`);
@@ -717,6 +830,10 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
717
830
  lines.push(`**Award ID:** ${escapeMarkdownInline(r.award_id)}`);
718
831
  if (r.generated_internal_id)
719
832
  lines.push(`**Chain ID (for get_award):** ${escapeMarkdownInline(r.generated_internal_id)}`);
833
+ if (r.recipient_id)
834
+ lines.push(`**Recipient ID (for get_recipient):** ${escapeMarkdownInline(r.recipient_id)}`);
835
+ if (r.uei)
836
+ lines.push(`**UEI:** ${escapeMarkdownInline(r.uei)}`);
720
837
  if (r.agency_slug)
721
838
  lines.push(`**Agency Slug (for get_agency):** ${escapeMarkdownInline(r.agency_slug)}`);
722
839
  if (typeof r.award_amount === 'number')
@@ -757,8 +874,11 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
757
874
  // the MAX_PAGE_OFFSET cap there is no next page to direct to: the handler's own
758
875
  // pagination_limit_exceeded guard rejects it.
759
876
  const nextPage = result.page_metadata.page + 1;
877
+ const beyond = total !== undefined
878
+ ? ` — ${(total - result.page_metadata.page * result.page_metadata.limit).toLocaleString()} matching awards lie past it`
879
+ : '';
760
880
  lines.push(nextPage * result.page_metadata.limit > MAX_PAGE_OFFSET
761
- ? `**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.`
881
+ ? `**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.`
762
882
  : `**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.`);
763
883
  }
764
884
  }