@cyanheads/usaspending-mcp-server 0.7.2 → 0.7.4

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 (81) hide show
  1. package/AGENTS.md +1 -1
  2. package/CLAUDE.md +1 -1
  3. package/README.md +29 -14
  4. package/changelog/0.7.x/0.7.3.md +29 -0
  5. package/changelog/0.7.x/0.7.4.md +35 -0
  6. package/dist/index.js +1 -6
  7. package/dist/index.js.map +1 -1
  8. package/dist/mcp-server/tools/definitions/agency-filters.d.ts +40 -0
  9. package/dist/mcp-server/tools/definitions/agency-filters.d.ts.map +1 -0
  10. package/dist/mcp-server/tools/definitions/agency-filters.js +125 -0
  11. package/dist/mcp-server/tools/definitions/agency-filters.js.map +1 -0
  12. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts +5 -1
  13. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.d.ts.map +1 -1
  14. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js +60 -15
  15. package/dist/mcp-server/tools/definitions/autocomplete-filters.tool.js.map +1 -1
  16. package/dist/mcp-server/tools/definitions/dates.d.ts +2 -0
  17. package/dist/mcp-server/tools/definitions/dates.d.ts.map +1 -1
  18. package/dist/mcp-server/tools/definitions/dates.js +2 -0
  19. package/dist/mcp-server/tools/definitions/dates.js.map +1 -1
  20. package/dist/mcp-server/tools/definitions/disaster-spending.tool.d.ts +1 -1
  21. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js +4 -4
  22. package/dist/mcp-server/tools/definitions/disaster-spending.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/filters.d.ts +78 -14
  24. package/dist/mcp-server/tools/definitions/filters.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/filters.js +117 -18
  26. package/dist/mcp-server/tools/definitions/filters.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts +2 -0
  28. package/dist/mcp-server/tools/definitions/get-agency.tool.d.ts.map +1 -1
  29. package/dist/mcp-server/tools/definitions/get-agency.tool.js +35 -13
  30. package/dist/mcp-server/tools/definitions/get-agency.tool.js.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.d.ts.map +1 -1
  32. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js +3 -6
  33. package/dist/mcp-server/tools/definitions/get-award-transactions.tool.js.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts +17 -0
  35. package/dist/mcp-server/tools/definitions/get-award.tool.d.ts.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-award.tool.js +122 -17
  37. package/dist/mcp-server/tools/definitions/get-award.tool.js.map +1 -1
  38. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts +1 -1
  39. package/dist/mcp-server/tools/definitions/get-recipient.tool.d.ts.map +1 -1
  40. package/dist/mcp-server/tools/definitions/get-recipient.tool.js +20 -10
  41. package/dist/mcp-server/tools/definitions/get-recipient.tool.js.map +1 -1
  42. package/dist/mcp-server/tools/definitions/index.d.ts +72 -11
  43. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  44. package/dist/mcp-server/tools/definitions/locations.d.ts +15 -1
  45. package/dist/mcp-server/tools/definitions/locations.d.ts.map +1 -1
  46. package/dist/mcp-server/tools/definitions/locations.js +31 -11
  47. package/dist/mcp-server/tools/definitions/locations.js.map +1 -1
  48. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts +34 -5
  49. package/dist/mcp-server/tools/definitions/search-awards.tool.d.ts.map +1 -1
  50. package/dist/mcp-server/tools/definitions/search-awards.tool.js +211 -89
  51. package/dist/mcp-server/tools/definitions/search-awards.tool.js.map +1 -1
  52. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts +1 -0
  53. package/dist/mcp-server/tools/definitions/search-recipients.tool.d.ts.map +1 -1
  54. package/dist/mcp-server/tools/definitions/search-recipients.tool.js +9 -5
  55. package/dist/mcp-server/tools/definitions/search-recipients.tool.js.map +1 -1
  56. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts +5 -2
  57. package/dist/mcp-server/tools/definitions/spending-by-category.tool.d.ts.map +1 -1
  58. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js +26 -17
  59. package/dist/mcp-server/tools/definitions/spending-by-category.tool.js.map +1 -1
  60. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts +5 -2
  61. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.d.ts.map +1 -1
  62. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js +22 -18
  63. package/dist/mcp-server/tools/definitions/spending-by-geography.tool.js.map +1 -1
  64. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts +4 -2
  65. package/dist/mcp-server/tools/definitions/spending-over-time.tool.d.ts.map +1 -1
  66. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js +13 -14
  67. package/dist/mcp-server/tools/definitions/spending-over-time.tool.js.map +1 -1
  68. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts +3 -1
  69. package/dist/mcp-server/tools/definitions/unavailable-sections.d.ts.map +1 -1
  70. package/dist/mcp-server/tools/definitions/unavailable-sections.js +9 -3
  71. package/dist/mcp-server/tools/definitions/unavailable-sections.js.map +1 -1
  72. package/dist/services/usaspending/types.d.ts +29 -2
  73. package/dist/services/usaspending/types.d.ts.map +1 -1
  74. package/dist/services/usaspending/types.js.map +1 -1
  75. package/dist/services/usaspending/usaspending-service.d.ts +36 -10
  76. package/dist/services/usaspending/usaspending-service.d.ts.map +1 -1
  77. package/dist/services/usaspending/usaspending-service.js +110 -33
  78. package/dist/services/usaspending/usaspending-service.js.map +1 -1
  79. package/package.json +5 -5
  80. package/server.json +3 -3
  81. package/skills/usaspending-guide/SKILL.md +10 -4
