@mindstone/mcp-server-xero 0.0.17 → 0.1.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.
Files changed (29) hide show
  1. package/README.md +46 -0
  2. package/dist/clients/xero-client.js +2 -3
  3. package/dist/handlers/create-xero-purchase-order.handler.js +50 -0
  4. package/dist/handlers/email-xero-invoice.handler.js +27 -0
  5. package/dist/handlers/list-xero-bank-summary.handler.js +38 -0
  6. package/dist/handlers/list-xero-budget-summary.handler.js +45 -0
  7. package/dist/handlers/list-xero-executive-summary.handler.js +37 -0
  8. package/dist/handlers/list-xero-purchase-orders.handler.js +29 -0
  9. package/dist/helpers/create-xero-tool.js +32 -1
  10. package/dist/helpers/get-deeplink.js +15 -4
  11. package/dist/helpers/xero-currencies.js +1 -1
  12. package/dist/server/xero-mcp-server.js +2 -1
  13. package/dist/tools/create/create-contact.tool.js +2 -3
  14. package/dist/tools/create/create-manual-journal.tool.js +2 -3
  15. package/dist/tools/create/create-purchase-order.tool.js +66 -0
  16. package/dist/tools/create/index.js +3 -1
  17. package/dist/tools/list/index.js +9 -1
  18. package/dist/tools/list/list-bank-summary.tool.js +41 -0
  19. package/dist/tools/list/list-budget-summary.tool.js +47 -0
  20. package/dist/tools/list/list-executive-summary.tool.js +36 -0
  21. package/dist/tools/list/list-purchase-orders.tool.js +97 -0
  22. package/dist/tools/tool-factory.js +4 -1
  23. package/dist/tools/update/email-invoice.tool.js +29 -0
  24. package/dist/tools/update/index.js +3 -1
  25. package/dist/tools/update/update-contact.tool.js +2 -3
  26. package/dist/tools/update/update-manual-journal-tool.js +2 -3
  27. package/dist/untrusted-content.js +119 -0
  28. package/package.json +1 -1
  29. package/dist/helpers/ensure-error.js +0 -13
package/README.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  This is a Model Context Protocol (MCP) server implementation for Xero. It provides a bridge between the MCP protocol and Xero's API, allowing for standardized access to Xero's accounting and business features.
4
4
 
