@expensebot/mcp-server-auth 0.6.22 → 0.6.23

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.
package/src/index.js CHANGED
@@ -49,6 +49,7 @@ const SERVER_INSTRUCTIONS = [
49
49
  "For a requested multi-step workflow, be concise: show the grounded preview, ask one clear yes/no confirmation when required, then complete every approved step. Prefer group_expenses for group-and-report requests even when the expenses already have that group. Do not add unsolicited tax, audit, substantiation, or client-AP advice, and do not second-guess an approved scope unless a tool reports an ambiguity, conflict, or failure. A request to create, share, or bill from a report is NOT a request for compliance, tax, deductibility, report-detail, business-purpose, attendee, or reimbursement analysis: never call those tools as a preflight or follow-up unless the user explicitly asks for that analysis. 'Without personal expenses' is only a report filter. isReimbursable is ExpenseBot workflow state, not a judgment about whether an expense may be billed to a client.",
50
50
  "For exact corrections across several expenses, use correct_expenses only after search_expenses has returned the exact expenseId values. Show its automatic preview, ask one yes/no question, then return its verified terminal result without adding advice. Use only attendee names the user explicitly supplied. For broad, ambiguous, mixed, or more than 100-row cleanup, link to Review Expenses instead.",
51
51
  "Across every tool, treat returned counts, totals, currencies, statuses, and completion evidence as authoritative. Never recompute them from detail rows or reinterpret a successful result. After an approved write completes, report the outcome and relevant links without reopening the user's approved scope or adding unrequested advice. Ask another question only when the tool reports an ambiguity, conflict, failure, or required external side effect.",
52
+ "When structuredContent is present, use it as the authoritative machine-readable result and use text only as the compatibility narrative. Respect explicit branch and pagination fields such as success, found, status, state, hasMore, nextCursor, and truncated. Never invent fields absent from the returned branch or merge stale values from an earlier call.",
52
53
  "For grouping workflows, call the destination a group in user-facing prose, even though ExpenseBot stores it in its Tag column; do not rename it a tag unless explaining the spreadsheet schema. Search and preview totals are provisional. After a confirmed group_expenses or create_report result, use only that terminal result's exact count, total, and currency, even when it differs from an earlier preview by rounding. A Bill Client URL is a reviewed handoff only: it does not mean an invoice was created, sent, or confirmed.",
53
54
  "Across every answer, answer the user's requested task first and stop when it is complete. Do not infer intent, risk, tax treatment, reimbursement eligibility, business purpose, attendees, client expectations, or currency preferences from merchants, locations, dates, or amounts. Offer analysis, warnings, or follow-up work only when the user asks for it or an authoritative tool result says action is required.",
54
55
  "A successful terminal write result supersedes intermediate search and preview observations. The final answer must follow the terminal result's responseGuidance and must not repeat exploratory candidates, excluded near-matches, or concerns that the terminal tool did not report. When a terminal result contains finalAnswer, return it verbatim and add nothing else. After a Bill Client handoff, do not offer report sharing or currency advice unless the user explicitly requested it.",
@@ -57,7 +58,7 @@ const SERVER_INSTRUCTIONS = [
57
58
  "After another expense submission, show the returned spreadsheetUrl and reviewExpensesUrl.",
58
59
  "For income writes, show spreadsheetUrl and reviewIncomeUrl.",
59
60
  "For Gmail scan progress or completion, call get_scan_status. Report its authoritative status and live phase; on completion show spreadsheetUrl and reviewExpensesUrl, and when action is needed show gmailScanUrl.",
60
- "For product, setup, billing, Gmail, report, workflow, or troubleshooting questions, call search_knowledge instead of guessing. Use fullAnswer:true when complete instructions are needed.",
61
+ "For product, setup, billing, Gmail, report, workflow, or troubleshooting questions, call search_knowledge instead of guessing. Set fullAnswer:true on the first call when the user asks for complete, detailed, or step-by-step instructions; use the default excerpt mode only for discovery or quick answers.",
61
62
  ].join("\n");
62
63
 
63
64
  if (onboardingMode) {
@@ -70,6 +71,32 @@ if (onboardingMode) {
70
71
 
71
72
  // ── Shared schemas ─────────────────────────────────────────────────────
72
73
  //
74
+ const OPENAI_FILE_REFERENCE_SCHEMA = {
75
+ type: "object",
76
+ description:
77
+ "Attached file reference supplied by ChatGPT. The server downloads the file securely.",
78
+ properties: {
79
+ download_url: {
80
+ type: "string",
81
+ format: "uri",
82
+ description: "Temporary HTTPS URL supplied by ChatGPT for downloading the attachment.",
83
+ },
84
+ file_id: {
85
+ type: "string",
86
+ description: "Attachment identifier supplied by ChatGPT.",
87
+ },
88
+ mime_type: {
89
+ type: "string",
90
+ description: "Attachment MIME type supplied by ChatGPT.",
91
+ },
92
+ file_name: {
93
+ type: "string",
94
+ description: "Original attachment filename supplied by ChatGPT.",
95
+ },
96
+ },
97
+ required: ["download_url", "file_id"],
98
+ };
99
+
73
100
  // dateRange is a discriminated union — historically every analytics tool
74
101
  // inlined the same flat object with all fields optional. OpenAI's app-review
75
102
  // scanner flagged that as "Unclear Arguments: dateRange has multiple required
@@ -167,11 +194,570 @@ const CLIENT_EMAIL_SCHEMA = {
167
194
  "Client account email. Accountants may use this only for an accepted ExpenseBot client.",
168
195
  };
169
196
 
197
+
198
+ // ── Tranche 1 output schemas (2026-09-09) — read-only tools ───────────────
199
+ // Same HONESTY RULE as the block above: `required` lists only fields present on
200
+ // EVERY successful response (verified against mcpActionExecutor.js). Conditional
201
+ // fields are described but never required; additionalProperties stays true.
202
+ // Helper-delegated payloads (buildX/loadX) keep `required` at the envelope only.
203
+ // Error responses never receive structuredContent, so these describe success.
204
+
205
+ // Shared by get_pnl / get_spending_summary / get_income_summary /
206
+ // get_deep_analytics / get_per_tag_pnl. These enqueue an async job and return a
207
+ // pending handle, OR (simple queries) resolve inline; poll_analytics returns the
208
+ // terminal data. Two branches, discriminated by `type`/`status`.
209
+ const ANALYTICS_QUERY_OUTPUT_SCHEMA = {
210
+ type: "object",
211
+ required: [],
212
+ additionalProperties: true,
213
+ description:
214
+ "Two branches. Async: type='analytics_pending' with jobId — poll poll_analytics until complete. Inline: message + data with the computed analytics (data may be null when there is no spreadsheet or no data yet). success is present only on the async branch.",
215
+ properties: {
216
+ success: { type: "boolean", description: "Async branch only." },
217
+ type: {
218
+ type: "string",
219
+ description: 'Async branch only: "analytics_pending" — poll pollEndpoint or call poll_analytics with jobId.',
220
+ },
221
+ jobId: { type: "string", description: "Async branch only." },
222
+ pollEndpoint: { type: "string", description: "Async branch only." },
223
+ pollInterval: { type: "number", description: "Async branch only: milliseconds." },
224
+ estimatedTime: { type: "number", description: "Async branch only: seconds." },
225
+ message: { type: "string", description: "Human-readable narrative (both branches)." },
226
+ response: { type: "string", description: "Chat alias of message." },
227
+ data: {
228
+ type: ["object", "null"],
229
+ additionalProperties: true,
230
+ description: "Inline branch: computed analytics, or null when no spreadsheet / no data.",
231
+ },
232
+ },
233
+ };
234
+
235
+ const GET_MILEAGE_SUMMARY_OUTPUT_SCHEMA = {
236
+ type: "object",
237
+ required: [],
238
+ additionalProperties: true,
239
+ description:
240
+ "Success returns message + data with the computed summary; success is not emitted on the inline analytics path.",
241
+ properties: {
242
+ success: { type: "boolean", description: "Present only on the error branch (out of scope) / async path." },
243
+ message: { type: "string" },
244
+ data: { type: ["object", "null"], additionalProperties: true },
245
+ },
246
+ };
247
+
248
+ const GET_SUBSCRIPTION_AUDIT_OUTPUT_SCHEMA = {
249
+ type: "object",
250
+ required: [],
251
+ additionalProperties: true,
252
+ description:
253
+ "Success returns message + data with the computed summary; success is not emitted on the inline analytics path.",
254
+ properties: {
255
+ success: { type: "boolean", description: "Present only on the error branch (out of scope) / async path." },
256
+ message: { type: "string" },
257
+ data: { type: ["object", "null"], additionalProperties: true },
258
+ },
259
+ };
260
+
261
+ const GET_TRIP_SUGGESTIONS_OUTPUT_SCHEMA = {
262
+ type: "object",
263
+ required: ["success"],
264
+ additionalProperties: true,
265
+ properties: {
266
+ success: { type: "boolean" },
267
+ count: { type: "integer" },
268
+ message: { type: "string" },
269
+ proposals: {
270
+ type: "array",
271
+ description: "Read-only trip proposals; accepting one continues through group_expenses.",
272
+ items: { type: "object", additionalProperties: true },
273
+ },
274
+ },
275
+ };
276
+
277
+ const LIST_CATEGORIES_OUTPUT_SCHEMA = {
278
+ type: "object",
279
+ required: ["success", "categories"],
280
+ additionalProperties: true,
281
+ properties: {
282
+ success: { type: "boolean" },
283
+ categories: { type: "array", items: { type: "string" }, description: "Expense categories for the user." },
284
+ billingAccounts: { type: "array", items: { type: "string" }, description: "Billing/card accounts, when configured." },
285
+ },
286
+ };
287
+
288
+ const LIST_INCOME_CATEGORIES_OUTPUT_SCHEMA = {
289
+ type: "object",
290
+ required: ["success", "categories"],
291
+ additionalProperties: true,
292
+ properties: {
293
+ success: { type: "boolean" },
294
+ categories: { type: "array", items: { type: "string" } },
295
+ legacy: { type: "array", items: { type: "string" }, description: "Deprecated income categories still accepted on read." },
296
+ notes: { type: "string" },
297
+ },
298
+ };
299
+
300
+ const LIST_TAGS_OUTPUT_SCHEMA = {
301
+ type: "object",
302
+ required: ["success", "tags"],
303
+ additionalProperties: true,
304
+ properties: {
305
+ success: { type: "boolean" },
306
+ tags: {
307
+ type: "array",
308
+ description: "Client / project / trip groups (Column K values).",
309
+ items: { type: "object", additionalProperties: true },
310
+ },
311
+ },
312
+ };
313
+
314
+ const LIST_REPORTS_OUTPUT_SCHEMA = {
315
+ type: "object",
316
+ required: ["success", "creationStatus"],
317
+ additionalProperties: true,
318
+ properties: {
319
+ success: { type: "boolean" },
320
+ creationStatus: {
321
+ type: "string",
322
+ description: 'Provenance of the listing, e.g. "existing_only".',
323
+ },
324
+ reports: {
325
+ type: "array",
326
+ description: "Present when the user has reports.",
327
+ items: { type: "object", additionalProperties: true },
328
+ },
329
+ page: { type: "integer" },
330
+ limit: { type: "integer" },
331
+ filter: { type: "string" },
332
+ responseGuidance: { type: "string" },
333
+ },
334
+ };
335
+
336
+ const GET_REPORT_DETAILS_OUTPUT_SCHEMA = {
337
+ type: "object",
338
+ required: ["success", "report"],
339
+ additionalProperties: true,
340
+ properties: {
341
+ success: { type: "boolean" },
342
+ report: { type: "object", additionalProperties: true, description: "The full stored report record." },
343
+ },
344
+ };
345
+
346
+ const GET_RECENT_ACTIVITY_OUTPUT_SCHEMA = {
347
+ type: "object",
348
+ required: ["success", "count", "actions"],
349
+ additionalProperties: true,
350
+ properties: {
351
+ success: { type: "boolean" },
352
+ count: { type: "integer" },
353
+ actions: {
354
+ type: "array",
355
+ items: {
356
+ type: "object",
357
+ additionalProperties: true,
358
+ properties: {
359
+ actionId: { type: "string" },
360
+ success: { type: "boolean" },
361
+ durationMs: { type: "number" },
362
+ timestamp: { type: "string" },
363
+ },
364
+ },
365
+ },
366
+ },
367
+ };
368
+
369
+ const GET_CLIENT_INVOICE_OUTPUT_SCHEMA = {
370
+ type: "object",
371
+ required: ["success"],
372
+ additionalProperties: true,
373
+ properties: {
374
+ success: { type: "boolean" },
375
+ message: { type: "string" },
376
+ invoice: {
377
+ type: "object",
378
+ description: "The invoice record. Absent only on the error branch (not-found), which never carries structuredContent.",
379
+ additionalProperties: true,
380
+ properties: {
381
+ invoiceId: { type: "string", description: "Durable invoice identity." },
382
+ invoiceNumber: { type: ["string", "null"] },
383
+ clientName: { type: ["string", "null"] },
384
+ clientTag: { type: ["string", "null"] },
385
+ status: { type: "string", description: 'Stored status, e.g. "open", "paid", "void".' },
386
+ displayStatus: {
387
+ type: "string",
388
+ enum: ["open", "overdue", "paid", "void", "superseded", "needs_review"],
389
+ description: "Derived: overdue is computed from status + dueDate, not stored.",
390
+ },
391
+ issueDate: { type: ["string", "null"] },
392
+ dueDate: { type: ["string", "null"] },
393
+ currency: { type: "string" },
394
+ subtotal: { type: "number" },
395
+ taxAmount: { type: "number" },
396
+ grandTotal: { type: "number" },
397
+ advanceApplied: { type: "number" },
398
+ balanceDue: { type: "number" },
399
+ paidDate: { type: ["string", "null"], description: "null until paid." },
400
+ paidAmount: { type: ["number", "null"], description: "null until paid." },
401
+ deliveryStatus: { type: "string" },
402
+ documentUrl: { type: ["string", "null"] },
403
+ pdfUrl: { type: ["string", "null"] },
404
+ reportUrl: { type: ["string", "null"] },
405
+ billClientUrl: { type: ["string", "null"] },
406
+ },
407
+ },
408
+ },
409
+ };
410
+
411
+ const LIST_CLIENT_INVOICES_OUTPUT_SCHEMA = {
412
+ type: "object",
413
+ required: ["success", "invoices"],
414
+ additionalProperties: true,
415
+ properties: {
416
+ success: { type: "boolean" },
417
+ invoices: {
418
+ type: "array",
419
+ items: {
420
+ type: "object",
421
+ additionalProperties: true,
422
+ properties: {
423
+ invoiceId: { type: "string" },
424
+ invoiceNumber: { type: ["string", "null"] },
425
+ clientName: { type: ["string", "null"] },
426
+ status: { type: "string" },
427
+ displayStatus: {
428
+ type: "string",
429
+ enum: ["open", "overdue", "paid", "void", "superseded", "needs_review"],
430
+ },
431
+ total: { type: "number" },
432
+ grandTotal: { type: "number" },
433
+ advanceApplied: { type: "number" },
434
+ currency: { type: "string" },
435
+ issueDate: { type: ["string", "null"] },
436
+ },
437
+ },
438
+ },
439
+ },
440
+ };
441
+
442
+ const GET_EXPENSE_BY_ID_OUTPUT_SCHEMA = {
443
+ type: "object",
444
+ required: ["success"],
445
+ additionalProperties: true,
446
+ properties: {
447
+ success: { type: "boolean" },
448
+ rowNumber: { type: "integer", description: "Resolved sheet row for the expense." },
449
+ expense: { type: "object", additionalProperties: true, description: "The expense record." },
450
+ reviewExpenseUrl: { type: "string" },
451
+ },
452
+ };
453
+
454
+ // Helper-delegated payloads: builders own the shape, so the honest contract is
455
+ // the envelope plus the one always-present collection where verified.
456
+ const GET_EXPENSE_SPLITS_OUTPUT_SCHEMA = {
457
+ type: "object",
458
+ required: ["success"],
459
+ additionalProperties: true,
460
+ properties: {
461
+ success: { type: "boolean" },
462
+ message: { type: "string" },
463
+ splits: { type: "array", items: { type: "object", additionalProperties: true } },
464
+ data: { type: "object", additionalProperties: true },
465
+ },
466
+ };
467
+
468
+ const GET_MONTHLY_BOOKS_REVIEW_OUTPUT_SCHEMA = {
469
+ type: "object",
470
+ required: ["success"],
471
+ additionalProperties: true,
472
+ properties: {
473
+ success: { type: "boolean" },
474
+ message: { type: "string" },
475
+ data: { type: "object", additionalProperties: true },
476
+ },
477
+ };
478
+
479
+ const GET_CREDITS_REFUNDS_OUTPUT_SCHEMA = {
480
+ type: "object",
481
+ required: ["success"],
482
+ additionalProperties: true,
483
+ properties: {
484
+ success: { type: "boolean" },
485
+ message: { type: "string" },
486
+ credits: { type: "array", items: { type: "object", additionalProperties: true } },
487
+ refunds: { type: "array", items: { type: "object", additionalProperties: true } },
488
+ data: { type: "object", additionalProperties: true },
489
+ },
490
+ };
491
+
492
+ const GET_CLIENT_ADVANCE_BALANCES_OUTPUT_SCHEMA = {
493
+ type: "object",
494
+ required: ["success"],
495
+ additionalProperties: true,
496
+ properties: {
497
+ success: { type: "boolean" },
498
+ message: { type: "string" },
499
+ homeCurrency: { type: "string" },
500
+ balances: { type: "array", items: { type: "object", additionalProperties: true } },
501
+ data: { type: "object", additionalProperties: true },
502
+ },
503
+ };
504
+
505
+ const GET_ACCOUNTING_INTEGRATION_STATUS_OUTPUT_SCHEMA = {
506
+ type: "object",
507
+ required: ["success"],
508
+ additionalProperties: true,
509
+ properties: {
510
+ success: { type: "boolean" },
511
+ message: { type: "string" },
512
+ data: { type: "object", additionalProperties: true, description: "Per-provider connection and rollout state." },
513
+ },
514
+ };
515
+
516
+ const GET_ACCOUNTING_PUSH_STATUS_OUTPUT_SCHEMA = {
517
+ type: "object",
518
+ required: ["success"],
519
+ additionalProperties: true,
520
+ properties: {
521
+ success: { type: "boolean" },
522
+ message: { type: "string" },
523
+ data: { type: "object", additionalProperties: true },
524
+ },
525
+ };
526
+
527
+
528
+ // ── Tranche 2 output schemas (2026-09-09) — checks, what-ifs, status, commerce ─
529
+ // Honest-loose (see tranche 1 header). Advisory/read tools. `required` holds
530
+ // only fields the executor emits on every success path; the what-if/check tools
531
+ // delegate their payload to scenario/handler builders, so those keep `required`
532
+ // at the envelope. Error responses never receive structuredContent.
533
+
534
+ // Shared by whatif_afford / whatif_client / whatif_tax_setaside:
535
+ // result = { success:true, message: scenario.template || evidence[0].value, data: scenario }
536
+ const WHATIF_OUTPUT_SCHEMA = {
537
+ type: "object",
538
+ required: ["success"],
539
+ additionalProperties: true,
540
+ properties: {
541
+ success: { type: "boolean" },
542
+ message: { type: "string", description: "Scenario narrative; may be absent if the scenario carried no template or evidence." },
543
+ data: { type: "object", additionalProperties: true, description: "The full what-if scenario: assumptions, evidence, and computed outcome." },
544
+ },
545
+ };
546
+
547
+ // Shared by check_compliance / check_feature / check_tax_deductibility (registry
548
+ // handlers). Success returns success:true plus a message and handler-specific
549
+ // fields; keep required at the envelope.
550
+ const CHECK_OUTPUT_SCHEMA = {
551
+ type: "object",
552
+ required: ["success"],
553
+ additionalProperties: true,
554
+ properties: {
555
+ success: { type: "boolean" },
556
+ message: { type: "string" },
557
+ data: { type: "object", additionalProperties: true },
558
+ },
559
+ };
560
+
561
+ const GET_SCAN_STATUS_OUTPUT_SCHEMA = {
562
+ type: "object",
563
+ required: ["success"],
564
+ additionalProperties: true,
565
+ description:
566
+ "Authoritative live scan state. Fields may sit at the top level or under data depending on the branch; nothing beyond success is guaranteed, so treat each as optional.",
567
+ properties: {
568
+ success: { type: "boolean" },
569
+ message: { type: "string" },
570
+ status: { type: ["string", "null"], description: "Scan lifecycle state." },
571
+ scanInProgress: { type: "boolean" },
572
+ lock: {
573
+ type: "object",
574
+ additionalProperties: true,
575
+ description: "Scan-lock state (active, startedAt, ageSeconds, dispatchComplete, pendingProcessingCount).",
576
+ },
577
+ latestScan: {
578
+ type: ["object", "null"],
579
+ additionalProperties: true,
580
+ description: "Most recent scan outcome (success, emailsFound, emailsTagged, timestamp).",
581
+ },
582
+ spreadsheetUrl: { type: ["string", "null"] },
583
+ reviewExpensesUrl: { type: ["string", "null"] },
584
+ gmailScanUrl: { type: ["string", "null"] },
585
+ data: { type: "object", additionalProperties: true },
586
+ },
587
+ };
588
+
170
589
  // ── Tool Definitions ───────────────────────────────────────────────────
171
590
 
591
+ // Output contracts for the first, highest-guess-cost tranche. `required`
592
+ // contains only fields present on every successful response. Conditional
593
+ // fields remain optional and additionalProperties stays true: an incomplete
594
+ // contract is preferable to a confident lie about a live response shape.
595
+ const SEARCH_EXPENSES_OUTPUT_SCHEMA = {
596
+ type: "object",
597
+ required: ["expenses", "count", "total"],
598
+ additionalProperties: true,
599
+ properties: {
600
+ message: { type: "string" },
601
+ expenses: {
602
+ type: "array",
603
+ description: "Matching expense rows, newest first, paginated.",
604
+ items: {
605
+ type: "object",
606
+ required: ["expenseId", "date", "amount", "tag", "updateEligible"],
607
+ additionalProperties: true,
608
+ properties: {
609
+ expenseId: {
610
+ type: "string",
611
+ description:
612
+ "Durable Receipt ID (Column Q). The only identity accepted by update_expense.",
613
+ },
614
+ merchant: { type: "string" },
615
+ date: { type: "string" },
616
+ dateIso: { type: "string", description: "Canonical YYYY-MM-DD when available." },
617
+ category: { type: "string" },
618
+ amount: { type: "number", description: "Functional/home-currency amount." },
619
+ currency: { type: "string", description: "Home currency code when available." },
620
+ originalAmount: { type: "number" },
621
+ originalCurrency: { type: "string" },
622
+ tag: { type: "string", description: "Column K group (client/project/trip)." },
623
+ location: { type: "string" },
624
+ matchedFields: { type: "array", items: { type: "string" } },
625
+ matchReason: { type: "string" },
626
+ updateEligible: { type: "boolean" },
627
+ },
628
+ },
629
+ },
630
+ total: { type: "number", description: "Sum of the matched set in home currency." },
631
+ count: { type: "integer", description: "Rows matched by the filters." },
632
+ totalMatched: { type: "integer", description: "Present for free-text searches." },
633
+ queryApplied: { type: "string" },
634
+ hasMore: { type: "boolean" },
635
+ nextCursor: {
636
+ type: ["string", "null"],
637
+ description: "Opaque signed continuation; reuse with identical filters.",
638
+ },
639
+ pageInfo: { type: "object", additionalProperties: true },
640
+ },
641
+ };
642
+
643
+ const SEARCH_KNOWLEDGE_OUTPUT_SCHEMA = {
644
+ type: "object",
645
+ required: ["success", "results"],
646
+ additionalProperties: true,
647
+ properties: {
648
+ success: { type: "boolean" },
649
+ results: {
650
+ type: "array",
651
+ items: {
652
+ type: "object",
653
+ required: ["id", "question", "answer"],
654
+ additionalProperties: true,
655
+ properties: {
656
+ id: { type: "string" },
657
+ question: { type: "string" },
658
+ answer: { type: "string" },
659
+ truncated: { type: "boolean" },
660
+ type: { type: "string" },
661
+ relevance: { type: "number" },
662
+ },
663
+ },
664
+ },
665
+ },
666
+ };
667
+
668
+ const GET_LAST_RECEIPT_RESULT_OUTPUT_SCHEMA = {
669
+ type: "object",
670
+ required: ["success", "found", "message"],
671
+ additionalProperties: true,
672
+ description:
673
+ "found:false means processing is still pending; found:true is a terminal result.",
674
+ properties: {
675
+ success: { type: "boolean", const: true },
676
+ found: { type: "boolean" },
677
+ state: {
678
+ type: "string",
679
+ const: "processing",
680
+ description: "Present on pending polls for a specific submission.",
681
+ },
682
+ message: { type: "string" },
683
+ verdict: {
684
+ type: "string",
685
+ enum: ["added", "duplicate", "skipped", "errored", "mixed", "unknown"],
686
+ description: "Terminal branch only.",
687
+ },
688
+ counts: {
689
+ type: "object",
690
+ additionalProperties: true,
691
+ required: ["submitted", "added", "duplicates", "skipped", "errors"],
692
+ properties: {
693
+ submitted: { type: "integer", minimum: 0 },
694
+ added: { type: "integer", minimum: 0 },
695
+ duplicates: { type: "integer", minimum: 0 },
696
+ skipped: { type: "integer", minimum: 0 },
697
+ errors: { type: "integer", minimum: 0 },
698
+ },
699
+ },
700
+ receipts: { type: "array", items: { type: "object", additionalProperties: true } },
701
+ submissionId: { type: ["string", "null"] },
702
+ spreadsheetUrl: { type: ["string", "null"] },
703
+ reviewExpensesUrl: { type: "string" },
704
+ data: { type: "object", additionalProperties: true },
705
+ timestamp: { type: ["string", "null"], format: "date-time" },
706
+ },
707
+ allOf: [
708
+ {
709
+ if: { properties: { found: { const: true } }, required: ["found"] },
710
+ then: {
711
+ required: [
712
+ "verdict",
713
+ "counts",
714
+ "receipts",
715
+ "submissionId",
716
+ "spreadsheetUrl",
717
+ "reviewExpensesUrl",
718
+ "data",
719
+ "timestamp",
720
+ ],
721
+ },
722
+ },
723
+ ],
724
+ };
725
+
726
+ const GET_SPREADSHEET_URL_OUTPUT_SCHEMA = {
727
+ type: "object",
728
+ required: [
729
+ "success",
730
+ "spreadsheetId",
731
+ "spreadsheetUrl",
732
+ "reviewExpensesUrl",
733
+ "reviewIncomeUrl",
734
+ "gmailScanUrl",
735
+ "gmailActionNeededUrl",
736
+ "reportsUrl",
737
+ "dashboardUrl",
738
+ "data",
739
+ "message",
740
+ ],
741
+ additionalProperties: true,
742
+ properties: {
743
+ success: { type: "boolean", const: true },
744
+ spreadsheetId: { type: "string", minLength: 1 },
745
+ spreadsheetUrl: { type: "string" },
746
+ reviewExpensesUrl: { type: "string" },
747
+ reviewIncomeUrl: { type: "string" },
748
+ gmailScanUrl: { type: "string" },
749
+ gmailActionNeededUrl: { type: "string" },
750
+ reportsUrl: { type: "string" },
751
+ dashboardUrl: { type: "string" },
752
+ data: { type: "object", additionalProperties: true },
753
+ message: { type: "string" },
754
+ },
755
+ };
756
+
172
757
  const TOOLS = [
173
758
  {
174
759
  name: "search_expenses",
760
+ outputSchema: SEARCH_EXPENSES_OUTPUT_SCHEMA,
175
761
  description:
176
762
  "Search and filter the user's expenses. Returns matching expense rows " +
177
763
  "from their spreadsheet. Filter by category, merchant, date range, " +
@@ -234,6 +820,7 @@ const TOOLS = [
234
820
  },
235
821
  {
236
822
  name: "get_spending_summary",
823
+ outputSchema: ANALYTICS_QUERY_OUTPUT_SCHEMA,
237
824
  description:
238
825
  "Summarize the user's recorded expenses with totals and breakdowns by " +
239
826
  "category, merchant, month, tag, source, or payment method. Supports " +
@@ -249,7 +836,11 @@ const TOOLS = [
249
836
  description:
250
837
  "Natural language question (e.g., 'how much did I spend in March', 'top merchants this quarter')",
251
838
  },
252
- categories: { type: "array", items: { type: "string" } },
839
+ categories: {
840
+ type: "array",
841
+ items: { type: "string" },
842
+ description: "Optional configured expense categories to include in the summary.",
843
+ },
253
844
  dateRange: DATE_RANGE_SCHEMA,
254
845
  groupBy: { type: "string", enum: ["category", "merchant", "month", "tag", "source", "paymentMethod"] },
255
846
  metric: { type: "string", enum: ["total", "count", "average"] },
@@ -258,6 +849,7 @@ const TOOLS = [
258
849
  },
259
850
  {
260
851
  name: "get_deep_analytics",
852
+ outputSchema: ANALYTICS_QUERY_OUTPUT_SCHEMA,
261
853
  description:
262
854
  "Run deeper, multi-step analytics on the user's expenses. Use for " +
263
855
  "explanatory questions like 'why did my spending increase' or " +
@@ -306,7 +898,11 @@ const TOOLS = [
306
898
  properties: {
307
899
  dateRange: DATE_RANGE_SCHEMA,
308
900
  title: { type: "string", description: "Custom report title" },
309
- categories: { type: "array", items: { type: "string" } },
901
+ categories: {
902
+ type: "array",
903
+ items: { type: "string" },
904
+ description: "Optional configured expense categories to include in the report.",
905
+ },
310
906
  tags: {
311
907
  type: "array",
312
908
  items: { type: "string" },
@@ -333,11 +929,19 @@ const TOOLS = [
333
929
  items: { type: "string", format: "email" },
334
930
  description: "Email addresses to share the report with",
335
931
  },
932
+ recipientRole: {
933
+ type: "string",
934
+ enum: ["reviewer", "accountant"],
935
+ default: "reviewer",
936
+ description:
937
+ "Access for every shareWith recipient. Use reviewer for one-report review, comments, approval, or change requests. Use accountant only when the user explicitly wants ongoing report management and accounting-software access.",
938
+ },
336
939
  },
337
940
  },
338
941
  },
339
942
  {
340
943
  name: "list_reports",
944
+ outputSchema: LIST_REPORTS_OUTPUT_SCHEMA,
341
945
  description:
342
946
  "List the user's expense reports with pagination. Filter by status " +
343
947
  "(All, Draft, Submitted, Shared). Each exact report includes its app, " +
@@ -348,9 +952,22 @@ const TOOLS = [
348
952
  type: "object",
349
953
  properties: {
350
954
  clientEmail: CLIENT_EMAIL_SCHEMA,
351
- page: { type: "integer", default: 1 },
352
- limit: { type: "integer", default: 20 },
353
- filter: { type: "string", enum: ["All", "Draft", "Submitted", "Shared"], default: "All" },
955
+ page: {
956
+ type: "integer",
957
+ default: 1,
958
+ description: "One-based results page to return.",
959
+ },
960
+ limit: {
961
+ type: "integer",
962
+ default: 20,
963
+ description: "Maximum reports to return on this page.",
964
+ },
965
+ filter: {
966
+ type: "string",
967
+ enum: ["All", "Draft", "Submitted", "Shared"],
968
+ default: "All",
969
+ description: "Optional report-status filter; All returns every authorized status.",
970
+ },
354
971
  },
355
972
  },
356
973
  },
@@ -371,6 +988,7 @@ const TOOLS = [
371
988
  },
372
989
  {
373
990
  name: "get_report_details",
991
+ outputSchema: GET_REPORT_DETAILS_OUTPUT_SCHEMA,
374
992
  description:
375
993
  "Get full details of a specific expense report including all expenses, " +
376
994
  "totals, and compliance status. Use only when the user explicitly asks " +
@@ -394,8 +1012,7 @@ const TOOLS = [
394
1012
  {
395
1013
  name: "share_report",
396
1014
  description:
397
- "Share an expense report with one or more email addresses for review " +
398
- "or approval.",
1015
+ "Share one existing expense report after confirmation. Default to reviewer: they can open and edit that report's Google Sheet, inspect receipts, comment, approve, or request changes, but cannot act for the owner or use accounting integrations. Use accountant only when the user explicitly asks for ongoing accounting access; it creates the established accountant relationship and broader report-management workflow.",
399
1016
  inputSchema: {
400
1017
  type: "object",
401
1018
  properties: {
@@ -404,12 +1021,20 @@ const TOOLS = [
404
1021
  type: "array",
405
1022
  items: { type: "string", format: "email" },
406
1023
  },
1024
+ recipientRole: {
1025
+ type: "string",
1026
+ enum: ["reviewer", "accountant"],
1027
+ default: "reviewer",
1028
+ description:
1029
+ "Use reviewer for report-only approval. Use accountant only for explicit ongoing accountant access.",
1030
+ },
407
1031
  },
408
1032
  required: ["reportId", "recipients"],
409
1033
  },
410
1034
  },
411
1035
  {
412
1036
  name: "check_compliance",
1037
+ outputSchema: CHECK_OUTPUT_SCHEMA,
413
1038
  description:
414
1039
  "Use only when the user explicitly asks to check an existing report for " +
415
1040
  "compliance issues such as missing business purpose or policy violations. " +
@@ -449,6 +1074,7 @@ const TOOLS = [
449
1074
  },
450
1075
  {
451
1076
  name: "check_tax_deductibility",
1077
+ outputSchema: CHECK_OUTPUT_SCHEMA,
452
1078
  description:
453
1079
  "Look up whether a specific expense type or purchase is tax-DEDUCTIBLE " +
454
1080
  "(business write-off rules) based on the user's country/jurisdiction. " +
@@ -474,12 +1100,16 @@ const TOOLS = [
474
1100
  },
475
1101
  {
476
1102
  name: "search_knowledge",
1103
+ outputSchema: SEARCH_KNOWLEDGE_OUTPUT_SCHEMA,
477
1104
  description:
478
1105
  "Search ExpenseBot's complete product and help knowledge base. Use this " +
479
1106
  "before guessing when the user asks how a feature works, what ExpenseBot " +
480
1107
  "supports, or needs setup, billing, Gmail, scan, report, workflow, or " +
481
- "troubleshooting instructions. Results are query-ranked; request the full " +
482
- "answer after identifying the relevant article.",
1108
+ "troubleshooting instructions. Set fullAnswer:true on the first call when " +
1109
+ "the user asks for complete, detailed, or step-by-step instructions. Use " +
1110
+ "the default excerpt mode for discovery and quick answers; if an excerpt " +
1111
+ "is truncated, call again with fullAnswer:true before presenting complete " +
1112
+ "instructions. Each result has a stable id.",
483
1113
  inputSchema: {
484
1114
  type: "object",
485
1115
  properties: {
@@ -495,7 +1125,7 @@ const TOOLS = [
495
1125
  type: "boolean",
496
1126
  default: false,
497
1127
  description:
498
- "Set true to return complete article answers instead of short excerpts.",
1128
+ "Set true on the first call for complete, detailed, or step-by-step instructions. Leave false for discovery or quick-answer excerpts.",
499
1129
  },
500
1130
  },
501
1131
  required: ["query"],
@@ -521,9 +1151,9 @@ const TOOLS = [
521
1151
  "call this tool ONCE with uploadRefs for all of them — that processes " +
522
1152
  "the whole set as a single batch, like the ExpenseBot web app. Do not " +
523
1153
  "call this tool once per file.\n\n" +
524
- "Only use the photo parameter for a single small image whose base64 you " +
525
- "can reliably include in full — large base64 payloads are frequently " +
526
- "dropped in transit, which silently loses the receipt.\n\n" +
1154
+ "Use the photo parameter for one image or PDF attached in ChatGPT. MCP " +
1155
+ "clients that cannot supply file references may use photoBase64 for one " +
1156
+ "small image; use the upload flow for large files or batches.\n\n" +
527
1157
  "Optional note and tag values use the same receipt metadata path as " +
528
1158
  "ExpenseBot's camera, file uploader, and forwarded-email intake. The " +
529
1159
  "note is stored in the Notes column (L); the tag is stored in the Tag " +
@@ -605,11 +1235,16 @@ const TOOLS = [
605
1235
  "is more than one file.",
606
1236
  },
607
1237
  photo: {
1238
+ ...OPENAI_FILE_REFERENCE_SCHEMA,
1239
+ description:
1240
+ "Single attached receipt image or PDF supplied by ChatGPT. For multiple " +
1241
+ "files or large files, use filesToUpload and uploadRefs instead.",
1242
+ },
1243
+ photoBase64: {
608
1244
  type: "string",
609
1245
  description:
610
- "Base64-encoded image or PDF data (JPEG, PNG, HEIC, WebP, or PDF). " +
611
- "Max 15MB. Only for small images — large payloads get truncated or " +
612
- "dropped in transit; use uploadRef instead.",
1246
+ "Legacy fallback for MCP clients that send one small image as complete " +
1247
+ "base64 data. ChatGPT should use photo or uploadRefs instead.",
613
1248
  },
614
1249
  filename: {
615
1250
  type: "string",
@@ -641,8 +1276,9 @@ const TOOLS = [
641
1276
  "through the same path as the web receipt uploader.",
642
1277
  },
643
1278
  },
644
- // Neither is individually required: the server accepts uploadRef OR
645
- // photo and returns a clear 400 naming both when it gets neither.
1279
+ // None is individually required: the server accepts uploadRef, photo,
1280
+ // or the legacy photoBase64 fallback and returns a clear error when it
1281
+ // gets none.
646
1282
  // Keeping photo in `required` would reintroduce the original failure --
647
1283
  // the client rejecting the call locally when a model omits base64, so
648
1284
  // nothing ever reaches the server and no diagnostic is recorded.
@@ -651,6 +1287,7 @@ const TOOLS = [
651
1287
  },
652
1288
  {
653
1289
  name: "get_last_receipt_result",
1290
+ outputSchema: GET_LAST_RECEIPT_RESULT_OUTPUT_SCHEMA,
654
1291
  description:
655
1292
  "Check the authoritative final outcome of a receipt image/PDF batch submitted " +
656
1293
  "with submit_receipt. After submit_receipt returns submissionId, call this " +
@@ -659,6 +1296,7 @@ const TOOLS = [
659
1296
  "batches allow longer. A pending result is normal and must not trigger a " +
660
1297
  "duplicate resubmission. Returns added, duplicate, skipped, or " +
661
1298
  "errored verdicts with exact counts and up to 10 processed receipt summaries. " +
1299
+ "found:false is pending and has no terminal verdict; found:true is terminal. " +
662
1300
  "On completion, tell the user what happened and show spreadsheetUrl plus " +
663
1301
  "reviewExpensesUrl. This is for uploaded receipts; use get_scan_status for " +
664
1302
  "Gmail scans. Read-only.",
@@ -878,7 +1516,10 @@ const TOOLS = [
878
1516
  type: "string",
879
1517
  description: "Tag for client/project attribution (optional)",
880
1518
  },
881
- notes: { type: "string" },
1519
+ notes: {
1520
+ type: "string",
1521
+ description: "Optional user-supplied context stored with the mileage entry.",
1522
+ },
882
1523
  },
883
1524
  required: ["distance", "purpose"],
884
1525
  },
@@ -943,10 +1584,16 @@ const TOOLS = [
943
1584
  type: "object",
944
1585
  properties: {
945
1586
  photo: {
1587
+ ...OPENAI_FILE_REFERENCE_SCHEMA,
1588
+ description:
1589
+ "Attached image or PDF supplied by ChatGPT for step 1. The server downloads and " +
1590
+ "parses the attachment securely.",
1591
+ },
1592
+ photoBase64: {
946
1593
  type: "string",
947
1594
  description:
948
- "Base64-encoded image/PDF bytes (step 1). On ChatGPT you may pass the attached file " +
949
- "reference object directly; the server fetches the bytes.",
1595
+ "Legacy fallback for MCP clients that send complete image/PDF bytes as base64. " +
1596
+ "ChatGPT should use photo.",
950
1597
  },
951
1598
  mimeType: {
952
1599
  type: "string",
@@ -1005,7 +1652,12 @@ const TOOLS = [
1005
1652
  type: "object",
1006
1653
  properties: {
1007
1654
  index: { type: "integer", description: "Preview row index" },
1008
- fields: { type: "object", additionalProperties: true },
1655
+ fields: {
1656
+ type: "object",
1657
+ additionalProperties: true,
1658
+ description:
1659
+ "Only the user-approved income fields to replace on this staged row: date, source, amount, currency, category, paymentMethod, description, notes, reference, fees, taxCollected, or tag.",
1660
+ },
1009
1661
  },
1010
1662
  required: ["index", "fields"],
1011
1663
  },
@@ -1040,10 +1692,16 @@ const TOOLS = [
1040
1692
  type: "object",
1041
1693
  properties: {
1042
1694
  csvContent: {
1695
+ ...OPENAI_FILE_REFERENCE_SCHEMA,
1696
+ description:
1697
+ "Attached CSV/TSV/text file supplied by ChatGPT for step 1. The server downloads " +
1698
+ "and decodes the attachment securely.",
1699
+ },
1700
+ csvText: {
1043
1701
  type: "string",
1044
1702
  description:
1045
- "Raw CSV/TSV/text content (step 1). On ChatGPT you may pass the attached file " +
1046
- "reference object directly; the server fetches and decodes the bytes.",
1703
+ "Legacy fallback for MCP clients that send raw CSV/TSV/text content inline. " +
1704
+ "ChatGPT should use csvContent.",
1047
1705
  },
1048
1706
  paymentMethod: {
1049
1707
  type: "string",
@@ -1090,7 +1748,12 @@ const TOOLS = [
1090
1748
  type: "object",
1091
1749
  properties: {
1092
1750
  index: { type: "integer", description: "Preview row index" },
1093
- fields: { type: "object", additionalProperties: true },
1751
+ fields: {
1752
+ type: "object",
1753
+ additionalProperties: true,
1754
+ description:
1755
+ "Only the user-approved income fields to replace on this staged row: date, source, amount, currency, category, paymentMethod, description, notes, reference, fees, taxCollected, or tag.",
1756
+ },
1094
1757
  },
1095
1758
  required: ["index", "fields"],
1096
1759
  },
@@ -1107,20 +1770,23 @@ const TOOLS = [
1107
1770
  },
1108
1771
  {
1109
1772
  name: "get_accounting_integration_status",
1773
+ outputSchema: GET_ACCOUNTING_INTEGRATION_STATUS_OUTPUT_SCHEMA,
1110
1774
  description:
1111
- "Check whether an accounting destination is connected and ready for owner-authorized " +
1112
- "agent posting. Returns the selected organization/account, authorization state, rollout " +
1113
- "state, and a setup or reconnect link. When an existing ExpenseBot report is available, " +
1775
+ "Check whether an accounting destination is connected and read-only setup state for the " +
1776
+ "owner. Returns the selected organization/company/business, stored connection state, rollout " +
1777
+ "state, and the single setup link for connecting or reconnecting the destination. When an existing ExpenseBot report is available, " +
1114
1778
  "pass reportId so the link opens that exact report's provider setup control instead of the " +
1115
- "general Reports setup. This is read-only and never posts accounting data. " +
1116
- "Zoho Books is the first supported provider; the contract is shared for future providers.",
1779
+ "general Reports setup. This is read-only and never posts accounting data. Agent-driven posting " +
1780
+ "is currently available only for Zoho Books (zoho_books); QuickBooks Online (quickbooks), Xero " +
1781
+ "(xero), Wave (wave), and FreeAgent (freeagent, beta) are accepted here for connection/setup " +
1782
+ "status only and report writesAuthorized=false until their canonical planning path is shared.",
1117
1783
  inputSchema: {
1118
1784
  type: "object",
1119
1785
  properties: {
1120
1786
  provider: {
1121
1787
  type: "string",
1122
- enum: ["zoho_books"],
1123
- description: "Accounting destination provider.",
1788
+ enum: ["zoho_books", "quickbooks", "xero", "wave", "freeagent"],
1789
+ description: "Accounting destination provider. QuickBooks Online, Xero, Wave, FreeAgent (beta), or Zoho Books.",
1124
1790
  },
1125
1791
  reportId: {
1126
1792
  type: "string",
@@ -1138,19 +1804,23 @@ const TOOLS = [
1138
1804
  "Review and then post an ExpenseBot report to the owner's accounting destination. " +
1139
1805
  "STEP 1: call with provider, reportId, and optional mode/mappings, without confirm. The " +
1140
1806
  "server reads the live report and destination, applies Omit/Personal/split/date/currency " +
1141
- "rules, checks bank-feed matches, and returns the complete proposal plus proposalId. " +
1807
+ "rules, checks Zoho bank-feed matches, and returns the complete proposal plus proposalId. " +
1142
1808
  "NOTHING is posted in step 1. Show the complete proposal and ask for approval. STEP 2: " +
1143
1809
  "call with only provider, proposalId, and confirm:true. The server posts only the frozen, " +
1144
1810
  "account-bound proposal, revalidates live state, and rejects changed reports or mappings. " +
1145
1811
  "Never add mapping fields to the confirmation call. Owner accounts only; acting for a " +
1146
- "client is not supported. Zoho Books is the first supported provider.",
1812
+ "client is not supported. Agent-driven posting is currently available only for Zoho Books " +
1813
+ "(zoho_books); QuickBooks Online, Xero, Wave, and FreeAgent are intentionally not accepted " +
1814
+ "by this tool yet because their previews cannot freeze/revalidate the canonical provider " +
1815
+ "plan that shareReport executes. Use those providers' web flows until they satisfy the " +
1816
+ "full push contract.",
1147
1817
  inputSchema: {
1148
1818
  type: "object",
1149
1819
  properties: {
1150
1820
  provider: {
1151
1821
  type: "string",
1152
1822
  enum: ["zoho_books"],
1153
- description: "Accounting destination provider.",
1823
+ description: "Accounting destination provider. Agent-driven posting is currently available only for Zoho Books.",
1154
1824
  },
1155
1825
  reportId: {
1156
1826
  type: "string",
@@ -1159,7 +1829,7 @@ const TOOLS = [
1159
1829
  mode: {
1160
1830
  type: "string",
1161
1831
  enum: ["auto", "expense", "bill"],
1162
- description: "Step 1 only: automatic document treatment, paid expenses, or bills.",
1832
+ description: "Step 1 only (Zoho Books): automatic document treatment, paid expenses, or bills.",
1163
1833
  },
1164
1834
  accountMappings: {
1165
1835
  type: "object",
@@ -1176,8 +1846,14 @@ const TOOLS = [
1176
1846
  additionalProperties: {
1177
1847
  type: "object",
1178
1848
  properties: {
1179
- tagId: { type: "string" },
1180
- optionId: { type: "string" },
1849
+ tagId: {
1850
+ type: "string",
1851
+ description: "Live accounting-provider reporting-tag ID returned in the step-1 proposal.",
1852
+ },
1853
+ optionId: {
1854
+ type: "string",
1855
+ description: "Live option ID belonging to tagId, returned in the step-1 proposal.",
1856
+ },
1181
1857
  },
1182
1858
  required: ["tagId", "optionId"],
1183
1859
  },
@@ -1201,21 +1877,33 @@ const TOOLS = [
1201
1877
  },
1202
1878
  {
1203
1879
  name: "get_accounting_push_status",
1880
+ outputSchema: GET_ACCOUNTING_PUSH_STATUS_OUTPUT_SCHEMA,
1204
1881
  description:
1205
- "Read the terminal posting and reconciliation status for an ExpenseBot report at an " +
1882
+ "Read the authoritative posting and reconciliation status for one ExpenseBot report at an " +
1206
1883
  "accounting destination. Use after a timeout or uncertain response before considering any " +
1207
- "retry. This tool is read-only and owner-account only.",
1884
+ "retry. Returns status, submission time, posting mode, posted receipt count, any public error, " +
1885
+ "and whether reconciliation is required. Never re-post a completed report or a report marked " +
1886
+ "needs_reconciliation; show that state to the owner instead. This tool is read-only and " +
1887
+ "owner-account only.",
1208
1888
  inputSchema: {
1209
1889
  type: "object",
1210
1890
  properties: {
1211
- provider: { type: "string", enum: ["zoho_books"] },
1212
- reportId: { type: "string" },
1891
+ provider: {
1892
+ type: "string",
1893
+ enum: ["zoho_books", "quickbooks", "xero", "wave", "freeagent"],
1894
+ description: "Accounting destination provider used for the prior posting attempt.",
1895
+ },
1896
+ reportId: {
1897
+ type: "string",
1898
+ description: "Exact ExpenseBot report ID from the prior proposal or posting attempt.",
1899
+ },
1213
1900
  },
1214
1901
  required: ["provider", "reportId"],
1215
1902
  },
1216
1903
  },
1217
1904
  {
1218
1905
  name: "list_categories",
1906
+ outputSchema: LIST_CATEGORIES_OUTPUT_SCHEMA,
1219
1907
  description:
1220
1908
  "List the user's configured expense categories and billing accounts. " +
1221
1909
  "Use this BEFORE calling tools that need a category (add_cash_expense, " +
@@ -1225,6 +1913,7 @@ const TOOLS = [
1225
1913
  },
1226
1914
  {
1227
1915
  name: "list_tags",
1916
+ outputSchema: LIST_TAGS_OUTPUT_SCHEMA,
1228
1917
  description:
1229
1918
  "List the user's configured groups. ExpenseBot stores clients, projects, " +
1230
1919
  "project codes, properties, and trips as tags (for example 'Client: " +
@@ -1241,6 +1930,7 @@ const TOOLS = [
1241
1930
  // surface them in completions when users ask income/profit questions.
1242
1931
  {
1243
1932
  name: "get_income_summary",
1933
+ outputSchema: ANALYTICS_QUERY_OUTPUT_SCHEMA,
1244
1934
  description:
1245
1935
  "Get income totals, breakdowns, and analytics from the Income tab. " +
1246
1936
  "Covers Schedule C / T2125 income, Schedule B drill-in (interest, " +
@@ -1279,6 +1969,7 @@ const TOOLS = [
1279
1969
  },
1280
1970
  {
1281
1971
  name: "get_pnl",
1972
+ outputSchema: ANALYTICS_QUERY_OUTPUT_SCHEMA,
1282
1973
  description:
1283
1974
  "Compute Profit & Loss (P&L / net income / margin) by combining the " +
1284
1975
  "Income tab with expense tabs. Examples: 'am I profitable this " +
@@ -1303,6 +1994,7 @@ const TOOLS = [
1303
1994
  },
1304
1995
  {
1305
1996
  name: "get_per_tag_pnl",
1997
+ outputSchema: ANALYTICS_QUERY_OUTPUT_SCHEMA,
1306
1998
  description:
1307
1999
  "Per-tag P&L — revenue, cost, profit, and margin grouped by tag " +
1308
2000
  "(per-client, per-property, per-event, per-realtor-deal). Requires " +
@@ -1332,6 +2024,7 @@ const TOOLS = [
1332
2024
  },
1333
2025
  {
1334
2026
  name: "list_income_categories",
2027
+ outputSchema: LIST_INCOME_CATEGORIES_OUTPUT_SCHEMA,
1335
2028
  description:
1336
2029
  "List ExpenseBot's fixed income tax categories. Unlike Expense Accounts, " +
1337
2030
  "these are not user-configured. Use this BEFORE calling add_income so " +
@@ -1340,6 +2033,7 @@ const TOOLS = [
1340
2033
  },
1341
2034
  {
1342
2035
  name: "get_recent_activity",
2036
+ outputSchema: GET_RECENT_ACTIVITY_OUTPUT_SCHEMA,
1343
2037
  description:
1344
2038
  "Show what the user (or their AI assistants) has recently done in " +
1345
2039
  "ExpenseBot via this MCP server: which tools were called, when, with " +
@@ -1427,6 +2121,7 @@ const TOOLS = [
1427
2121
  // questions instead of the generic get_spending_summary.
1428
2122
  {
1429
2123
  name: "get_mileage_summary",
2124
+ outputSchema: GET_MILEAGE_SUMMARY_OUTPUT_SCHEMA,
1430
2125
  description:
1431
2126
  "Mileage analytics — totals, breakdowns by month / client / " +
1432
2127
  "purpose / category, plus deduction framing (cents-per-mile or " +
@@ -1455,6 +2150,7 @@ const TOOLS = [
1455
2150
  },
1456
2151
  {
1457
2152
  name: "get_subscription_audit",
2153
+ outputSchema: GET_SUBSCRIPTION_AUDIT_OUTPUT_SCHEMA,
1458
2154
  description:
1459
2155
  "Subscription audit — wraps the Subscription Auditor engine to " +
1460
2156
  "find recurring charges, duplicates, price increases, and " +
@@ -1484,6 +2180,7 @@ const TOOLS = [
1484
2180
  // ── Read-only mutation helpers + onboarding (v0.7.0) ─────────────────
1485
2181
  {
1486
2182
  name: "get_expense_by_id",
2183
+ outputSchema: GET_EXPENSE_BY_ID_OUTPUT_SCHEMA,
1487
2184
  description:
1488
2185
  "Fetch a single expense row by its sheet row number or by its " +
1489
2186
  "ExpenseBot expenseId (the exact Receipt ID in Column Q). Returns the row's " +
@@ -1522,6 +2219,7 @@ const TOOLS = [
1522
2219
  },
1523
2220
  {
1524
2221
  name: "get_spreadsheet_url",
2222
+ outputSchema: GET_SPREADSHEET_URL_OUTPUT_SCHEMA,
1525
2223
  description:
1526
2224
  "Return the user's master ExpenseBot Google Sheet plus authenticated " +
1527
2225
  "ExpenseBot workspace links, each with a label and a description of when " +
@@ -1538,6 +2236,15 @@ const TOOLS = [
1538
2236
  "or General Settings link. Category, G/L, and account-code requests use " +
1539
2237
  "Category management; client, project, and trip groups use Group " +
1540
2238
  "management; questions about what counts as Personal use Personal rules. " +
2239
+ "For client billing setup, use the returned clientBillingHandoffs instead " +
2240
+ "of giving a generic dashboard tour: manageClients creates or manages the " +
2241
+ "client list, tagReadyExpenses opens Review Expenses filtered to blank or " +
2242
+ "default-Business rows, and createClientReport opens report creation by " +
2243
+ "group after expenses have been assigned. Choose the one next step that " +
2244
+ "matches the user's current state. If the user names a client and an exact " +
2245
+ "expense scope and asks the assistant to do the work, use search_expenses " +
2246
+ "and group_expenses instead; show its grounded preview and require explicit " +
2247
+ "confirmation before changing any rows. " +
1541
2248
  "When the user asks to choose receipt images from Google Photos, use the " +
1542
2249
  "returned Google Photos link; it opens the existing authenticated picker " +
1543
2250
  "and handles any required Google consent in ExpenseBot. When they ask " +
@@ -1574,6 +2281,7 @@ const TOOLS = [
1574
2281
  },
1575
2282
  {
1576
2283
  name: "check_feature",
2284
+ outputSchema: CHECK_OUTPUT_SCHEMA,
1577
2285
  description:
1578
2286
  "Check whether ExpenseBot supports a specific feature ('does ExpenseBot " +
1579
2287
  "support X', 'can it integrate with Y'). Searches the public knowledge " +
@@ -1619,6 +2327,7 @@ const TOOLS = [
1619
2327
  // "estimates — confirm with your tax professional" in their response.
1620
2328
  {
1621
2329
  name: "whatif_afford",
2330
+ outputSchema: WHATIF_OUTPUT_SCHEMA,
1622
2331
  description:
1623
2332
  "Can I afford $X/month? Recomputes the user's Safe Monthly Draw " +
1624
2333
  "(how much they can safely pay themselves) with an added recurring " +
@@ -1641,6 +2350,7 @@ const TOOLS = [
1641
2350
  },
1642
2351
  {
1643
2352
  name: "whatif_client",
2353
+ outputSchema: WHATIF_OUTPUT_SCHEMA,
1644
2354
  description:
1645
2355
  "What if a client pays late or leaves? mode='late30' shifts that " +
1646
2356
  "client's OPEN invoice amounts out of the near-term expectation " +
@@ -1669,6 +2379,7 @@ const TOOLS = [
1669
2379
  },
1670
2380
  {
1671
2381
  name: "whatif_tax_setaside",
2382
+ outputSchema: WHATIF_OUTPUT_SCHEMA,
1672
2383
  description:
1673
2384
  "What should I set aside for taxes? Surfaces the same monthly tax " +
1674
2385
  "set-aside estimate already computed for Safe Monthly Draw — wiring, " +
@@ -1714,6 +2425,7 @@ const TOOLS = [
1714
2425
  },
1715
2426
  {
1716
2427
  name: "get_scan_status",
2428
+ outputSchema: GET_SCAN_STATUS_OUTPUT_SCHEMA,
1717
2429
  description:
1718
2430
  "Check the authoritative status of the user's Gmail receipt scans. " +
1719
2431
  "Returns the active scan lock, the same live phase and item progress " +
@@ -1727,20 +2439,22 @@ const TOOLS = [
1727
2439
  },
1728
2440
  {
1729
2441
  name: "list_client_invoices",
2442
+ outputSchema: LIST_CLIENT_INVOICES_OUTPUT_SCHEMA,
1730
2443
  description:
1731
2444
  "List the user's issued client invoices (accounts receivable) — who owes " +
1732
2445
  "them money, how much, and when it is due. Examples: 'which invoices are " +
1733
2446
  "outstanding', 'what does Acme still owe me', 'any overdue invoices', " +
1734
- "'how much am I waiting to get paid'. status accepts 'open' (default), " +
1735
- "'paid', or 'all'. Read-only — it does not create, send, or mark invoices paid.",
2447
+ "'how much am I waiting to get paid'. status accepts 'active' (default), " +
2448
+ "'open', 'overdue', 'needs_review', 'paid', 'void', 'superseded', or 'all'. " +
2449
+ "Returns invoice numbers, status, totals by currency, delivery state, and private document links. Read-only.",
1736
2450
  inputSchema: {
1737
2451
  type: "object",
1738
2452
  properties: {
1739
2453
  clientEmail: CLIENT_EMAIL_SCHEMA,
1740
2454
  status: {
1741
2455
  type: "string",
1742
- enum: ["open", "paid", "all"],
1743
- description: "Filter by invoice status (default open).",
2456
+ enum: ["active", "open", "overdue", "needs_review", "paid", "void", "superseded", "all"],
2457
+ description: "Filter by invoice status (default active/outstanding).",
1744
2458
  },
1745
2459
  clientName: {
1746
2460
  type: "string",
@@ -1753,8 +2467,157 @@ const TOOLS = [
1753
2467
  },
1754
2468
  },
1755
2469
  },
2470
+ {
2471
+ name: "get_client_invoice",
2472
+ outputSchema: GET_CLIENT_INVOICE_OUTPUT_SCHEMA,
2473
+ description:
2474
+ "Get the full financial and delivery summary for one issued client invoice, " +
2475
+ "including subtotal, markup, tax, advance applied, balance due, dates, status, " +
2476
+ "source report, and private Google Doc/PDF/DOCX links when available. Provide " +
2477
+ "invoiceId or invoiceNumber — one is required; invoiceNumber is accepted only " +
2478
+ "when it is unique. Read-only.",
2479
+ inputSchema: {
2480
+ type: "object",
2481
+ properties: {
2482
+ clientEmail: CLIENT_EMAIL_SCHEMA,
2483
+ invoiceId: {
2484
+ type: "string",
2485
+ description: "Stable invoice ID from list_client_invoices. Required unless invoiceNumber is supplied.",
2486
+ },
2487
+ invoiceNumber: {
2488
+ type: "string",
2489
+ description: "Human invoice number when invoiceId is unavailable; it must identify one unique invoice.",
2490
+ },
2491
+ },
2492
+ },
2493
+ },
2494
+ {
2495
+ name: "prepare_client_invoice",
2496
+ description:
2497
+ "Prepare a client invoice from a saved ExpenseBot report without creating it. " +
2498
+ "Reads canonical report rows, allocates a unique invoice number, verifies the " +
2499
+ "client ledger identity and advance, and returns exact totals plus a short-lived " +
2500
+ "preparationId. Call this first, show the preview to the user, then call " +
2501
+ "create_client_invoice after explicit confirmation. It reserves the invoice number " +
2502
+ "and preview for 30 minutes but creates no invoice, document, Income row, email, or payment.",
2503
+ inputSchema: {
2504
+ type: "object",
2505
+ properties: {
2506
+ reportId: { type: "string", description: "Saved ExpenseBot report ID to invoice." },
2507
+ clientName: { type: "string", description: "Full client or business name shown on the invoice." },
2508
+ issueDate: { type: "string", format: "date", description: "Calendar-valid invoice date in YYYY-MM-DD format." },
2509
+ receiptIds: { type: "array", items: { type: "string" }, description: "Optional exact report receipt IDs. Defaults to every current report expense." },
2510
+ invoiceNumber: { type: "string", description: "Optional custom invoice number. ExpenseBot allocates one when omitted." },
2511
+ paymentTerms: {
2512
+ type: "string",
2513
+ enum: ["due_on_receipt", "net7", "net14", "net15", "net30", "net45", "net60"],
2514
+ description: "Invoice due terms. Defaults to the client's billing profile or net30.",
2515
+ },
2516
+ clientAddress: {
2517
+ type: "string",
2518
+ description: "Optional billing address printed in the invoice's Bill To section.",
2519
+ },
2520
+ billToEmail: { type: "string", description: "Optional client email printed on the invoice. This does not send email." },
2521
+ markupPct: { type: "number", minimum: 0, maximum: 100, description: "Markup applied only to rebilled expense rows." },
2522
+ taxPct: {
2523
+ type: "number",
2524
+ minimum: 0,
2525
+ maximum: 100,
2526
+ description: "Tax percentage applied after markup and custom line items; use 0 for no tax.",
2527
+ },
2528
+ taxLabel: { type: "string", description: "Tax label such as HST, GST, or VAT." },
2529
+ advanceApplied: { type: "number", minimum: 0, description: "Verified client advance to apply against this invoice." },
2530
+ customLineItems: {
2531
+ type: "array",
2532
+ maxItems: 25,
2533
+ items: {
2534
+ type: "object",
2535
+ properties: {
2536
+ description: {
2537
+ type: "string",
2538
+ description: "User-approved fee or service description shown on the invoice.",
2539
+ },
2540
+ amount: {
2541
+ type: "number",
2542
+ exclusiveMinimum: 0,
2543
+ description: "Positive amount for this fee or service line in the invoice currency.",
2544
+ },
2545
+ },
2546
+ required: ["description", "amount"],
2547
+ },
2548
+ description: "Optional fee/service lines. They are taxed but never marked up.",
2549
+ },
2550
+ mentionSupportingReceipts: {
2551
+ type: "boolean",
2552
+ description: "When true, note on the invoice that supporting receipts are available.",
2553
+ },
2554
+ },
2555
+ required: ["reportId", "clientName", "issueDate"],
2556
+ },
2557
+ },
2558
+ {
2559
+ name: "create_client_invoice",
2560
+ description:
2561
+ "Create the exact invoice previously returned by prepare_client_invoice. This is " +
2562
+ "a confirmed write: it revalidates the report snapshot and client identity, creates " +
2563
+ "a private editable Google Doc plus private PDF and DOCX copies, records the issued " +
2564
+ "invoice, and supersedes an older active invoice for the same report. It does not " +
2565
+ "send email or create an Income row. If tax is positive, confirmTax must be true.",
2566
+ inputSchema: {
2567
+ type: "object",
2568
+ properties: {
2569
+ preparationId: { type: "string", description: "Short-lived ID returned by prepare_client_invoice." },
2570
+ reportId: { type: "string", description: "In in-app chat, the saved report ID to prepare and confirm." },
2571
+ clientName: { type: "string", description: "In in-app chat, the full client name shown on the invoice." },
2572
+ issueDate: { type: "string", format: "date", description: "In in-app chat, a calendar-valid YYYY-MM-DD invoice date." },
2573
+ receiptIds: { type: "array", items: { type: "string" } },
2574
+ invoiceNumber: { type: "string" },
2575
+ paymentTerms: { type: "string", enum: ["due_on_receipt", "net7", "net14", "net15", "net30", "net45", "net60"] },
2576
+ clientAddress: { type: "string" },
2577
+ billToEmail: { type: "string" },
2578
+ markupPct: { type: "number", minimum: 0, maximum: 100 },
2579
+ taxPct: { type: "number", minimum: 0, maximum: 100 },
2580
+ taxLabel: { type: "string" },
2581
+ advanceApplied: { type: "number", minimum: 0 },
2582
+ customLineItems: {
2583
+ type: "array",
2584
+ maxItems: 25,
2585
+ items: {
2586
+ type: "object",
2587
+ properties: {
2588
+ description: { type: "string" },
2589
+ amount: { type: "number", exclusiveMinimum: 0 },
2590
+ },
2591
+ required: ["description", "amount"],
2592
+ },
2593
+ },
2594
+ mentionSupportingReceipts: { type: "boolean" },
2595
+ confirmTax: { type: "boolean", description: "True only after the user confirms the displayed tax label and rate." },
2596
+ operationId: { type: "string", description: "Optional retry key. Reuse it after an uncertain response." },
2597
+ },
2598
+ },
2599
+ },
2600
+ {
2601
+ name: "mark_client_invoice_paid",
2602
+ description:
2603
+ "Mark an issued client invoice as paid after explicit confirmation. Requires " +
2604
+ "a strict calendar-valid paidDate in YYYY-MM-DD format. This updates the " +
2605
+ "accounts-receivable invoice record only; it never creates or moves an Income " +
2606
+ "row. Record the actual payment separately or link an existing Income row.",
2607
+ inputSchema: {
2608
+ type: "object",
2609
+ properties: {
2610
+ invoiceId: { type: "string", description: "Stable invoice ID from list_client_invoices." },
2611
+ paidDate: { type: "string", format: "date", description: "Calendar-valid payment date in YYYY-MM-DD format." },
2612
+ paidAmount: { type: "number", minimum: 0, description: "Optional amount received." },
2613
+ paidVia: { type: "string", description: "Optional payment method or source, such as bank transfer or check." },
2614
+ },
2615
+ required: ["invoiceId", "paidDate"],
2616
+ },
2617
+ },
1756
2618
  {
1757
2619
  name: "get_expense_splits",
2620
+ outputSchema: GET_EXPENSE_SPLITS_OUTPUT_SCHEMA,
1758
2621
  description:
1759
2622
  "Show how an expense was split across categories, clients, properties, or " +
1760
2623
  "business vs personal portions. Returns the single parent payment with its " +
@@ -1772,15 +2635,18 @@ const TOOLS = [
1772
2635
  },
1773
2636
  dateRange: {
1774
2637
  description:
1775
- "Optional window to search for split expenses. Both bounds inclusive, YYYY-MM-DD.",
2638
+ "Optional open-ended or closed window to search for split expenses. Supply startDate, endDate, or both; supplied bounds are inclusive YYYY-MM-DD dates.",
1776
2639
  type: "object",
2640
+ additionalProperties: false,
1777
2641
  properties: {
1778
2642
  startDate: {
1779
2643
  type: "string",
2644
+ format: "date",
1780
2645
  description: "Inclusive start date in YYYY-MM-DD format.",
1781
2646
  },
1782
2647
  endDate: {
1783
2648
  type: "string",
2649
+ format: "date",
1784
2650
  description: "Inclusive end date in YYYY-MM-DD format.",
1785
2651
  },
1786
2652
  },
@@ -1799,6 +2665,7 @@ const TOOLS = [
1799
2665
  },
1800
2666
  {
1801
2667
  name: "get_monthly_books_review",
2668
+ outputSchema: GET_MONTHLY_BOOKS_REVIEW_OUTPUT_SCHEMA,
1802
2669
  description:
1803
2670
  "Month-end summary of the user's books for one calendar month: income " +
1804
2671
  "recorded, money spent, net, top spending categories and merchants, plus " +
@@ -1822,6 +2689,7 @@ const TOOLS = [
1822
2689
  },
1823
2690
  {
1824
2691
  name: "get_credits_refunds",
2692
+ outputSchema: GET_CREDITS_REFUNDS_OUTPUT_SCHEMA,
1825
2693
  description:
1826
2694
  "List card refunds, cashback/rewards, and statement credits that " +
1827
2695
  "ExpenseBot has already recorded — either as negative expenses or matched " +
@@ -1835,15 +2703,18 @@ const TOOLS = [
1835
2703
  clientEmail: CLIENT_EMAIL_SCHEMA,
1836
2704
  dateRange: {
1837
2705
  description:
1838
- "Optional window to narrow results. Both bounds inclusive, YYYY-MM-DD.",
2706
+ "Optional open-ended or closed window to narrow results. Supply startDate, endDate, or both; supplied bounds are inclusive YYYY-MM-DD dates.",
1839
2707
  type: "object",
2708
+ additionalProperties: false,
1840
2709
  properties: {
1841
2710
  startDate: {
1842
2711
  type: "string",
2712
+ format: "date",
1843
2713
  description: "Inclusive start date in YYYY-MM-DD format.",
1844
2714
  },
1845
2715
  endDate: {
1846
2716
  type: "string",
2717
+ format: "date",
1847
2718
  description: "Inclusive end date in YYYY-MM-DD format.",
1848
2719
  },
1849
2720
  },
@@ -1857,9 +2728,10 @@ const TOOLS = [
1857
2728
  },
1858
2729
  {
1859
2730
  name: "get_client_advance_balances",
2731
+ outputSchema: GET_CLIENT_ADVANCE_BALANCES_OUTPUT_SCHEMA,
1860
2732
  description:
1861
- "Read the same per-client advance balances shown in ExpenseBot's Open " +
1862
- "Balances section. Use for questions like 'how much of Acme's advance " +
2733
+ "Read the same per-client advance balances shown in ExpenseBot's Client " +
2734
+ "advances section. Use for questions like 'how much of Acme's advance " +
1863
2735
  "remains?', 'which client floats are still open?', or 'do I owe a client " +
1864
2736
  "a refund?'. A negative ledger balance means money remains to refund; a " +
1865
2737
  "positive balance means the client owes the user. Returns the existing " +
@@ -1872,19 +2744,14 @@ const TOOLS = [
1872
2744
  clientName: {
1873
2745
  type: "string",
1874
2746
  description:
1875
- "Optional client name or canonical Client tag. Omit to list all open balances.",
1876
- },
1877
- days: {
1878
- type: "integer",
1879
- minimum: 30,
1880
- maximum: 3650,
1881
- description: "Lookback window in days (default 365).",
2747
+ "Optional client name or canonical Client tag. Omit to list every open balance backed by a recorded client advance.",
1882
2748
  },
1883
2749
  },
1884
2750
  },
1885
2751
  },
1886
2752
  {
1887
2753
  name: "get_trip_suggestions",
2754
+ outputSchema: GET_TRIP_SUGGESTIONS_OUTPUT_SCHEMA,
1888
2755
  description:
1889
2756
  "Show ExpenseBot's current high-confidence Trip Intelligence proposals from Review Expenses. Read-only: never groups, tags, creates reports, or writes to the spreadsheet. Each proposal returns strict YYYY-MM-DD dates, evidence, locations, and the exact Receipt IDs with expected current tags. Do not infer a client/project from geography. When nextAction is present, use exactly its group_expenses params with confirm:false, show the canonical preview, then ask for explicit confirmation before any write. Never send confirm:true from this read result alone. In accountant clientEmail mode this tool can read accepted clients but may return no executable nextAction; hand off to Review Expenses or the owner's own assistant connection to apply.",
1890
2757
  inputSchema: {
@@ -1919,8 +2786,13 @@ const TOOLS = [
1919
2786
  group: {
1920
2787
  type: "object",
1921
2788
  additionalProperties: false,
2789
+ description: "The user-named destination group to apply to every eligible selected expense.",
1922
2790
  properties: {
1923
- kind: { type: "string", enum: ["client", "project", "trip", "job", "group"] },
2791
+ kind: {
2792
+ type: "string",
2793
+ enum: ["client", "project", "trip", "job", "group"],
2794
+ description: "How to label the destination in user-facing confirmation text.",
2795
+ },
1924
2796
  name: { type: "string", description: "The group name in the user's own words." },
1925
2797
  },
1926
2798
  required: ["kind", "name"],
@@ -1928,11 +2800,13 @@ const TOOLS = [
1928
2800
  selection: {
1929
2801
  type: "object",
1930
2802
  additionalProperties: false,
2803
+ description: "Exact expenses returned by search_expenses and approved for this bounded operation.",
1931
2804
  properties: {
1932
2805
  items: {
1933
2806
  type: "array",
1934
2807
  minItems: 1,
1935
2808
  maxItems: 500,
2809
+ description: "One exact receipt identity per selected expense; never broaden this list after preview.",
1936
2810
  items: {
1937
2811
  type: "object",
1938
2812
  additionalProperties: false,
@@ -1941,7 +2815,13 @@ const TOOLS = [
1941
2815
  expected: {
1942
2816
  type: "object",
1943
2817
  additionalProperties: false,
1944
- properties: { tag: { type: "string" } },
2818
+ description: "Optional current state copied from search results for conflict detection.",
2819
+ properties: {
2820
+ tag: {
2821
+ type: "string",
2822
+ description: "Current group/tag value observed before preview; an empty string means ungrouped.",
2823
+ },
2824
+ },
1945
2825
  },
1946
2826
  },
1947
2827
  required: ["receiptId"],
@@ -1958,7 +2838,10 @@ const TOOLS = [
1958
2838
  confirm: { type: "boolean", description: "Omit/false for preview; true only after explicit approval." },
1959
2839
  approveNewGroup: { type: "boolean", description: "True only when the preview says a new group is required." },
1960
2840
  createReport: { type: "boolean", description: "Create a report from the exact eligible grouped expenses." },
1961
- reportTitle: { type: "string" },
2841
+ reportTitle: {
2842
+ type: "string",
2843
+ description: "Optional title when createReport is true; otherwise ExpenseBot derives one from the group.",
2844
+ },
1962
2845
  excludePersonal: {
1963
2846
  type: "boolean",
1964
2847
  description: "Exclude Personal-tagged and Personal-category expenses from both grouping and the exact report.",
@@ -2042,14 +2925,22 @@ const TOOLS = [
2042
2925
  type: {
2043
2926
  type: "string",
2044
2927
  enum: ["category", "businessPurpose", "attendees"],
2928
+ description: "The one correction kind to apply to every exact selected expense.",
2929
+ },
2930
+ category: {
2931
+ type: "string",
2932
+ description: "Configured expense category to apply when type is category.",
2933
+ },
2934
+ businessPurpose: {
2935
+ type: "string",
2936
+ description: "User-supplied business purpose to apply when type is businessPurpose.",
2045
2937
  },
2046
- category: { type: "string" },
2047
- businessPurpose: { type: "string" },
2048
2938
  attendees: {
2049
2939
  type: "array",
2050
2940
  minItems: 1,
2051
2941
  maxItems: 25,
2052
2942
  items: { type: "string" },
2943
+ description: "Attendee names explicitly supplied by the user when type is attendees; never infer names.",
2053
2944
  },
2054
2945
  attendeeMode: {
2055
2946
  type: "string",
@@ -2063,11 +2954,13 @@ const TOOLS = [
2063
2954
  selection: {
2064
2955
  type: "object",
2065
2956
  additionalProperties: false,
2957
+ description: "Exact expenses returned by search_expenses and approved for this bounded correction.",
2066
2958
  properties: {
2067
2959
  items: {
2068
2960
  type: "array",
2069
2961
  minItems: 1,
2070
2962
  maxItems: 100,
2963
+ description: "One exact receipt identity per selected expense; never broaden this list after preview.",
2071
2964
  items: {
2072
2965
  type: "object",
2073
2966
  additionalProperties: false,
@@ -2083,8 +2976,14 @@ const TOOLS = [
2083
2976
  description:
2084
2977
  "Optional optimistic-concurrency values copied from the search result.",
2085
2978
  properties: {
2086
- category: { type: "string" },
2087
- notes: { type: "string" },
2979
+ category: {
2980
+ type: "string",
2981
+ description: "Current category observed before preview for conflict detection.",
2982
+ },
2983
+ notes: {
2984
+ type: "string",
2985
+ description: "Current structured Notes value observed before preview for conflict detection.",
2986
+ },
2088
2987
  },
2089
2988
  },
2090
2989
  },
@@ -2169,13 +3068,14 @@ async function handleTool(name, args) {
2169
3068
  };
2170
3069
 
2171
3070
  case "search_expenses":
2172
- return formatResult(
3071
+ return formatResultWithSchema(
3072
+ "search_expenses",
2173
3073
  await client.execute("query_expenses", args)
2174
3074
  );
2175
3075
 
2176
3076
  case "get_spending_summary": {
2177
3077
  const { clientEmail: _clientEmail, ...businessArgs } = args;
2178
- return formatResult(
3078
+ return formatResultWithSchema(name,
2179
3079
  await client.execute("query_analytics", {
2180
3080
  ...args,
2181
3081
  message: args.query || JSON.stringify(businessArgs),
@@ -2184,7 +3084,7 @@ async function handleTool(name, args) {
2184
3084
  }
2185
3085
 
2186
3086
  case "get_deep_analytics":
2187
- return formatResult(
3087
+ return formatResultWithSchema(name,
2188
3088
  await client.execute("query_analytics", {
2189
3089
  ...args,
2190
3090
  message: args.query,
@@ -2193,24 +3093,24 @@ async function handleTool(name, args) {
2193
3093
  );
2194
3094
 
2195
3095
  case "create_report":
2196
- return formatResult(await client.execute("create_report", args));
3096
+ return formatResultWithSchema(name, await client.execute("create_report", args));
2197
3097
 
2198
3098
  case "list_reports":
2199
- return formatResult(await client.execute("list_reports", args));
3099
+ return formatResultWithSchema(name, await client.execute("list_reports", args));
2200
3100
 
2201
3101
  case "request_accounting_integration":
2202
- return formatResult(
3102
+ return formatResultWithSchema(name,
2203
3103
  await client.execute("request_accounting_integration", args)
2204
3104
  );
2205
3105
 
2206
3106
  case "get_report_details":
2207
- return formatResult(await client.execute("get_report_details", args));
3107
+ return formatResultWithSchema(name, await client.execute("get_report_details", args));
2208
3108
 
2209
3109
  case "share_report":
2210
- return formatResult(await client.execute("share_report", args));
3110
+ return formatResultWithSchema(name, await client.execute("share_report", args));
2211
3111
 
2212
3112
  case "check_compliance":
2213
- return formatResult(
3113
+ return formatResultWithSchema(name,
2214
3114
  await client.execute("help_compliance", {
2215
3115
  reportId: args.reportId,
2216
3116
  userRequest: args.userRequest,
@@ -2218,10 +3118,10 @@ async function handleTool(name, args) {
2218
3118
  );
2219
3119
 
2220
3120
  case "fix_compliance":
2221
- return formatResult(await client.execute("batch_fix", args));
3121
+ return formatResultWithSchema(name, await client.execute("batch_fix", args));
2222
3122
 
2223
3123
  case "check_tax_deductibility":
2224
- return formatResult(
3124
+ return formatResultWithSchema(name,
2225
3125
  await client.execute("tax_query", {
2226
3126
  message: args.query,
2227
3127
  category: args.category,
@@ -2230,17 +3130,28 @@ async function handleTool(name, args) {
2230
3130
  );
2231
3131
 
2232
3132
  case "search_knowledge":
2233
- // Works in both modes — falls back to public /api/discover when no client
3133
+ // Works in both modes. The public MCP endpoint returns the same contract
3134
+ // as the authenticated action; the legacy /api/discover response does not.
2234
3135
  if (onboardingMode) {
2235
3136
  try {
2236
- const url = new URL("/api/discover", "https://www.expensebot.ai");
2237
- url.searchParams.set("query", args?.query || "");
2238
- url.searchParams.set("utm_source", "mcp-onboarding");
3137
+ const url = new URL(
3138
+ "/api/mcp/public/execute",
3139
+ process.env.EXPENSEBOT_API_BASE || "https://www.expensebot.ai"
3140
+ );
2239
3141
  const res = await fetch(url.toString(), {
2240
- headers: { "User-Agent": "expensebot-mcp-auth/onboarding" },
3142
+ method: "POST",
3143
+ headers: {
3144
+ "Content-Type": "application/json",
3145
+ "User-Agent": "expensebot-mcp-auth/onboarding",
3146
+ },
3147
+ body: JSON.stringify({
3148
+ actionId: "search_knowledge",
3149
+ params: args,
3150
+ }),
2241
3151
  });
3152
+ if (!res.ok) throw new Error(`API error ${res.status}`);
2242
3153
  const data = await res.json();
2243
- return formatResult(data);
3154
+ return formatResultWithSchema("search_knowledge", data);
2244
3155
  } catch (err) {
2245
3156
  return {
2246
3157
  content: [{ type: "text", text: `Search failed: ${err.message}` }],
@@ -2248,17 +3159,23 @@ async function handleTool(name, args) {
2248
3159
  };
2249
3160
  }
2250
3161
  }
2251
- return formatResult(
3162
+ return formatResultWithSchema(
3163
+ "search_knowledge",
2252
3164
  await client.execute("search_knowledge", args)
2253
3165
  );
2254
3166
 
2255
3167
  case "submit_receipt":
2256
- return formatResult(
2257
- await client.execute("submit_receipt", args)
3168
+ return formatResultWithSchema(name,
3169
+ await client.execute("submit_receipt", {
3170
+ ...args,
3171
+ photo: args.photo ?? args.photoBase64,
3172
+ photoBase64: undefined,
3173
+ })
2258
3174
  );
2259
3175
 
2260
3176
  case "get_last_receipt_result":
2261
- return formatResult(
3177
+ return formatResultWithSchema(
3178
+ "get_last_receipt_result",
2262
3179
  await client.execute("get_last_receipt_result", {
2263
3180
  submissionId: args.submissionId,
2264
3181
  withinSeconds: args.withinSeconds,
@@ -2266,20 +3183,23 @@ async function handleTool(name, args) {
2266
3183
  );
2267
3184
 
2268
3185
  case "get_spreadsheet_url":
2269
- return formatResult(await client.execute("get_spreadsheet_url", {}));
3186
+ return formatResultWithSchema(
3187
+ "get_spreadsheet_url",
3188
+ await client.execute("get_spreadsheet_url", {})
3189
+ );
2270
3190
 
2271
3191
  case "add_cash_expense":
2272
- return formatResult(
3192
+ return formatResultWithSchema(name,
2273
3193
  await client.execute("add_cash_expense", args)
2274
3194
  );
2275
3195
 
2276
3196
  case "parse_expense":
2277
- return formatResult(
3197
+ return formatResultWithSchema(name,
2278
3198
  await client.execute("parse_expense", { text: args.text })
2279
3199
  );
2280
3200
 
2281
3201
  case "process_gmail_receipts":
2282
- return formatResult(
3202
+ return formatResultWithSchema(name,
2283
3203
  await client.execute("process_gmail_receipts", {
2284
3204
  emailIds: args.emailIds,
2285
3205
  accountEmail: args.accountEmail,
@@ -2287,7 +3207,7 @@ async function handleTool(name, args) {
2287
3207
  );
2288
3208
 
2289
3209
  case "scan_gmail":
2290
- return formatResult(
3210
+ return formatResultWithSchema(name,
2291
3211
  await client.execute("scan_gmail", {
2292
3212
  lookbackDays: args.lookbackDays,
2293
3213
  startDate: args.startDate,
@@ -2297,35 +3217,47 @@ async function handleTool(name, args) {
2297
3217
  );
2298
3218
 
2299
3219
  case "add_mileage_entry":
2300
- return formatResult(await client.execute("add_mileage_entry", args));
3220
+ return formatResultWithSchema(name, await client.execute("add_mileage_entry", args));
2301
3221
 
2302
3222
  case "add_income":
2303
- return formatResult(await client.execute("add_income", args));
3223
+ return formatResultWithSchema(name, await client.execute("add_income", args));
2304
3224
 
2305
3225
  // Two-phase income import (v-next) — pass-through; the backend owns the
2306
3226
  // parse -> durable preview -> confirm -> chunked canonical write contract.
2307
3227
  case "add_income_from_file":
2308
- return formatResult(await client.execute("add_income_from_file", args));
3228
+ return formatResultWithSchema(name,
3229
+ await client.execute("add_income_from_file", {
3230
+ ...args,
3231
+ photo: args.photo ?? args.photoBase64,
3232
+ photoBase64: undefined,
3233
+ })
3234
+ );
2309
3235
 
2310
3236
  case "add_income_from_csv":
2311
- return formatResult(await client.execute("add_income_from_csv", args));
3237
+ return formatResultWithSchema(name,
3238
+ await client.execute("add_income_from_csv", {
3239
+ ...args,
3240
+ csvContent: args.csvContent ?? args.csvText,
3241
+ csvText: undefined,
3242
+ })
3243
+ );
2312
3244
 
2313
3245
  case "get_accounting_integration_status":
2314
- return formatResult(
3246
+ return formatResultWithSchema(name,
2315
3247
  await client.execute("get_accounting_integration_status", args)
2316
3248
  );
2317
3249
 
2318
3250
  case "send_report_to_accounting":
2319
- return formatResult(await client.execute("send_report_to_accounting", args));
3251
+ return formatResultWithSchema(name, await client.execute("send_report_to_accounting", args));
2320
3252
 
2321
3253
  case "get_accounting_push_status":
2322
- return formatResult(await client.execute("get_accounting_push_status", args));
3254
+ return formatResultWithSchema(name, await client.execute("get_accounting_push_status", args));
2323
3255
 
2324
3256
  case "list_categories":
2325
- return formatResult(await client.execute("list_categories", {}));
3257
+ return formatResultWithSchema(name, await client.execute("list_categories", {}));
2326
3258
 
2327
3259
  case "list_tags":
2328
- return formatResult(await client.execute("list_tags", {}));
3260
+ return formatResultWithSchema(name, await client.execute("list_tags", {}));
2329
3261
 
2330
3262
  // ── Income & P&L analytics (v0.6.0) — proxy to query_analytics ──
2331
3263
  case "get_income_summary": {
@@ -2337,7 +3269,7 @@ async function handleTool(name, args) {
2337
3269
  if (args.groupBy) {
2338
3270
  q = `${q} grouped by ${args.groupBy}`;
2339
3271
  }
2340
- return formatResult(
3272
+ return formatResultWithSchema(name,
2341
3273
  await client.execute("query_analytics", {
2342
3274
  ...args,
2343
3275
  message: q,
@@ -2347,7 +3279,7 @@ async function handleTool(name, args) {
2347
3279
  }
2348
3280
 
2349
3281
  case "get_pnl":
2350
- return formatResult(
3282
+ return formatResultWithSchema(name,
2351
3283
  await client.execute("query_analytics", {
2352
3284
  ...args,
2353
3285
  message: args.query || "P&L summary",
@@ -2360,7 +3292,7 @@ async function handleTool(name, args) {
2360
3292
  if (args.tagPrefix) {
2361
3293
  q = `${q} (limit to tag prefix '${args.tagPrefix}')`;
2362
3294
  }
2363
- return formatResult(
3295
+ return formatResultWithSchema(name,
2364
3296
  await client.execute("query_analytics", {
2365
3297
  ...args,
2366
3298
  message: q,
@@ -2370,12 +3302,12 @@ async function handleTool(name, args) {
2370
3302
  }
2371
3303
 
2372
3304
  case "list_income_categories":
2373
- return formatResult(
3305
+ return formatResultWithSchema(name,
2374
3306
  await client.execute("list_income_categories", {})
2375
3307
  );
2376
3308
 
2377
3309
  case "get_recent_activity":
2378
- return formatResult(
3310
+ return formatResultWithSchema(name,
2379
3311
  await client.execute("get_recent_activity", {
2380
3312
  limit: args.limit || 20,
2381
3313
  sinceDays: args.sinceDays || 7,
@@ -2384,7 +3316,7 @@ async function handleTool(name, args) {
2384
3316
  );
2385
3317
 
2386
3318
  case "trace_document":
2387
- return formatResult(
3319
+ return formatResultWithSchema(name,
2388
3320
  await client.execute("trace_document", {
2389
3321
  query: args.query,
2390
3322
  receiptId: args.receiptId,
@@ -2402,7 +3334,7 @@ async function handleTool(name, args) {
2402
3334
  case "get_mileage_summary": {
2403
3335
  let q = args.query || "mileage summary";
2404
3336
  if (args.groupBy) q = `${q} grouped by ${args.groupBy}`;
2405
- return formatResult(
3337
+ return formatResultWithSchema(name,
2406
3338
  await client.execute("query_analytics", {
2407
3339
  ...args,
2408
3340
  message: q,
@@ -2416,7 +3348,7 @@ async function handleTool(name, args) {
2416
3348
  if (args.focus && args.focus !== "all") {
2417
3349
  q = `${q} (focus: ${args.focus})`;
2418
3350
  }
2419
- return formatResult(
3351
+ return formatResultWithSchema(name,
2420
3352
  await client.execute("query_analytics", {
2421
3353
  ...args,
2422
3354
  message: q,
@@ -2427,7 +3359,7 @@ async function handleTool(name, args) {
2427
3359
 
2428
3360
  // ── Read-only mutation helpers (v0.7.0) ──
2429
3361
  case "get_expense_by_id":
2430
- return formatResult(
3362
+ return formatResultWithSchema(name,
2431
3363
  await client.execute("get_expense_by_id", {
2432
3364
  rowNumber: args.rowNumber,
2433
3365
  expenseId: args.expenseId,
@@ -2435,7 +3367,7 @@ async function handleTool(name, args) {
2435
3367
  );
2436
3368
 
2437
3369
  case "export_report":
2438
- return formatResult(
3370
+ return formatResultWithSchema(name,
2439
3371
  await client.execute("export_report", { reportId: args.reportId })
2440
3372
  );
2441
3373
 
@@ -2459,7 +3391,7 @@ async function handleTool(name, args) {
2459
3391
  ],
2460
3392
  };
2461
3393
  }
2462
- return formatResult(await client.execute("get_pricing", {}));
3394
+ return formatResultWithSchema(name, await client.execute("get_pricing", {}));
2463
3395
  }
2464
3396
 
2465
3397
  case "check_feature": {
@@ -2473,7 +3405,7 @@ async function handleTool(name, args) {
2473
3405
  headers: { "User-Agent": "expensebot-mcp-auth/0.6.0" },
2474
3406
  });
2475
3407
  const data = await res.json();
2476
- return formatResult(data);
3408
+ return formatResultWithSchema(name, data);
2477
3409
  } catch (err) {
2478
3410
  return {
2479
3411
  content: [{ type: "text", text: `Feature check failed: ${err.message}` }],
@@ -2481,7 +3413,7 @@ async function handleTool(name, args) {
2481
3413
  };
2482
3414
  }
2483
3415
  }
2484
- return formatResult(
3416
+ return formatResultWithSchema(name,
2485
3417
  await client.execute("check_feature", { feature: args.feature })
2486
3418
  );
2487
3419
  }
@@ -2508,20 +3440,20 @@ async function handleTool(name, args) {
2508
3440
 
2509
3441
  // ── Pulse CFO Slice 4 — What-If ──
2510
3442
  case "whatif_afford":
2511
- return formatResult(
3443
+ return formatResultWithSchema(name,
2512
3444
  await client.execute("whatif_afford", { deltaMonthly: args.deltaMonthly })
2513
3445
  );
2514
3446
 
2515
3447
  case "whatif_client":
2516
- return formatResult(
3448
+ return formatResultWithSchema(name,
2517
3449
  await client.execute("whatif_client", { clientName: args.clientName, mode: args.mode })
2518
3450
  );
2519
3451
 
2520
3452
  case "whatif_tax_setaside":
2521
- return formatResult(await client.execute("whatif_tax_setaside", {}));
3453
+ return formatResultWithSchema(name, await client.execute("whatif_tax_setaside", {}));
2522
3454
 
2523
3455
  case "scan_gmail_years":
2524
- return formatResult(
3456
+ return formatResultWithSchema(name,
2525
3457
  await client.execute("scan_gmail_years", {
2526
3458
  years: args.years,
2527
3459
  accountEmail: args.accountEmail,
@@ -2530,10 +3462,10 @@ async function handleTool(name, args) {
2530
3462
  );
2531
3463
 
2532
3464
  case "get_scan_status":
2533
- return formatResult(await client.execute("get_scan_status", {}));
3465
+ return formatResultWithSchema(name, await client.execute("get_scan_status", {}));
2534
3466
 
2535
3467
  case "list_client_invoices":
2536
- return formatResult(
3468
+ return formatResultWithSchema(name,
2537
3469
  await client.execute("list_client_invoices", {
2538
3470
  clientEmail: args.clientEmail,
2539
3471
  status: args.status,
@@ -2542,8 +3474,44 @@ async function handleTool(name, args) {
2542
3474
  })
2543
3475
  );
2544
3476
 
3477
+ case "get_client_invoice":
3478
+ return formatResultWithSchema(name,
3479
+ await client.execute("get_client_invoice", {
3480
+ clientEmail: args.clientEmail,
3481
+ invoiceId: args.invoiceId,
3482
+ invoiceNumber: args.invoiceNumber,
3483
+ })
3484
+ );
3485
+
3486
+ case "prepare_client_invoice":
3487
+ return formatResultWithSchema(name,
3488
+ await client.execute("prepare_client_invoice", {
3489
+ ...args,
3490
+ })
3491
+ );
3492
+
3493
+ case "create_client_invoice":
3494
+ return formatResultWithSchema(name,
3495
+ await client.execute("create_client_invoice", {
3496
+ clientEmail: args.clientEmail,
3497
+ preparationId: args.preparationId,
3498
+ confirmTax: args.confirmTax,
3499
+ operationId: args.operationId,
3500
+ })
3501
+ );
3502
+
3503
+ case "mark_client_invoice_paid":
3504
+ return formatResultWithSchema(name,
3505
+ await client.execute("mark_client_invoice_paid", {
3506
+ invoiceId: args.invoiceId,
3507
+ paidDate: args.paidDate,
3508
+ paidAmount: args.paidAmount,
3509
+ paidVia: args.paidVia,
3510
+ })
3511
+ );
3512
+
2545
3513
  case "get_expense_splits":
2546
- return formatResult(
3514
+ return formatResultWithSchema(name,
2547
3515
  await client.execute("get_expense_splits", {
2548
3516
  clientEmail: args.clientEmail,
2549
3517
  receiptId: args.receiptId,
@@ -2554,7 +3522,7 @@ async function handleTool(name, args) {
2554
3522
  );
2555
3523
 
2556
3524
  case "get_monthly_books_review":
2557
- return formatResult(
3525
+ return formatResultWithSchema(name,
2558
3526
  await client.execute("get_monthly_books_review", {
2559
3527
  clientEmail: args.clientEmail,
2560
3528
  period: args.period,
@@ -2562,7 +3530,7 @@ async function handleTool(name, args) {
2562
3530
  );
2563
3531
 
2564
3532
  case "get_credits_refunds":
2565
- return formatResult(
3533
+ return formatResultWithSchema(name,
2566
3534
  await client.execute("get_credits_refunds", {
2567
3535
  clientEmail: args.clientEmail,
2568
3536
  dateRange: args.dateRange,
@@ -2571,16 +3539,15 @@ async function handleTool(name, args) {
2571
3539
  );
2572
3540
 
2573
3541
  case "get_client_advance_balances":
2574
- return formatResult(
3542
+ return formatResultWithSchema(name,
2575
3543
  await client.execute("get_client_advance_balances", {
2576
3544
  clientEmail: args.clientEmail,
2577
3545
  clientName: args.clientName,
2578
- days: args.days,
2579
3546
  })
2580
3547
  );
2581
3548
 
2582
3549
  case "group_expenses":
2583
- return formatResult(
3550
+ return formatResultWithSchema(name,
2584
3551
  await client.execute("group_expenses", {
2585
3552
  group: args.group,
2586
3553
  selection: args.selection,
@@ -2598,7 +3565,7 @@ async function handleTool(name, args) {
2598
3565
  );
2599
3566
 
2600
3567
  case "get_trip_suggestions":
2601
- return formatResult(
3568
+ return formatResultWithSchema(name,
2602
3569
  await client.execute("get_trip_suggestions", {
2603
3570
  clientEmail: args.clientEmail,
2604
3571
  limit: args.limit,
@@ -2606,7 +3573,7 @@ async function handleTool(name, args) {
2606
3573
  );
2607
3574
 
2608
3575
  case "correct_expenses":
2609
- return formatResult(
3576
+ return formatResultWithSchema(name,
2610
3577
  await client.execute("correct_expenses", {
2611
3578
  change: args.change,
2612
3579
  selection: args.selection,
@@ -2618,7 +3585,7 @@ async function handleTool(name, args) {
2618
3585
  );
2619
3586
 
2620
3587
  case "update_expense":
2621
- return formatResult(
3588
+ return formatResultWithSchema(name,
2622
3589
  await client.execute("update_expense", {
2623
3590
  expenseId: args.expenseId,
2624
3591
  fields: args.fields,
@@ -2722,9 +3689,30 @@ function formatResult(result) {
2722
3689
 
2723
3690
  // ── MCP Server Setup ───────────────────────────────────────────────────
2724
3691
 
3692
+ const OUTPUT_SCHEMA_BY_TOOL = new Map(
3693
+ TOOLS.filter((tool) => tool.outputSchema).map((tool) => [
3694
+ tool.name,
3695
+ tool.outputSchema,
3696
+ ])
3697
+ );
3698
+
3699
+ function formatResultWithSchema(toolName, result) {
3700
+ const formatted = formatResult(result);
3701
+ if (
3702
+ !formatted.isError &&
3703
+ OUTPUT_SCHEMA_BY_TOOL.has(toolName) &&
3704
+ result &&
3705
+ typeof result === "object" &&
3706
+ !Array.isArray(result)
3707
+ ) {
3708
+ formatted.structuredContent = result;
3709
+ }
3710
+ return formatted;
3711
+ }
3712
+
2725
3713
  async function main() {
2726
3714
  const server = new Server(
2727
- { name: "expensebot-auth", version: "0.6.22" },
3715
+ { name: "expensebot-auth", version: "0.6.23" },
2728
3716
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
2729
3717
  );
2730
3718