@teamnetwork-nz/xero-mcp-server 1.13.1 → 1.14.1

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
@@ -6,8 +6,8 @@ Provides AI agents and MCP-compatible clients (e.g. Claude Desktop) with tools t
6
6
 
7
7
  ## Features
8
8
 
9
- - **Invoices** — create, list (with status/date filters), update, authorise, void, get full detail, download as PDF
10
- - **Contacts** — create, list, update, archive
9
+ - **Invoices** - create, list, structured search, native batch lookup, settlement/history inspection, update, authorise, void, get full detail, download as PDF
10
+ - **Contacts** - create, list, identifier-based resolution, update, archive
11
11
  - **Quotes** — create, list, update, convert to invoice
12
12
  - **Payments & Credit Notes** — create, list, update
13
13
  - **Bank Transactions & Manual Journals** — create, list, update
@@ -149,15 +149,22 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
149
149
  | Tool | Description |
150
150
  |---|---|
151
151
  | `list-invoices` | List invoices with optional filters: status, contact, invoice number, date range |
152
+ | `xero_search_transactions` | Structured search by invoice number, reference, supplier/contact, date, amount, status and type |
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 |
152
155
  | `get-invoice` | Get full details of a single invoice including all line items |
156
+ | `xero_get_bill_settlement` | Trace payments, credits, prepayments, overpayments and the outstanding balance |
157
+ | `xero_get_invoice_history` | Retrieve Xero-recorded invoice/bill history events (not a complete field-level audit trail) |
153
158
  | `create-invoice` | Create a new draft invoice (AR or AP) |
154
159
  | `update-invoice` | Update a draft invoice |
155
160
  | `authorise-invoice` | Promote a DRAFT or SUBMITTED invoice to AUTHORISED |
156
161
  | `void-invoice` | Void an AUTHORISED invoice, or delete a DRAFT invoice |
157
162
  | `get-invoice-pdf` | Download the Xero-generated invoice PDF to local disk |
158
163
  | `list-invoice-attachments` | List all file attachments on an invoice |
164
+ | `xero_list_bill_attachments` | Return compact structured attachment metadata without binary content |
159
165
  | `upload-invoice-attachment` | Upload a local file (e.g. Crystal Reports PDF) as an invoice attachment |
160
166
  | `get-invoice-attachment` | Download an invoice attachment to local disk |
167
+ | `xero_get_bill_attachment` | Explicit metadata-verified attachment download with a configurable size limit |
161
168
  | `delete-invoice-attachment` | Delete an attachment from an invoice |
162
169
 
163
170
  ### Quotes
@@ -172,6 +179,7 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
172
179
  | Tool | Description |
173
180
  |---|---|
174
181
  | `list-contacts` | List contacts with optional search term |
182
+ | `xero_find_contact` | Resolve a contact by ID, name, contact/account number, email or tax number without silently choosing ambiguous matches |
175
183
  | `create-contact` | Create a new contact |
176
184
  | `update-contact` | Update an existing contact |
177
185
  | `archive-contact` | Archive a contact (Xero does not support hard deletion) |
@@ -224,6 +232,12 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
224
232
  | `list-aged-receivables-by-contact` | Aged receivables for a contact |
225
233
  | `list-aged-payables-by-contact` | Aged payables for a contact |
226
234
 
235
+ `list-profit-and-loss` enforces a single-calendar-month base range and returns
236
+ comparison-column metadata containing each label, actual date window, and MTD flag.
237
+ Multi-month base ranges are rejected because Xero can return misleading rolling totals.
238
+ For N completed monthly columns, request the current month with `periods=N` and ignore
239
+ the first MTD column, or make N separate calls with `periods=0`.
240
+
227
241
  ### Payroll *(requires `XERO_ENABLE_PAYROLL=true`)*
228
242
  | Tool | Description |
229
243
  |---|---|
@@ -256,6 +270,27 @@ The server supplies MCP `instructions` that are automatically delivered to the c
256
270
 
257
271
  For a full query playbook, see the MCP resource `xero://guidance/agent-playbook` (or `AGENTS.md` for local reference).
258
272
 
