@teamnetwork-nz/xero-mcp-server 1.14.0 → 1.14.2

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/README.md CHANGED
@@ -151,6 +151,7 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
151
151
  | `list-invoices` | List invoices with optional filters: status, contact, invoice number, date range |
152
152
  | `xero_search_transactions` | Structured search by invoice number, reference, supplier/contact, date, amount, status and type |
153
153
  | `xero_batch_invoice_lookup` | Native exact lookup for up to 100 invoice numbers with per-input duplicate/unmatched results |
154
+ | `xero_lookup_invoice` | Scalar exact invoice-number lookup for clients affected by Hermes array coercion |
154
155
  | `get-invoice` | Get full details of a single invoice including all line items |
155
156
  | `xero_get_bill_settlement` | Trace payments, credits, prepayments, overpayments and the outstanding balance |
156
157
  | `xero_get_invoice_history` | Retrieve Xero-recorded invoice/bill history events (not a complete field-level audit trail) |
@@ -231,6 +232,26 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
231
232
  | `list-aged-receivables-by-contact` | Aged receivables for a contact |
232
233
  | `list-aged-payables-by-contact` | Aged payables for a contact |
233
234
 
235
+ `list-profit-and-loss` enforces a single-calendar-month base range and returns
236
+ comparison-column metadata containing each label, MCP-derived date window, MTD flag,
237
+ `source: MCP_DERIVED`, and `verifiedCallShape: true`. Multi-month base ranges are rejected
238
+ because Xero can return misleading rolling totals. Comparison calls with `periods>=1` also
239
+ require the current calendar month as the base; completed-month comparisons are rejected.
240
+ For N completed monthly columns, request the current month with `periods=N` and ignore
241
+ the first MTD column, or make N separate calls with `periods=0`.
242
+
243
+ ### Pagination
244
+
245
+ For tools with `page` and `pageSize`, `Found N` is the count for the current page, not a
246
+ total. To retrieve the complete filtered result set, increment `page` until a page contains
247
+ fewer records than `pageSize`. `xero_search_transactions` and `xero_find_contact` expose
248
+ `pagination.complete`, `pagination.truncated`, and `pagination.nextPage` instead. Xero does
249
+ not expose a configurable page size for `list-quotes`; continue until it returns an empty page.
250
+
251
+ Attachment filenames are non-authoritative and may contain amounts that differ from the
252
+ bill's gross total. Use Xero invoice `SubTotal`, `TotalTax`, and `Total` fields for financial
253
+ reconciliation, and retrieve binary attachment content only when explicitly needed.
254
+
234
255
  ### Payroll *(requires `XERO_ENABLE_PAYROLL=true`)*
235
256
  | Tool | Description |
236
257
  |---|---|
@@ -281,7 +302,8 @@ separate `reference` search remains available for records that use that field.
281
302
  looking identifiers are intentionally not coerced to numbers. The reported Hermes
282
303
  `coerce_tool_args` defect is outside this repository and must also be corrected in
283
304
  the Hermes runtime if that client still rewrites valid JSON arrays before sending
284
- the MCP request.
305
+ the MCP request. Until then, use scalar `xero_lookup_invoice` for exact single-value
306
+ lookups or `xero_search_transactions` for broader matching.
285
307
 
286
308
  ## For Developers
287
309
 
@@ -1,6 +1,83 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { formatError } from "../helpers/format-error.js";
3
3
  import { getClientHeaders } from "../helpers/get-client-headers.js";
