@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
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @fileoverview Resolve spending agency names and apply both agency tiers per role.
3
+ * @module mcp-server/tools/definitions/agency-filters
4
+ */
5
+ import { type Context, z } from '@cyanheads/mcp-ts-core';
6
+ import type { USASpendingService } from '../../../services/usaspending/usaspending-service.js';
7
+ /** Names from the same directory, with independent awarding and funding roles. */
8
+ export declare const AGENCY_FILTER_FIELDS: {
9
+ agency_name: z.ZodOptional<z.ZodString>;
10
+ funding_agency_name: z.ZodOptional<z.ZodString>;
11
+ };
12
+ /** Effective names selected after input precedence. */
13
+ export type AgencyFilters = z.infer<z.ZodObject<typeof AGENCY_FILTER_FIELDS>>;
14
+ /** Echo the names actually sent after best-effort lookup. */
15
+ export declare const AGENCY_FILTER_ENRICHMENT: {
16
+ applied_agency_name: z.ZodOptional<z.ZodString>;
17
+ applied_funding_agency_name: z.ZodOptional<z.ZodString>;
18
+ };
19
+ /** Look up distinct effective names in parallel under one deadline; disclose unresolved inputs. */
20
+ export declare function resolveAgencyFilters(svc: USASpendingService, input: AgencyFilters | undefined, ctx: Context): Promise<{
21
+ names: {
22
+ agency_name?: string | undefined;
23
+ funding_agency_name?: string | undefined;
24
+ };
25
+ notices: string[];
26
+ }>;
27
+ /** Match either tier within each supplied role, retaining matches under every parent. */
28
+ export declare function applyAgencyFilters(filters: Record<string, unknown>, names: AgencyFilters): void;
29
+ /** Output enrichment shared by search and analytics. */
30
+ export declare function agencyFilterEcho(names: AgencyFilters): {
31
+ applied_agency_name?: string;
32
+ applied_funding_agency_name?: string;
33
+ };
34
+ /** Agency predicates mentioned in empty-result guidance. */
35
+ export declare function describeAgencyFilters(names: AgencyFilters): string[];
36
+ //# sourceMappingURL=agency-filters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agency-filters.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/agency-filters.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,OAAO,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,+CAA+C,CAAC;AAKxF,kFAAkF;AAClF,eAAO,MAAM,oBAAoB;IAC/B,WAAW;IAMX,mBAAmB;CAMpB,CAAC;AAEF,uDAAuD;AACvD,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC;AAK9E,6DAA6D;AAC7D,eAAO,MAAM,wBAAwB;IACnC,mBAAmB;IACnB,2BAA2B;CAI5B,CAAC;AAkDF,mGAAmG;AACnG,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,kBAAkB,EACvB,KAAK,EAAE,aAAa,GAAG,SAAS,EAChC,GAAG,EAAE,OAAO;;;;;;GA2Bb;AAED,yFAAyF;AACzF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,EAAE,aAAa,GAAG,IAAI,CAY/F;AAED,wDAAwD;AACxD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,aAAa;;;EAOpD;AAED,4DAA4D;AAC5D,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,EAAE,CAEpE"}
@@ -0,0 +1,123 @@
1
+ /**
2
+ * @fileoverview Resolve spending agency names and apply both agency tiers per role.
3
+ * @module mcp-server/tools/definitions/agency-filters
4
+ */
5
+ import { z } from '@cyanheads/mcp-ts-core';
6
+ import { JsonRpcErrorCode, McpError } from '@cyanheads/mcp-ts-core/errors';
7
+ const LOOKUP_LIMIT = 50;
8
+ const LOOKUP_TIMEOUT_MS = 2_000;
9
+ /** Names from the same directory, with independent awarding and funding roles. */
10
+ export const AGENCY_FILTER_FIELDS = {
11
+ agency_name: z
12
+ .string()
13
+ .optional()
14
+ .describe('Awarding top-tier or sub-tier agency name. Use the matched name from usaspending_autocomplete_filters type=awarding_agency, or toptier_name to select the whole parent department. A sub-tier name shared by several parents matches under all parents. Exact case-insensitive names and unambiguous abbreviations resolve to the directory spelling.'),
15
+ funding_agency_name: z
16
+ .string()
17
+ .optional()
18
+ .describe('Funding top-tier or sub-tier agency name. Use the matched name from usaspending_autocomplete_filters type=awarding_agency. Exact case-insensitive names and unambiguous abbreviations resolve to the directory spelling. When agency_name is also supplied, awards must match both roles.'),
19
+ };
20
+ const AGENCY_ROLES = { agency_name: 'awarding', funding_agency_name: 'funding' };
21
+ const AGENCY_KEYS = ['agency_name', 'funding_agency_name'];
22
+ /** Echo the names actually sent after best-effort lookup. */
23
+ export const AGENCY_FILTER_ENRICHMENT = {
24
+ applied_agency_name: z.string().optional().describe('Awarding agency name sent to USAspending'),
25
+ applied_funding_agency_name: z
26
+ .string()
27
+ .optional()
28
+ .describe('Funding agency name sent to USAspending'),
29
+ };
30
+ async function resolveName(svc, name, ctx, deadlineAt) {
31
+ try {
32
+ const { results } = await svc.autocompleteAwardingAgency(name, LOOKUP_LIMIT, ctx, deadlineAt);
33
+ ctx.signal.throwIfAborted();
34
+ const top = results?.toptier_agency ?? [];
35
+ const sub = results?.subtier_agency ?? [];
36
+ const rows = [...top, ...sub];
37
+ const folded = name.toLowerCase();
38
+ const exact = rows.flatMap((row) => row.name && row.name.toLowerCase() === folded ? [row.name] : []);
39
+ const matches = exact.length
40
+ ? exact
41
+ : rows.flatMap((row) => row.name && row.abbreviation?.toLowerCase() === folded ? [row.name] : []);
42
+ const candidates = [...new Set(matches)];
43
+ const [candidate] = candidates;
44
+ if (top.length >= LOOKUP_LIMIT || sub.length >= LOOKUP_LIMIT) {
45
+ return { name, reason: 'the agency directory result reached its limit', candidates };
46
+ }
47
+ if (candidate && candidates.length === 1)
48
+ return { name: candidate };
49
+ return {
50
+ name,
51
+ reason: candidates.length
52
+ ? 'multiple distinct agency names matched'
53
+ : 'no exact agency name or abbreviation matched',
54
+ candidates,
55
+ };
56
+ }
57
+ catch (err) {
58
+ ctx.signal.throwIfAborted();
59
+ if (!(err instanceof McpError) ||
60
+ (err.code !== JsonRpcErrorCode.Timeout &&
61
+ err.code !== JsonRpcErrorCode.ServiceUnavailable &&
62
+ err.code !== JsonRpcErrorCode.RateLimited)) {
63
+ throw err;
64
+ }
65
+ return { name, reason: 'the agency directory was unavailable' };
66
+ }
67
+ }
68
+ /** Look up distinct effective names in parallel under one deadline; disclose unresolved inputs. */
69
+ export async function resolveAgencyFilters(svc, input, ctx) {
70
+ if (!input?.agency_name && !input?.funding_agency_name)
71
+ return { names: {}, notices: [] };
72
+ const lookups = new Map();
73
+ const deadlineAt = Date.now() + LOOKUP_TIMEOUT_MS;
74
+ for (const key of AGENCY_KEYS) {
75
+ const name = input?.[key];
76
+ if (name && !lookups.has(name))
77
+ lookups.set(name, resolveName(svc, name, ctx, deadlineAt));
78
+ }
79
+ const names = {};
80
+ const notices = [];
81
+ const resolved = new Map(await Promise.all([...lookups].map(async ([name, lookup]) => [name, await lookup])));
82
+ for (const key of AGENCY_KEYS) {
83
+ const name = input?.[key];
84
+ const match = name ? resolved.get(name) : undefined;
85
+ if (!match)
86
+ continue;
87
+ names[key] = match.name;
88
+ if (match.reason) {
89
+ const candidates = match.candidates?.map((candidate) => JSON.stringify(candidate)).join(', ');
90
+ notices.push(`Could not verify ${key}=${JSON.stringify(name)} because ${match.reason}. Sent the original name.${candidates ? ` Matching names: ${candidates}.` : ''} Use usaspending_autocomplete_filters type=awarding_agency to check the name.`);
91
+ }
92
+ }
93
+ return { names, notices };
94
+ }
95
+ /** Match either tier within each supplied role, retaining matches under every parent. */
96
+ export function applyAgencyFilters(filters, names) {
97
+ const agencies = AGENCY_KEYS.flatMap((key) => {
98
+ const name = names[key];
99
+ const type = AGENCY_ROLES[key];
100
+ return name
101
+ ? [
102
+ { type, tier: 'toptier', name },
103
+ { type, tier: 'subtier', name },
104
+ ]
105
+ : [];
106
+ });
107
+ if (agencies.length)
108
+ filters.agencies = agencies;
109
+ }
110
+ /** Output enrichment shared by search and analytics. */
111
+ export function agencyFilterEcho(names) {
112
+ return {
113
+ ...(names.agency_name ? { applied_agency_name: names.agency_name } : {}),
114
+ ...(names.funding_agency_name
115
+ ? { applied_funding_agency_name: names.funding_agency_name }
116
+ : {}),
117
+ };
118
+ }
119
+ /** Agency predicates mentioned in empty-result guidance. */
120
+ export function describeAgencyFilters(names) {
121
+ return AGENCY_KEYS.flatMap((key) => (names[key] ? [`${key}=${JSON.stringify(names[key])}`] : []));
122
+ }
123
+ //# sourceMappingURL=agency-filters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agency-filters.js","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/agency-filters.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAgB,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAG3E,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC,kFAAkF;AAClF,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,WAAW,EAAE,CAAC;SACX,MAAM,EAAE;SACR,QAAQ,EAAE;SACV,QAAQ,CACP,uVAAuV,CACxV;IACH,mBAAmB,EAAE,CAAC;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QACL,GAAG,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACxE,GAAG,CAAC,KAAK,CAAC,mBAAmB;YAC3B,CAAC,CAAC,EAAE,2BAA2B,EAAE,KAAK,CAAC,mBAAmB,EAAE;YAC5D,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;AACJ,CAAC;AAED,4DAA4D;AAC5D,MAAM,UAAU,qBAAqB,CAAC,KAAoB;IACxD,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACpG,CAAC"}
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @fileoverview Tool to look up valid code values for filter fields: NAICS, PSC, CFDA,
3
- * agency names, and recipient names.
2
+ * @fileoverview Tool to look up valid code values for filter fields: NAICS, PSC, CFDA, DEF,
3
+ * agency names, recipient names, and US state, county, and congressional district codes.
4
4
  * @module mcp-server/tools/definitions/autocomplete-filters.tool