@@ -1,16 +1,17 @@
1
1
  /**
2
2
  * @fileoverview Tool to search federal awards by keyword, recipient, agency, award type,
3
- * NAICS, Assistance Listing, PSC, or DEF code, place of performance or recipient
4
- * location, or date range.
3
+ * NAICS, Assistance Listing, PSC, or DEF code, contract competition, set-aside, or
4
+ * pricing code, place of performance or recipient location, or date range.
5
5
  * @module mcp-server/tools/definitions/search-awards.tool
6
6
  */
7
7
  import { tool, z } from '@cyanheads/mcp-ts-core';
8
- import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
8
+ import { JsonRpcErrorCode, timeout } from '@cyanheads/mcp-ts-core/errors';
9
9
  import { escapeMarkdownInline } from '@cyanheads/mcp-ts-core/utils';
10
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';
11
12
  import { countLimit, LimitClampSchema, limitClampTrailer } from './count-limit.js';
12
- import { ANALYTICS_DATE_FIELDS, blankableIsoDate, filledBoundNotice, floorViolationMessage, invertedRangeMessage, optionalIsoDate, resolveDateRange, } from './dates.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';
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, AWARD_TYPE_GROUP_LIST, applyCodeFilters, applyLocationFilters, CODE_FILTER_FIELDS, CONTRACT_FILTER_FIELDS, codeFilterEcho, contractFilterEcho, describeCodeFilters, describeContractFilters, describeLocationFilters, locationFilterEcho, NESTED_LOCATION_FILTER_FIELDS, nestedTwins, normalizeCodeFilters, normalizeContractFilters, normalizeEffectiveFilters, PROCUREMENT_AWARD_TYPE_CODES, resolveLocationFilters, } from './filters.js';
14
15
  import { formatCurrency } from './formatting.js';
15
16
  import { LocationFilterSchema, resolveLocation } from './locations.js';
16
17
  import { emptyPageNotice, resolveHasNext } from './pagination.js';
@@ -84,13 +85,14 @@ const AWARD_TYPE_GROUPS = {
84
85
  loans: { label: 'loans', codes: AWARD_TYPE_CODES.loans, sorts: LOAN_SORTS },
85
86
  other: { label: 'other', codes: AWARD_TYPE_CODES.other, sorts: CONTRACT_SORTS },
86
87
  };
88
+ /** The group names in {@link AWARD_TYPE_GROUPS} order, which output and notices follow. */
89
+ const AWARD_TYPE_GROUP_NAMES = Object.keys(AWARD_TYPE_GROUPS);
87
90
  /**
88
91
  * The group every code belongs to, or `undefined` when the codes span groups or
89
92
  * include one outside them — upstream's own 422 then decides, unguessed.
90
93
  */
91
94
  function resolveAwardTypeGroup(codes) {
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))));
95
+ const groups = new Set(codes.map((code) => AWARD_TYPE_GROUP_NAMES.find((name) => AWARD_TYPE_GROUPS[name].codes.includes(code))));
94
96
  const [only] = groups;
95
97
  return groups.size === 1 ? only : undefined;
96
98
  }
@@ -115,15 +117,56 @@ const MAX_PAGE_OFFSET = 50_000;
115
117
  */
116
118
  const CURSOR_WINDOW_OFFSET = 10_000;
117
119
  /**
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.
120
+ * How long the count requests may run, measured from the start of the call: about
121
+ * 2.5× the slowest cold total count measured (an 18-year all-contracts filter); warm
122
+ * repeats answer in well under a second. Both counts share it. Past it a count is
123
+ * aborted and its section reported unavailable, so a slow count never holds the
124
+ * answer longer.
122
125
  */
123
126
  const COUNT_DEADLINE_MS = 10_000;