273
+ ### Structured lookup contracts
274
+
275
+ The `xero_*` lookup tools return compact JSON with a consistent `matchStatus`
276
+ (`EXACT`, `MULTIPLE`, `CANDIDATES`, `NOT_FOUND`, or `ERROR`), an explicit
277
+ `ambiguous` flag, pagination completeness/continuation metadata where relevant,
278
+ and structured errors. Xero and external identifiers remain strings; money values
279
+ are returned as decimal strings with their currency code.
280
+
281
+ For TEAMlink purchase bills, live API verification confirmed that the convention
282
+ `<supplier-invoice-number> / <TEAMlink-orderId>` is stored in Xero's
283
+ `InvoiceNumber` field (for example `4462570 / 121058`), while `Reference` is empty.
284
+ Exact and batch searches therefore use Xero's native `InvoiceNumbers` filter. The
285
+ separate `reference` search remains available for records that use that field.
286
+
287
+ `xero_batch_invoice_lookup.invoiceNumbers` is a native JSON string array. Numeric-
288
+ looking identifiers are intentionally not coerced to numbers. The reported Hermes
289
+ `coerce_tool_args` defect is outside this repository and must also be corrected in
290
+ the Hermes runtime if that client still rewrites valid JSON arrays before sending
291
+ the MCP request. Until then, use scalar `xero_lookup_invoice` for exact single-value
292
+ lookups or `xero_search_transactions` for broader matching.
293
+
259
294
  ## For Developers
260
295
 
261
296
  ### Local development setup
@@ -0,0 +1,48 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { formatError } from "../helpers/format-error.js";
3
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
4
+ import { compactInvoice } from "./search-xero-transactions.handler.js";
5
+ export function assembleBatchInvoiceLookup(invoiceNumbers, invoices) {
6
+ const results = invoiceNumbers.map((input) => {
7
+ const matches = invoices
8
+ .filter((invoice) => (invoice.invoiceNumber ?? "").trim().toLocaleLowerCase() === input.trim().toLocaleLowerCase())
9
+ .map(compactInvoice);
10
+ return {
11
+ input,
12
+ matchStatus: matches.length === 0 ? "NOT_FOUND" : matches.length > 1 ? "MULTIPLE" : "EXACT",
13
+ ambiguous: matches.length > 1,
14
+ matches,
15
+ };
16
+ });
17
+ const unmatched = results.filter((result) => result.matchStatus === "NOT_FOUND").map((result) => result.input);
18
+ const ambiguous = results.some((result) => result.ambiguous);
19
+ return {
20
+ matchStatus: ambiguous
21
+ ? "MULTIPLE"
22
+ : unmatched.length === invoiceNumbers.length
23
+ ? "NOT_FOUND"
24
+ : unmatched.length > 0
25
+ ? "CANDIDATES"
26
+ : "EXACT",
27
+ ambiguous,
28
+ results,
29
+ unmatched,
30
+ error: null,
31
+ };
32
+ }
33
+ export async function batchXeroInvoiceLookup(invoiceNumbers, type) {
34
+ try {
35
+ await xeroClient.authenticate();
36
+ const response = await xeroClient.accountingApi.getInvoices(xeroClient.tenantId, undefined, type ? `Type=="${type}"` : undefined, undefined, undefined, invoiceNumbers, undefined, undefined, 1, false, false, undefined, true, 1000, undefined, getClientHeaders());
37
+ return assembleBatchInvoiceLookup(invoiceNumbers, response.body.invoices ?? []);
38
+ }
39
+ catch (error) {
40
+ return {
41
+ matchStatus: "ERROR",
42
+ ambiguous: false,
43
+ results: [],
44
+ unmatched: [],
45
+ error: { code: "XERO_API_ERROR", message: formatError(error), retryable: true },
46
+ };
47
+ }
48
+ }
@@ -13,7 +13,11 @@ export async function downloadXeroInvoiceAttachment(invoiceId, fileName, content
13
13
  await xeroClient.authenticate();
14
14
  const response = await xeroClient.accountingApi.getInvoiceAttachmentByFileName(xeroClient.tenantId, invoiceId, fileName, contentType, getClientHeaders());
15
15
  const dir = getDownloadPath();
16
- const savePath = path.join(dir, fileName);
16
+ const safeFileName = path.basename(fileName);
17
+ if (safeFileName !== fileName || safeFileName === "." || safeFileName === "..") {
18
+ throw new Error("Invalid attachment filename.");
19
+ }
20
+ const savePath = path.join(dir, safeFileName);
17
21
  fs.writeFileSync(savePath, response.body);
18
22
  return { result: savePath, isError: false, error: null };
19
23
  }