5
5
  */
6
6
  import { z } from '@cyanheads/mcp-ts-core';
@@ -9,6 +9,8 @@ export declare const autocompleteFiltersTool: import("@cyanheads/mcp-ts-core").T
9
9
  type: z.ZodEnum<{
10
10
  awarding_agency: "awarding_agency";
11
11
  cfda: "cfda";
12
+ def_code: "def_code";
13
+ location: "location";
12
14
  naics: "naics";
13
15
  psc: "psc";
14
16
  recipient: "recipient";
@@ -19,8 +21,16 @@ export declare const autocompleteFiltersTool: import("@cyanheads/mcp-ts-core").T
19
21
  type: z.ZodString;
20
22
  search_text: z.ZodString;
21
23
  results: z.ZodArray<z.ZodObject<{
24
+ kind: z.ZodOptional<z.ZodEnum<{
25
+ county: "county";
26
+ district: "district";
27
+ state: "state";
28
+ }>>;
22
29
  code: z.ZodOptional<z.ZodString>;
23
30
  name: z.ZodOptional<z.ZodString>;
31
+ public_law: z.ZodOptional<z.ZodString>;
32
+ disaster_group: z.ZodOptional<z.ZodString>;
33
+ state: z.ZodOptional<z.ZodString>;
24
34
  abbreviation: z.ZodOptional<z.ZodString>;
25
35
  tier: z.ZodOptional<z.ZodEnum<{
26
36
  subtier: "subtier";
@@ -36,7 +46,7 @@ export declare const autocompleteFiltersTool: import("@cyanheads/mcp-ts-core").T
36
46
  }, z.core.$strip>, readonly [{
37
47
  readonly reason: "no_match";
38
48
  readonly code: JsonRpcErrorCode.NotFound;
39
- readonly when: "No codes or names matched the search text.";
49
+ readonly when: "No codes or names matched the search text; for location, no US state, county, or congressional district did.";
40
50
  readonly recovery: "Try a broader search term, different spelling, or shorter keyword fragment.";
41
51
  }, {
42
52
  readonly reason: "api_unavailable";
@@ -59,6 +69,11 @@ export declare const autocompleteFiltersTool: import("@cyanheads/mcp-ts-core").T
59
69
  readonly truncated: z.ZodOptional<z.ZodBoolean>;
60
70
  readonly shown: z.ZodOptional<z.ZodNumber>;
61
71
  readonly cap: z.ZodOptional<z.ZodNumber>;
72
+ readonly limitClamp: z.ZodOptional<z.ZodObject<{
73
+ field: z.ZodString;
74
+ requested: z.ZodNumber;
75
+ applied: z.ZodNumber;
76
+ }, z.core.$strip>>;
62
77
  readonly notice: z.ZodOptional<z.ZodString>;
63
78
  }>;
64
79
  //# sourceMappingURL=autocomplete-filters.tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"autocomplete-filters.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/autocomplete-filters.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAQjE,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgTlC,CAAC"}
1
+ {"version":3,"file":"autocomplete-filters.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/autocomplete-filters.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAiEjE,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgZlC,CAAC"}
@@ -1,33 +1,77 @@
1
1
  /**
2
- * @fileoverview Tool to look up valid code values for filter fields: NAICS, PSC, CFDA,
3
- * agency names, and recipient names.
2
+ * @fileoverview Tool to look up valid code values for filter fields: NAICS, PSC, CFDA, DEF,
3
+ * agency names, recipient names, and US state, county, and congressional district codes.
4
4
  * @module mcp-server/tools/definitions/autocomplete-filters.tool
5
5
  */
6
6
  import { tool, z } from '@cyanheads/mcp-ts-core';
7
7
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
8
8
  import { escapeMarkdownInline } from '@cyanheads/mcp-ts-core/utils';
9
+ import { LOCATION_AUTOCOMPLETE_LIMIT_MAX, } from '../../../services/usaspending/types.js';
9
10
  import { getUSASpendingService } from '../../../services/usaspending/usaspending-service.js';
10
- /** Largest `limit` every autocomplete route accepts; 501 is rejected with HTTP 400. */
11
- const UPSTREAM_LIMIT_MAX = 500;
11
+ import { countLimit, LimitClampSchema, limitClampTrailer } from './count-limit.js';
12
+ import { postalForStateFips, postalForUpstreamStateName, stateFipsForPostal } from './locations.js';
13
+ /** Capped at the largest `limit` the code and name autocomplete routes accept; 501 is rejected with HTTP 400. */
14
+ const LIMIT = countLimit({ tool: 'usaspending_autocomplete_filters', default: 10, cap: 500 });
15
+ /** A congressional district as `autocomplete/location/` writes it: postal code, dash, two-digit district. */
16
+ const CURRENT_DISTRICT = /^([A-Z]{2})-(\d{2})$/;
17
+ /**
18
+ * Rows a location filter or `shape_codes` takes, in table order: states (postal code,
19
+ * from upstream's name), counties (5-digit FIPS code, state from its prefix), current
20
+ * districts (state FIPS + district number). A row whose state the postal ↔ FIPS table
21
+ * lacks is dropped, never guessed. `full` names each bucket that came back holding
22
+ * `requested` rows, so more of that kind may exist.
23
+ */
24
+ function mapLocationBuckets(resp, requested) {
25
+ const states = resp.results?.states ?? [];
26
+ const counties = resp.results?.counties ?? [];
27
+ const districts = resp.results?.districts_current ?? [];
28
+ const rows = [
29
+ ...states.flatMap(({ state_name: name }) => {
30
+ const postal = name ? postalForUpstreamStateName(name) : undefined;
31
+ return name && postal ? [{ kind: 'state', code: postal, name }] : [];
32
+ }),
33
+ ...counties.flatMap(({ county_fips: fips, county_name: name }) => {
34
+ const state = fips && /^\d{5}$/.test(fips) ? postalForStateFips(fips.slice(0, 2)) : undefined;
35
+ return fips && state
36
+ ? [{ kind: 'county', code: fips, ...(name ? { name } : {}), state }]
37
+ : [];
38
+ }),
39
+ ...districts.flatMap(({ current_cd }) => {
40
+ const match = current_cd ? CURRENT_DISTRICT.exec(current_cd) : null;
41
+ const fips = match?.[1] ? stateFipsForPostal(match[1]) : undefined;
42
+ return match?.[1] && fips
43
+ ? [
44
+ {
45
+ kind: 'district',
46
+ code: `${fips}${match[2]}`,
47
+ name: match[0],
48
+ state: match[1],
49
+ },
50
+ ]
51
+ : [];
52
+ }),
53
+ ];
54
+ const buckets = [
55
+ ['state', states],
56
+ ['county', counties],
57
+ ['district', districts],
58
+ ];
59
+ const full = buckets.filter(([, bucket]) => bucket.length >= requested).map(([kind]) => kind);
60
+ return { rows, full };
61
+ }
12
62
  export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters', {
13
63
  title: 'Autocomplete Codes and Names',
14
- description: 'Look up valid code values for filter fields by searching free-text descriptions. Use the type parameter to select the lookup table: naics (NAICS industry codes), psc (product/service codes), cfda (CFDA/Assistance Listing program numbers), awarding_agency (agency and sub-agency names, each with its tier and top-tier parent — agency_name filters take the matched name; a sub-tier name shared by several parents matches under all parents), or recipient (recipient names with UEI/DUNS). Call this before filtering awards when you know a description but not the exact code. Returns matching codes and names for use in other tool filters.',
64
+ description: 'Look up valid code values for filter fields by searching free-text descriptions. Use the type parameter to select the lookup table: naics (NAICS industry codes), psc (product/service codes), cfda (CFDA/Assistance Listing program numbers), def_code (Disaster/Emergency Funding codes by code, appropriation title, or public law), awarding_agency (agency and sub-agency names, each with its tier and top-tier parent — agency_name and funding_agency_name filters take the matched name; a sub-tier name shared by several parents matches under all parents), recipient (recipient names with UEI/DUNS), or location (US state, county, and congressional district names, resolved to the codes the location filters and usaspending_spending_by_geography shape_codes take). Call this before filtering awards when you know a description but not the exact code. Returns matching codes and names for use in other tool filters.',
15
65
  annotations: { readOnlyHint: true, openWorldHint: true, idempotentHint: true },
16
66
  input: z.object({
17
67
  type: z
18
- .enum(['naics', 'psc', 'cfda', 'awarding_agency', 'recipient'])
19
- .describe('Lookup table to search: naics (industry codes), psc (product/service codes, for the psc_codes filter), cfda (Assistance Listing program numbers, for the assistance_listings filter), awarding_agency (agency and sub-agency names), recipient (recipient names). Both filters are taken by usaspending_search_awards and by the filters object of usaspending_spending_by_category, usaspending_spending_by_geography, and usaspending_spending_over_time.'),
68
+ .enum(['naics', 'psc', 'cfda', 'awarding_agency', 'recipient', 'location', 'def_code'])
69
+ .describe('Lookup table to search: naics (industry codes), psc (product/service codes, for psc_codes), cfda (Assistance Listing program numbers, for assistance_listings), def_code (Disaster/Emergency Funding codes, for def_codes), awarding_agency (agency and sub-agency names), recipient (recipient names), location (US states with DC and the territories, counties, and current congressional districts, matched from the start of their name: "King County", "Santa Fe", "WA-07"; countries, cities, and ZIP codes are not returned). The psc_codes, assistance_listings, and def_codes filters are taken by usaspending_search_awards and the spending analytics tools.'),
20
70
  search_text: z
21
71
  .string()
22
72
  .min(1)
23
- .describe('Free-text search string — use a description, keyword, or partial code to find matches'),
24
- limit: z
25
- .number()
26
- .int()
27
- .min(1)
28
- .max(UPSTREAM_LIMIT_MAX)
29
- .default(10)
30
- .describe('Maximum number of results to return (1–500), enforced client-side. Agency matches combine independently capped top-tier then sub-tier buckets, preserving their order without deduplicating names; offices are excluded. The recipient lookup unions three upstream match buckets (name, UEI, DUNS) and can return up to 3x this value, so its results are capped to this limit before returning — the cap keeps them in bucket order, so name matches fill the page first and identifier matches appear only in whatever room is left. To resolve a specific UEI or DUNS, pass the identifier itself as search_text. Every lookup returns at most limit rows.'),
73
+ .describe('Free-text search string. For def_code, use an exact code or part of an appropriation title or public law. For other lookups, use a description, keyword, or partial code.'),
74
+ limit: LIMIT.schema.describe('Maximum number of results to return. Default 10, at most 500 per call. Agency matches combine independently capped top-tier then sub-tier buckets, preserving their order without deduplicating names; offices are excluded. Location matches combine state, then county, then district rows, and upstream returns at most 100 of each kind. The recipient lookup unions three upstream match buckets (name, UEI, DUNS) and can return up to 3x this value, so its results are capped to this limit before returning — the cap keeps them in bucket order, so name matches fill the page first and identifier matches appear only in whatever room is left. To resolve a specific UEI or DUNS, pass the identifier itself as search_text. Every lookup returns at most limit rows.'),
31
75
  }),
32
76
  output: z.object({
33
77
  type: z.string().describe('Lookup table searched'),
@@ -35,14 +79,30 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
35
79
  results: z
36
80
  .array(z
37
81
  .object({
82
+ kind: z
83
+ .enum(['state', 'county', 'district'])
84
+ .optional()
85
+ .describe('location only: what the row names — a US state, DC, or territory; a county; or a current congressional district'),
38
86
  code: z
39
87
  .string()
40
88
  .optional()
41
- .describe('Code value (NAICS code, PSC code, or Assistance Listing/CFDA number); use this in filter parameters — an Assistance Listing number goes in usaspending_search_awards assistance_listings. Agency rows carry toptier_code instead.'),
89
+ .describe("Code value (NAICS, PSC, Assistance Listing/CFDA, DEF, or location code); use this in filter parameters — an Assistance Listing number goes in assistance_listings and a DEF code in def_codes. A location row's code by kind: state, the 2-letter postal code for a location filter's state and state shape_codes; county, the 5-digit state + county FIPS code for a location filter's county and county shape_codes; district, the 4-digit state FIPS + district number for district shape_codes on usaspending_spending_by_geography. Agency rows carry toptier_code instead."),
42
90
  name: z
43
91
  .string()
44
92
  .optional()
45
- .describe("Human-readable name or description; for awarding_agency, the matched agency's own name, which for a sub-agency differs from toptier_name"),
93
+ .describe("Human-readable name or description; for awarding_agency, the matched agency's own name, which for a sub-agency differs from toptier_name; for location, upstream's uppercase name (WASHINGTON, KING, WA-07)"),
94
+ public_law: z
95
+ .string()
96
+ .optional()
97
+ .describe('def_code only: public law for the funding code, when supplied'),
98
+ disaster_group: z
99
+ .string()
100
+ .optional()
101
+ .describe('def_code only: USAspending disaster grouping, when supplied'),
102
+ state: z
103
+ .string()
104
+ .optional()
105
+ .describe('location only: the 2-letter postal code of the state a county or district lies in'),
46
106
  abbreviation: z
47
107
  .string()
48
108
  .optional()
@@ -54,11 +114,11 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
54
114
  toptier_name: z
55
115
  .string()
56
116
  .optional()
57
- .describe('awarding_agency only: the top-tier parent name. Use the matched name in agency_name on usaspending_search_awards and spending analytics to select the sub-agency; use toptier_name intentionally to select its whole parent department.'),
117
+ .describe('awarding_agency only: the top-tier parent name. Use the matched name in agency_name or funding_agency_name on usaspending_search_awards and spending analytics to select the sub-agency; use toptier_name intentionally to select its whole parent department.'),
58
118
  toptier_code: z
59
119
  .string()
60
120
  .optional()
61
- .describe('awarding_agency only: the 3-digit top-tier agency code, accepted by usaspending_get_agency'),
121
+ .describe('awarding_agency only: the directory top-tier agency code, accepted by usaspending_get_agency'),
62
122
  subtier_code: z
63
123
  .string()
64
124
  .optional()
@@ -72,7 +132,7 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
72
132
  .optional()
73
133
  .describe('DUNS number (legacy) — recipient type only; populated when the search text matches a DUNS'),
74
134
  })
75
- .describe('Matched entry — code/name for code lookups, name with tier and top-tier parent for agencies, name plus optional UEI/DUNS for recipients'))
135
+ .describe('Matched entry — code/name for code lookups, name with tier and top-tier parent for agencies, name plus optional UEI/DUNS for recipients, kind/code/name plus state for locations'))
76
136
  .describe('Matching codes and names'),
77
137
  total: z.number().describe('Number of results returned'),
78
138
  }),
@@ -81,7 +141,7 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
81
141
  // discloses truncation only when that row (or a recipient bucket overflow) came back.
82
142
  enrichment: {
83
143
  lookup_type: z.string().describe('Lookup table that was searched'),
84
- query: z.string().describe('Search text sent to the autocomplete API'),
144
+ query: z.string().describe('Lookup search text'),
85
145
  result_count: z.number().describe('Number of matching results returned'),
86
146
  truncated: z
87
147
  .boolean()
@@ -89,19 +149,21 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
89
149
  .describe('True when more matches exist beyond the limit and were left out. Absent when every match was returned.'),
90
150
  shown: z.number().optional().describe('Number of results returned, when truncated.'),
91
151
  cap: z.number().optional().describe('The limit that was applied, when truncated.'),
152
+ limitClamp: LimitClampSchema,
92
153
  notice: z
93
154
  .string()
94
155
  .optional()
95
- .describe('How to reach the matches left out when truncated, or — when limit is 500 and all 500 slots filled — that the upstream maximum was reached and more matches may exist. Absent otherwise.'),
156
+ .describe('A reduced limit; how to reach the matches left out when truncated; and that an upstream maximum was reached so more matches may exist — all 500 slots filled at limit 500, or 100 rows of one location kind. Absent when none applies.'),
96
157
  },
97
158
  enrichmentTrailer: {
159
+ limitClamp: limitClampTrailer,
98
160
  notice: { render: (notice) => (notice ? `> ${escapeMarkdownInline(notice)}` : '') },
99
161
  },
100
162
  errors: [
101
163
  {
102
164
  reason: 'no_match',
103
165
  code: JsonRpcErrorCode.NotFound,
104
- when: 'No codes or names matched the search text.',
166
+ when: 'No codes or names matched the search text; for location, no US state, county, or congressional district did.',
105
167
  recovery: 'Try a broader search term, different spelling, or shorter keyword fragment.',
106
168
  },
107
169
  {
@@ -126,15 +188,48 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
126
188
  type: input.type,
127
189
  search_text: input.search_text,
128
190
  });
191
+ const limit = LIMIT.apply(ctx, 'limit', input.limit);
192
+ const notices = limit.notice ? [limit.notice] : [];
129
193
  const svc = getUSASpendingService();
130
194
  let rawResults = [];
195
+ /** Location buckets that came back holding `requested` rows: more of that kind may exist. */
196
+ let fullLocationKinds = [];
131
197
  /**
132
198
  * One row past `limit` tells a capped list from one that exactly fills the page. Every
133
- * autocomplete route rejects `limit` above 500 with HTTP 400, so at 500 there is no
134
- * room for the extra row and a full page can only say the ceiling was reached.
199
+ * code and name route rejects `limit` above 500 with HTTP 400, and the location route
200
+ * fails above 100, so at that ceiling there is no room for the extra row and a full
201
+ * page or bucket can only say the ceiling was reached.
135
202
  */
136
- const requested = Math.min(input.limit + 1, UPSTREAM_LIMIT_MAX);
137
- if (input.type === 'naics') {
203
+ const requested = Math.min(limit.applied + 1, input.type === 'location' ? LOCATION_AUTOCOMPLETE_LIMIT_MAX : LIMIT.cap);
204
+ if (input.type === 'location') {
205
+ const resp = await svc.autocompleteLocation(input.search_text, requested, ctx);
206
+ const mapped = mapLocationBuckets(resp, requested);
207
+ rawResults = mapped.rows;
208
+ fullLocationKinds = mapped.full;
209
+ }
210
+ else if (input.type === 'def_code') {
211
+ const codes = await svc.getDefCodesReference(ctx);
212
+ const query = input.search_text.trim().toLowerCase();
213
+ const exact = [];
214
+ const byText = [];
215
+ for (const entry of codes) {
216
+ const codeMatch = entry.code.toLowerCase() === query;
217
+ const textMatch = query !== '' &&
218
+ (entry.title?.toLowerCase().includes(query) ||
219
+ entry.public_law?.toLowerCase().includes(query));
220
+ if (!codeMatch && !textMatch)
221
+ continue;
222
+ const row = {
223
+ code: entry.code,
224
+ ...(entry.title ? { name: entry.title } : {}),
225
+ ...(entry.public_law ? { public_law: entry.public_law } : {}),
226
+ ...(entry.disaster ? { disaster_group: entry.disaster } : {}),
227
+ };
228
+ (codeMatch ? exact : byText).push(row);
229
+ }
230
+ rawResults = [...exact, ...byText];
231
+ }
232
+ else if (input.type === 'naics') {
138
233
  const resp = await svc.autocompleteNaics(input.search_text, requested, ctx);
139
234
  rawResults = (resp.results ?? []).map((r) => ({
140
235
  ...(r.naics ? { code: r.naics } : {}),
@@ -189,11 +284,19 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
189
284
  /**
190
285
  * `autocomplete/recipient/` applies `limit` per match bucket (name, UEI, DUNS) and
191
286
  * unions them. Agency autocomplete caps each tier independently; omit offices and
192
- * union top-tier then sub-tier rows. Judge truncation on the relevant bucket union
287
+ * union top-tier then sub-tier rows. Location autocomplete caps each kind; union
288
+ * states, counties, then districts. Judge truncation on the relevant bucket union
193
289
  * before the combined caller slice to `limit`.
194
290
  */
195
291
  const received = rawResults.length;
196
- rawResults = rawResults.slice(0, input.limit);
292
+ rawResults = rawResults.slice(0, limit.applied);
293
+ if (rawResults.length === 0 && input.type === 'location') {
294
+ throw ctx.fail('no_match', `No US state, county, or congressional district matched "${input.search_text}"`, {
295
+ recovery: {
296
+ hint: `The location lookup resolves US states, counties, and congressional districts only, not countries, cities, or ZIP codes. Names match from their start: search "King County", "District of Columbia", or "WA-07", or check the spelling.`,
297
+ },
298
+ });
299
+ }
197
300
  if (rawResults.length === 0) {
198
301
  throw ctx.fail('no_match', `No ${input.type} results matched "${input.search_text}"`, {
199
302
  recovery: {
@@ -206,27 +309,47 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
206
309
  query: input.search_text,
207
310
  result_count: rawResults.length,
208
311
  });
209
- const narrow = input.limit < UPSTREAM_LIMIT_MAX
210
- ? `Raise limit (max ${UPSTREAM_LIMIT_MAX}) or use a more specific search term.`
312
+ const narrow = limit.applied < LIMIT.cap
313
+ ? `Raise limit (max ${LIMIT.cap}) or use a more specific search term.`
211
314
  : 'Use a more specific search term.';
212
- if (received > input.limit) {
315
+ /**
316
+ * A location bucket holding the probe row proves more matches of its kind even when
317
+ * rows dropped for an unmapped state leave fewer than `limit` kept. A bucket that
318
+ * filled the 100-row ceiling without a probe row can only say the ceiling was reached.
319
+ */
320
+ const truncated = received > limit.applied || (requested > limit.applied && fullLocationKinds.length > 0);
321
+ const kindsAtCeiling = requested <= limit.applied ? fullLocationKinds : [];
322
+ if (truncated) {
323
+ /**
324
+ * The recipient cap is a head-slice over name-then-UEI-then-DUNS, and upstream
325
+ * fills the name bucket to the requested size on its own whenever the corpus
326
+ * allows. So a saturated recipient page holds name matches only, and raising
327
+ * `limit` raises the name bucket with it — it never reaches the identifier buckets
328
+ * behind it. Pointing that caller at `limit` alone would misdirect them.
329
+ */
330
+ notices.push(input.type === 'recipient'
331
+ ? `More matches exist beyond limit. ${narrow} Matches on a UEI or DUNS are not reachable this way once name matches fill the page; to resolve one, pass the identifier itself as search_text.`
332
+ : `More matches exist beyond limit. ${narrow}`);
333
+ }
334
+ else if (input.type !== 'location' &&
335
+ input.type !== 'def_code' &&
336
+ requested === limit.applied &&
337
+ received === limit.applied) {
338
+ notices.push(`Returned the upstream maximum of ${LIMIT.cap} matches, so more may exist. ${narrow}`);
339
+ }
340
+ if (kindsAtCeiling.length > 0) {
341
+ notices.push(`Upstream returns at most ${LOCATION_AUTOCOMPLETE_LIMIT_MAX} location matches of each kind, and the ${kindsAtCeiling.join(' and ')} matches reached it, so more may exist. Use a more specific search term.`);
342
+ }
343
+ // `notice` is last-wins and `truncated({ guidance })` writes it too, so every sentence joins into one write.
344
+ if (truncated) {
213
345
  ctx.enrich.truncated({
214
346
  shown: rawResults.length,
215
- cap: input.limit,
216
- /**
217
- * The recipient cap is a head-slice over name-then-UEI-then-DUNS, and upstream
218
- * fills the name bucket to the requested size on its own whenever the corpus
219
- * allows. So a saturated recipient page holds name matches only, and raising
220
- * `limit` raises the name bucket with it — it never reaches the identifier buckets
221
- * behind it. Pointing that caller at `limit` alone would misdirect them.
222
- */
223
- guidance: input.type === 'recipient'
224
- ? `More matches exist beyond limit. ${narrow} Matches on a UEI or DUNS are not reachable this way once name matches fill the page; to resolve one, pass the identifier itself as search_text.`
225
- : `More matches exist beyond limit. ${narrow}`,
347
+ cap: limit.applied,
348
+ guidance: notices.join(' '),
226
349
  });
227
350
  }
228
- else if (requested === input.limit && received === input.limit) {
229
- ctx.enrich.notice(`Returned the upstream maximum of ${UPSTREAM_LIMIT_MAX} matches, so more may exist. ${narrow}`);
351
+ else if (notices.length) {
352
+ ctx.enrich.notice(notices.join(' '));
230
353
  }
231
354
  return {
232
355
  type: input.type,
@@ -242,10 +365,14 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
242
365
  ];
243
366
  for (const r of result.results) {
244
367
  const parts = [];
368
+ if (r.kind)
369
+ parts.push(`**Kind:** ${escapeMarkdownInline(r.kind)}`);
245
370
  if (r.code)
246
371
  parts.push(`**Code:** ${escapeMarkdownInline(r.code)}`);
247
372
  if (r.name)
248
373
  parts.push(`**Name:** ${escapeMarkdownInline(r.name)}${r.abbreviation ? ` (${escapeMarkdownInline(r.abbreviation)})` : ''}`);
374
+ if (r.state)
375
+ parts.push(`**State:** ${escapeMarkdownInline(r.state)}`);
249
376
  if (r.tier)
250
377
  parts.push(`**Tier:** ${escapeMarkdownInline(r.tier)}`);
251
378
  if (r.toptier_name)
@@ -256,6 +383,10 @@ export const autocompleteFiltersTool = tool('usaspending_autocomplete_filters',
256
383
  parts.push(`**Sub-tier code:** ${escapeMarkdownInline(r.subtier_code)}`);
257
384
  if (r.duns)
258
385
  parts.push(`**DUNS:** ${escapeMarkdownInline(r.duns)}`);
386
+ if (r.public_law)
387
+ parts.push(`**Public Law:** ${escapeMarkdownInline(r.public_law)}`);
388
+ if (r.disaster_group)
389
+ parts.push(`**Disaster Group:** ${escapeMarkdownInline(r.disaster_group)}`);
259
390
  lines.push(`- ${parts.join(' | ')}`);
260
391
  }
261
392
  lines.push(`\n**Total:** ${result.total}`);