127
+ /**
128
+ * How long the group count may run past the later of the search and the total
129
+ * count before it is cut and `matches_by_group` reported unavailable. On cold
130
+ * queries the count across every group lags those two by under this on narrow
131
+ * filters, but by several seconds on the widest date range, where waiting for it
132
+ * under the shared deadline would more than double the call for a best-effort field.
133
+ */
134
+ const GROUP_COUNT_GRACE_MS = 2_000;
135
+ /**
136
+ * The group count's settled result, or a timeout standing in for it once it has run
137
+ * {@link GROUP_COUNT_GRACE_MS} past the search and the total count. The caller
138
+ * aborts the request it stopped waiting for.
139
+ */
140
+ async function settleWithinGrace(leg) {
141
+ let timer;
142
+ const cut = new Promise((resolve) => {
143
+ timer = setTimeout(() => resolve({
144
+ status: 'rejected',
145
+ reason: timeout(`The count across award-type groups was still running ${GROUP_COUNT_GRACE_MS / 1000} s after the search and the total count finished, so it was cut.`, { reason: 'api_timeout', retryable: true }),
146
+ }), GROUP_COUNT_GRACE_MS);
147
+ });
148
+ try {
149
+ return await Promise.race([leg, cut]);
150
+ }
151
+ finally {
152
+ clearTimeout(timer);
153
+ }
154
+ }
124
155
  /** search/spending_by_award/ answers a limit above 100 with a 422. */
125
156
  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.');
157
+ const UnavailableSectionSchema = unavailableSectionSchema(['total', 'matches_by_group'], "total: page_metadata.total and totalCount, from the count sent with the search's filters. matches_by_group: matches_by_group, from the count sent without award_type_codes.");
158
+ /**
159
+ * The other groups with matches, each with its count and the codes that search it.
160
+ * Upstream applies every filter to every group, so a filter only some groups carry
161
+ * (NAICS, PSC, the contract filters, assistance listings) zeroes the rest, and this
162
+ * never points at a group the call's filters exclude.
163
+ */
164
+ function otherGroupsNotice(selected, matches) {
165
+ const others = AWARD_TYPE_GROUP_NAMES.filter((name) => name !== selected && matches[name] > 0);
166
+ if (others.length === 0)
167
+ return;
168
+ return `Other award-type groups match these filters: ${others.map((name) => `${name} ${matches[name].toLocaleString()} (award_type_codes ${AWARD_TYPE_GROUPS[name].codes.join(', ')})`).join(', ')}. Search one by setting award_type_codes to its codes.`;
169
+ }
127
170
  /** Paging guidance before the 10,000-result offset where the cursor pair stops. */
128
171
  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