5
+ ## Provenance
6
+
7
+ This package is Mindstone's maintained build of Xero's community Xero MCP server, announced on the [Xero Developer Blog](https://devblog.xero.com/xero-introduces-new-model-context-protocol-server-for-smarter-accounting-data-integration) and developed upstream at [XeroAPI/xero-mcp-server](https://github.com/XeroAPI/xero-mcp-server). It adds improvements and hardening by Mindstone on top of the upstream project.
8
+
9
+ <!-- BEGIN INSTALL_LINKS: do not edit by hand; regenerated by scripts/gen-install-links.mjs -->
10
+ ## One-click install
11
+
12
+ [![Add to Cursor](https://img.shields.io/badge/Add_to_Cursor-black?style=for-the-badge&logo=cursor&logoColor=white)](cursor://anysphere.cursor-deeplink/mcp/install?name=Xero&config=eyJ0eXBlIjoic3RkaW8iLCJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBtaW5kc3RvbmUvbWNwLXNlcnZlci14ZXJvIl0sImVudiI6eyJYRVJPX0NMSUVOVF9JRCI6IiIsIlhFUk9fQ0xJRU5UX1NFQ1JFVCI6IiIsIlhFUk9fQ0xJRU5UX0JFQVJFUl9UT0tFTiI6IiJ9fQ)
13
+ [![Add to VS Code](https://img.shields.io/badge/Add_to_VS_Code-007ACC?style=for-the-badge&logo=visual-studio-code&logoColor=white)](vscode:mcp/install?%7B%22name%22%3A%22Xero%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40mindstone%2Fmcp-server-xero%22%5D%2C%22env%22%3A%7B%22XERO_CLIENT_ID%22%3A%22%22%2C%22XERO_CLIENT_SECRET%22%3A%22%22%2C%22XERO_CLIENT_BEARER_TOKEN%22%3A%22%22%7D%7D)
14
+ [![Add to VS Code Insiders](https://img.shields.io/badge/Add_to_VS_Code_Insiders-24bfa5?style=for-the-badge&logo=visual-studio-code&logoColor=white)](vscode-insiders:mcp/install?%7B%22name%22%3A%22Xero%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40mindstone%2Fmcp-server-xero%22%5D%2C%22env%22%3A%7B%22XERO_CLIENT_ID%22%3A%22%22%2C%22XERO_CLIENT_SECRET%22%3A%22%22%2C%22XERO_CLIENT_BEARER_TOKEN%22%3A%22%22%7D%7D)
15
+
16
+ After clicking the button, your host will prompt you to fill: `XERO_CLIENT_ID`, `XERO_CLIENT_SECRET`, `XERO_CLIENT_BEARER_TOKEN`.
17
+
18
+ <details>
19
+ <summary>Manual config for Claude Desktop / Claude Code / Goose / Continue.dev (Xero)</summary>
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "Xero": {
25
+ "command": "npx",
26
+ "args": [
27
+ "-y",
28
+ "@mindstone/mcp-server-xero"
29
+ ],
30
+ "env": {
31
+ "XERO_CLIENT_ID": "",
32
+ "XERO_CLIENT_SECRET": "",
33
+ "XERO_CLIENT_BEARER_TOKEN": ""
34
+ }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ </details>
41
+ <!-- END INSTALL_LINKS -->
42
+
5
43
  ## Features
6
44
 
7
45
  - Xero OAuth2 authentication with custom connections
@@ -93,6 +131,8 @@ NOTE: The `XERO_CLIENT_BEARER_TOKEN` will take precedence over the `XERO_CLIENT_
93
131
 
94
132
  ### Available MCP Commands
95
133
 
134
+ > **Tool naming:** this connector's tools use unprefixed dash-case names (e.g. `list-invoices`, `create-contact`), inherited from its fork lineage. Sibling connectors use prefixed snake_case names (e.g. `list_quickbooks_invoices`). In multi-server hosts, unprefixed generic names can collide with other servers' tools. Renaming would be a breaking change for existing configurations, so the names are kept as-is; if your host supports namespacing/aliasing, prefer enabling it for this server.
135
+
96
136
  - `list-accounts`: Retrieve a list of accounts
97
137
  - `list-contacts`: Retrieve a list of contacts from Xero
98
138
  - `list-credit-notes`: Retrieve a list of credit notes
@@ -100,6 +140,9 @@ NOTE: The `XERO_CLIENT_BEARER_TOKEN` will take precedence over the `XERO_CLIENT_
100
140
  - `list-items`: Retrieve a list of items
101
141
  - `list-organisation-details`: Retrieve details about an organisation
102
142
  - `list-profit-and-loss`: Retrieve a profit and loss report
143
+ - `list-bank-summary`: Retrieve the bank summary report (per-account balances and movements)
144
+ - `list-budget-summary`: Retrieve the budget summary report (budget vs actuals)
145
+ - `list-executive-summary`: Retrieve the executive summary report (key financial metrics snapshot)
103
146
  - `list-quotes`: Retrieve a list of quotes
104
147
  - `list-tax-rates`: Retrieve a list of tax rates
105
148
  - `list-payments`: Retrieve a list of payments
@@ -118,11 +161,13 @@ NOTE: The `XERO_CLIENT_BEARER_TOKEN` will take precedence over the `XERO_CLIENT_
118
161
  - `list-contact-groups`: Retrieve a list of contact groups
119
162
  - `list-currencies`: Retrieve currencies enabled in the connected Xero organisation
120
163
  - `list-invoice-attachments`: Retrieve files attached to a Xero invoice
164
+ - `list-purchase-orders`: Retrieve a list of purchase orders
121
165
  - `create-contact`: Create a new contact
122
166
  - `create-credit-note`: Create a new credit note
123
167
  - `create-invoice`: Create a new invoice. Supports optional `currencyCode`, such as `USD`, when that currency is enabled in the connected Xero organisation.
124
168
  - `create-payment`: Create a new payment
125
169
  - `create-quote`: Create a new quote
170
+ - `create-purchase-order`: Create a new purchase order
126
171
  - `create-credit-note`: Create a new credit note
127
172
  - `create-payroll-timesheet`: Create a new Payroll Timesheet
128
173
  - `update-contact`: Update an existing contact
@@ -145,6 +190,7 @@ NOTE: The `XERO_CLIENT_BEARER_TOKEN` will take precedence over the `XERO_CLIENT_
145
190
  - `add-payroll-timesheet-line`: Add new line on an existing Payroll Timesheet
146
191
  - `delete-payroll-timesheet`: Delete an existing Payroll Timesheet
147
192
  - `get-payroll-timesheet`: Retrieve an existing Payroll Timesheet
193
+ - `email-invoice`: Email a copy of an AUTHORISED invoice to its related contact
148
194
 
149
195
  For detailed API documentation, please refer to the [MCP Protocol Specification](https://modelcontextprotocol.io/).
150
196
 
@@ -1,7 +1,7 @@
1
1
  import axios from "axios";
2
2
  import dotenv from "dotenv";
3
3
  import { XeroClient, } from "xero-node";
4
- import { ensureError } from "../helpers/ensure-error.js";
4
+ import { formatError } from "../helpers/format-error.js";
5
5
  import { formatTokenRequestError } from "../helpers/format-token-error.js";
6
6
  import { XERO_CUSTOM_CONNECTION_SCOPE } from "./xero-scopes.js";
7
7
  dotenv.config();
@@ -44,8 +44,7 @@ class MCPXeroClient extends XeroClient {
44
44
  this.shortCode = organisation.shortCode ?? "";
45
45
  }
46
46
  catch (error) {
47
- const err = ensureError(error);
48
- throw new Error(`Failed to get Organisation short code: ${err.message}`);
47
+ throw new Error(`Failed to get Organisation short code: ${formatError(error)}`);
49
48
  }
50
49
  }
51
50
  return this.shortCode;
@@ -0,0 +1,50 @@
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 { assertXeroCurrencyEnabled } from "../helpers/xero-currencies.js";
5
+ import { PurchaseOrder } from "xero-node";
6
+ async function createPurchaseOrder(contactId, lineItems, reference, date, deliveryDate, purchaseOrderNumber, currencyCode, status) {
7
+ await xeroClient.authenticate();
8
+ await assertXeroCurrencyEnabled(currencyCode);
9
+ const purchaseOrder = {
10
+ contact: {
11
+ contactID: contactId,
12
+ },
13
+ lineItems: lineItems,
14
+ ...(date ? { date } : {}),
15
+ ...(deliveryDate ? { deliveryDate } : {}),
16
+ ...(reference ? { reference } : {}),
17
+ ...(purchaseOrderNumber ? { purchaseOrderNumber } : {}),
18
+ ...(currencyCode ? { currencyCode } : {}),
19
+ status: status ?? PurchaseOrder.StatusEnum.DRAFT,
20
+ };
21
+ const response = await xeroClient.accountingApi.createPurchaseOrders(xeroClient.tenantId, {
22
+ purchaseOrders: [purchaseOrder],
23
+ }, true, // summarizeErrors
24
+ undefined, // idempotencyKey
25
+ getClientHeaders());
26
+ return response.body.purchaseOrders?.[0];
27
+ }
28
+ /**
29
+ * Create a new purchase order in Xero
30
+ */
31
+ export async function createXeroPurchaseOrder(contactId, lineItems, reference, date, deliveryDate, purchaseOrderNumber, currencyCode, status) {
32
+ try {
33
+ const createdPurchaseOrder = await createPurchaseOrder(contactId, lineItems, reference, date, deliveryDate, purchaseOrderNumber, currencyCode, status);
34
+ if (!createdPurchaseOrder) {
35
+ throw new Error("Purchase order creation failed.");
36
+ }
37
+ return {
38
+ result: createdPurchaseOrder,
39
+ isError: false,
40
+ error: null,
41
+ };
42
+ }
43
+ catch (error) {
44
+ return {
45
+ result: null,
46
+ isError: true,
47
+ error: formatError(error),
48
+ };
49
+ }
50
+ }
@@ -0,0 +1,27 @@
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
+ /**
5
+ * Email a copy of an invoice to its related contact via Xero.
6
+ * The invoice must be AUTHORISED — Xero rejects emails for DRAFT or
7
+ * SUBMITTED invoices.
8
+ */
9
+ export async function emailXeroInvoice(invoiceId) {
10
+ try {
11
+ await xeroClient.authenticate();
12
+ await xeroClient.accountingApi.emailInvoice(xeroClient.tenantId, invoiceId, {}, undefined, // idempotencyKey
13
+ getClientHeaders());
14
+ return {
15
+ result: true,
16
+ isError: false,
17
+ error: null,
18
+ };
19
+ }
20
+ catch (error) {
21
+ return {
22
+ result: null,
23
+ isError: true,
24
+ error: formatError(error),
25
+ };
26
+ }
27
+ }
@@ -0,0 +1,38 @@
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
+ async function fetchBankSummary(fromDate, toDate) {
5
+ await xeroClient.authenticate();
6
+ const response = await xeroClient.accountingApi.getReportBankSummary(xeroClient.tenantId, fromDate, toDate, getClientHeaders());
7
+ return response.body.reports?.[0] ?? null;
8
+ }
9
+ /**
10
+ * Get the bank summary report from Xero (opening/closing balances and
11
+ * movements per bank account over a period).
12
+ * @param fromDate Optional start date for the report (YYYY-MM-DD)
13
+ * @param toDate Optional end date for the report (YYYY-MM-DD)
14
+ */
15
+ export async function listXeroBankSummary(fromDate, toDate) {
16
+ try {
17
+ const report = await fetchBankSummary(fromDate, toDate);
18
+ if (!report) {
19
+ return {
20
+ result: null,
21
+ isError: true,
22
+ error: "Failed to fetch bank summary data from Xero.",
23
+ };
24
+ }
25
+ return {
26
+ result: report,
27
+ isError: false,
28
+ error: null,
29
+ };
30
+ }
31
+ catch (error) {
32
+ return {
33
+ result: null,
34
+ isError: true,
35
+ error: formatError(error),
36
+ };
37
+ }
38
+ }
@@ -0,0 +1,45 @@
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
+ // The SDK takes timeframe as a number of months (1=MONTH, 3=QUARTER, 12=YEAR).
5
+ const TIMEFRAME_MONTHS = {
6
+ MONTH: 1,
7
+ QUARTER: 3,
8
+ YEAR: 12,
9
+ };
10
+ async function fetchBudgetSummary(date, periods, timeframe) {
11
+ await xeroClient.authenticate();
12
+ const response = await xeroClient.accountingApi.getReportBudgetSummary(xeroClient.tenantId, date, periods, timeframe ? TIMEFRAME_MONTHS[timeframe] : undefined, getClientHeaders());
13
+ return response.body.reports?.[0] ?? null;
14
+ }
15
+ /**
16
+ * Get the budget summary report from Xero (budgeted vs actual figures per
17
+ * account).
18
+ * @param date Optional date for the report (YYYY-MM-DD)
19
+ * @param periods Optional number of periods to compare (1-12)
20
+ * @param timeframe Optional period size to compare (MONTH, QUARTER, YEAR)
21
+ */
22
+ export async function listXeroBudgetSummary(date, periods, timeframe) {
23
+ try {
24
+ const report = await fetchBudgetSummary(date, periods, timeframe);
25
+ if (!report) {
26
+ return {
27
+ result: null,
28
+ isError: true,
29
+ error: "Failed to fetch budget summary data from Xero.",
30
+ };
31
+ }
32
+ return {
33
+ result: report,
34
+ isError: false,
35
+ error: null,
36
+ };
37
+ }
38
+ catch (error) {
39
+ return {
40
+ result: null,
41
+ isError: true,
42
+ error: formatError(error),
43
+ };
44
+ }
45
+ }
@@ -0,0 +1,37 @@
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
+ async function fetchExecutiveSummary(date) {
5
+ await xeroClient.authenticate();
6
+ const response = await xeroClient.accountingApi.getReportExecutiveSummary(xeroClient.tenantId, date, getClientHeaders());
7
+ return response.body.reports?.[0] ?? null;
8
+ }
9
+ /**
10
+ * Get the executive summary report from Xero (a high-level snapshot of key
11
+ * financial metrics such as cash, debtors, creditors, and profit).
12
+ * @param date Optional date for the report (YYYY-MM-DD)
13
+ */
14
+ export async function listXeroExecutiveSummary(date) {
15
+ try {
16
+ const report = await fetchExecutiveSummary(date);
17
+ if (!report) {
18
+ return {
19
+ result: null,
20
+ isError: true,
21
+ error: "Failed to fetch executive summary data from Xero.",
22
+ };
23
+ }
24
+ return {
25
+ result: report,
26
+ isError: false,
27
+ error: null,
28
+ };
29
+ }
30
+ catch (error) {
31
+ return {
32
+ result: null,
33
+ isError: true,
34
+ error: formatError(error),
35
+ };
36
+ }
37
+ }
@@ -0,0 +1,29 @@
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
+ async function getPurchaseOrders(status, dateFrom, dateTo, order, page, pageSize) {
5
+ await xeroClient.authenticate();
6
+ const response = await xeroClient.accountingApi.getPurchaseOrders(xeroClient.tenantId, undefined, // ifModifiedSince
7
+ status, dateFrom, dateTo, order, page, pageSize ?? 100, getClientHeaders());
8
+ return response.body.purchaseOrders ?? [];
9
+ }
10
+ /**
11
+ * List purchase orders from Xero
12
+ */
13
+ export async function listXeroPurchaseOrders(page = 1, status, dateFrom, dateTo, order, pageSize) {
14
+ try {
15
+ const purchaseOrders = await getPurchaseOrders(status, dateFrom, dateTo, order, page, pageSize);
16
+ return {
17
+ result: purchaseOrders,
18
+ isError: false,
19
+ error: null,
20
+ };
21
+ }
22
+ catch (error) {
23
+ return {
24
+ result: null,
25
+ isError: true,
26
+ error: formatError(error),
27
+ };
28
+ }
29
+ }
@@ -1,6 +1,37 @@
1
+ import { wrapUntrusted } from "../untrusted-content.js";
2
+ import { formatError } from "./format-error.js";
3
+ /**
4
+ * AGENTS.md security invariant #6: any text block a tool returns can carry
5
+ * Xero-authored (attacker-controllable) text — contact names, line item
6
+ * descriptions, references, history details/changes, validation messages.
7
+ * Envelope every text block here, at the single factory every tool is built
8
+ * with, so individual tools cannot forget to wrap their external text.
9
+ */
10
+ function envelopToolResult(result, source) {
11
+ return {
12
+ ...result,
13
+ content: result.content?.map((block) => block.type === "text"
14
+ ? { ...block, text: wrapUntrusted(block.text, source) ?? block.text }
15
+ : block),
16
+ };
17
+ }
1
18
  export const CreateXeroTool = (name, description, schema, handler) => () => ({
2
19
  name: name,
3
20
  description: description,
4
21
  schema: schema,
5
- handler: handler,
22
+ handler: (async (args, extra) => {
23
+ try {
24
+ return envelopToolResult(await handler(args, extra), `xero.${name}`);
25
+ }
26
+ catch (error) {
27
+ // A rejection would otherwise bypass the envelope: the SDK serialises
28
+ // the raw error message into a plain, unwrapped text block. Format it
29
+ // (whitelisted fields only — SDK rejections can carry bearer tokens)
30
+ // and route it through the same choke point as any other result.
31
+ return envelopToolResult({
32
+ content: [{ type: "text", text: formatError(error) }],
33
+ isError: true,
34
+ }, `xero.${name}`);
35
+ }
36
+ }),
6
37
  });
@@ -1,4 +1,5 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
+ import { formatError } from "./format-error.js";
2
3
  import { contactDeepLink, creditNoteDeepLink, invoiceDeepLink, paymentDeepLink, manualJournalDeepLink, quoteDeepLink, billDeepLink, } from "../consts/deeplinks.js";
3
4
  export var DeepLinkType;
4
5
  (function (DeepLinkType) {
@@ -11,16 +12,26 @@ export var DeepLinkType;
11
12
  DeepLinkType[DeepLinkType["BILL"] = 6] = "BILL";
12
13
  })(DeepLinkType || (DeepLinkType = {}));
13
14
  /**
14
- * Gets a deep link for a specific type and item ID.
15
- * This will also fetch the org short code from the Xero client.
15
+ * Gets a deep link for a specific type and item ID, or `null` when the link
16
+ * cannot be resolved. Best-effort by design: every caller has already
17
+ * committed a successful write in Xero, so a deeplink failure must never
18
+ * surface as a tool error — the model would retry and duplicate the record.
16
19
  * @param type
17
20
  * @param itemId
18
21
  * @returns
19
22
  */
20
23
  export const getDeepLink = async (type, itemId) => {
21
- const orgShortCode = await xeroClient.getShortCode();
24
+ let orgShortCode;
25
+ try {
26
+ orgShortCode = await xeroClient.getShortCode();
27
+ }
28
+ catch (error) {
29
+ console.warn(`Failed to resolve Xero deep link: ${formatError(error)}`);
30
+ return null;
31
+ }
22
32
  if (!orgShortCode) {
23
- throw new Error("Failed to retrieve organisation short code");
33
+ console.warn("Failed to resolve Xero deep link: no organisation short code");
34
+ return null;
24
35
  }
25
36
  switch (type) {
26
37
  case DeepLinkType.CONTACT:
@@ -19,5 +19,5 @@ export async function assertXeroCurrencyEnabled(currencyCode) {
19
19
  const enabledList = enabledCurrencyCodes.length
20
20
  ? enabledCurrencyCodes.join(", ")
21
21
  : "none";
22
- throw new Error(`Currency ${currencyCode} is not enabled in this Xero organisation. Enabled currencies: ${enabledList}. Add ${currencyCode} in Xero before creating or updating invoices in that currency.`);
22
+ throw new Error(`Currency ${currencyCode} is not enabled in this Xero organisation. Enabled currencies: ${enabledList}. Add ${currencyCode} in Xero before creating or updating records in that currency.`);
23
23
  }
@@ -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
  }
12
13
  return XeroMcpServer.instance;
@@ -1,7 +1,7 @@
1
1
  import { createXeroContact } from "../../handlers/create-xero-contact.handler.js";
2
2
  import { z } from "zod";
3
3
  import { DeepLinkType, getDeepLink } from "../../helpers/get-deeplink.js";
4
- import { ensureError } from "../../helpers/ensure-error.js";
4
+ import { formatError } from "../../helpers/format-error.js";
5
5
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
6
6
  const CreateContactTool = CreateXeroTool("create-contact", "Create a contact in Xero.\
7
7
  When a contact is created, a deep link to the contact in Xero is returned. \
@@ -42,12 +42,11 @@ const CreateContactTool = CreateXeroTool("create-contact", "Create a contact in
42
42
  };
43
43
  }
44
44
  catch (error) {
45
- const err = ensureError(error);
46
45
  return {
47
46
  content: [
48
47
  {
49
48
  type: "text",
50
- text: `Error creating contact: ${err.message}`,
49
+ text: `Error creating contact: ${formatError(error)}`,
51
50
  },
52
51
  ],
53
52
  };
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
3
  import { createXeroManualJournal } from "../../handlers/create-xero-manual-journal.handler.js";
4
4
  import { DeepLinkType, getDeepLink } from "../../helpers/get-deeplink.js";
5
- import { ensureError } from "../../helpers/ensure-error.js";
5
+ import { formatError } from "../../helpers/format-error.js";
6
6
  const CreateManualJournalTool = CreateXeroTool("create-manual-journal", "Create a manual journal in Xero.\
7
7
  Retrieve a list of account codes in Xero to use for the journal lines.\
8
8
  Journal lines must contain at least two individual journal lines with account codes, \
@@ -102,12 +102,11 @@ const CreateManualJournalTool = CreateXeroTool("create-manual-journal", "Create
102
102
  };
103
103
  }
104
104
  catch (error) {
105
- const err = ensureError(error);
106
105
  return {
107
106
  content: [
108
107
  {
109
108
  type: "text",
110
- text: `Error creating manual journal: ${err.message}`,
109
+ text: `Error creating manual journal: ${formatError(error)}`,
111
110
  },
112
111
  ],
113
112
  };
@@ -0,0 +1,66 @@
1
+ import { z } from "zod";
2
+ import { createXeroPurchaseOrder } from "../../handlers/create-xero-purchase-order.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ import { CurrencyCode, PurchaseOrder } from "xero-node";
5
+ const lineItemSchema = z.object({
6
+ description: z.string().describe("The description of the line item"),
7
+ quantity: z.number().describe("The quantity of the line item"),
8
+ unitAmount: z.number().describe("The price per unit of the line item"),
9
+ accountCode: z.string().describe("The account code of the line item - can be obtained from the list-accounts tool"),
10
+ taxType: z.string().describe("The tax type of the line item - can be obtained from the list-tax-rates tool"),
11
+ itemCode: z.string().describe("The item code of the line item - can be obtained from the list-items tool").optional(),
12
+ });
13
+ const CreatePurchaseOrderTool = CreateXeroTool("create-purchase-order", "Create a purchase order in Xero for a supplier. The purchase order is created as DRAFT unless a status is specified.", {
14
+ contactId: z.string().describe("The ID of the supplier contact to create the purchase order for. \
15
+ Can be obtained from the list-contacts tool."),
16
+ lineItems: z.array(lineItemSchema),
17
+ reference: z.string().describe("An additional reference for the purchase order.").optional(),
18
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format").describe("The date the purchase order was issued (YYYY-MM-DD format). Defaults to today.").optional(),
19
+ deliveryDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format").describe("The date the goods are to be delivered (YYYY-MM-DD format).").optional(),
20
+ purchaseOrderNumber: z.string().describe("A unique alpha-numeric code for the purchase order. When omitted, Xero auto-generates one from the organisation settings.").optional(),
21
+ currencyCode: z.nativeEnum(CurrencyCode).describe("Optional purchase order currency, such as USD. Only use a currency enabled in the connected Xero organisation.").optional(),
22
+ status: z.enum(["DRAFT", "SUBMITTED", "AUTHORISED"]).describe("The status to create the purchase order with. Defaults to DRAFT.").optional(),
23
+ }, async ({ contactId, lineItems, reference, date, deliveryDate, purchaseOrderNumber, currencyCode, status }) => {
24
+ const statusMap = {
25
+ DRAFT: PurchaseOrder.StatusEnum.DRAFT,
26
+ SUBMITTED: PurchaseOrder.StatusEnum.SUBMITTED,
27
+ AUTHORISED: PurchaseOrder.StatusEnum.AUTHORISED,
28
+ };
29
+ const result = await createXeroPurchaseOrder(contactId, lineItems, reference, date, deliveryDate, purchaseOrderNumber, currencyCode, status ? statusMap[status] : undefined);
30
+ if (result.isError) {
31
+ return {
32
+ content: [
33
+ {
34
+ type: "text",
35
+ text: `Error creating purchase order: ${result.error}`,
36
+ },
37
+ ],
38
+ };
39
+ }
40
+ const purchaseOrder = result.result;
41
+ return {
42
+ content: [
43
+ {
44
+ type: "text",
45
+ text: [
46
+ "Purchase order created successfully:",
47
+ `ID: ${purchaseOrder?.purchaseOrderID}`,
48
+ `Purchase Order: ${purchaseOrder?.purchaseOrderNumber}`,
49
+ `Contact: ${purchaseOrder?.contact?.name}`,
50
+ purchaseOrder?.date ? `Date: ${purchaseOrder.date}` : null,
51
+ purchaseOrder?.deliveryDate
52
+ ? `Delivery Date: ${purchaseOrder.deliveryDate}`
53
+ : null,
54
+ purchaseOrder?.currencyCode
55
+ ? `Currency: ${purchaseOrder.currencyCode}`
56
+ : null,
57
+ `Total: ${purchaseOrder?.total}`,
58
+ `Status: ${purchaseOrder?.status}`,
59
+ ]
60
+ .filter(Boolean)
61
+ .join("\n"),
62
+ },
63
+ ],
64
+ };
65
+ });
66
+ export default CreatePurchaseOrderTool;
@@ -5,6 +5,7 @@ import CreateInvoiceTool from "./create-invoice.tool.js";
5
5
  import CreateItemTool from "./create-item.tool.js";
6
6
  import CreateManualJournalTool from "./create-manual-journal.tool.js";
7
7
  import CreatePaymentTool from "./create-payment.tool.js";
8
+ import CreatePurchaseOrderTool from "./create-purchase-order.tool.js";
8
9
  import CreatePayrollTimesheetTool from "./create-payroll-timesheet.tool.js";
9
10
  import CreateQuoteTool from "./create-quote.tool.js";
10
11
  import CreateTrackingCategoryTool from "./create-tracking-category.tool.js";
@@ -20,5 +21,6 @@ export const CreateTools = [
20
21
  CreateBankTransactionTool,
21
22
  CreatePayrollTimesheetTool,
22
23
  CreateTrackingCategoryTool,
23
- CreateTrackingOptionsTool
24
+ CreateTrackingOptionsTool,
25
+ CreatePurchaseOrderTool
24
26
  ];
@@ -1,7 +1,9 @@
1
1
  import ListAccountsTool from "./list-accounts.tool.js";
2
2
  import ListAgedPayablesByContact from "./list-aged-payables-by-contact.tool.js";
3
3
  import ListAgedReceivablesByContact from "./list-aged-receivables-by-contact.tool.js";
4
+ import ListBankSummaryTool from "./list-bank-summary.tool.js";
4
5
  import ListBankTransactionsTool from "./list-bank-transactions.tool.js";
6
+ import ListBudgetSummaryTool from "./list-budget-summary.tool.js";
5
7
  import ListContactsTool from "./list-contacts.tool.js";
6
8
  import ListCreditNotesTool from "./list-credit-notes.tool.js";
7
9
  import ListCurrenciesTool from "./list-currencies.tool.js";
@@ -10,6 +12,7 @@ import ListItemsTool from "./list-items.tool.js";
10
12
  import ListManualJournalsTool from "./list-manual-journals.tool.js";
11
13
  import ListOrganisationDetailsTool from "./list-organisation-details.tool.js";
12
14
  import ListPaymentsTool from "./list-payments.tool.js";
15
+ import ListPurchaseOrdersTool from "./list-purchase-orders.tool.js";
13
16
  import ListPayrollEmployeeLeaveBalancesTool from "./list-payroll-employee-leave-balances.tool.js";
14
17
  import ListPayrollEmployeeLeaveTypesTool from "./list-payroll-employee-leave-types.tool.js";
15
18
  import ListPayrollEmployeeLeaveTool from "./list-payroll-employee-leave.tool.js";
@@ -25,6 +28,7 @@ import ListTrackingCategoriesTool from "./list-tracking-categories.tool.js";
25
28
  import ListTrialBalanceTool from "./list-trial-balance.tool.js";
26
29
  import ListContactGroupsTool from "./list-contact-groups.tool.js";
27
30
  import ListInvoiceAttachmentsTool from "./list-invoice-attachments.tool.js";
31
+ import ListExecutiveSummaryTool from "./list-executive-summary.tool.js";
28
32
  export const ListTools = [
29
33
  ListAccountsTool,
30
34
  ListContactsTool,
@@ -52,5 +56,9 @@ export const ListTools = [
52
56
  ListPayrollTimesheetsTool,
53
57
  ListContactGroupsTool,
54
58
  ListTrackingCategoriesTool,
55
- ListInvoiceAttachmentsTool
59
+ ListInvoiceAttachmentsTool,
60
+ ListBankSummaryTool,
61
+ ListBudgetSummaryTool,
62
+ ListExecutiveSummaryTool,
63
+ ListPurchaseOrdersTool
56
64
  ];
@@ -0,0 +1,41 @@
1
+ import { z } from "zod";
2
+ import { listXeroBankSummary } from "../../handlers/list-xero-bank-summary.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ const ListBankSummaryTool = CreateXeroTool("list-bank-summary", "Get the bank summary report from Xero: opening and closing balances plus total money in/out per bank account over a period. Useful for cash-position questions.", {
5
+ fromDate: z
6
+ .string()
7
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
8
+ .optional()
9
+ .describe("Optional start date of the report period (YYYY-MM-DD)"),
10
+ toDate: z
11
+ .string()
12
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
13
+ .optional()
14
+ .describe("Optional end date of the report period (YYYY-MM-DD)"),
15
+ }, async ({ fromDate, toDate }) => {
16
+ const response = await listXeroBankSummary(fromDate, toDate);
17
+ if (response.error !== null) {
18
+ return {
19
+ content: [
20
+ {
21
+ type: "text",
22
+ text: `Error getting bank summary report: ${response.error}`,
23
+ },
24
+ ],
25
+ };
26
+ }
27
+ const report = response.result;
28
+ return {
29
+ content: [
30
+ {
31
+ type: "text",
32
+ text: `Bank Summary Report: ${report?.reportName ?? "Unnamed"}`,
33
+ },
34
+ {
35
+ type: "text",
36
+ text: JSON.stringify(report.rows, null, 2),
37
+ },
38
+ ],
39
+ };
40
+ });
41
+ export default ListBankSummaryTool;
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ import { listXeroBudgetSummary } from "../../handlers/list-xero-budget-summary.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ const ListBudgetSummaryTool = CreateXeroTool("list-budget-summary", "Get the budget summary report from Xero: budgeted vs actual figures per account. Useful for 'are we tracking to budget?' questions. Requires budgets to be set up in the Xero organisation.", {
5
+ date: z
6
+ .string()
7
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
8
+ .optional()
9
+ .describe("Optional date for the report (YYYY-MM-DD)"),
10
+ periods: z
11
+ .number()
12
+ .int()
13
+ .min(1)
14
+ .max(12)
15
+ .optional()
16
+ .describe("Optional number of periods to compare (1-12)"),
17
+ timeframe: z
18
+ .enum(["MONTH", "QUARTER", "YEAR"])
19
+ .optional()
20
+ .describe("Optional period size to compare (MONTH, QUARTER, YEAR)"),
21
+ }, async ({ date, periods, timeframe }) => {
22
+ const response = await listXeroBudgetSummary(date, periods, timeframe);
23
+ if (response.error !== null) {
24
+ return {
25
+ content: [
26
+ {
27
+ type: "text",
28
+ text: `Error getting budget summary report: ${response.error}`,
29
+ },
30
+ ],
31
+ };
32
+ }
33
+ const report = response.result;
34
+ return {
35
+ content: [
36
+ {
37
+ type: "text",
38
+ text: `Budget Summary Report: ${report?.reportName ?? "Unnamed"}`,
39
+ },
40
+ {
41
+ type: "text",
42
+ text: JSON.stringify(report.rows, null, 2),
43
+ },
44
+ ],
45
+ };
46
+ });
47
+ export default ListBudgetSummaryTool;
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+ import { listXeroExecutiveSummary } from "../../handlers/list-xero-executive-summary.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ const ListExecutiveSummaryTool = CreateXeroTool("list-executive-summary", "Get the executive summary report from Xero: a high-level snapshot of key financial metrics (cash, debtors, creditors, revenue, profit) for a date. Useful for 'how is the business doing?' questions.", {
5
+ date: z
6
+ .string()
7
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
8
+ .optional()
9
+ .describe("Optional date for the report (YYYY-MM-DD)"),
10
+ }, async ({ date }) => {
11
+ const response = await listXeroExecutiveSummary(date);
12
+ if (response.error !== null) {
13
+ return {
14
+ content: [
15
+ {
16
+ type: "text",
17
+ text: `Error getting executive summary report: ${response.error}`,
18
+ },
19
+ ],
20
+ };
21
+ }
22
+ const report = response.result;
23
+ return {
24
+ content: [
25
+ {
26
+ type: "text",
27
+ text: `Executive Summary Report: ${report?.reportName ?? "Unnamed"}`,
28
+ },
29
+ {
30
+ type: "text",
31
+ text: JSON.stringify(report.rows, null, 2),
32
+ },
33
+ ],
34
+ };
35
+ });
36
+ export default ListExecutiveSummaryTool;
@@ -0,0 +1,97 @@
1
+ import { z } from "zod";
2
+ import { listXeroPurchaseOrders } from "../../handlers/list-xero-purchase-orders.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ const ListPurchaseOrdersTool = CreateXeroTool("list-purchase-orders", `List purchase orders in Xero. Returns up to pageSize results per page (default 100, max 100).
5
+
6
+ FILTERING: Use status to filter (DRAFT, SUBMITTED, AUTHORISED, BILLED, DELETED). Use dateFrom/dateTo for date ranges (YYYY-MM-DD).
7
+
8
+ PAGINATION: If results returned equals pageSize, there may be more pages. Call again with page+1.`, {
9
+ page: z
10
+ .number()
11
+ .int()
12
+ .min(1)
13
+ .optional()
14
+ .describe("Page number (1-based). If results equal pageSize, there may be more pages."),
15
+ status: z
16
+ .enum(["DRAFT", "SUBMITTED", "AUTHORISED", "BILLED", "DELETED"])
17
+ .optional()
18
+ .describe("Filter by purchase order status"),
19
+ dateFrom: z
20
+ .string()
21
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
22
+ .optional()
23
+ .describe("Only purchase orders on or after this date (YYYY-MM-DD)"),
24
+ dateTo: z
25
+ .string()
26
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format")
27
+ .optional()
28
+ .describe("Only purchase orders on or before this date (YYYY-MM-DD)"),
29
+ orderBy: z
30
+ .enum(["Date", "DeliveryDate", "PurchaseOrderNumber"])
31
+ .optional()
32
+ .describe("Sort field. Default: Xero's default order"),
33
+ orderDirection: z
34
+ .enum(["ASC", "DESC"])
35
+ .optional()
36
+ .describe("Sort direction. Only applied when orderBy is set"),
37
+ pageSize: z
38
+ .number()
39
+ .int()
40
+ .min(1)
41
+ .max(100)
42
+ .optional()
43
+ .describe("Results per page (default 100, max 100)"),
44
+ }, async ({ page, status, dateFrom, dateTo, orderBy, orderDirection, pageSize }) => {
45
+ const order = orderBy
46
+ ? `${orderBy} ${orderDirection ?? "ASC"}`
47
+ : undefined;
48
+ const response = await listXeroPurchaseOrders(page ?? 1, status, dateFrom, dateTo, order, pageSize);
49
+ if (response.error !== null) {
50
+ return {
51
+ content: [
52
+ {
53
+ type: "text",
54
+ text: `Error listing purchase orders: ${response.error}`,
55
+ },
56
+ ],
57
+ };
58
+ }
59
+ const purchaseOrders = response.result;
60
+ const effectivePageSize = pageSize ?? 100;
61
+ const count = purchaseOrders?.length ?? 0;
62
+ return {
63
+ content: [
64
+ {
65
+ type: "text",
66
+ text: count === effectivePageSize
67
+ ? `Found ${count} purchase orders. The number of results equals pageSize (${effectivePageSize}), so there may be more pages.`
68
+ : `Found ${count} purchase orders:`,
69
+ },
70
+ ...(purchaseOrders?.map((purchaseOrder) => ({
71
+ type: "text",
72
+ text: [
73
+ `Purchase Order ID: ${purchaseOrder.purchaseOrderID}`,
74
+ `Purchase Order: ${purchaseOrder.purchaseOrderNumber}`,
75
+ purchaseOrder.reference
76
+ ? `Reference: ${purchaseOrder.reference}`
77
+ : null,
78
+ `Status: ${purchaseOrder.status || "Unknown"}`,
79
+ purchaseOrder.contact
80
+ ? `Contact: ${purchaseOrder.contact.name} (${purchaseOrder.contact.contactID})`
81
+ : null,
82
+ purchaseOrder.date ? `Date: ${purchaseOrder.date}` : null,
83
+ purchaseOrder.deliveryDate
84
+ ? `Delivery Date: ${purchaseOrder.deliveryDate}`
85
+ : null,
86
+ purchaseOrder.currencyCode
87
+ ? `Currency: ${purchaseOrder.currencyCode}`
88
+ : null,
89
+ `Total: ${purchaseOrder.total || 0}`,
90
+ ]
91
+ .filter(Boolean)
92
+ .join("\n"),
93
+ })) || []),
94
+ ],
95
+ };
96
+ });
97
+ export default ListPurchaseOrdersTool;
@@ -18,7 +18,10 @@ export function ToolFactory(server) {
18
18
  DeleteTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, WRITE_ANNOTATIONS, tool.handler));
19
19
  GetTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, READ_ONLY_ANNOTATIONS, tool.handler));
20
20
  CreateTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, WRITE_ANNOTATIONS, tool.handler));
21
- HistoryTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, tool.name.startsWith("get-") ? READ_ONLY_ANNOTATIONS : WRITE_ANNOTATIONS, tool.handler));
21
+ HistoryTools.map((tool) => tool()).forEach((tool) => {
22
+ const isReadOnly = tool.name.startsWith("get-");
23
+ server.tool(tool.name, tool.description, tool.schema, isReadOnly ? READ_ONLY_ANNOTATIONS : WRITE_ANNOTATIONS, tool.handler);
24
+ });
22
25
  ListTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, READ_ONLY_ANNOTATIONS, tool.handler));
23
26
  UpdateTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, WRITE_ANNOTATIONS, tool.handler));
24
27
  }
@@ -0,0 +1,29 @@
1
+ import { z } from "zod";
2
+ import { emailXeroInvoice } from "../../handlers/email-xero-invoice.handler.js";
3
+ import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
4
+ const EmailInvoiceTool = CreateXeroTool("email-invoice", "Email a copy of an invoice to its related contact via Xero. The invoice must be AUTHORISED — Xero rejects emails for DRAFT or SUBMITTED invoices. Use list-invoices to find the invoice ID.", {
5
+ invoiceId: z
6
+ .string()
7
+ .describe("The Xero invoice ID (UUID) of the AUTHORISED invoice to email"),
8
+ }, async ({ invoiceId }) => {
9
+ const response = await emailXeroInvoice(invoiceId);
10
+ if (response.error !== null) {
11
+ return {
12
+ content: [
13
+ {
14
+ type: "text",
15
+ text: `Error emailing invoice: ${response.error}`,
16
+ },
17
+ ],
18
+ };
19
+ }
20
+ return {
21
+ content: [
22
+ {
23
+ type: "text",
24
+ text: `Invoice ${invoiceId} was emailed to its related contact.`,
25
+ },
26
+ ],
27
+ };
28
+ });
29
+ export default EmailInvoiceTool;
@@ -1,4 +1,5 @@
1
1
  import ApprovePayrollTimesheetTool from "./approve-payroll-timesheet.tool.js";
2
+ import EmailInvoiceTool from "./email-invoice.tool.js";
2
3
  import RevertPayrollTimesheetTool from "./revert-payroll-timesheet.tool.js";
3
4
  import UpdateBankTransactionTool from "./update-bank-transaction.tool.js";
4
5
  import UpdateContactTool from "./update-contact.tool.js";
@@ -24,5 +25,6 @@ export const UpdateTools = [
24
25
  UpdatePayrollTimesheetLineTool,
25
26
  RevertPayrollTimesheetTool,
26
27
  UpdateTrackingCategoryTool,
27
- UpdateTrackingOptionsTool
28
+ UpdateTrackingOptionsTool,
29
+ EmailInvoiceTool
28
30
  ];
@@ -1,7 +1,7 @@
1
1
  import { updateXeroContact } from "../../handlers/update-xero-contact.handler.js";
2
2
  import { z } from "zod";
3
3
  import { DeepLinkType, getDeepLink } from "../../helpers/get-deeplink.js";
4
- import { ensureError } from "../../helpers/ensure-error.js";
4
+ import { formatError } from "../../helpers/format-error.js";
5
5
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
6
6
  const UpdateContactTool = CreateXeroTool("update-contact", "Update a contact in Xero.\
7
7
  When a contact is updated, a deep link to the contact in Xero is returned. \
@@ -55,12 +55,11 @@ const UpdateContactTool = CreateXeroTool("update-contact", "Update a contact in
55
55
  };
56
56
  }
57
57
  catch (error) {
58
- const err = ensureError(error);
59
58
  return {
60
59
  content: [
61
60
  {
62
61
  type: "text",
63
- text: `Error creating contact: ${err.message}`,
62
+ text: `Error updating contact: ${formatError(error)}`,
64
63
  },
65
64
  ],
66
65
  };
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { CreateXeroTool } from "../../helpers/create-xero-tool.js";
3
3
  import { DeepLinkType, getDeepLink } from "../../helpers/get-deeplink.js";
4
- import { ensureError } from "../../helpers/ensure-error.js";
4
+ import { formatError } from "../../helpers/format-error.js";
5
5
  import { updateXeroManualJournal } from "../../handlers/update-xero-manual-journal.handler.js";
6
6
  const UpdateManualJournalTool = CreateXeroTool("update-manual-journal", "Update a manual journal in Xero. Only works on draft manual journals.\
7
7
  Do not modify line items or parameters that have not been specified by the user.", {
@@ -75,12 +75,11 @@ const UpdateManualJournalTool = CreateXeroTool("update-manual-journal", "Update
75
75
  };
76
76
  }
77
77
  catch (error) {
78
- const err = ensureError(error);
79
78
  return {
80
79
  content: [
81
80
  {
82
81
  type: "text",
83
- text: `Error updating manual journal: ${err.message}`,
82
+ text: `Error updating manual journal: ${formatError(error)}`,
84
83
  },
85
84
  ],
86
85
  };
@@ -0,0 +1,119 @@
1
+ /**
2
+ * AGENTS.md security invariant #6 — content fetched from an external system
3
+ * MUST be wrapped in an `<untrusted-content source="…">…</untrusted-content>`
4
+ * envelope (with close-tag breakout escaping) before it is returned to the
5
+ * LLM, so the model treats third-party / attacker-controllable text as DATA,
6
+ * not as instructions.
7
+ *
8
+ * This is the canonical implementation a new connector ships with. It is a
9
+ * VENDORED copy of the shared reference in `test-harness/src/untrusted-content.ts`
10
+ * — connectors cannot `import` the test-harness at runtime (it is a
11
+ * test/dev-only `file:` dependency that is never published into a connector's
12
+ * `dist/`), so the helper lives in the connector's own runtime source. Keep
13
+ * this byte-for-byte in sync with the shared reference; do NOT weaken the
14
+ * escaping back to a simple `replaceAll` (that family misses whitespace / case
15
+ * close-tag variants like `</untrusted-content >` / `</UNTRUSTED-CONTENT>`).
16
+ *
17
+ * `scripts/check-untrusted-coverage.mjs` greps for a reference to
18
+ * `untrusted-content` in any connector that talks to an external system; this
19
+ * file (and the call sites that import from it) is what satisfies that gate.
20
+ */
21
+ const UNTRUSTED_CLOSE_TAG_VARIANT = /<\/untrusted-content\s*>/gi;
22
+ const ESCAPED_UNTRUSTED_CLOSE_TAG = '<\\/untrusted-content>';
23
+ const UNTRUSTED_ENVELOPE = /^<untrusted-content source="[^"]*">([\s\S]*)<\/untrusted-content>$/;
24
+ function escapeAttr(s) {
25
+ return s.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
26
+ }
27
+ /**
28
+ * Rewrite every `</untrusted-content>` variant (case-insensitive, optional
29
+ * whitespace before `>`) inside `s` to a benign textual form, so an attacker
30
+ * who controls the wrapped content cannot terminate the envelope early.
31
+ */
32
+ function escapeCloseTagSentinels(s) {
33
+ return s.replace(UNTRUSTED_CLOSE_TAG_VARIANT, ESCAPED_UNTRUSTED_CLOSE_TAG);
34
+ }
35
+ function unescapeCloseTagSentinels(s) {
36
+ return s.replaceAll(ESCAPED_UNTRUSTED_CLOSE_TAG, '</untrusted-content>');
37
+ }
38
+ /**
39
+ * Wrap a single untrusted string in an `<untrusted-content source="…">`
40
+ * envelope, escaping any embedded close-tag variant so the envelope cannot be
41
+ * broken out of.
42
+ *
43
+ * `undefined` and `null` are passed through untouched so callers can apply the wrapper
44
+ * uniformly to optional fields without branching.
45
+ *
46
+ * Idempotent: when `text` is already a properly-shaped envelope for the SAME
47
+ * `source` (starts with the matching OPEN tag, ends with CLOSE, and contains no
48
+ * internal close-tag variants), the original string is returned unchanged so
49
+ * `wrapUntrusted(wrapUntrusted(s, src), src) === wrapUntrusted(s, src)`.
50
+ */
51
+ export function wrapUntrusted(text, source) {
52
+ if (text === undefined || text === null)
53
+ return undefined;
54
+ const open = `<untrusted-content source="${escapeAttr(source)}">`;
55
+ const close = '</untrusted-content>';
56
+ if (text.startsWith(open) && text.endsWith(close) && text.length >= open.length + close.length) {
57
+ const inner = text.slice(open.length, text.length - close.length);
58
+ if (!UNTRUSTED_CLOSE_TAG_VARIANT.test(inner)) {
59
+ UNTRUSTED_CLOSE_TAG_VARIANT.lastIndex = 0; // reset stateful /g regex
60
+ return text;
61
+ }
62
+ UNTRUSTED_CLOSE_TAG_VARIANT.lastIndex = 0;
63
+ }
64
+ return `${open}${escapeCloseTagSentinels(text)}${close}`;
65
+ }
66
+ /**
67
+ * Strip one `<untrusted-content>` envelope from `text` if present, returning raw
68
+ * strings unchanged. This is intentionally one-layer and idempotent for already
69
+ * raw input so callers can accept either displayed wrapped content or manually
70
+ * authored content.
71
+ */
72
+ export function unwrapUntrusted(text) {
73
+ const match = UNTRUSTED_ENVELOPE.exec(text);
74
+ if (!match)
75
+ return text;
76
+ return unescapeCloseTagSentinels(match[1]);
77
+ }
78
+ /**
79
+ * Recursively wrap every string key and value reachable inside `value` (strings,
80
+ * arrays, plain-object property keys and values) in an `<untrusted-content>` envelope.
81
+ *
82
+ * Use this when a whole response blob is third-party data and you want to
83
+ * envelope it wholesale rather than enumerate fields. Non-string leaves (numbers,
84
+ * booleans, null) pass through unchanged.
85
+ */
86
+ export function wrapUntrustedJsonStrings(value, source) {
87
+ if (typeof value === 'string') {
88
+ return wrapUntrusted(value, source);
89
+ }
90
+ if (Array.isArray(value)) {
91
+ return value.map((item) => wrapUntrustedJsonStrings(item, source));
92
+ }
93
+ if (value && typeof value === 'object') {
94
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
95
+ wrapUntrusted(key, source) ?? key,
96
+ wrapUntrustedJsonStrings(item, source),
97
+ ]));
98
+ }
99
+ return value;
100
+ }
101
+ /**
102
+ * Recursively unwrap every string key and value reachable inside `value`.
103
+ * Non-string leaves pass through unchanged.
104
+ */
105
+ export function unwrapUntrustedJsonStrings(value) {
106
+ if (typeof value === 'string') {
107
+ return unwrapUntrusted(value);
108
+ }
109
+ if (Array.isArray(value)) {
110
+ return value.map((item) => unwrapUntrustedJsonStrings(item));
111
+ }
112
+ if (value && typeof value === 'object') {
113
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
114
+ unwrapUntrusted(key),
115
+ unwrapUntrustedJsonStrings(item),
116
+ ]));
117
+ }
118
+ return value;
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-xero",
3
- "version": "0.0.17",
3
+ "version": "0.1.0",
4
4
  "mcpName": "io.github.mindstone/mcp-server-xero",
5
5
  "description": "Xero MCP server for invoices, contacts, payments, quotes, and financial reports",
6
6
  "license": "MIT",
@@ -1,13 +0,0 @@
1
- export function ensureError(value) {
2
- if (value instanceof Error)
3
- return value;
4
- let stringified = "[Unable to stringify the thrown value]";
5
- try {
6
- stringified = JSON.stringify(value);
7
- }
8
- catch {
9
- /* empty */
10
- }
11
- const error = new Error(`Error thrown: ${stringified}`);
12
- return error;
13
- }