northbid 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,598 @@
1
+ // Tool definitions. Descriptions carry the domain knowledge a model needs,
2
+ // so the server is usable without any client-specific skill or prompt file.
3
+
4
+ import {
5
+ getAwards, getTenders, InputError, searchAwards, searchStandingOffers, searchTenders, summarizeAwards,
6
+ } from './search.js';
7
+ import { lines } from './text.js';
8
+
9
+ export const INSTRUCTIONS = `Northbid searches Government of Canada procurement data published by CanadaBuys. It is an unofficial tool; data is cached locally and refreshed from the source automatically.
10
+
11
+ Coverage: currently open federal tender notices; active standing offers and supply arrangements; and award notices (who won, and for how much) published on CanadaBuys since August 2022. Provincial and municipal tenders, and awards before August 2022, are not included.
12
+
13
+ Using it well:
14
+ - Notices are bilingual. Search matches English and French text at once and ignores accents; pass lang "fr" to get French output.
15
+ - Keyword search needs every word unless you use OR. Procurement titles vary, so combine synonyms and both languages, e.g. "translation OR traduction OR interpretation".
16
+ - Start with search_tenders, then call get_tender for the notices worth reading in full.
17
+ - To learn who won similar work before and at what price, use search_awards; summarize_awards ranks suppliers or buyers by award count and value.
18
+ - Closing times are UTC-05:00 all year, not local time.
19
+ - Award values are as published, in the contract's own currency, and usually include amendments. Standing offers and supply arrangements carry no value.
20
+ - The first award search downloads about 110 MB and can take a minute.
21
+ - New notices can take up to a day to appear. Each result carries source_updated; tell the user the data date and that the linked CanadaBuys page is authoritative before they bid.`;
22
+
23
+ const CATEGORY = { construction: 'CNST', goods: 'GD', services: 'SRV', services_related_to_goods: 'SRVTGD' };
24
+ const CATEGORY_LABEL = Object.fromEntries(Object.entries(CATEGORY).map(([label, code]) => [code, label]));
25
+ const OTHER = { en: 'fr', fr: 'en' };
26
+
27
+ const DATE = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$' };
28
+ const LANG = { type: 'string', enum: ['en', 'fr'], default: 'en', description: 'Output language.' };
29
+ const LIMIT = { type: 'integer', minimum: 1, maximum: 50, default: 10, description: 'Results per page (1-50).' };
30
+ const OFFSET = { type: 'integer', minimum: 0, maximum: 100000, default: 0, description: 'Results to skip, for paging.' };
31
+ const MATCH = {
32
+ type: 'string', enum: ['all', 'any'], default: 'all',
33
+ description: 'Whether a notice must contain all query terms or any of them. An explicit OR in the query always applies.',
34
+ };
35
+ const QUERY_SYNTAX =
36
+ 'Words match in English and French, ignoring case and accents. Use "double quotes" for an exact phrase, ' +
37
+ 'a trailing * for a prefix (engineer*), and uppercase OR between alternatives.';
38
+
39
+ const loc = (row, col, lang) => row[`${col}_${lang}`] || row[`${col}_${OTHER[lang]}`];
40
+
41
+ function compact(obj) {
42
+ const out = {};
43
+ for (const [k, v] of Object.entries(obj)) {
44
+ if (v === '' || v === null || v === undefined || (Array.isArray(v) && v.length === 0)) continue;
45
+ out[k] = v;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ function capped(values, max) {
51
+ return values.length > max ? [...values.slice(0, max), `+${values.length - max} more`] : values;
52
+ }
53
+
54
+ function excerpt(text, max) {
55
+ const flat = text.replace(/\s+/g, ' ');
56
+ return flat.length > max ? `${flat.slice(0, max).trimEnd()}…` : flat;
57
+ }
58
+
59
+ // CanadaBuys addresses a notice by its reference number, lowercased, keeping
60
+ // only letters, digits and single hyphens.
61
+ const NOTICE_PATH = {
62
+ tender: { en: 'tender-opportunities/tender-notice', fr: 'occasions-de-marche/appels-d-offres' },
63
+ award: { en: 'tender-opportunities/award-notice', fr: 'occasions-de-marche/avis-d-attribution' },
64
+ };
65
+
66
+ function canadaBuysUrl(reference, lang, kind = 'tender') {
67
+ const slug = reference.toLowerCase().replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-');
68
+ return lang === 'fr'
69
+ ? `https://achatscanada.canada.ca/fr/${NOTICE_PATH[kind].fr}/${slug}`
70
+ : `https://canadabuys.canada.ca/en/${NOTICE_PATH[kind].en}/${slug}`;
71
+ }
72
+
73
+ const categories = (row) => lines(row.categories).map((c) => CATEGORY_LABEL[c] ?? c);
74
+
75
+ function tenderSummary(row, lang) {
76
+ return compact({
77
+ reference_number: row.reference_number,
78
+ solicitation_number: row.solicitation_number,
79
+ title: loc(row, 'title', lang),
80
+ buyer: loc(row, 'buyer', lang),
81
+ categories: categories(row),
82
+ notice_type: loc(row, 'notice_type', lang),
83
+ published: row.publication_date,
84
+ closes: row.closing_date,
85
+ regions_of_delivery: capped(lines(loc(row, 'regions_of_delivery', lang)), 4),
86
+ excerpt: excerpt(loc(row, 'description', lang), 240),
87
+ url: canadaBuysUrl(row.reference_number, lang),
88
+ });
89
+ }
90
+
91
+ function tenderDetail(row, lang, maxChars) {
92
+ const langs = lang === 'both' ? ['en', 'fr'] : [lang];
93
+ const out = {
94
+ reference_number: row.reference_number,
95
+ solicitation_number: row.solicitation_number,
96
+ amendment_number: row.amendment_number,
97
+ status: loc(row, 'status', langs[0]),
98
+ categories: categories(row),
99
+ published: row.publication_date,
100
+ closes: row.closing_date,
101
+ amended: row.amendment_date,
102
+ expected_contract_start: row.expected_start_date,
103
+ expected_contract_end: row.expected_end_date,
104
+ unspsc_codes: lines(row.unspsc_codes),
105
+ gsin_codes: lines(row.gsin_codes),
106
+ contact: compact({ name: row.contact_name, email: row.contact_email, phone: row.contact_phone }),
107
+ };
108
+ if (Object.keys(out.contact).length === 0) delete out.contact;
109
+ for (const l of langs) {
110
+ // With both languages every bilingual field is suffixed; a field missing
111
+ // in one language is left out rather than filled from the other.
112
+ const key = (name) => (langs.length > 1 ? `${name}_${l}` : name);
113
+ const get = (col) => (langs.length > 1 ? row[`${col}_${l}`] : loc(row, col, l));
114
+ const description = get('description');
115
+ Object.assign(out, {
116
+ [key('title')]: get('title'),
117
+ [key('buyer')]: get('buyer'),
118
+ [key('buyer_address')]: get('buyer_address'),
119
+ [key('end_users')]: lines(get('end_user')),
120
+ [key('notice_type')]: get('notice_type'),
121
+ [key('procurement_method')]: get('procurement_method'),
122
+ [key('selection_criteria')]: get('selection_criteria'),
123
+ [key('limited_tendering_reason')]: lines(get('limited_tendering_reason')),
124
+ [key('trade_agreements')]: lines(get('trade_agreements')),
125
+ [key('regions_of_opportunity')]: lines(get('regions_of_opportunity')),
126
+ [key('regions_of_delivery')]: lines(get('regions_of_delivery')),
127
+ [key('unspsc')]: lines(get('unspsc')),
128
+ [key('gsin')]: lines(get('gsin')),
129
+ [key('description')]: description.length > maxChars ? `${description.slice(0, maxChars).trimEnd()}…` : description,
130
+ [key('description_truncated')]: description.length > maxChars ? true : '',
131
+ [key('url')]: canadaBuysUrl(row.reference_number, l),
132
+ [key('bidding_url')]: get('notice_url'),
133
+ [key('attachments')]: capped(get('attachments').split(/[\s,;]+/).filter((u) => /^https?:/.test(u)), 25),
134
+ });
135
+ }
136
+ return compact(out);
137
+ }
138
+
139
+ function standingOfferSummary(row, lang) {
140
+ const legal = row.supplier_legal_name;
141
+ const operating = row.supplier_operating_name;
142
+ return compact({
143
+ agreement_number: row.agreement_number,
144
+ agreement_type: loc(row, 'agreement_type', lang),
145
+ title: loc(row, 'title', lang),
146
+ supplier: row.supplier_name || legal,
147
+ supplier_legal_name: legal.toLowerCase() === row.supplier_name.toLowerCase() ? '' : legal,
148
+ supplier_operating_name: operating.toLowerCase() === legal.toLowerCase() ? '' : operating,
149
+ department: loc(row, 'department', lang),
150
+ commodities: capped(lines(loc(row, 'commodity', lang)), 5),
151
+ awarded: row.award_date,
152
+ expires: row.expiry_date,
153
+ delivery_points: capped(lines(loc(row, 'delivery_points', lang)), 6),
154
+ });
155
+ }
156
+
157
+ // Dates in the data are local to the publisher; compare against the local day.
158
+ function today() {
159
+ const d = new Date();
160
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
161
+ }
162
+
163
+ function page(store, table, { total, rows }, args, warnings, render) {
164
+ const results = rows.map(render);
165
+ return {
166
+ total,
167
+ offset: args.offset,
168
+ returned: results.length,
169
+ ...compact({ next_offset: args.offset + results.length < total ? args.offset + results.length : '' }),
170
+ results,
171
+ ...compact({ source_updated: store.sourceUpdated(table), warnings }),
172
+ };
173
+ }
174
+
175
+ // Zero means the source gave no value; leave both fields out.
176
+ const money = (row) => (row.value > 0 ? { value: row.value, currency: row.currency } : {});
177
+
178
+ function awardSummary(row, lang) {
179
+ return compact({
180
+ reference_number: row.reference_number,
181
+ solicitation_number: row.solicitation_number,
182
+ title: loc(row, 'title', lang),
183
+ supplier: row.supplier_name,
184
+ supplier_location: loc(row, 'supplier_location', lang),
185
+ buyer: loc(row, 'buyer', lang),
186
+ end_users: capped(lines(loc(row, 'end_user', lang)), 3),
187
+ ...money(row),
188
+ awarded: row.award_date,
189
+ contract_end: row.contract_end_date,
190
+ instrument_type: loc(row, 'instrument_type', lang),
191
+ procurement_method: loc(row, 'procurement_method', lang),
192
+ categories: categories(row),
193
+ status: row.status_en === 'Active' ? '' : loc(row, 'status', lang),
194
+ url: canadaBuysUrl(row.reference_number, lang, 'award'),
195
+ });
196
+ }
197
+
198
+ function awardDetail(row, lang, maxChars) {
199
+ const description = loc(row, 'description', lang);
200
+ const contact = compact({ name: row.contact_name, email: row.contact_email, phone: row.contact_phone });
201
+ return compact({
202
+ reference_number: row.reference_number,
203
+ solicitation_number: row.solicitation_number,
204
+ contract_number: row.contract_number,
205
+ amendment_number: row.amendment_number,
206
+ amendment_type: loc(row, 'amendment_type', lang),
207
+ status: loc(row, 'status', lang),
208
+ title: loc(row, 'title', lang),
209
+ supplier: row.supplier_name,
210
+ supplier_location: loc(row, 'supplier_location', lang),
211
+ buyer: loc(row, 'buyer', lang),
212
+ end_users: lines(loc(row, 'end_user', lang)),
213
+ ...money(row),
214
+ awarded: row.award_date,
215
+ published: row.publication_date,
216
+ amended: row.amendment_date,
217
+ contract_start: row.contract_start_date,
218
+ contract_end: row.contract_end_date,
219
+ instrument_type: loc(row, 'instrument_type', lang),
220
+ categories: categories(row),
221
+ notice_type: loc(row, 'notice_type', lang),
222
+ procurement_method: loc(row, 'procurement_method', lang),
223
+ selection_criteria: loc(row, 'selection_criteria', lang),
224
+ limited_tendering_reason: lines(loc(row, 'limited_tendering_reason', lang)),
225
+ trade_agreements: lines(loc(row, 'trade_agreements', lang)),
226
+ regions_of_delivery: lines(loc(row, 'regions_of_delivery', lang)),
227
+ unspsc_codes: lines(row.unspsc_codes),
228
+ unspsc: lines(loc(row, 'unspsc', lang)),
229
+ description: description.length > maxChars ? `${description.slice(0, maxChars).trimEnd()}…` : description,
230
+ description_truncated: description.length > maxChars ? true : '',
231
+ contact: Object.keys(contact).length ? contact : '',
232
+ url: canadaBuysUrl(row.reference_number, lang, 'award'),
233
+ });
234
+ }
235
+
236
+ const AWARD_FILTERS = {
237
+ query: {
238
+ type: 'string', maxLength: 500,
239
+ description:
240
+ `Keywords searched in titles, descriptions, commodity names, supplier and buyer names, and solicitation and contract numbers. ${QUERY_SYNTAX}`,
241
+ },
242
+ match: MATCH,
243
+ supplier: { type: 'string', maxLength: 200, description: 'Words from the winning supplier\'s legal name, e.g. "Deloitte".' },
244
+ buyer: {
245
+ type: 'string', maxLength: 200,
246
+ description:
247
+ 'Words from the contracting or end-user organization name, in either language. Public Services and Procurement ' +
248
+ 'Canada buys on behalf of other departments, which then appear as end users.',
249
+ },
250
+ category: {
251
+ type: 'array', items: { type: 'string', enum: Object.keys(CATEGORY) },
252
+ description: 'Procurement categories; an award matching any listed category is returned.',
253
+ },
254
+ unspsc: {
255
+ type: 'string', pattern: '^\\d{2,8}$',
256
+ description: 'UNSPSC commodity code or prefix. A segment or family code such as 43000000 or 4323 also matches every code beneath it.',
257
+ },
258
+ region: { type: 'string', maxLength: 100, description: 'Text contained in a region of delivery, e.g. "Ontario" or "National Capital Region".' },
259
+ competitive: {
260
+ type: 'boolean',
261
+ description:
262
+ 'true for competitively awarded contracts only; false for non-competitive awards and advance contract award notices only. ' +
263
+ 'Awards with no stated method match neither.',
264
+ },
265
+ awarded_after: { ...DATE, description: 'Only contracts awarded on or after this date (YYYY-MM-DD).' },
266
+ awarded_before: { ...DATE, description: 'Only contracts awarded on or before this date (YYYY-MM-DD).' },
267
+ min_value: {
268
+ type: 'integer', minimum: 0, maximum: 1_000_000_000_000,
269
+ description: 'Only awards worth at least this amount, in the contract currency (almost always CAD). Above zero, this drops awards with no stated value.',
270
+ },
271
+ max_value: {
272
+ type: 'integer', minimum: 0, maximum: 1_000_000_000_000,
273
+ description: 'Only awards with a stated value of at most this amount.',
274
+ },
275
+ include_cancelled: { type: 'boolean', default: false, description: 'Also return cancelled award notices.' },
276
+ };
277
+
278
+ const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
279
+
280
+ /** @param {import('./store.js').Store} store */
281
+ export function createTools(store) {
282
+ return [
283
+ {
284
+ name: 'search_tenders',
285
+ title: 'Search open federal tenders',
286
+ description:
287
+ 'Search currently open Government of Canada tender notices from CanadaBuys (requests for proposal, ' +
288
+ 'standing offer and supply arrangement requests, requests for information, advance contract award notices). ' +
289
+ 'Use it to find bidding opportunities by keyword, buyer, category, commodity code, delivery region or closing date. ' +
290
+ 'Returns short summaries; call get_tender for full details. With no arguments it lists the tenders closing soonest. ' +
291
+ 'Covers federal organizations only.',
292
+ inputSchema: {
293
+ type: 'object',
294
+ additionalProperties: false,
295
+ properties: {
296
+ query: {
297
+ type: 'string', maxLength: 500,
298
+ description: `Keywords searched in titles, descriptions, commodity names and buyer names. ${QUERY_SYNTAX}`,
299
+ },
300
+ match: MATCH,
301
+ category: {
302
+ type: 'array', items: { type: 'string', enum: Object.keys(CATEGORY) },
303
+ description: 'Procurement categories; a notice matching any listed category is returned.',
304
+ },
305
+ buyer: {
306
+ type: 'string', maxLength: 200,
307
+ description: 'Words from the contracting or end-user organization name, in either language, e.g. "National Defence".',
308
+ },
309
+ region: {
310
+ type: 'string', maxLength: 100,
311
+ description:
312
+ 'Text contained in a region of delivery, e.g. "Ontario", "National Capital Region", "British Columbia". ' +
313
+ 'Nationwide tenders are listed under "Canada" and are not returned for a provincial filter.',
314
+ },
315
+ unspsc: {
316
+ type: 'string', pattern: '^\\d{2,8}$',
317
+ description:
318
+ 'UNSPSC commodity code or prefix. A segment or family code such as 43000000 or 4323 also matches every code beneath it.',
319
+ },
320
+ notice_type: {
321
+ type: 'string', maxLength: 100,
322
+ description: 'Text contained in the notice type, e.g. "Request for Proposal", "Request for Information", "Standing Offer".',
323
+ },
324
+ closing_after: { ...DATE, description: 'Only tenders closing on or after this date (YYYY-MM-DD).' },
325
+ closing_before: { ...DATE, description: 'Only tenders closing on or before this date (YYYY-MM-DD).' },
326
+ published_after: { ...DATE, description: 'Only tenders published on or after this date (YYYY-MM-DD).' },
327
+ include_past_deadline: {
328
+ type: 'boolean', default: false,
329
+ description:
330
+ 'The source lists some notices as open after their closing date has passed. They are hidden unless this is true.',
331
+ },
332
+ sort: {
333
+ type: 'string', enum: ['relevance', 'closing_soonest', 'newest'],
334
+ description: 'Defaults to relevance when a query is given, otherwise closing_soonest.',
335
+ },
336
+ lang: LANG,
337
+ limit: LIMIT,
338
+ offset: OFFSET,
339
+ },
340
+ },
341
+ annotations: { title: 'Search open federal tenders', ...READ },
342
+ async handler(args) {
343
+ const warnings = await store.refresh('tenders');
344
+ const mapped = { ...args, category: args.category?.map((c) => CATEGORY[c]), today: today() };
345
+ return page(store, 'tenders', searchTenders(store.db, mapped), args, warnings, (r) => tenderSummary(r, args.lang));
346
+ },
347
+ },
348
+ {
349
+ name: 'get_tender',
350
+ title: 'Get tender details',
351
+ description:
352
+ 'Get the full record for one open tender notice: description, dates, buyer and end users, selection criteria, ' +
353
+ 'trade agreements, commodity codes, contact, attachments and links. Look it up by the reference_number or ' +
354
+ 'solicitation_number returned by search_tenders. A solicitation number shared by several notices returns all of them.',
355
+ inputSchema: {
356
+ type: 'object',
357
+ additionalProperties: false,
358
+ required: ['id'],
359
+ properties: {
360
+ id: { type: 'string', maxLength: 100, description: 'Reference number or solicitation number, exactly as shown in search results.' },
361
+ lang: { type: 'string', enum: ['en', 'fr', 'both'], default: 'en', description: 'Output language; "both" returns each text field in English and French.' },
362
+ max_description_chars: {
363
+ type: 'integer', minimum: 200, maximum: 50000, default: 6000,
364
+ description: 'Cut the description to this many characters. Raise it when description_truncated is true and you need the rest.',
365
+ },
366
+ },
367
+ },
368
+ annotations: { title: 'Get tender details', ...READ },
369
+ async handler(args) {
370
+ const warnings = await store.refresh('tenders');
371
+ const rows = getTenders(store.db, args.id);
372
+ if (rows.length === 0) {
373
+ throw new InputError(
374
+ `No open tender has reference or solicitation number "${args.id}". It may have closed or been cancelled; ` +
375
+ 'only open notices are loaded. Use search_tenders to find current notices.',
376
+ );
377
+ }
378
+ return compact({
379
+ tenders: rows.map((r) => tenderDetail(r, args.lang, args.max_description_chars)),
380
+ source_updated: store.sourceUpdated('tenders'),
381
+ warnings,
382
+ });
383
+ },
384
+ },
385
+ {
386
+ name: 'search_standing_offers',
387
+ title: 'Search standing offers and supply arrangements',
388
+ description:
389
+ 'Search active federal standing offers and supply arrangements issued by Public Services and Procurement Canada: ' +
390
+ 'pre-qualified suppliers that departments can buy from without a new open competition. Use it to see who already ' +
391
+ 'holds an agreement for a commodity, what a given supplier holds, or when agreements expire and may be re-competed. ' +
392
+ 'Agreement types: SA (supply arrangement), NMSO and RMSO (national and regional master standing offers), ' +
393
+ 'NISO, RISO and DISO (national, regional and departmental individual standing offers).',
394
+ inputSchema: {
395
+ type: 'object',
396
+ additionalProperties: false,
397
+ properties: {
398
+ query: {
399
+ type: 'string', maxLength: 500,
400
+ description: `Keywords searched in agreement titles, commodity names, supplier names and departments. ${QUERY_SYNTAX}`,
401
+ },
402
+ match: MATCH,
403
+ supplier: { type: 'string', maxLength: 200, description: 'Words from the supplier legal, operating or standardized name.' },
404
+ department: { type: 'string', maxLength: 200, description: 'Words from the department the agreement serves, in either language.' },
405
+ commodity: {
406
+ type: 'string', pattern: '^\\d{2,8}$',
407
+ description: 'UNSPSC commodity code or prefix; a segment or family code also matches every code beneath it.',
408
+ },
409
+ agreement_type: { type: 'string', maxLength: 20, description: 'Agreement type code, e.g. SA, NMSO, RMSO, NISO, RISO, DISO.' },
410
+ region: { type: 'string', maxLength: 100, description: 'Text contained in a delivery point, e.g. "Alberta" or "National Capital Region".' },
411
+ include_expired: { type: 'boolean', default: false, description: 'Also return agreements whose expiry date has passed.' },
412
+ lang: LANG,
413
+ limit: LIMIT,
414
+ offset: OFFSET,
415
+ },
416
+ },
417
+ annotations: { title: 'Search standing offers and supply arrangements', ...READ },
418
+ async handler(args) {
419
+ const warnings = await store.refresh('standing_offers');
420
+ const found = searchStandingOffers(store.db, args, today());
421
+ return page(store, 'standing_offers', found, args, warnings, (r) => standingOfferSummary(r, args.lang));
422
+ },
423
+ },
424
+ {
425
+ name: 'search_awards',
426
+ title: 'Search federal contract awards',
427
+ description:
428
+ 'Search Government of Canada award notices published on CanadaBuys since August 2022: which supplier won a contract, ' +
429
+ 'standing offer or supply arrangement, from which buyer, when, and for how much. Use it to find the incumbent before a ' +
430
+ 're-competition, what similar work has sold for, which contracts end soon, or what a competitor has won. ' +
431
+ 'Each notice shows its latest amendment. Returns short summaries; call get_award for full details. ' +
432
+ 'With no arguments it lists the most recent awards. The first call downloads about 110 MB and can take a minute.',
433
+ inputSchema: {
434
+ type: 'object',
435
+ additionalProperties: false,
436
+ properties: {
437
+ ...AWARD_FILTERS,
438
+ sort: {
439
+ type: 'string', enum: ['relevance', 'newest', 'highest_value'],
440
+ description: 'Defaults to relevance when a query is given, otherwise newest (by award date).',
441
+ },
442
+ lang: LANG,
443
+ limit: LIMIT,
444
+ offset: OFFSET,
445
+ },
446
+ },
447
+ annotations: { title: 'Search federal contract awards', ...READ },
448
+ async handler(args) {
449
+ const warnings = await store.refresh('awards');
450
+ const mapped = { ...args, category: args.category?.map((c) => CATEGORY[c]) };
451
+ return page(store, 'awards', searchAwards(store.db, mapped), args, warnings, (r) => awardSummary(r, args.lang));
452
+ },
453
+ },
454
+ {
455
+ name: 'get_award',
456
+ title: 'Get award details',
457
+ description:
458
+ 'Get the full record for an award notice: supplier, value, contract dates, procurement method, selection criteria, ' +
459
+ 'limited tendering reason, trade agreements, commodity codes, description and contact. Look it up by reference number, ' +
460
+ 'solicitation number or contract number. A solicitation that led to several awards, as supply arrangements do, ' +
461
+ 'returns the 20 most recent and the total count.',
462
+ inputSchema: {
463
+ type: 'object',
464
+ additionalProperties: false,
465
+ required: ['id'],
466
+ properties: {
467
+ id: { type: 'string', maxLength: 100, description: 'Reference, solicitation or contract number, exactly as shown in search results.' },
468
+ lang: LANG,
469
+ max_description_chars: {
470
+ type: 'integer', minimum: 200, maximum: 50000, default: 6000,
471
+ description: 'Cut the description to this many characters. Raise it when description_truncated is true and you need the rest.',
472
+ },
473
+ },
474
+ },
475
+ annotations: { title: 'Get award details', ...READ },
476
+ async handler(args) {
477
+ const warnings = await store.refresh('awards');
478
+ const { total, rows } = getAwards(store.db, args.id, 20);
479
+ if (total === 0) {
480
+ throw new InputError(
481
+ `No award notice has reference, solicitation or contract number "${args.id}". Awards before August 2022 are ` +
482
+ 'not loaded, and not every tender leads to a published award. Use search_awards to search by keyword.',
483
+ );
484
+ }
485
+ return compact({
486
+ total,
487
+ awards: rows.map((r) => awardDetail(r, args.lang, args.max_description_chars)),
488
+ source_updated: store.sourceUpdated('awards'),
489
+ warnings,
490
+ });
491
+ },
492
+ },
493
+ {
494
+ name: 'summarize_awards',
495
+ title: 'Summarize contract awards',
496
+ description:
497
+ 'Count award notices and total their value by supplier, buyer or award year, using the same filters as search_awards. ' +
498
+ 'Use it to rank the suppliers winning a kind of work, see which organizations buy it, profile one supplier or buyer, ' +
499
+ 'or follow spending over time. Totals add Canadian-dollar values only and are indicative: standing offers and supply ' +
500
+ 'arrangements have no value, a supplier spelled two ways counts as two, and values are as last amended. ' +
501
+ 'The buyer is the contracting organization, often Public Services and Procurement Canada acting for another department.',
502
+ inputSchema: {
503
+ type: 'object',
504
+ additionalProperties: false,
505
+ required: ['group_by'],
506
+ properties: {
507
+ group_by: { type: 'string', enum: ['supplier', 'buyer', 'year'], description: 'What each row of the summary is.' },
508
+ ...AWARD_FILTERS,
509
+ sort: {
510
+ type: 'string', enum: ['total_value', 'awards'], default: 'total_value',
511
+ description: 'Rank by total Canadian-dollar value or by number of awards. Years are always listed newest first.',
512
+ },
513
+ lang: LANG,
514
+ limit: LIMIT,
515
+ offset: OFFSET,
516
+ },
517
+ },
518
+ annotations: { title: 'Summarize contract awards', ...READ },
519
+ async handler(args) {
520
+ const warnings = await store.refresh('awards');
521
+ const mapped = { ...args, category: args.category?.map((c) => CATEGORY[c]) };
522
+ const { overall, rows } = summarizeAwards(store.db, mapped);
523
+ const results = rows.map((r) => ({
524
+ [args.group_by]: r.name || '(not stated)',
525
+ awards: r.awards,
526
+ total_value_cad: Math.round(r.total_value_cad),
527
+ largest_value_cad: Math.round(r.largest_value_cad),
528
+ first_award: r.first_award,
529
+ latest_award: r.latest_award,
530
+ }));
531
+ return {
532
+ awards: overall.awards,
533
+ total_value_cad: Math.round(overall.total_value_cad),
534
+ awards_without_value: overall.without_value,
535
+ awards_in_other_currencies: overall.other_currency,
536
+ total: overall.groups,
537
+ offset: args.offset,
538
+ returned: results.length,
539
+ ...compact({ next_offset: args.offset + results.length < overall.groups ? args.offset + results.length : '' }),
540
+ results,
541
+ ...compact({ source_updated: store.sourceUpdated('awards'), warnings }),
542
+ };
543
+ },
544
+ },
545
+ {
546
+ name: 'data_status',
547
+ title: 'Show data status',
548
+ description:
549
+ 'Report which CanadaBuys files are loaded in the local cache, how many records each holds, when the source ' +
550
+ 'published them and when they were last checked. Use it to tell the user how current the data is. Does not download anything.',
551
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
552
+ annotations: { title: 'Show data status', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
553
+ async handler() {
554
+ return store.status();
555
+ },
556
+ },
557
+ {
558
+ name: 'refresh_data',
559
+ title: 'Refresh data from CanadaBuys',
560
+ description:
561
+ 'Check CanadaBuys now for newer versions of every data file and download those that changed, replacing the local cache. ' +
562
+ 'Searches already refresh on their own schedule (new tenders every 2 hours, open tenders and this year\'s awards every 6, ' +
563
+ 'the rest daily); call this only when the user asks for the latest data or a search reported a refresh warning. ' +
564
+ 'It also downloads the award files if no award search has been run yet, which can take a minute.',
565
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
566
+ annotations: { title: 'Refresh data from CanadaBuys', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
567
+ async handler() {
568
+ const warnings = await store.refresh(null, { force: true });
569
+ return compact({ ...store.status(), warnings });
570
+ },
571
+ },
572
+ ];
573
+ }
574
+
575
+ export const PROMPTS = [
576
+ {
577
+ name: 'find_opportunities',
578
+ title: 'Find federal bidding opportunities',
579
+ description: 'Find open Government of Canada tenders that fit a business.',
580
+ arguments: [
581
+ { name: 'business', description: 'What the business sells or does.', required: true },
582
+ { name: 'region', description: 'Where it can deliver, e.g. a province or "Canada".', required: false },
583
+ { name: 'language', description: 'Reply language: en or fr.', required: false },
584
+ ],
585
+ render: ({ business, region, language }) =>
586
+ `Find open Government of Canada tenders that fit this business: ${business}\n` +
587
+ (region ? `It can deliver in: ${region}\n` : '') +
588
+ `\nSteps:\n` +
589
+ `1. List the goods or services it could supply and the English and French terms a buyer would use for them.\n` +
590
+ `2. Run search_tenders several times with those terms joined by OR${region ? ', once filtered to the region and once for region "Canada"' : ''}. Use lang "${language === 'fr' ? 'fr' : 'en'}".\n` +
591
+ `3. Drop poor fits, then call get_tender on the best candidates to confirm scope, selection criteria and closing time.\n` +
592
+ `4. Run search_standing_offers with the same terms to show who already holds related agreements, ` +
593
+ `and search_awards to show who won similar contracts recently and for how much.\n` +
594
+ `5. Present a shortlist as a table: title, buyer, closing date (UTC-05:00), why it fits, link. ` +
595
+ `State the data date from source_updated and that the CanadaBuys page is authoritative.` +
596
+ (language === 'fr' ? '\nReply in French.' : ''),
597
+ },
598
+ ];
@@ -0,0 +1,57 @@
1
+ // Checks tool arguments against the subset of JSON Schema the tool definitions
2
+ // use, and fills in defaults. Messages name the offending argument so a model
3
+ // can correct the call.
4
+
5
+ import { InputError } from './search.js';
6
+
7
+ function checkValue(name, spec, value) {
8
+ if (spec.type === 'string') {
9
+ if (typeof value !== 'string') throw new InputError(`"${name}" must be a string.`);
10
+ if (spec.maxLength && value.length > spec.maxLength) {
11
+ throw new InputError(`"${name}" must be at most ${spec.maxLength} characters.`);
12
+ }
13
+ if (spec.pattern && !new RegExp(spec.pattern).test(value)) {
14
+ throw new InputError(`"${name}" has the wrong format. ${spec.description}`);
15
+ }
16
+ } else if (spec.type === 'integer') {
17
+ if (!Number.isInteger(value)) throw new InputError(`"${name}" must be an integer.`);
18
+ if (value < spec.minimum || value > spec.maximum) {
19
+ throw new InputError(`"${name}" must be between ${spec.minimum} and ${spec.maximum}.`);
20
+ }
21
+ } else if (spec.type === 'boolean') {
22
+ if (typeof value !== 'boolean') throw new InputError(`"${name}" must be true or false.`);
23
+ } else if (spec.type === 'array') {
24
+ if (!Array.isArray(value)) throw new InputError(`"${name}" must be an array.`);
25
+ for (const item of value) checkValue(`${name}[]`, spec.items, item);
26
+ }
27
+ if (spec.enum && !spec.enum.includes(value)) {
28
+ throw new InputError(`"${name}" must be one of: ${spec.enum.join(', ')}.`);
29
+ }
30
+ }
31
+
32
+ /**
33
+ * @param {{ properties: Record<string, any>, required?: string[] }} schema
34
+ * @param {unknown} args
35
+ * @returns {Record<string, any>} validated arguments with defaults applied
36
+ */
37
+ export function validate(schema, args) {
38
+ if (args === undefined || args === null) args = {};
39
+ if (typeof args !== 'object' || Array.isArray(args)) throw new InputError('Arguments must be an object.');
40
+ const out = {};
41
+ for (const [name, value] of Object.entries(args)) {
42
+ const spec = schema.properties[name];
43
+ if (!spec) {
44
+ throw new InputError(`Unknown argument "${name}". Allowed: ${Object.keys(schema.properties).join(', ')}.`);
45
+ }
46
+ if (value === null || value === undefined) continue;
47
+ checkValue(name, spec, value);
48
+ out[name] = value;
49
+ }
50
+ for (const name of schema.required ?? []) {
51
+ if (out[name] === undefined) throw new InputError(`"${name}" is required.`);
52
+ }
53
+ for (const [name, spec] of Object.entries(schema.properties)) {
54
+ if (out[name] === undefined && spec.default !== undefined) out[name] = spec.default;
55
+ }
56
+ return out;
57
+ }