172
  /**
@@ -144,7 +187,7 @@ function knownTotalGuidance(page, limit, total) {
144
187
  }
145
188
  export const searchAwardsTool = tool('usaspending_search_awards', {
146
189
  title: 'Search Federal Awards',
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.',
190
+ description: `Search federal awards by keyword, recipient, agency, award type, NAICS code, assistance listing (CFDA) number, PSC, DEF code, extent competed, set-aside, contract pricing, 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). The contract filters extent_competed_type_codes, set_aside_type_codes, and contract_pricing_type_codes take the FPDS codes usaspending_get_award returns: 1–8 letters or digits, sent uppercased; an empty list is unset, several values match any of them, and an unknown code matches nothing. Only contracts and IDVs carry these codes, so a call whose award types include an assistance code is rejected as contract_filters_type_mismatch. 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 for the call's filters and award_type_codes. Page numbers reach results up to a ${MAX_PAGE_OFFSET.toLocaleString()}-result offset (page × limit); past it, continue with last_record_sort_value and last_record_unique_id from page_metadata, which the upstream returns only while page × limit is under ${CURSOR_WINDOW_OFFSET.toLocaleString()}, so capture the pair before then. With both cursor fields supplied, page is ignored. 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
191
  annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true },
149
192
  input: z.object({
150
193
  keyword: z
@@ -155,11 +198,8 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
155
198
  .array(z.string())
156
199
  .min(1)
157
200
  .default(['A', 'B', 'C', 'D'])
158
- .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.'),
159
- agency_name: z
160
- .string()
161
- .optional()
162
- .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.'),
201
+ .describe(`Filter by award type codes. All codes must belong to a single group: ${AWARD_TYPE_GROUP_LIST}. Defaults to contracts. Mixing groups causes a 422 error. The group decides which sort values apply.`),
202
+ ...AGENCY_FILTER_FIELDS,
163
203
  recipient_name: z
164
204
  .string()
165
205
  .optional()
@@ -169,6 +209,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
169
209
  .optional()
170
210
  .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.'),
171
211
  ...CODE_FILTER_FIELDS,
212
+ ...CONTRACT_FILTER_FIELDS,
172
213
  time_period: z
173
214
  .object({
174
215
  start_date: blankableIsoDate('Start date in ISO 8601 format (YYYY-MM-DD); earliest valid: 2007-10-01. Blank ("") leaves the start open, filled with 2007-10-01.'),
@@ -176,7 +217,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
176
217
  })
177
218
  .strict()
178
219
  .optional()
179
- .describe('Filter awards by date range (action date). Both blank means no date filter; one blank end is filled and named in the notice.'),
220
+ .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."),
180
221
  location_filter: LocationFilterSchema,
181
222
  sort: z
182
223
  .enum([
@@ -194,16 +235,11 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
194
235
  .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.'),
195
236
  order: z.enum(['asc', 'desc']).default('desc').describe('Sort direction'),
196
237
  limit: LIMIT.schema.describe('Awards per page. Default 10, at most 100 per call.'),
197
- page: z
198
- .number()
199
- .int()
200
- .min(1)
201
- .default(1)
202
- .describe(`Page number (1-based). Page-number pagination caps at a ${MAX_PAGE_OFFSET.toLocaleString()}-result offset (page × limit), but the keyset cursor below is only returned while the offset stays under ${CURSOR_WINDOW_OFFSET.toLocaleString()} — capture the cursor pair before paging past that, or the only way forward is page numbers.`),
238
+ page: z.number().int().min(1).default(1).describe('Page number (1-based).'),
203
239
  last_record_sort_value: z
204
240
  .string()
205
241
  .optional()
206
- .describe(`Keyset-pagination cursor: the last_record_sort_value from a prior response page_metadata. Provide together with last_record_unique_id to fetch the next page past the ${MAX_PAGE_OFFSET.toLocaleString()}-result page-number cap. The upstream stops emitting the pair once page × limit reaches ${CURSOR_WINDOW_OFFSET.toLocaleString()}, so take it from a page below that offset. When both cursor fields are supplied, page is ignored.`),
242
+ .describe('Keyset-pagination cursor: the last_record_sort_value from a prior response page_metadata. Provide together with last_record_unique_id.'),
207
243
  last_record_unique_id: z
208
244
  .number()
209
245
  .int()
@@ -214,31 +250,23 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
214
250
  keywords: z
215
251
  .array(z.string())
216
252
  .optional()
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'),
253
+ .describe('Same as the top-level keyword, as a list of terms.'),
218
254
  award_type_codes: z
219
255
  .array(z.string())
220
256
  .optional()
221
- .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.'),
222
- agency_name: z
223
- .string()
224
- .optional()
225
- .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.'),
226
- recipient_name: z
227
- .string()
228
- .optional()
229
- .describe('Recipient name search (partial match); maps to recipient_search_text. Use instead of recipient_id, which this endpoint ignores.'),
230
- naics_codes: z
231
- .array(z.string())
232
- .optional()
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'),
234
- ...CODE_FILTER_FIELDS,
235
- ...LOCATION_FILTER_FIELDS,
236
- time_period_start: optionalIsoDate('Start date (YYYY-MM-DD); earliest valid 2007-10-01. Given alone, the range runs through today (UTC).'),
237
- time_period_end: optionalIsoDate('End date (YYYY-MM-DD). Given alone, the range starts at 2007-10-01, the earliest searchable date.'),
257
+ .describe('Same as the top-level award_type_codes.'),
258
+ ...nestedTwins(AGENCY_FILTER_FIELDS),
259
+ recipient_name: z.string().optional().describe('Same as the top-level recipient_name.'),
260
+ naics_codes: z.array(z.string()).optional().describe('Same as the top-level naics_codes.'),
261
+ ...nestedTwins(CODE_FILTER_FIELDS),
262
+ ...nestedTwins(CONTRACT_FILTER_FIELDS),
263
+ ...NESTED_LOCATION_FILTER_FIELDS,
264
+ time_period_start: optionalIsoDate('Same as the top-level time_period.start_date.'),
265
+ time_period_end: optionalIsoDate('Same as the top-level time_period.end_date.'),
238
266
  })
239
267
  .strict()
240
268
  .optional()
241
- .describe('Optional analytics-style filter object mirroring the shape the spending analytics tools accept, for reusing one filter set across tools. When both this object and the equivalent top-level flat filters are given, this object wins per-field. recipient_id is rejected — this endpoint silently ignores it; filter by recipient via recipient_name.'),
269
+ .describe("Optional analytics-style filter object mirroring the shape the spending analytics tools accept, for reusing one filter set across tools. A nonempty value here wins over its top-level counterpart per field; an empty list, a blank string, or an all-blank location falls back to the top-level value. recipient_id is rejected — this endpoint silently ignores it; filter by recipient via recipient_name. The three contract filters are award search's alone; the analytics tools reject them."),
242
270
  }),
243
271
  output: z.object({
244
272
  results: z
@@ -299,42 +327,46 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
299
327
  .describe('Matching award summaries'),
300
328
  page_metadata: z
301
329
  .object({
302
- has_next: z
303
- .boolean()
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.`),
330
+ has_next: z.boolean().describe('Whether more results remain.'),
305
331
  page: z.number().describe('Current page number'),
306
332
  limit: z.number().describe('Results per page'),
307
333
  total: z
308
334
  .number()
309
335
  .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.'),
336
+ .describe("Awards matching every filter, award_type_codes included, across all pages: codes naming part of a group count only that part, so matches_by_group's entry for the group can exceed it. Absent when the total count failed; unavailable_sections then names it."),
311
337
  last_record_sort_value: z
312
338
  .string()
313
339
  .optional()
314
- .describe(`Keyset-pagination cursor for the next page — pass back as last_record_sort_value to continue past the ${MAX_PAGE_OFFSET.toLocaleString()}-result page limit. Absent once page × limit reaches ${CURSOR_WINDOW_OFFSET.toLocaleString()}, where the upstream stops emitting the pair.`),
340
+ .describe('Keyset-pagination cursor for the next page — pass back as last_record_sort_value.'),
315
341
  last_record_unique_id: z
316
342
  .number()
317
343
  .optional()
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.'),
344
+ .describe('Keyset-pagination cursor for the next page — pass back as last_record_unique_id alongside last_record_sort_value.'),
345
+ })
346
+ .describe(`Pagination metadata: has_next, the page and limit, the total match count, and the keyset cursor pair. With total known on page-number paging, has_next is true exactly when rows lie past this page. Without it — the count failed, or the page came by cursor — has_next is true on any full page, because the upstream's own next-page 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, and a short or empty page marks the end. The cursor pair is absent once page × limit reaches ${CURSOR_WINDOW_OFFSET.toLocaleString()}, where the upstream stops emitting it.`),
347
+ matches_by_group: z
348
+ .object({
349
+ contracts: z.number().describe('Matching contracts.'),
350
+ idvs: z.number().describe('Matching IDVs.'),
351
+ grants: z.number().describe('Matching grants.'),
352
+ direct_payments: z.number().describe('Matching direct payments.'),
353
+ loans: z.number().describe('Matching loans.'),
354
+ other: z.number().describe('Matching other assistance awards.'),
319
355
  })
320
- .describe('Pagination metadata: has_next, the page and limit, the total match count, and the keyset cursor pair.'),
356
+ .optional()
357
+ .describe("Awards matching every filter but award_type_codes, per award-type group — what a search of another group would find. The selected group's entry counts the whole group, so it can exceed page_metadata.total when award_type_codes name part of it. A filter only some groups carry (naics_codes, psc_codes, the contract filters, assistance_listings) leaves the others at 0. Absent when award_type_codes is the only filter. Best-effort: absent when its count failed or ran more than 2 s past the search and the total count, which unavailable_sections then names."),
321
358
  }),
322
359
  // Agent-facing search context: applied filters, upstream API notices, and an optional
323
360
  // recovery notice for empty pages. Populated via ctx.enrich() so it reaches both
324
361
  // structuredContent and content[] without a format() entry.
325
362
  enrichment: {
326
363
  page: z.number().describe('Current page number returned'),
327
- has_next: z
328
- .boolean()
329
- .describe('Whether more results remain: exact with a known total on page-number paging, otherwise true on any full page.'),
364
+ has_next: z.boolean().describe('Same as page_metadata.has_next.'),
330
365
  truncated: z
331
366
  .boolean()
332
367
  .optional()
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.'),
368
+ .describe('True when rows are known to lie past this page: page × limit is below the total, or the upstream reports a next page. Unlike has_next, a full page alone never sets it.'),
369
+ totalCount: z.number().optional().describe('Same as page_metadata.total.'),
338
370
  shown: z
339
371
  .number()
340
372
  .optional()
@@ -348,7 +380,12 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
348
380
  .optional()
349
381
  .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.'),
350
382
  applied_keyword: z.string().optional().describe('Keyword filter applied to this search'),
351
- applied_agency_name: z.string().optional().describe('Awarding agency name filter applied'),
383
+ applied_recipient_name: z
384
+ .string()
385
+ .optional()
386
+ .describe('Effective recipient name sent upstream'),
387
+ applied_award_type_codes: z.string().describe('Award type codes sent, comma-separated'),
388
+ ...AGENCY_FILTER_ENRICHMENT,
352
389
  applied_naics_codes: z
353
390
  .string()
354
391
  .optional()
@@ -365,6 +402,18 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
365
402
  .string()
366
403
  .optional()
367
404
  .describe('DEF codes sent, uppercased (comma-separated)'),
405
+ applied_extent_competed_type_codes: z
406
+ .string()
407
+ .optional()
408
+ .describe('Extent-competed codes sent, uppercased (comma-separated)'),
409
+ applied_set_aside_type_codes: z
410
+ .string()
411
+ .optional()
412
+ .describe('Set-aside codes sent, uppercased (comma-separated)'),
413
+ applied_contract_pricing_type_codes: z
414
+ .string()
415
+ .optional()
416
+ .describe('Contract pricing codes sent, uppercased (comma-separated)'),
368
417
  applied_location: z
369
418
  .string()
370
419
  .optional()
@@ -384,12 +433,12 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
384
433
  unavailable_sections: z
385
434
  .array(UnavailableSectionSchema)
386
435
  .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.`),
436
+ .describe(`Present when a count request failed, was rejected, or ran past the ${COUNT_DEADLINE_MS / 1000}-second deadline both counts share, or when the group count ran more than ${GROUP_COUNT_GRACE_MS / 1000} s past the search and the total count; the awards on the page are unaffected. Absent when every count sent loaded.`),
388
437
  limitClamp: LimitClampSchema,
389
438
  notice: z
390
439
  .string()
391
440
  .optional()
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.'),
441
+ .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, other award-type groups with matches and their award_type_codes, and any section that failed to load. Absent when none applies.'),
393
442
  },
394
443
  // upstream_messages is an array — supply a markdown renderer so the content[] trailer
395
444
  // shows a bullet list instead of a one-line JSON blob (structuredContent is unaffected).
@@ -492,6 +541,13 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
492
541
  retryable: false,
493
542
  recovery: 'Set award_type_codes to contracts A/B/C/D (the default) or IDVs IDV_A/IDV_B/IDV_B_A/IDV_B_B/IDV_B_C/IDV_C/IDV_D/IDV_E alongside psc_codes.',
494
543
  },
544
+ {
545
+ reason: 'contract_filters_type_mismatch',
546
+ code: JsonRpcErrorCode.ValidationError,
547
+ when: 'extent_competed_type_codes, set_aside_type_codes, or contract_pricing_type_codes was given while the award type codes include assistance codes.',
548
+ retryable: false,
549
+ recovery: 'Set award_type_codes to contracts A/B/C/D (the default) or IDVs IDV_A/IDV_B/IDV_B_A/IDV_B_B/IDV_B_C/IDV_C/IDV_D/IDV_E, or drop extent_competed_type_codes, set_aside_type_codes, and contract_pricing_type_codes to search assistance awards.',
550
+ },
495
551
  {
496
552
  reason: 'invalid_location',
497
553
  code: JsonRpcErrorCode.ValidationError,
@@ -501,7 +557,6 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
501
557
  },
502
558
  ],
503
559
  async handler(input, ctx) {
504
- const countDeadlineAt = Date.now() + COUNT_DEADLINE_MS;
505
560
  // Every read below uses the applied limit, never input.limit.
506
561
  const { applied: limit, notice: clampNotice } = LIMIT.apply(ctx, 'limit', input.limit);
507
562
  ctx.log.info('usaspending_search_awards', {
@@ -538,7 +593,6 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
538
593
  const awardTypeCodes = f?.award_type_codes?.length
539
594
  ? f.award_type_codes
540
595
  : input.award_type_codes;
541
- const agencyName = f?.agency_name || input.agency_name;
542
596
  const recipientName = f?.recipient_name || input.recipient_name;
543
597
  const mergedNaicsCodes = f?.naics_codes && f.naics_codes.length > 0 ? f.naics_codes : input.naics_codes;
544
598
  const effective = normalizeEffectiveFilters({
@@ -585,10 +639,22 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
585
639
  psc_codes: f?.psc_codes?.length ? f.psc_codes : input.psc_codes,
586
640
  def_codes: f?.def_codes?.length ? f.def_codes : input.def_codes,
587
641
  });
642
+ const contractCodes = normalizeContractFilters({
643
+ extent_competed_type_codes: f?.extent_competed_type_codes?.length
644
+ ? f.extent_competed_type_codes
645
+ : input.extent_competed_type_codes,
646
+ set_aside_type_codes: f?.set_aside_type_codes?.length
647
+ ? f.set_aside_type_codes
648
+ : input.set_aside_type_codes,
649
+ contract_pricing_type_codes: f?.contract_pricing_type_codes?.length
650
+ ? f.contract_pricing_type_codes
651
+ : input.contract_pricing_type_codes,
652
+ });
588
653
  /**
589
- * Contracts and IDVs carry no listings, and assistance awards no PSC: upstream
590
- * answers either pairing with 200, zero rows, and no message, which reads as
591
- * "no such awards" rather than a mismatched filter.
654
+ * Contracts and IDVs carry no listings, and assistance awards no PSC or
655
+ * contract filter code: upstream answers each such pairing with 200, zero
656
+ * rows, and no message, which reads as "no such awards" rather than a
657
+ * mismatched filter.
592
658
  */