@@ -0,0 +1,63 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { formatError } from "../helpers/format-error.js";
3
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
4
+ import { joinWhere } from "../helpers/build-where-clause.js";
5
+ import { escapeXeroString } from "../helpers/xero-query.js";
6
+ import { failedLookup, successfulLookup } from "../types/lookup-result.js";
7
+ function matches(actual, expected, exact) {
8
+ const left = (actual ?? "").trim().toLocaleLowerCase();
9
+ const right = expected.trim().toLocaleLowerCase();
10
+ return exact ? left === right : left.includes(right);
11
+ }
12
+ export function filterContactMatches(contacts, params) {
13
+ const exact = params.matchMode === "exact";
14
+ return contacts.filter((contact) => (!params.contactId || contact.contactID === params.contactId) &&
15
+ (!params.name || matches(contact.name, params.name, exact)) &&
16
+ (!params.contactNumber || matches(contact.contactNumber, params.contactNumber, exact)) &&
17
+ (!params.accountNumber || matches(contact.accountNumber, params.accountNumber, exact)) &&
18
+ (!params.email || matches(contact.emailAddress, params.email, exact)) &&
19
+ (!params.taxNumber || matches(contact.taxNumber, params.taxNumber, exact)));
20
+ }
21
+ function compactContact(contact) {
22
+ return {
23
+ contactId: contact.contactID ?? "",
24
+ name: contact.name ?? null,
25
+ contactNumber: contact.contactNumber ?? null,
26
+ accountNumber: contact.accountNumber ?? null,
27
+ email: contact.emailAddress ?? null,
28
+ taxNumber: contact.taxNumber ?? null,
29
+ status: contact.contactStatus ? String(contact.contactStatus) : null,
30
+ isCustomer: contact.isCustomer ?? false,
31
+ isSupplier: contact.isSupplier ?? false,
32
+ };
33
+ }
34
+ export async function findXeroContact(params) {
35
+ const identifier = params.name ?? params.contactNumber ?? params.email;
36
+ try {
37
+ await xeroClient.authenticate();
38
+ const where = joinWhere([
39
+ ...(params.accountNumber ? [`AccountNumber=="${escapeXeroString(params.accountNumber)}"`] : []),
40
+ ...(params.taxNumber ? [`TaxNumber=="${escapeXeroString(params.taxNumber)}"`] : []),
41
+ ...(params.role === "customer" ? ["IsCustomer==true"] : []),
42
+ ...(params.role === "supplier" ? ["IsSupplier==true"] : []),
43
+ 'ContactStatus=="ACTIVE"',
44
+ ]);
45
+ const apiPageSize = Math.min(params.pageSize + 1, 100);
46
+ const response = await xeroClient.accountingApi.getContacts(xeroClient.tenantId, undefined, where, "Name ASC", params.contactId ? [params.contactId] : undefined, params.page, false, false, identifier, apiPageSize, getClientHeaders());
47
+ const raw = response.body.contacts ?? [];
48
+ const filtered = filterContactMatches(raw, params);
49
+ const truncated = raw.length > params.pageSize || filtered.length > params.pageSize;
50
+ const matchesFound = filtered.slice(0, params.pageSize).map(compactContact);
51
+ return successfulLookup(matchesFound, params.matchMode === "exact", {
52
+ page: params.page,
53
+ pageSize: params.pageSize,
54
+ returned: matchesFound.length,
55
+ truncated,
56
+ nextPage: truncated ? params.page + 1 : null,
57
+ complete: !truncated,
58
+ });
59
+ }
60
+ catch (error) {
61
+ return failedLookup(formatError(error));
62
+ }
63
+ }
@@ -0,0 +1,65 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { decimalString } from "../helpers/xero-query.js";
3
+ import { formatError } from "../helpers/format-error.js";
4
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
5
+ import { formatXeroDate } from "../helpers/datetime.js";
6
+ import { failedLookup, successfulLookup } from "../types/lookup-result.js";
7
+ export async function getXeroBillSettlement(invoiceId) {
8
+ try {
9
+ await xeroClient.authenticate();
10
+ const response = await xeroClient.accountingApi.getInvoice(xeroClient.tenantId, invoiceId, undefined, getClientHeaders());
11
+ const invoice = response.body.invoices?.[0];
12
+ if (!invoice)
13
+ return successfulLookup([], true);
14
+ const amountPaid = invoice.amountPaid ?? 0;
15
+ const amountCredited = invoice.amountCredited ?? 0;
16
+ const amountDue = invoice.amountDue ?? 0;
17
+ const result = {
18
+ invoiceId: invoice.invoiceID ?? invoiceId,
19
+ invoiceNumber: invoice.invoiceNumber ?? null,
20
+ status: invoice.status ? String(invoice.status) : null,
21
+ settlementState: amountDue <= 0 ? "FULLY_PAID" : amountPaid > 0 || amountCredited > 0 ? "PARTLY_PAID" : "UNPAID",
22
+ currency: invoice.currencyCode ? String(invoice.currencyCode) : null,
23
+ total: decimalString(invoice.total),
24
+ amountPaid: decimalString(invoice.amountPaid),
25
+ amountCredited: decimalString(invoice.amountCredited),
26
+ amountDue: decimalString(invoice.amountDue),
27
+ payments: (invoice.payments ?? []).map((payment) => ({
28
+ paymentId: payment.paymentID ?? null,
29
+ date: payment.date ? formatXeroDate(payment.date) : null,
30
+ amount: decimalString(payment.amount),
31
+ reference: payment.reference ?? null,
32
+ status: payment.status ? String(payment.status) : null,
33
+ accountCode: payment.account?.code ?? null,
34
+ isReconciled: payment.isReconciled ?? false,
35
+ })),
36
+ creditNotes: (invoice.creditNotes ?? []).map((credit) => ({
37
+ creditNoteId: credit.creditNoteID ?? null,
38
+ creditNoteNumber: credit.creditNoteNumber ?? null,
39
+ date: credit.date ? formatXeroDate(credit.date) : null,
40
+ total: decimalString(credit.total),
41
+ appliedAmount: decimalString(credit.appliedAmount),
42
+ remainingCredit: decimalString(credit.remainingCredit),
43
+ })),
44
+ prepayments: (invoice.prepayments ?? []).map((prepayment) => ({
45
+ prepaymentId: prepayment.prepaymentID ?? null,
46
+ reference: prepayment.reference ?? null,
47
+ date: prepayment.date ? formatXeroDate(prepayment.date) : null,
48
+ total: decimalString(prepayment.total),
49
+ appliedAmount: decimalString(prepayment.appliedAmount),
50
+ remainingCredit: decimalString(prepayment.remainingCredit),
51
+ })),
52
+ overpayments: (invoice.overpayments ?? []).map((overpayment) => ({
53
+ overpaymentId: overpayment.overpaymentID ?? null,
54
+ date: overpayment.date ? formatXeroDate(overpayment.date) : null,
55
+ total: decimalString(overpayment.total),
56
+ appliedAmount: decimalString(overpayment.appliedAmount),
57
+ remainingCredit: decimalString(overpayment.remainingCredit),
58
+ })),
59
+ };
60
+ return successfulLookup([result], true);
61
+ }
62
+ catch (error) {
63
+ return failedLookup(formatError(error));
64
+ }
65
+ }
@@ -0,0 +1,24 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { formatError } from "../helpers/format-error.js";
3
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
4
+ import { failedLookup, successfulLookup } from "../types/lookup-result.js";
5
+ export async function getXeroInvoiceHistory(invoiceId) {
6
+ try {
7
+ await xeroClient.authenticate();
8
+ const response = await xeroClient.accountingApi.getInvoiceHistory(xeroClient.tenantId, invoiceId, getClientHeaders());
9
+ const records = (response.body.historyRecords ?? []).map((record) => ({
10
+ timestamp: record.dateUTC ? new Date(record.dateUTC).toISOString() : null,
11
+ details: record.details ?? null,
12
+ changes: record.changes ?? null,
13
+ user: record.user ?? null,
14
+ }));
15
+ return successfulLookup([{
16
+ invoiceId,
17
+ completeness: "XERO_RECORDED_EVENTS_ONLY",
18
+ events: records,
19
+ }], true);
20
+ }
21
+ catch (error) {
22
+ return failedLookup(formatError(error));
23
+ }
24
+ }
@@ -1,6 +1,70 @@
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
+ function parseDateOnly(value) {
8
+ const date = new Date(`${value}T00:00:00Z`);
9
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) {
10
+ throw new McpError(ErrorCode.InvalidParams, `Invalid date: ${value}. Expected YYYY-MM-DD.`);
11
+ }
12
+ return date;
13
+ }
14
+ export function validateProfitAndLossDateRange(fromDate, toDate) {
15
+ if (!fromDate || !toDate)
16
+ return;
17
+ const from = parseDateOnly(fromDate);
18
+ const to = parseDateOnly(toDate);
19
+ if (to < from || from.getUTCFullYear() !== to.getUTCFullYear() || from.getUTCMonth() !== to.getUTCMonth()) {
20
+ throw new McpError(ErrorCode.InvalidParams, PROFIT_AND_LOSS_RANGE_ERROR);
21
+ }
22
+ }
23
+ function shiftDate(value, months) {
24
+ const day = value.getUTCDate();
25
+ const shifted = new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth() + months, 1));
26
+ const lastDay = new Date(Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth() + 1, 0)).getUTCDate();
27
+ shifted.setUTCDate(Math.min(day, lastDay));
28
+ return shifted;
29
+ }
30
+ function isoDate(value) {
31
+ return value.toISOString().slice(0, 10);
32
+ }
33
+ function isLastDayOfMonth(value) {
34
+ return value.getUTCDate() === new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth() + 1, 0)).getUTCDate();
35
+ }
36
+ export function buildComparisonColumnMetadata(report, fromDate, toDate, periods = 0, timeframe = "MONTH", today = localDateString()) {
37
+ if (!fromDate || !toDate)
38
+ return [];
39
+ validateProfitAndLossDateRange(fromDate, toDate);
40
+ const from = parseDateOnly(fromDate);
41
+ const to = parseDateOnly(toDate);
42
+ const todayDate = parseDateOnly(today);
43
+ const header = report.rows?.find((row) => String(row.rowType) === "Header" || Number(row.rowType) === 0);
44
+ const labels = header?.cells?.slice(1).map((cell) => cell.value ?? null) ?? [];
45
+ const stepMonths = timeframe === "QUARTER" ? 3 : timeframe === "YEAR" ? 12 : 1;
46
+ const fullMonthWindow = from.getUTCDate() === 1 && isLastDayOfMonth(to);
47
+ return Array.from({ length: periods + 1 }, (_, columnIndex) => {
48
+ const offset = -columnIndex * stepMonths;
49
+ const columnFrom = shiftDate(from, offset);
50
+ const shiftedTo = shiftDate(to, offset);
51
+ const requestedTo = fullMonthWindow
52
+ ? new Date(Date.UTC(shiftedTo.getUTCFullYear(), shiftedTo.getUTCMonth() + 1, 0))
53
+ : shiftedTo;
54
+ const isMonthToDate = columnIndex === 0 &&
55
+ columnFrom.getUTCDate() === 1 &&
56
+ columnFrom.getUTCFullYear() === todayDate.getUTCFullYear() &&
57
+ columnFrom.getUTCMonth() === todayDate.getUTCMonth() &&
58
+ requestedTo >= todayDate;
59
+ return {
60
+ columnIndex,
61
+ label: labels[columnIndex] ?? null,
62
+ fromDate: isoDate(columnFrom),
63
+ toDate: isoDate(isMonthToDate ? todayDate : requestedTo),
64
+ isMonthToDate,
65
+ };
66
+ });
67
+ }
4
68
  /**
5
69
  * Internal function to fetch profit and loss data from Xero
6
70
  */