4
+ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
5
+ import { localDateString } from "../helpers/datetime.js";
6
+ export const PROFIT_AND_LOSS_RANGE_ERROR = "list-profit-and-loss requires fromDate and toDate to span a single calendar month; for N monthly columns, call N times with periods=0, or set fromDate=1st-of-current-month, toDate=last-day-of-current-month, periods=N and drop the first (MTD) column.";
7
+ export const PROFIT_AND_LOSS_COMPARISON_ERROR = "list-profit-and-loss comparison periods require the current calendar month as the base; completed-month bases can return misleading comparison slices. Set fromDate to the first day and toDate to the last day of the current month, use periods=N, and drop the first (MTD) column, or call each completed month separately with periods=0.";
8
+ function parseDateOnly(value) {
9
+ const date = new Date(`${value}T00:00:00Z`);
10
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) {
11
+ throw new McpError(ErrorCode.InvalidParams, `Invalid date: ${value}. Expected YYYY-MM-DD.`);
12
+ }
13
+ return date;
14
+ }
15
+ export function validateProfitAndLossDateRange(fromDate, toDate, periods = 0, timeframe = "MONTH", today = localDateString()) {
16
+ if (!fromDate || !toDate)
17
+ return;
18
+ const from = parseDateOnly(fromDate);
19
+ const to = parseDateOnly(toDate);
20
+ if (to < from || from.getUTCFullYear() !== to.getUTCFullYear() || from.getUTCMonth() !== to.getUTCMonth()) {
21
+ throw new McpError(ErrorCode.InvalidParams, PROFIT_AND_LOSS_RANGE_ERROR);
22
+ }
23
+ if (periods >= 1 && (timeframe === undefined || timeframe === "MONTH")) {
24
+ const current = parseDateOnly(today);
25
+ const isCurrentCalendarMonth = from.getUTCFullYear() === current.getUTCFullYear() &&
26
+ from.getUTCMonth() === current.getUTCMonth() &&
27
+ from.getUTCDate() === 1 &&
28
+ isLastDayOfMonth(to);
29
+ if (!isCurrentCalendarMonth) {
30
+ throw new McpError(ErrorCode.InvalidParams, PROFIT_AND_LOSS_COMPARISON_ERROR);
31
+ }
32
+ }
33
+ }
34
+ function shiftDate(value, months) {
35
+ const day = value.getUTCDate();
36
+ const shifted = new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth() + months, 1));
37
+ const lastDay = new Date(Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth() + 1, 0)).getUTCDate();
38
+ shifted.setUTCDate(Math.min(day, lastDay));
39
+ return shifted;
40
+ }
41
+ function isoDate(value) {
42
+ return value.toISOString().slice(0, 10);
43
+ }
44
+ function isLastDayOfMonth(value) {
45
+ return value.getUTCDate() === new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth() + 1, 0)).getUTCDate();
46
+ }
47
+ export function buildComparisonColumnMetadata(report, fromDate, toDate, periods = 0, timeframe = "MONTH", today = localDateString()) {
48
+ if (!fromDate || !toDate)
49
+ return [];
50
+ validateProfitAndLossDateRange(fromDate, toDate, periods, timeframe, today);
51
+ const from = parseDateOnly(fromDate);
52
+ const to = parseDateOnly(toDate);
53
+ const todayDate = parseDateOnly(today);
54
+ const header = report.rows?.find((row) => String(row.rowType) === "Header" || Number(row.rowType) === 0);
55
+ const labels = header?.cells?.slice(1).map((cell) => cell.value ?? null) ?? [];
56
+ const stepMonths = timeframe === "QUARTER" ? 3 : timeframe === "YEAR" ? 12 : 1;
57
+ const fullMonthWindow = from.getUTCDate() === 1 && isLastDayOfMonth(to);
58
+ return Array.from({ length: periods + 1 }, (_, columnIndex) => {
59
+ const offset = -columnIndex * stepMonths;
60
+ const columnFrom = shiftDate(from, offset);
61
+ const shiftedTo = shiftDate(to, offset);
62
+ const requestedTo = fullMonthWindow
63
+ ? new Date(Date.UTC(shiftedTo.getUTCFullYear(), shiftedTo.getUTCMonth() + 1, 0))
64
+ : shiftedTo;
65
+ const isMonthToDate = columnIndex === 0 &&
66
+ columnFrom.getUTCDate() === 1 &&
67
+ columnFrom.getUTCFullYear() === todayDate.getUTCFullYear() &&
68
+ columnFrom.getUTCMonth() === todayDate.getUTCMonth() &&
69
+ requestedTo >= todayDate;
70
+ return {
71
+ columnIndex,
72
+ label: labels[columnIndex] ?? null,
73
+ fromDate: isoDate(columnFrom),
74
+ toDate: isoDate(isMonthToDate ? todayDate : requestedTo),
75
+ isMonthToDate,
76
+ source: "MCP_DERIVED",
77
+ verifiedCallShape: true,
78
+ };
79
+ });
80
+ }
4
81
  /**
5
82
  * Internal function to fetch profit and loss data from Xero
6
83
  */
@@ -27,6 +104,7 @@ async function fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standard
27
104
  * @param paymentsOnly Optional boolean to include only accounts with payments
28
105
  */