593
659
  if (codes.assistance_listings &&
594
660
  awardTypeCodes.some((code) => PROCUREMENT_AWARD_TYPE_CODES.has(code))) {
@@ -597,6 +663,11 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
597
663
  if (codes.psc_codes && awardTypeCodes.some((code) => ASSISTANCE_AWARD_TYPE_CODES.has(code))) {
598
664
  throw ctx.fail('psc_codes_type_mismatch', `psc_codes match only contracts and IDVs, but award_type_codes [${awardTypeCodes.join(', ')}] include assistance codes, which carry no PSC.`);
599
665
  }
666
+ const contractKeys = Object.keys(contractCodes);
667
+ if (contractKeys.length > 0 &&
668
+ awardTypeCodes.some((code) => ASSISTANCE_AWARD_TYPE_CODES.has(code))) {
669
+ throw ctx.fail('contract_filters_type_mismatch', `${contractKeys.join(', ')} match only contracts and IDVs, but award_type_codes [${awardTypeCodes.join(', ')}] include assistance codes, which carry no competition, set-aside, or pricing codes.`);
670
+ }
600
671
  // Upstream checks the sort against the group's field mapping and answers 400
601
672
  // outside it. Codes spanning groups skip the check: upstream's 422 decides.
602
673
  const groupName = resolveAwardTypeGroup(awardTypeCodes);
@@ -628,19 +699,27 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
628
699
  if (keywords?.length)
629
700
  filters.keywords = keywords;
630
701
  filters.award_type_codes = awardTypeCodes;
631
- if (agencyName) {
632
- filters.agencies = awardingAgencyFilters(agencyName);
633
- }
702
+ const names = {
703
+ agency_name: f?.agency_name?.trim() || input.agency_name,
704
+ funding_agency_name: f?.funding_agency_name?.trim() || input.funding_agency_name,
705
+ };
706
+ const agencies = names.agency_name || names.funding_agency_name
707
+ ? await resolveAgencyFilters(svc, names, ctx)
708
+ : { names, notices: [] };
709
+ applyAgencyFilters(filters, agencies.names);
634
710
  if (recipientName)
635
711
  filters.recipient_search_text = [recipientName];
636
712
  if (naicsCodes?.length) {
637
713
  filters.naics_codes = { require: naicsCodes };
638
714
  }
639
715
  applyCodeFilters(filters, codes);
716
+ // Upstream takes the contract filters under the keys the tool declares.
717
+ Object.assign(filters, contractCodes);
640
718
  if (timePeriod) {
641
719
  filters.time_period = [{ start_date: timePeriod.start_date, end_date: timePeriod.end_date }];
642
720
  }
643
721
  applyLocationFilters(filters, locations);
722
+ const countDeadlineAt = Date.now() + COUNT_DEADLINE_MS;
644
723
  const searchRequest = svc.searchAwards({
645
724
  filters,
646
725
  fields: isLoan ? [...AWARD_SEARCH_FIELDS, ...LOAN_FIELDS] : AWARD_SEARCH_FIELDS,
@@ -657,20 +736,42 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
657
736
  : { page: input.page }),
658
737
  }, ctx);