@@ -27,6 +91,7 @@ async function fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standard
27
91
  * @param paymentsOnly Optional boolean to include only accounts with payments
28
92
  */
29
93
  export async function listXeroProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly) {
94
+ validateProfitAndLossDateRange(fromDate, toDate);
30
95
  try {
31
96
  const profitAndLoss = await fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly);
32
97
  if (!profitAndLoss) {
@@ -0,0 +1,90 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { dateWhereConditions, joinWhere } from "../helpers/build-where-clause.js";
3
+ import { decimalString } from "../helpers/xero-query.js";
4
+ import { formatError } from "../helpers/format-error.js";
5
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
6
+ import { formatXeroDate } from "../helpers/datetime.js";
7
+ import { failedLookup, successfulLookup } from "../types/lookup-result.js";
8
+ export function buildInvoiceSearchQuery(params) {
9
+ const whereParts = [
10
+ ...dateWhereConditions("Date", params.fromDate, params.toDate),
11
+ ...(params.type ? [`Type=="${params.type}"`] : []),
12
+ ...(params.amount !== undefined ? [`Total==${params.amount}`] : []),
13
+ ...(params.minAmount !== undefined ? [`Total>=${params.minAmount}`] : []),
14
+ ...(params.maxAmount !== undefined ? [`Total<=${params.maxAmount}`] : []),
15
+ ];
16
+ const nativeExactInvoice = params.invoiceNumber && params.matchMode === "exact";
17
+ const searchTerm = nativeExactInvoice
18
+ ? undefined
19
+ : params.invoiceNumber ?? params.reference ?? params.supplier;
20
+ return {
21
+ where: joinWhere(whereParts),
22
+ invoiceNumbers: nativeExactInvoice ? [params.invoiceNumber] : undefined,
23
+ contactIds: params.contactId ? [params.contactId] : undefined,
24
+ statuses: params.statuses,
25
+ searchTerm,
26
+ };
27
+ }
28
+ function textMatches(actual, expected, mode) {
29
+ const left = (actual ?? "").trim().toLocaleLowerCase();
30
+ const right = expected.trim().toLocaleLowerCase();
31
+ if (mode === "candidate")
32
+ return true;
33
+ return mode === "exact" ? left === right : left.includes(right);
34
+ }
35
+ export function filterInvoiceMatches(invoices, params) {
36
+ return invoices.filter((invoice) => {
37
+ if (params.invoiceNumber && !textMatches(invoice.invoiceNumber, params.invoiceNumber, params.matchMode))
38
+ return false;
39
+ if (params.reference && !textMatches(invoice.reference, params.reference, params.matchMode))
40
+ return false;
41
+ if (params.supplier && !textMatches(invoice.contact?.name, params.supplier, params.matchMode))
42
+ return false;
43
+ return true;
44
+ });
45
+ }
46
+ export function compactInvoice(invoice) {
47
+ return {
48
+ invoiceId: invoice.invoiceID ?? "",
49
+ invoiceNumber: invoice.invoiceNumber ?? null,
50
+ reference: invoice.reference || null,
51
+ type: invoice.type ? String(invoice.type) : null,
52
+ status: invoice.status ? String(invoice.status) : null,
53
+ contact: { id: invoice.contact?.contactID ?? null, name: invoice.contact?.name ?? null },
54
+ date: invoice.date ? formatXeroDate(invoice.date) : null,
55
+ dueDate: invoice.dueDate ? formatXeroDate(invoice.dueDate) : null,
56
+ total: decimalString(invoice.total),
57
+ amountPaid: decimalString(invoice.amountPaid),
58
+ amountCredited: decimalString(invoice.amountCredited),
59
+ amountDue: decimalString(invoice.amountDue),
60
+ currency: invoice.currencyCode ? String(invoice.currencyCode) : null,
61
+ hasAttachments: invoice.hasAttachments ?? false,
62
+ };
63
+ }
64
+ export function shouldUseInvoiceSummaryOnly(params) {
65
+ return params.amount === undefined && params.minAmount === undefined && params.maxAmount === undefined;
66
+ }
67
+ export async function searchXeroTransactions(params) {
68
+ try {
69
+ await xeroClient.authenticate();
70
+ const query = buildInvoiceSearchQuery(params);
71
+ const apiPageSize = Math.min(params.pageSize + 1, 1000);
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());
74
+ const raw = response.body.invoices ?? [];
75
+ const filtered = filterInvoiceMatches(raw, params);
76
+ const truncated = raw.length > params.pageSize || filtered.length > params.pageSize;
77
+ const matches = filtered.slice(0, params.pageSize).map(compactInvoice);
78
+ return successfulLookup(matches, params.matchMode === "exact", {
79
+ page: params.page,
80
+ pageSize: params.pageSize,
81
+ returned: matches.length,
82
+ truncated,
83
+ nextPage: truncated ? params.page + 1 : null,
84
+ complete: !truncated,
85
+ });
86
+ }
87
+ catch (error) {
88
+ return failedLookup(formatError(error));
89
+ }
90
+ }
@@ -0,0 +1,6 @@
1
+ export function escapeXeroString(value) {
2
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3
+ }
4
+ export function decimalString(value) {
5
+ return value === undefined ? null : String(value);
6
+ }
@@ -1,4 +1,5 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { getPackageVersion } from "../helpers/get-package-version.js";
2
3
  export class XeroMcpServer {
3
4
  static instance = null;
4
5
  constructor() { }
@@ -6,7 +7,7 @@ export class XeroMcpServer {
6
7
  if (XeroMcpServer.instance === null) {
7
8
  XeroMcpServer.instance = new McpServer({
8
9
  name: "Xero MCP Server",
9
- version: "1.0.0",
10
+ version: getPackageVersion(),
10
11
  }, {
11
12
  instructions: [
12
13
  "You are connected to the Xero accounting API via MCP tools.",
@@ -0,0 +1,32 @@
1
+ import { z } from "zod";
2
+ import { downloadXeroInvoiceAttachment } from "../../handlers/download-xero-invoice-attachment.handler.js";
3
+ import { listXeroInvoiceAttachments } from "../../handlers/list-xero-invoice-attachments.handler.js";
4
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
5
+ import { failedLookup, jsonToolResponse, successfulLookup } from "../../types/lookup-result.js";
6
+ const GetBillAttachmentTool = CreateXeroTool("xero_get_bill_attachment", "Explicitly retrieve one attachment from a Xero bill or invoice. Verifies the filename against Xero metadata and enforces a configurable size ceiling before downloading.", {
7
+ invoiceId: z.string().uuid(),
8
+ fileName: z.string().min(1),
9
+ maxBytes: z.number().int().min(1).max(25 * 1024 * 1024).default(10 * 1024 * 1024),
10
+ }, async ({ invoiceId, fileName, maxBytes }) => {
11
+ const metadata = await listXeroInvoiceAttachments(invoiceId);
12
+ if (metadata.isError)
13
+ return jsonToolResponse(failedLookup(metadata.error));
14
+ const attachment = metadata.result.find((item) => item.fileName === fileName);
15
+ if (!attachment)
16
+ return jsonToolResponse(successfulLookup([], true));
17
+ if (attachment.contentLength !== undefined && attachment.contentLength > maxBytes) {
18
+ return jsonToolResponse(failedLookup(`Attachment is ${attachment.contentLength} bytes, exceeding maxBytes=${maxBytes}.`));
19
+ }
20
+ const result = await downloadXeroInvoiceAttachment(invoiceId, fileName, attachment.mimeType ?? "application/octet-stream");
21
+ if (result.isError)
22
+ return jsonToolResponse(failedLookup(result.error));
23
+ return jsonToolResponse(successfulLookup([{
24
+ invoiceId,
25
+ attachmentId: attachment.attachmentID ?? null,
26
+ fileName,
27
+ mimeType: attachment.mimeType ?? null,
28
+ contentLength: attachment.contentLength === undefined ? null : String(attachment.contentLength),
29
+ localPath: result.result,
30
+ }], true));
31
+ });
32
+ export default GetBillAttachmentTool;
@@ -0,0 +1,6 @@
1
+ import { z } from "zod";
2
+ import { getXeroBillSettlement } from "../../handlers/get-xero-bill-settlement.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { jsonToolResponse } from "../../types/lookup-result.js";
5
+ const GetBillSettlementTool = CreateXeroTool("xero_get_bill_settlement", "Trace settlement of one Xero bill or invoice by UUID, including payments, credit notes, prepayments, overpayments and the current outstanding balance.", { invoiceId: z.string().uuid() }, async ({ invoiceId }) => jsonToolResponse(await getXeroBillSettlement(invoiceId)));
6
+ export default GetBillSettlementTool;
@@ -0,0 +1,6 @@
1
+ import { z } from "zod";
2
+ import { getXeroInvoiceHistory } from "../../handlers/get-xero-invoice-history.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { jsonToolResponse } from "../../types/lookup-result.js";
5
+ const GetInvoiceHistoryTool = CreateXeroTool("xero_get_invoice_history", "Return Xero's recorded history events for an invoice or bill. This is not a complete field-by-field audit trail.", { invoiceId: z.string().uuid() }, async ({ invoiceId }) => jsonToolResponse(await getXeroInvoiceHistory(invoiceId)));
6
+ export default GetInvoiceHistoryTool;
@@ -2,10 +2,16 @@ import GetPayrollTimesheetTool from "./get-payroll-timesheet.tool.js";
2
2
  import GetInvoiceTool from "./get-invoice.tool.js";
3
3
  import GetInvoiceAttachmentTool from "./get-invoice-attachment.tool.js";
4
4
  import GetInvoicePdfTool from "./get-invoice-pdf.tool.js";
5
+ import GetBillSettlementTool from "./get-bill-settlement.tool.js";
6
+ import GetBillAttachmentTool from "./get-bill-attachment.tool.js";
7
+ import GetInvoiceHistoryTool from "./get-invoice-history.tool.js";
5
8
  export const CoreGetTools = [
6
9
  GetInvoiceTool,
7
10
  GetInvoiceAttachmentTool,
8
11
  GetInvoicePdfTool,
12
+ GetBillSettlementTool,
13
+ GetBillAttachmentTool,
14
+ GetInvoiceHistoryTool,
9
15
  ];
10
16
  export const PayrollGetTools = [
11
17
  GetPayrollTimesheetTool,
@@ -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 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
+ invoiceNumbers: z.array(z.string().min(1)).min(1).max(100),
7
+ type: z.enum(["ACCREC", "ACCPAY"]).optional(),
8
+ }, async ({ invoiceNumbers, type }) => jsonToolResponse(await batchXeroInvoiceLookup(invoiceNumbers, type)));
9
+ export default BatchInvoiceLookupTool;
@@ -0,0 +1,22 @@
1
+ import { z } from "zod";
2
+ import { findXeroContact } from "../../handlers/find-xero-contact.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { failedLookup, jsonToolResponse } from "../../types/lookup-result.js";
5
+ 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
+ contactId: z.string().uuid().optional(),
7
+ name: z.string().min(1).optional(),
8
+ contactNumber: z.string().min(1).optional(),
9
+ accountNumber: z.string().min(1).optional(),
10
+ email: z.string().email().optional(),
11
+ taxNumber: z.string().min(1).optional().describe("GST/VAT/ABN/NZBN tax identifier as stored by Xero."),
12
+ role: z.enum(["customer", "supplier"]).optional(),
13
+ 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),
16
+ }, async (params) => {
17
+ if (![params.contactId, params.name, params.contactNumber, params.accountNumber, params.email, params.taxNumber].some(Boolean)) {
18
+ return jsonToolResponse(failedLookup("At least one supported contact identifier is required."));
19
+ }
20
+ return jsonToolResponse(await findXeroContact(params));
21
+ });
22
+ export default FindContactTool;
@@ -28,6 +28,11 @@ import ListTrackingCategoriesTool from "./list-tracking-categories.tool.js";
28
28
  import ListTrialBalanceTool from "./list-trial-balance.tool.js";
29
29
  import ListContactGroupsTool from "./list-contact-groups.tool.js";
30
30
  import ListInvoiceAttachmentsTool from "./list-invoice-attachments.tool.js";
31
+ import SearchTransactionsTool from "./search-transactions.tool.js";
32
+ import BatchInvoiceLookupTool from "./batch-invoice-lookup.tool.js";
33
+ import FindContactTool from "./find-contact.tool.js";
34
+ import ListBillAttachmentsTool from "./list-bill-attachments.tool.js";
35
+ import LookupInvoiceTool from "./lookup-invoice.tool.js";
31
36
  export const CoreListTools = [
32
37
  ListAccountsTool,
33
38
  ListContactsTool,
@@ -46,6 +51,11 @@ export const CoreListTools = [
46
51
  ListContactGroupsTool,
47
52
  ListTrackingCategoriesTool,
48
53
  ListInvoiceAttachmentsTool,
54
+ SearchTransactionsTool,
55
+ BatchInvoiceLookupTool,
56
+ FindContactTool,
57
+ ListBillAttachmentsTool,
58
+ LookupInvoiceTool,
49
59
  ];
50
60
  export const ReportListTools = [
51
61
  ListTrialBalanceTool,
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ import { listXeroInvoiceAttachments } from "../../handlers/list-xero-invoice-attachments.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
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 }) => {
6
+ const response = await listXeroInvoiceAttachments(invoiceId);
7
+ if (response.isError)
8
+ return jsonToolResponse(failedLookup(response.error));
9
+ const attachments = response.result.map((attachment) => ({
10
+ attachmentId: attachment.attachmentID ?? null,
11
+ fileName: attachment.fileName ?? null,
12
+ mimeType: attachment.mimeType ?? null,
13
+ contentLength: attachment.contentLength === undefined ? null : String(attachment.contentLength),
14
+ includeOnline: attachment.includeOnline ?? false,
15
+ }));
16
+ return jsonToolResponse({
17
+ matchStatus: attachments.length ? "EXACT" : "NOT_FOUND",
18
+ ambiguous: false,
19
+ matches: attachments,
20
+ pagination: null,
21
+ error: null,
22
+ });
23
+ });
24
+ export default ListBillAttachmentsTool;
@@ -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 — the prior comparison columns are still full months. 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),
@@ -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;
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+ import { searchXeroTransactions } from "../../handlers/search-xero-transactions.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { jsonToolResponse } from "../../types/lookup-result.js";
5
+ 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
+ invoiceNumber: z.string().min(1).optional(),
7
+ reference: z.string().min(1).optional(),
8
+ contactId: z.string().uuid().optional(),
9
+ supplier: z.string().min(1).optional().describe("Contact/supplier name."),
10
+ fromDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
11
+ toDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
12
+ amount: z.number().nonnegative().optional().describe("Exact invoice total."),
13
+ minAmount: z.number().nonnegative().optional(),
14
+ maxAmount: z.number().nonnegative().optional(),
15
+ statuses: z.array(z.enum(["DRAFT", "SUBMITTED", "AUTHORISED", "PAID", "VOIDED", "DELETED"])).min(1).optional(),
16
+ type: z.enum(["ACCREC", "ACCPAY"]).optional(),
17
+ 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),
20
+ }, async (params) => jsonToolResponse(await searchXeroTransactions(params)));
21
+ export default SearchTransactionsTool;
@@ -0,0 +1,36 @@
1
+ export function matchStatusFor(count, exact) {
2
+ if (count === 0)
3
+ return "NOT_FOUND";
4
+ if (count > 1)
5
+ return "MULTIPLE";
6
+ return exact ? "EXACT" : "CANDIDATES";
7
+ }
8
+ export function successfulLookup(matches, exact, pagination = null) {
9
+ const incompleteEmpty = matches.length === 0 && pagination?.complete === false;
10
+ return {
11
+ matchStatus: incompleteEmpty ? "CANDIDATES" : matchStatusFor(matches.length, exact),
12
+ ambiguous: matches.length > 1 || incompleteEmpty,
13
+ matches,
14
+ pagination,
15
+ error: null,
16
+ };
17
+ }
18
+ export function failedLookup(message) {
19
+ const lower = message.toLowerCase();
20
+ return {
21
+ matchStatus: "ERROR",
22
+ ambiguous: false,
23
+ matches: [],
24
+ pagination: null,
25
+ error: {
26
+ code: lower.includes("429") || lower.includes("rate limit") ? "RATE_LIMITED" : "XERO_API_ERROR",
27
+ message,
28
+ retryable: lower.includes("429") || lower.includes("rate limit") || lower.includes("timeout"),
29
+ },
30
+ };
31
+ }
32
+ export function jsonToolResponse(value) {
33
+ return {
34
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }],
35
+ };
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/xero-mcp-server",
3
- "version": "1.13.1",
3
+ "version": "1.14.1",
4
4
  "description": "MCP server implementation for Xero integration - TEAMnetwork",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -12,6 +12,7 @@
12
12
  ],
13
13
  "scripts": {
14
14
  "build": "tsc && shx chmod +x dist/*.js",
15
+ "test": "npm run build && node --test test/*.test.js",
15
16
  "prepare": "npm run build",
16
17
  "watch": "tsc --watch",
17
18
  "lint:fix": "eslint --fix",