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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,21 @@ 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 |
152
154
  | `get-invoice` | Get full details of a single invoice including all line items |
155
+ | `xero_get_bill_settlement` | Trace payments, credits, prepayments, overpayments and the outstanding balance |
156
+ | `xero_get_invoice_history` | Retrieve Xero-recorded invoice/bill history events (not a complete field-level audit trail) |
153
157
  | `create-invoice` | Create a new draft invoice (AR or AP) |
154
158
  | `update-invoice` | Update a draft invoice |
155
159
  | `authorise-invoice` | Promote a DRAFT or SUBMITTED invoice to AUTHORISED |
156
160
  | `void-invoice` | Void an AUTHORISED invoice, or delete a DRAFT invoice |
157
161
  | `get-invoice-pdf` | Download the Xero-generated invoice PDF to local disk |
158
162
  | `list-invoice-attachments` | List all file attachments on an invoice |
163
+ | `xero_list_bill_attachments` | Return compact structured attachment metadata without binary content |
159
164
  | `upload-invoice-attachment` | Upload a local file (e.g. Crystal Reports PDF) as an invoice attachment |
160
165
  | `get-invoice-attachment` | Download an invoice attachment to local disk |
166
+ | `xero_get_bill_attachment` | Explicit metadata-verified attachment download with a configurable size limit |
161
167
  | `delete-invoice-attachment` | Delete an attachment from an invoice |
162
168
 
163
169
  ### Quotes
@@ -172,6 +178,7 @@ Date inputs to the Xero API (invoice dates, fromDate, toDate, etc.) are `YYYY-MM
172
178
  | Tool | Description |
173
179
  |---|---|
174
180
  | `list-contacts` | List contacts with optional search term |
181
+ | `xero_find_contact` | Resolve a contact by ID, name, contact/account number, email or tax number without silently choosing ambiguous matches |
175
182
  | `create-contact` | Create a new contact |
176
183
  | `update-contact` | Update an existing contact |
177
184
  | `archive-contact` | Archive a contact (Xero does not support hard deletion) |
@@ -256,6 +263,26 @@ The server supplies MCP `instructions` that are automatically delivered to the c
256
263
 
257
264
  For a full query playbook, see the MCP resource `xero://guidance/agent-playbook` (or `AGENTS.md` for local reference).
258
265
 
266
+ ### Structured lookup contracts
267
+
268
+ The `xero_*` lookup tools return compact JSON with a consistent `matchStatus`
269
+ (`EXACT`, `MULTIPLE`, `CANDIDATES`, `NOT_FOUND`, or `ERROR`), an explicit
270
+ `ambiguous` flag, pagination completeness/continuation metadata where relevant,
271
+ and structured errors. Xero and external identifiers remain strings; money values
272
+ are returned as decimal strings with their currency code.
273
+
274
+ For TEAMlink purchase bills, live API verification confirmed that the convention
275
+ `<supplier-invoice-number> / <TEAMlink-orderId>` is stored in Xero's
276
+ `InvoiceNumber` field (for example `4462570 / 121058`), while `Reference` is empty.
277
+ Exact and batch searches therefore use Xero's native `InvoiceNumbers` filter. The
278
+ separate `reference` search remains available for records that use that field.
279
+
280
+ `xero_batch_invoice_lookup.invoiceNumbers` is a native JSON string array. Numeric-
281
+ looking identifiers are intentionally not coerced to numbers. The reported Hermes
282
+ `coerce_tool_args` defect is outside this repository and must also be corrected in
283
+ the Hermes runtime if that client still rewrites valid JSON arrays before sending
284
+ the MCP request.
285
+
259
286
  ## For Developers
260
287
 
261
288
  ### 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
+ }
@@ -0,0 +1,86 @@
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 async function searchXeroTransactions(params) {
65
+ try {
66
+ await xeroClient.authenticate();
67
+ const query = buildInvoiceSearchQuery(params);
68
+ 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());
70
+ const raw = response.body.invoices ?? [];
71
+ const filtered = filterInvoiceMatches(raw, params);
72
+ const truncated = raw.length > params.pageSize || filtered.length > params.pageSize;
73
+ const matches = filtered.slice(0, params.pageSize).map(compactInvoice);
74
+ return successfulLookup(matches, params.matchMode === "exact", {
75
+ page: params.page,
76
+ pageSize: params.pageSize,
77
+ returned: matches.length,
78
+ truncated,
79
+ nextPage: truncated ? params.page + 1 : null,
80
+ complete: !truncated,
81
+ });
82
+ }
83
+ catch (error) {
84
+ return failedLookup(formatError(error));
85
+ }
86
+ }
@@ -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 native batch request. Accepts a real JSON array of strings; numeric-looking identifiers remain strings. Reports each input independently, including duplicates and unmatched values.", {
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,10 @@ 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";
31
35
  export const CoreListTools = [
32
36
  ListAccountsTool,
33
37
  ListContactsTool,
@@ -46,6 +50,10 @@ export const CoreListTools = [
46
50
  ListContactGroupsTool,
47
51
  ListTrackingCategoriesTool,
48
52
  ListInvoiceAttachmentsTool,
53
+ SearchTransactionsTool,
54
+ BatchInvoiceLookupTool,
55
+ FindContactTool,
56
+ ListBillAttachmentsTool,
49
57
  ];
50
58
  export const ReportListTools = [
51
59
  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;
@@ -8,7 +8,7 @@ const ListProfitAndLossTool = CreateXeroTool("list-profit-and-loss", "Lists prof
8
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."),
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 (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."),
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) => {
@@ -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 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.", {
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.0",
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",