659
738
  /**
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.
739
+ * Two counts run beside the search as best-effort side reads, one attempt each
740
+ * under the shared deadline, and only when the codes resolve to one group: codes
741
+ * spanning groups fail the search with upstream's 422. The total count gets the
742
+ * very `filters` object the search sends, so every filter reaches both. The group
743
+ * count gets those filters without award_type_codes, so upstream reports every
744
+ * group's matches. It is a separate request, not the source of `total`, because a
745
+ * count across every group runs slower on broad filters and a late one must not
746
+ * cost the total; nor may it cost the call much time, so it is cut once it runs
747
+ * GROUP_COUNT_GRACE_MS past the search and the total count. USAspending's count
748
+ * rejects an empty `filters`, so with no filter beside the codes it is not sent.
749
+ * Settled up front, so a count that rejects after a failed search is still
750
+ * handled; the search is awaited alone, so its failure surfaces at once. Any
751
+ * count still in flight when the handler leaves is aborted.
665
752
  */
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.
753
+ const { award_type_codes: _awardTypeCodes, ...groupFilters } = filters;
754
+ const sideReads = new AbortController();
755
+ const settle = (count) => Promise.allSettled([count]).then(([leg]) => leg);
756
+ const totalLeg = settle(groupName ? svc.countAwards(filters, ctx, countDeadlineAt, sideReads.signal) : undefined);
757
+ const groupLeg = settle(groupName && Object.keys(groupFilters).length > 0
758
+ ? svc.countAwards(groupFilters, ctx, countDeadlineAt, sideReads.signal)
759
+ : undefined);
760
+ let data;
761
+ let countResult;
762
+ let groupCountResult;
763
+ try {
764
+ data = await searchRequest;
765
+ countResult = await totalLeg;
766
+ groupCountResult = await settleWithinGrace(groupLeg);
767
+ }
768
+ finally {
769
+ sideReads.abort();
770
+ }
771
+ // A failed count leaves its field unknown and is disclosed; a caller abort rethrows.
672
772
  const unavailable = [];