29
106
  export async function listXeroProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly) {
107
+ validateProfitAndLossDateRange(fromDate, toDate, periods, timeframe);
30
108
  try {
31
109
  const profitAndLoss = await fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly);
32
110
  if (!profitAndLoss) {
@@ -61,12 +61,16 @@ export function compactInvoice(invoice) {
61
61
  hasAttachments: invoice.hasAttachments ?? false,
62
62
  };
63
63
  }
64
+ export function shouldUseInvoiceSummaryOnly(params) {
65
+ return params.amount === undefined && params.minAmount === undefined && params.maxAmount === undefined;
66
+ }
64
67
  export async function searchXeroTransactions(params) {
65
68
  try {
66
69
  await xeroClient.authenticate();
67
70
  const query = buildInvoiceSearchQuery(params);
68
71
  const apiPageSize = Math.min(params.pageSize + 1, 1000);
69
- const response = await xeroClient.accountingApi.getInvoices(xeroClient.tenantId, undefined, query.where, "UpdatedDateUTC DESC", undefined, query.invoiceNumbers, query.contactIds, query.statuses, params.page, false, false, undefined, true, apiPageSize, query.searchTerm, getClientHeaders());
72
+ const summaryOnly = shouldUseInvoiceSummaryOnly(params);
73
+ const response = await xeroClient.accountingApi.getInvoices(xeroClient.tenantId, undefined, query.where, "UpdatedDateUTC DESC", undefined, query.invoiceNumbers, query.contactIds, query.statuses, params.page, false, false, undefined, summaryOnly, apiPageSize, query.searchTerm, getClientHeaders());
70
74
  const raw = response.body.invoices ?? [];
71
75
  const filtered = filterInvoiceMatches(raw, params);
72
76
  const truncated = raw.length > params.pageSize || filtered.length > params.pageSize;
@@ -0,0 +1,3 @@
1
+ export const PAGE_NUMBER_GUIDANCE = 'The "Found N" count is for the current page, not the total in Xero.';
2
+ export const PAGE_SIZE_GUIDANCE = "To retrieve all matching records, increment page until a page returns fewer than pageSize records.";
3
+ export const STRUCTURED_PAGE_GUIDANCE = "Follow pagination.nextPage while pagination.complete is false; pagination.returned is the current page count, not the total in Xero.";
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { batchXeroInvoiceLookup } from "../../handlers/batch-xero-invoice-lookup.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { jsonToolResponse } from "../../types/lookup-result.js";
5
- const BatchInvoiceLookupTool = CreateXeroTool("xero_batch_invoice_lookup", "Look up multiple exact Xero InvoiceNumber values in one native batch request. Accepts a real JSON array of strings; numeric-looking identifiers remain strings. Reports each input independently, including duplicates and unmatched values.", {
5
+ const BatchInvoiceLookupTool = CreateXeroTool("xero_batch_invoice_lookup", "Look up multiple exact Xero InvoiceNumber values in one batch request. Accepts an array of strings, preserves numeric-looking invoice numbers as strings, and reports exact matches, duplicates, and unmatched values for each input.", {
6
6
  invoiceNumbers: z.array(z.string().min(1)).min(1).max(100),
7
7
  type: z.enum(["ACCREC", "ACCPAY"]).optional(),
8
8
  }, async ({ invoiceNumbers, type }) => jsonToolResponse(await batchXeroInvoiceLookup(invoiceNumbers, type)));
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { findXeroContact } from "../../handlers/find-xero-contact.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { failedLookup, jsonToolResponse } from "../../types/lookup-result.js";
5
+ import { STRUCTURED_PAGE_GUIDANCE } from "../../helpers/pagination-guidance.js";
5
6
  const FindContactTool = CreateXeroTool("xero_find_contact", "Resolve a Xero customer or supplier using supported identifiers. Ambiguous matches are returned explicitly and never selected automatically.", {
6
7
  contactId: z.string().uuid().optional(),
7
8
  name: z.string().min(1).optional(),
@@ -11,8 +12,8 @@ const FindContactTool = CreateXeroTool("xero_find_contact", "Resolve a Xero cust
11
12
  taxNumber: z.string().min(1).optional().describe("GST/VAT/ABN/NZBN tax identifier as stored by Xero."),
12
13
  role: z.enum(["customer", "supplier"]).optional(),
13
14
  matchMode: z.enum(["exact", "contains"]).default("exact"),
14
- page: z.number().int().min(1).default(1),
15
- pageSize: z.number().int().min(1).max(50).default(10),
15
+ page: z.number().int().min(1).default(1).describe(`Page number for paginated matches. ${STRUCTURED_PAGE_GUIDANCE}`),
16
+ pageSize: z.number().int().min(1).max(50).default(10).describe(`Maximum matches returned on this page (1-50, default 10). ${STRUCTURED_PAGE_GUIDANCE}`),
16
17
  }, async (params) => {
17
18
  if (![params.contactId, params.name, params.contactNumber, params.accountNumber, params.email, params.taxNumber].some(Boolean)) {
18
19
  return jsonToolResponse(failedLookup("At least one supported contact identifier is required."));
@@ -32,6 +32,7 @@ import SearchTransactionsTool from "./search-transactions.tool.js";
32
32
  import BatchInvoiceLookupTool from "./batch-invoice-lookup.tool.js";
33
33
  import FindContactTool from "./find-contact.tool.js";
34
34
  import ListBillAttachmentsTool from "./list-bill-attachments.tool.js";
35
+ import LookupInvoiceTool from "./lookup-invoice.tool.js";
35
36
  export const CoreListTools = [
36
37
  ListAccountsTool,
37
38
  ListContactsTool,
@@ -54,6 +55,7 @@ export const CoreListTools = [
54
55
  BatchInvoiceLookupTool,
55
56
  FindContactTool,
56
57
  ListBillAttachmentsTool,
58
+ LookupInvoiceTool,
57
59
  ];
58
60
  export const ReportListTools = [
59
61
  ListTrialBalanceTool,
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
3
4
  import { listXeroBankTransactions } from "../../handlers/list-xero-bank-transactions.handler.js";
4
5
  import { formatLineItem } from "../../helpers/format-line-item.js";
5
6
  import { formatXeroDate } from "../../helpers/datetime.js";
@@ -11,14 +12,14 @@ const ListBankTransactionsTool = CreateXeroTool("list-bank-transactions", "List
11
12
  "money out → transactionType=SPEND with date range; " +
12
13
  "transfers → transactionType=SPEND-TRANSFER or RECEIVE-TRANSFER. " +
13
14
  "Always set a fromDate/toDate or isReconciled filter before paginating.", {
14
- page: z.number().describe("Page number for pagination (starts at 1)."),
15
+ page: z.number().describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
15
16
  bankAccountId: z.string().optional().describe("Filter by bank account ID. Get IDs from list-accounts."),
16
17
  fromDate: z.string().optional().describe("Transactions on or after this date (YYYY-MM-DD)."),
17
18
  toDate: z.string().optional().describe("Transactions on or before this date (YYYY-MM-DD)."),
18
19
  status: z.enum(["AUTHORISED", "DELETED", "VOIDED"]).optional().describe("Filter by status. Defaults to AUTHORISED (active transactions only). Pass DELETED or VOIDED only if you explicitly need those records."),
19
20
  isReconciled: z.boolean().optional().describe("Filter by reconciliation status. Use isReconciled=false to find unreconciled transactions. Never scan pages to find unreconciled items — use this filter."),
20
21
  transactionType: z.enum(["SPEND", "RECEIVE", "SPEND-TRANSFER", "RECEIVE-TRANSFER", "SPEND-PREPAYMENT", "RECEIVE-PREPAYMENT", "SPEND-OVERPAYMENT", "RECEIVE-OVERPAYMENT"]).optional().describe("Filter by transaction type. SPEND = money out, RECEIVE = money in, *-TRANSFER = bank transfers."),
21
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
22
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
22
23
  }, async ({ bankAccountId, page, fromDate, toDate, status, isReconciled, transactionType, pageSize }) => {
23
24
  const response = await listXeroBankTransactions(page, bankAccountId, fromDate, toDate, status, pageSize, isReconciled, transactionType);
24
25
  if (response.isError) {
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { listXeroInvoiceAttachments } from "../../handlers/list-xero-invoice-attachments.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { failedLookup, jsonToolResponse } from "../../types/lookup-result.js";
5
- const ListBillAttachmentsTool = CreateXeroTool("xero_list_bill_attachments", "List compact attachment metadata for a Xero bill or invoice. Binary content is never included; use xero_get_bill_attachment for explicit retrieval.", { invoiceId: z.string().uuid() }, async ({ invoiceId }) => {
5
+ const ListBillAttachmentsTool = CreateXeroTool("xero_list_bill_attachments", "List compact attachment metadata for a Xero bill or invoice. Attachment filenames are non-authoritative and may contain an amount different from the bill's gross total; use the Xero invoice SubTotal, TotalTax, and Total fields for reconciliation. Binary content is never included; use xero_get_bill_attachment for explicit retrieval.", { invoiceId: z.string().uuid() }, async ({ invoiceId }) => {
6
6
  const response = await listXeroInvoiceAttachments(invoiceId);
7
7
  if (response.isError)
8
8
  return jsonToolResponse(failedLookup(response.error));
@@ -1,5 +1,6 @@
1
1
  import { listXeroContacts } from "../../handlers/list-xero-contacts.handler.js";
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
3
4
  import { z } from "zod";
4
5
  import { formatUtcDatetime } from "../../helpers/datetime.js";
5
6
  const ListContactsTool = CreateXeroTool("list-contacts", "List contacts from Xero. " +
@@ -13,13 +14,13 @@ const ListContactsTool = CreateXeroTool("list-contacts", "List contacts from Xer
13
14
  "accountNumber (user-defined), taxNumber (NZBN/ABN/VAT), isCustomer/isSupplier flags, " +
14
15
  "phones (type + number, short form), addresses (type + line1/city/region/postcode/country, short form), " +
15
16
  "AR/AP tax types, defaultCurrency, contactStatus, contactGroups, and lastUpdated.", {
16
- page: z.number().optional().describe("Page number for pagination (starts at 1)."),
17
+ page: z.number().optional().describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
17
18
  searchTerm: z.string().optional().describe("Case-insensitive search across Name, FirstName, LastName, ContactNumber, EmailAddress. Use this instead of listing all contacts."),
18
19
  contactRole: z.enum(["customer", "supplier"]).optional().describe("Filter to customers only (IsCustomer==true) or suppliers only (IsSupplier==true). Use customer for AR work, supplier for AP work."),
19
20
  fromDate: z.string().optional().describe("Return contacts updated on or after this date (YYYY-MM-DD)."),
20
21
  toDate: z.string().optional().describe("Return contacts updated on or before this date (YYYY-MM-DD)."),
21
22
  status: z.enum(["ACTIVE", "ARCHIVED"]).optional().describe("Filter by contact status. Defaults to ACTIVE (excludes archived contacts). Pass ARCHIVED only if you specifically need deactivated contacts."),
22
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
23
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
23
24
  }, async (params) => {
24
25
  const { page, searchTerm, contactRole, fromDate, toDate, status, pageSize } = params;
25
26
  const response = await listXeroContacts(page, searchTerm, fromDate, toDate, status, pageSize, contactRole);
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroCreditNotes } from "../../handlers/list-xero-credit-notes.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
4
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
6
  const ListCreditNotesTool = CreateXeroTool("list-credit-notes", "List credit notes from Xero. " +
6
7
  "ACCREC = sales credit notes (issued to customers). ACCPAY = purchase credit notes (received from suppliers). " +
@@ -10,14 +11,14 @@ const ListCreditNotesTool = CreateXeroTool("list-credit-notes", "List credit not
10
11
  "supplier credits → type=ACCPAY. " +
11
12
  "Results include RemainingCredit/AppliedAmount and, where Xero returns them, the invoices " +
12
13
  "each credit note has been allocated against — no need to diff invoice Total vs AmountDue to find this.", {
13
- page: z.number().describe("Page number for pagination (starts at 1)."),
14
+ page: z.number().describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
14
15
  type: z.enum(["ACCREC", "ACCPAY"]).optional().describe("ACCREC = sales/customer credit notes. ACCPAY = purchase/supplier credit notes."),
15
16
  contactId: z.string().optional().describe("Filter by contact ID."),
16
17
  fromDate: z.string().optional().describe("Credit note date on or after this date (YYYY-MM-DD)."),
17
18
  toDate: z.string().optional().describe("Credit note date on or before this date (YYYY-MM-DD)."),
18
19
  statuses: z.array(z.enum(["DRAFT", "SUBMITTED", "AUTHORISED", "PAID", "VOIDED", "DELETED"])).optional().describe("Filter by status. Defaults to [DRAFT, SUBMITTED, AUTHORISED, PAID] — active records only. Pass VOIDED or DELETED explicitly only if those records are specifically needed."),
19
20
  hasRemainingCredit: z.boolean().optional().describe("If true, only returns credit notes with RemainingCredit>0 (i.e. not yet fully allocated). Use to find credits available to apply."),
20
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
21
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
21
22
  }, async ({ page, type, contactId, fromDate, toDate, statuses, hasRemainingCredit, pageSize }) => {
22
23
  const response = await listXeroCreditNotes(page, contactId, fromDate, toDate, statuses, pageSize, type, hasRemainingCredit);
23
24
  if (response.error !== null) {
@@ -3,6 +3,7 @@ import { listXeroInvoices } from "../../handlers/list-xero-invoices.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { formatLineItem } from "../../helpers/format-line-item.js";
5
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
6
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
6
7
  const ListInvoicesTool = CreateXeroTool("list-invoices", "List invoices from Xero. " +
7
8
  "ACCREC = sales invoices (Accounts Receivable, money owed to you). " +
8
9
  "ACCPAY = bills/purchase invoices (Accounts Payable, money you owe suppliers). " +
@@ -13,7 +14,7 @@ const ListInvoicesTool = CreateXeroTool("list-invoices", "List invoices from Xer
13
14
  "bills to pay → type=ACCPAY, statuses=[AUTHORISED], minAmountDue=0.01; " +
14
15
  "recent drafts → statuses=[DRAFT], fromDate=<date>. " +
15
16
  "Set pageSize to the minimum needed. Only paginate if the user asks for more.", {
16
- page: z.number().describe("Page number for pagination. Starts at 1."),
17
+ page: z.number().describe(`Page number for pagination. Starts at 1. ${PAGE_NUMBER_GUIDANCE}`),
17
18
  type: z.enum(["ACCREC", "ACCPAY"]).optional().describe("ACCREC = sales invoices / accounts receivable. ACCPAY = bills / accounts payable. Always set this unless you genuinely need both."),
18
19
  contactIds: z.array(z.string()).optional().describe("Filter by one or more contact IDs."),
19
20
  invoiceNumbers: z.array(z.string()).optional().describe("Filter by specific invoice numbers. Line items are included in the response when this is set."),
@@ -25,7 +26,7 @@ const ListInvoicesTool = CreateXeroTool("list-invoices", "List invoices from Xer
25
26
  toDate: z.string().optional().describe("Invoice date on or before this date (YYYY-MM-DD)."),
26
27
  minAmountDue: z.number().optional().describe("Only return invoices with AmountDue greater than this value. Use 0.01 to exclude fully paid invoices without needing to filter by date."),
27
28
  overdueOnly: z.boolean().optional().describe("If true, returns only invoices past their due date with an outstanding balance. Equivalent to AmountDue>0 AND DueDate<=today. Use with type=ACCREC and statuses=[AUTHORISED] for AR chasing."),
28
- pageSize: z.number().min(1).max(1000).optional().default(100).describe("Results per page (1–1000, default 100). Use a smaller value if you only need a few results."),
29
+ pageSize: z.number().min(1).max(1000).optional().default(100).describe(`Results per page (1-1000, default 100). Use a smaller value if you only need a few results. ${PAGE_SIZE_GUIDANCE}`),
29
30
  }, async ({ page, type, contactIds, invoiceNumbers, statuses, fromDate, toDate, minAmountDue, overdueOnly, pageSize }) => {
30
31
  const response = await listXeroInvoices(page, contactIds, invoiceNumbers, statuses, fromDate, toDate, pageSize, type, minAmountDue, overdueOnly);
31
32
  if (response.error !== null) {
@@ -1,5 +1,6 @@
1
1
  import { listXeroManualJournals } from "../../handlers/list-xero-manual-journals.handler.js";
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
3
4
  import { z } from "zod";
4
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
6
  const ListManualJournalsTool = CreateXeroTool("list-manual-journals", `List all manual journals from Xero.
@@ -16,8 +17,8 @@ If they want the next page, call this tool again with the next page number, modi
16
17
  .string()
17
18
  .optional()
18
19
  .describe("Optional date YYYY-MM-DD to filter journals modified after this date"),
19
- page: z.number().optional().describe("Optional page number for pagination"),
20
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Number of results per page (1–100, default 50)."),
20
+ page: z.number().optional().describe(`Optional page number for pagination. ${PAGE_NUMBER_GUIDANCE}`),
21
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Number of results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
21
22
  }, async (args) => {
22
23
  const response = await listXeroManualJournals(args?.page, args?.manualJournalId, args?.modifiedAfter, args?.pageSize);
23
24
  if (response.isError) {
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroOverpayments } from "../../handlers/list-xero-overpayments.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
4
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
6
  const ListOverpaymentsTool = CreateXeroTool("list-overpayments", "List overpayments from Xero. Overpayments are a SEPARATE record type from Payments — " +
6
7
  "they're created when a customer pays more than an invoice total, or a supplier is paid " +
@@ -11,13 +12,13 @@ const ListOverpaymentsTool = CreateXeroTool("list-overpayments", "List overpayme
11
12
  "Common patterns: " +
12
13
  "all overpayment activity for a contact → contactId; " +
13
14
  "unallocated overpayments still available to apply → hasRemainingCredit=true.", {
14
- page: z.number().default(1).describe("Page number for pagination (starts at 1)."),
15
+ page: z.number().default(1).describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
15
16
  contactId: z.string().optional().describe("Filter by contact ID."),
16
17
  fromDate: z.string().optional().describe("Overpayment date on or after this date (YYYY-MM-DD)."),
17
18
  toDate: z.string().optional().describe("Overpayment date on or before this date (YYYY-MM-DD)."),
18
19
  statuses: z.array(z.enum(["AUTHORISED", "PAID", "VOIDED"])).optional().describe("Filter by status. Defaults to [AUTHORISED, PAID] — active records only. Pass VOIDED explicitly only if those records are specifically needed."),
19
20
  hasRemainingCredit: z.boolean().optional().describe("If true, only returns overpayments with RemainingCredit>0 (i.e. not yet fully allocated). Use to find credit available to apply."),
20
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
21
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
21
22
  }, async ({ page, contactId, fromDate, toDate, statuses, hasRemainingCredit, pageSize }) => {
22
23
  const response = await listXeroOverpayments(page, contactId, fromDate, toDate, statuses, pageSize, hasRemainingCredit);
23
24
  if (response.error !== null) {
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroPayments } from "../../handlers/list-xero-payments.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
4
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
6
  function paymentFormatter(payment) {
6
7
  return [
@@ -44,7 +45,7 @@ const ListPaymentsTool = CreateXeroTool("list-payments", "List payments recorded
44
45
  "all payments from/to a contact → contactId; " +
45
46
  "payments in a date range → fromDate + toDate. " +
46
47
  "Note: this shows payment records only, not invoice balances. Use list-invoices with minAmountDue to find unpaid invoices.", {
47
- page: z.number().default(1).describe("Page number for pagination (starts at 1)."),
48
+ page: z.number().default(1).describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
48
49
  contactId: z.string().optional().describe("Filter payments by contact (matches Invoice.Contact.ContactID). Use to find all payments from or to a specific customer or supplier."),
49
50
  invoiceNumber: z.string().optional().describe("Filter by invoice number."),
50
51
  invoiceId: z.string().optional().describe("Filter by invoice ID."),
@@ -52,7 +53,7 @@ const ListPaymentsTool = CreateXeroTool("list-payments", "List payments recorded
52
53
  reference: z.string().optional().describe("Filter by payment reference."),
53
54
  fromDate: z.string().optional().describe("Payments on or after this date (YYYY-MM-DD)."),
54
55
  toDate: z.string().optional().describe("Payments on or before this date (YYYY-MM-DD)."),
55
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
56
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
56
57
  }, async ({ page, contactId, invoiceNumber, invoiceId, paymentId, reference, fromDate, toDate, pageSize }) => {
57
58
  const response = await listXeroPayments(page, {
58
59
  contactId,
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { listXeroPrepayments } from "../../handlers/list-xero-prepayments.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { PAGE_NUMBER_GUIDANCE, PAGE_SIZE_GUIDANCE } from "../../helpers/pagination-guidance.js";
4
5
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
6
  const ListPrepaymentsTool = CreateXeroTool("list-prepayments", "List prepayments from Xero. Prepayments are a SEPARATE record type from Payments — " +
6
7
  "they're created when a customer pays before an invoice is raised (or a supplier is paid " +
@@ -10,13 +11,13 @@ const ListPrepaymentsTool = CreateXeroTool("list-prepayments", "List prepayments
10
11
  "Common patterns: " +
11
12
  "all prepayment activity for a contact → contactId; " +
12
13
  "unallocated prepayments still available to apply → hasRemainingCredit=true.", {
13
- page: z.number().default(1).describe("Page number for pagination (starts at 1)."),
14
+ page: z.number().default(1).describe(`Page number for pagination (starts at 1). ${PAGE_NUMBER_GUIDANCE}`),
14
15
  contactId: z.string().optional().describe("Filter by contact ID."),
15
16
  fromDate: z.string().optional().describe("Prepayment date on or after this date (YYYY-MM-DD)."),
16
17
  toDate: z.string().optional().describe("Prepayment date on or before this date (YYYY-MM-DD)."),
17
18
  statuses: z.array(z.enum(["AUTHORISED", "PAID", "VOIDED"])).optional().describe("Filter by status. Defaults to [AUTHORISED, PAID] — active records only. Pass VOIDED explicitly only if those records are specifically needed."),
18
19
  hasRemainingCredit: z.boolean().optional().describe("If true, only returns prepayments with RemainingCredit>0 (i.e. not yet fully allocated). Use to find credit available to apply."),
19
- pageSize: z.number().min(1).max(100).optional().default(50).describe("Results per page (1–100, default 50)."),
20
+ pageSize: z.number().min(1).max(100).optional().default(50).describe(`Results per page (1–100, default 50). ${PAGE_SIZE_GUIDANCE}`),
20
21
  }, async ({ page, contactId, fromDate, toDate, statuses, hasRemainingCredit, pageSize }) => {
21
22
  const response = await listXeroPrepayments(page, contactId, fromDate, toDate, statuses, pageSize, hasRemainingCredit);
22
23
  if (response.error !== null) {
@@ -1,14 +1,14 @@
1
1
  import { z } from "zod";
2
- import { listXeroProfitAndLoss } from "../../handlers/list-xero-profit-and-loss.handler.js";
2
+ import { buildComparisonColumnMetadata, listXeroProfitAndLoss } from "../../handlers/list-xero-profit-and-loss.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { formatUtcDatetime } from "../../helpers/datetime.js";
5
5
  const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists profit and loss report in Xero. This provides a summary of revenue, expenses, and profit or loss over a specified period of time.", {
6
6
  fromDate: z.string().optional().describe("Optional start date in YYYY-MM-DD format"),
7
7
  toDate: z.string().optional().describe("Optional end date in YYYY-MM-DD format"),
8
- periods: z.number().int().min(1).max(11).optional().describe("Optional number of prior comparison periods (1-11). Xero returns the requested base period plus this many comparisons, so periods=3 returns 4 columns."),
8
+ periods: z.number().int().min(0).max(11).optional().describe("Optional number of prior comparison periods (0-11). Xero returns the requested base period plus this many comparisons, so periods=3 returns 4 columns. Use periods=0 for a single column."),
9
9
  timeframe: z.enum(["MONTH", "QUARTER", "YEAR"]).optional().describe("Optional spacing between comparison periods (MONTH, QUARTER, YEAR). It does not split a multi-month fromDate/toDate range into individual columns — " +
10
10
  "Xero repeats the whole fromDate/toDate span for each comparison. Example: for 4 separate monthly columns, set fromDate/toDate to a single month and periods=3, NOT a 4-month range with periods=3 (which instead returns 4 rolling 4-month totals). " +
11
- "If fromDate/toDate covers the CURRENT, still-in-progress month, Xero returns month-to-date actuals (as of today) for that base column, not a projected full month — prior comparison columns carry the same day-of-month truncation. To get full-month totals for every column (including the most recent), set toDate to the end of the last fully completed month rather than the current month."),
11
+ "If fromDate/toDate covers the CURRENT, still-in-progress month, Xero returns month-to-date actuals for the base column; prior comparison columns are completed periods. To obtain N reliable completed monthly columns, request the current calendar month with periods=N and ignore the first MTD column. Multi-month base ranges are rejected at runtime because Xero returns misleading rolling totals."),
12
12
  standardLayout: z.boolean().optional().describe("Optional flag to use standard layout"),
13
13
  paymentsOnly: z.boolean().optional().describe("Optional flag to include only accounts with payments"),
14
14
  }, async (args) => {
@@ -24,6 +24,7 @@ const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists prof
24
24
  };
25
25
  }
26
26
  const profitAndLossReport = response.result;
27
+ const comparisonColumnMetadata = buildComparisonColumnMetadata(profitAndLossReport, args?.fromDate, args?.toDate, args?.periods, args?.timeframe);
27
28
  return {
28
29
  content: [
29
30
  {
@@ -38,6 +39,10 @@ const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists prof
38
39
  type: "text",
39
40
  text: `Updated At: ${profitAndLossReport?.updatedDateUTC ? formatUtcDatetime(profitAndLossReport.updatedDateUTC) : "Unknown"}`,
40
41
  },
42
+ {
43
+ type: "text",
44
+ text: `Comparison Column Metadata: ${JSON.stringify(comparisonColumnMetadata)}`,
45
+ },
41
46
  {
42
47
  type: "text",
43
48
  text: JSON.stringify(profitAndLossReport.rows, null, 2),
@@ -3,7 +3,7 @@ import { listXeroQuotes } from "../../handlers/list-xero-quotes.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { formatUtcDatetime, formatXeroDate } from "../../helpers/datetime.js";
5
5
  const ListQuotesTool = CreateXeroTool("list-quotes", "List quotes in Xero. Supports filtering by contact, quote number, status, and date range.", {
6
- page: z.number().describe("Page number for pagination (starts at 1)."),
6
+ page: z.number().describe("Page number for pagination (starts at 1). Xero does not expose a pageSize for quotes; to retrieve all matching quotes, increment page until Xero returns an empty page. The 'Found N' count is for the current page, not the total in Xero."),
7
7
  contactId: z.string().optional().describe("Filter by contact ID."),
8
8
  quoteNumber: z.string().optional().describe("Filter by quote number."),
9
9
  dateFrom: z.string().optional().describe("Return quotes on or after this date (YYYY-MM-DD)."),
@@ -0,0 +1,9 @@
1
+ import { z } from "zod";
2
+ import { batchXeroInvoiceLookup } from "../../handlers/batch-xero-invoice-lookup.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { jsonToolResponse } from "../../types/lookup-result.js";
5
+ const LookupInvoiceTool = CreateXeroTool("xero_lookup_invoice", "Look up one Xero invoice or purchase bill by its exact InvoiceNumber value and report exact, duplicate, or unmatched results.", {
6
+ invoiceNumber: z.string().min(1),
7
+ type: z.enum(["ACCREC", "ACCPAY"]).optional(),
8
+ }, async ({ invoiceNumber, type }) => jsonToolResponse(await batchXeroInvoiceLookup([invoiceNumber], type)));
9
+ export default LookupInvoiceTool;
@@ -2,7 +2,8 @@ import { z } from "zod";
2
2
  import { searchXeroTransactions } from "../../handlers/search-xero-transactions.handler.js";
3
3
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
4
  import { jsonToolResponse } from "../../types/lookup-result.js";
5
- const SearchTransactionsTool = CreateXeroTool("xero_search_transactions", "Search Xero sales invoices and purchase bills using server-side filters. For TEAMlink purchase bills, the verified convention '<supplier invoice> / <order ID>' is stored in InvoiceNumber, not Reference. Returns compact structured match, ambiguity, pagination and error metadata.", {
5
+ import { STRUCTURED_PAGE_GUIDANCE } from "../../helpers/pagination-guidance.js";
6
+ const SearchTransactionsTool = CreateXeroTool("xero_search_transactions", "Search Xero sales invoices and purchase bills by invoice number, reference, contact, date, amount, status, or type. Uses Xero server-side filters where available, verifies the requested match mode, and returns compact match, ambiguity, pagination, and error metadata.", {
6
7
  invoiceNumber: z.string().min(1).optional(),
7
8
  reference: z.string().min(1).optional(),
8
9
  contactId: z.string().uuid().optional(),
@@ -15,7 +16,7 @@ const SearchTransactionsTool = CreateXeroTool("xero_search_transactions", "Searc
15
16
  statuses: z.array(z.enum(["DRAFT", "SUBMITTED", "AUTHORISED", "PAID", "VOIDED", "DELETED"])).min(1).optional(),
16
17
  type: z.enum(["ACCREC", "ACCPAY"]).optional(),
17
18
  matchMode: z.enum(["exact", "contains", "candidate"]).default("exact"),
18
- page: z.number().int().min(1).default(1),
19
- pageSize: z.number().int().min(1).max(100).default(25),
19
+ page: z.number().int().min(1).default(1).describe(`Page number for paginated matches. ${STRUCTURED_PAGE_GUIDANCE}`),
20
+ pageSize: z.number().int().min(1).max(100).default(25).describe(`Maximum matches returned on this page (1-100, default 25). ${STRUCTURED_PAGE_GUIDANCE}`),
20
21
  }, async (params) => jsonToolResponse(await searchXeroTransactions(params)));
21
22
  export default SearchTransactionsTool;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/xero-mcp-server",
3
- "version": "1.14.0",
3
+ "version": "1.14.2",
4
4
  "description": "MCP server implementation for Xero integration - TEAMnetwork",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",