673
773
  const counts = settleSection(ctx, 'total', countResult, unavailable);
774
+ const matchesByGroup = settleSection(ctx, 'matches_by_group', groupCountResult, unavailable);
674
775
  const total = groupName && counts ? counts[groupName] : undefined;
675
776
  const results = (data.results ?? []).map((r) => ({
676
777
  ...(r['Award ID'] ? { award_id: String(r['Award ID']) } : {}),
@@ -753,9 +854,12 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
753
854
  has_next: page_metadata.has_next,
754
855
  ...(data.messages?.length ? { upstream_messages: data.messages } : {}),
755
856
  ...(keywords?.length ? { applied_keyword: keywords.join(', ') } : {}),
756
- ...(agencyName ? { applied_agency_name: agencyName } : {}),
857
+ ...(recipientName ? { applied_recipient_name: recipientName } : {}),
858
+ applied_award_type_codes: awardTypeCodes.join(', '),
859
+ ...agencyFilterEcho(agencies.names),
757
860
  ...(naicsCodes?.length ? { applied_naics_codes: naicsCodes.join(', ') } : {}),
758
861
  ...codeFilterEcho(codes),
862
+ ...contractFilterEcho(contractCodes),
759
863
  ...locationFilterEcho(locations),
760
864
  ...(timePeriod
761
865
  ? {
@@ -768,7 +872,7 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
768
872
  ctx.enrich.total(total);
769
873
  // enrich.notice is last-wins, and enrich.truncated writes the notice too, so
770
874
  // every notice source joins into one string written at the end.
771
- const notices = [clampNotice];
875
+ const notices = [clampNotice, ...agencies.notices];
772
876
  /**
773
877
  * The truncated/shown/cap disclosure needs evidence that rows exist past this
774
878
  * page: the known total, or the upstream hasNext. Without a total, an exactly-full
@@ -782,20 +886,30 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
782
886
  }
783
887
  notices.push(guidance);
784
888
  }
785
- notices.push(filledBoundNotice(timePeriod, filledFields));
889
+ notices.push(timePeriod ? filledBoundNotice(timePeriod, filledFields) : NO_DATE_FILTER_NOTICE);
786
890
  if (results.length === 0) {
787
891
  const filterParts = [];
892
+ const agencyParts = describeAgencyFilters(agencies.names);
788
893
  if (keywords?.length)
789
894
  filterParts.push(`keyword="${keywords.join(', ')}"`);
790
- if (agencyName)
791
- filterParts.push(`agency="${agencyName}"`);
792
- filterParts.push(...describeCodeFilters(codes), ...describeLocationFilters(locations));
895
+ if (recipientName)
896
+ filterParts.push(`recipient_name="${recipientName}"`);
897
+ filterParts.push(...agencyParts);
898
+ filterParts.push(...describeCodeFilters(codes), ...describeContractFilters(contractCodes), ...describeLocationFilters(locations));
793
899
  filterParts.push(`types=${awardTypeCodes.join(',')}`);
794
900
  const filterText = filterParts.join(', ');
795
901
  notices.push(pagedTotal !== undefined
796
902
  ? emptyPageNotice(page, limit, pagedTotal, `No awards match ${filterText}.`)
797
903
  : `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.'}`);
904
+ if (pagedTotal !== undefined && pagedTotal > 0) {
905
+ if (recipientName)
906
+ notices.push(`Recipient filter: recipient_name="${recipientName}".`);
907
+ if (agencyParts.length)
908
+ notices.push(`Agency filters: ${agencyParts.join(', ')}.`);
909
+ }
798
910
  }
911
+ if (groupName && matchesByGroup)
912
+ notices.push(otherGroupsNotice(groupName, matchesByGroup));
799
913
  if (unavailable.length > 0) {
800
914
  ctx.enrich({ unavailable_sections: unavailable });
801
915
  notices.push(unavailableNotice(unavailable));
@@ -803,12 +917,20 @@ export const searchAwardsTool = tool('usaspending_search_awards', {
803
917
  const notice = notices.filter(Boolean).join(' ');
804
918
  if (notice)
805
919
  ctx.enrich.notice(notice);
806
- return { results, page_metadata };
920
+ return {
921
+ results,
922
+ page_metadata,
923
+ ...(matchesByGroup ? { matches_by_group: matchesByGroup } : {}),
924
+ };
807
925
  },
808
926
  format: (result) => {
809
927
  const lines = ['## Federal Award Search Results'];
810
928
  const { total } = result.page_metadata;
811
929
  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'}`);
930
+ const groups = result.matches_by_group;
931
+ if (groups) {
932
+ lines.push(`\n**Matches by award-type group:** ${AWARD_TYPE_GROUP_NAMES.map((name) => `${name} ${groups[name].toLocaleString()}`).join(' | ')}`);
933
+ }
812
934
  for (const r of result.results) {
813
935
  lines.push('');
814
936
  lines.push(`### ${escapeMarkdownInline(r.recipient_name ?? r.award_id ?? r.generated_internal_id ?? 'Unknown')}`);