@teamnetwork-nz/xero-mcp-server 1.16.2 → 1.17.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/dist/index.js CHANGED
@@ -5,11 +5,13 @@ import { ToolFactory } from "./tools/tool-factory.js";
5
5
  import { registerResources } from "./resources/register-resources.js";
6
6
  import { createHttpServer } from "./http-server.js";
7
7
  import { parsePositiveInt } from "./env.js";
8
+ import { registerCapabilities } from './resources/capabilities.js';
8
9
  const main = async () => {
9
10
  const createConfiguredServer = () => {
10
11
  const server = XeroMcpServer.GetServer(true);
11
- ToolFactory(server);
12
+ const tools = ToolFactory(server);
12
13
  registerResources(server);
14
+ registerCapabilities(server, tools);
13
15
  return server;
14
16
  };
15
17
  // Start receiving messages on stdin and sending messages on stdout
@@ -0,0 +1,2 @@
1
+ // Generated by scripts/generate-playbook.mjs; edit AGENTS.md.
2
+ export const agentPlaybook = "# Xero MCP Server — Agent Usage Guide\n\nThis server provides MCP tools for the Xero accounting API. The guidelines below exist to\nprevent common inefficiencies — specifically, scanning large result sets when the API can\nfilter server-side.\n\n---\n\n## Golden rule: filter first, paginate last\n\nEvery list tool supports server-side filtering. **Never retrieve all records and scan them\nclient-side.** Always apply the most specific filter available before considering pagination.\n\n---\n\n## Common task patterns\n\n### Unpaid sales invoices (AR — money owed to you)\n```\nlist-invoices: type=ACCREC, statuses=[AUTHORISED], minAmountDue=0.01\n```\n`ACCREC` = Accounts Receivable = sales invoices. `AUTHORISED` = approved and outstanding.\n`minAmountDue=0.01` excludes fully-paid invoices without needing a date filter.\n\n### Overdue invoices (chasing)\n```\nlist-invoices: type=ACCREC, statuses=[AUTHORISED], overdueOnly=true\n```\n`overdueOnly` computes `AmountDue>0 AND DueDate<=today` server-side. No scanning needed.\n\n### Bills to pay (AP — money you owe suppliers)\n```\nlist-invoices: type=ACCPAY, statuses=[AUTHORISED], minAmountDue=0.01\n```\n`ACCPAY` = Accounts Payable = purchase invoices / bills.\n\n### Exact invoice/bill and TEAMlink lookup\n```\nxero_search_transactions: invoiceNumber=<value>, matchMode=exact, type=ACCPAY|ACCREC\nxero_batch_invoice_lookup: invoiceNumbers=[<value>, ...], type=ACCPAY|ACCREC\n```\nTEAMlink purchase-bill values (shown here with a synthetic example) such as\n`SYNTHETIC-BILL / TEST-REFERENCE` are returned by the Xero API in `InvoiceNumber`; `Reference` is\nempty on the verified record. Use the native invoice-number filter for exact and\nbatch lookup. Keep identifiers as strings, including numeric-looking values.\n\n### Broader invoice/bill investigation\n```\nxero_search_transactions: reference=<text>|supplier=<name>, matchMode=exact|contains|candidate\n```\nThe structured result distinguishes exact, ambiguous, candidate, incomplete and\nfailed searches. Do not interpret an API error or truncated search as definitive\n`NOT_FOUND`.\n\n### Unreconciled bank transactions\n```\nlist-bank-transactions: isReconciled=false, fromDate=<start>, toDate=<end>\n```\n**Never paginate through all transactions looking for unreconciled ones.** Use `isReconciled=false`.\n\n### Cash received in a period\n```\nlist-bank-transactions: transactionType=RECEIVE, fromDate=<start>, toDate=<end>\n```\n\n### Cash spent in a period\n```\nlist-bank-transactions: transactionType=SPEND, fromDate=<start>, toDate=<end>\n```\n\n### Find a contact by name or email\n```\nlist-contacts: searchTerm=<name or email>\n```\nDo not list all contacts and scan. `searchTerm` searches Name, FirstName, LastName,\nContactNumber, and EmailAddress server-side.\n\n### All customers (AR workflows)\n```\nlist-contacts: contactRole=customer, status=ACTIVE\n```\n\n### All suppliers (AP workflows)\n```\nlist-contacts: contactRole=supplier, status=ACTIVE\n```\n\n### Payments from/to a specific contact\n```\nlist-payments: contactId=<id>, fromDate=<start>, toDate=<end>\n```\n**This does not return overpayments or prepayments.** They are separate Xero resources —\ncall `list-overpayments` and `list-prepayments` with the same `contactId`/date filters to get\nthe complete picture. Any customer/supplier statement or balance reconciliation that only\ncalls `list-payments` will silently miss overpayment and prepayment activity.\n\n### Accurate contact statement / balance reconciliation\nTo reproduce what Xero itself shows for a contact (invoices, payments, credit notes,\noverpayments, prepayments, and the resulting balance), assemble all of:\n```\nlist-invoices: contactIds=[<id>], type=ACCREC|ACCPAY\nlist-payments: contactId=<id>\nlist-credit-notes: contactId=<id>, type=ACCRECCREDIT|ACCPAYCREDIT\nlist-overpayments: contactId=<id>\nlist-prepayments: contactId=<id>\n```\nsorted by date, then cross-check the resulting balance against\n`list-aged-receivables-by-contact` / `list-aged-payables-by-contact` (Xero's own report engine,\nand the closest thing to ground truth). Two gotchas when doing this:\n- An overpayment/prepayment's `Allocations` show which invoice it was later applied against —\n read that directly rather than trying to infer it from invoice `Total` vs `AmountDue`.\n- The aged-by-contact reports do **not** filter their invoice list by the `reportDate` param —\n a report requested for a past date still lists invoices raised after that date (only their\n Paid/Credited columns are correctly computed as-at that date). For a true historical balance,\n filter the returned rows client-side to invoices dated on or before your target date.\n\n### Unallocated credit notes available to apply\n```\nlist-credit-notes: statuses=[AUTHORISED], hasRemainingCredit=true, type=ACCREC\n```\n\n### Which invoice was a credit note applied to?\n`list-credit-notes` results include `Remaining Credit`, `Applied Amount`, and an `Allocations`\nbreakdown (amount, date, invoice) when Xero returns them. Read this directly from the result —\ndo not fetch every customer invoice and diff `Total` vs `AmountDue` to work it out.\n\n### Monthly profit and loss comparison\n```\nlist-profit-and-loss: fromDate=<first day of latest month>, toDate=<last day of latest month>, periods=<months wanted minus 1>, timeframe=MONTH\n```\n`periods` is the number of **prior comparison periods**, not the total number of columns.\nXero returns the requested base period plus that many comparisons, so four monthly columns\nrequire a one-month date range and `periods=3`. Xero repeats the entire `fromDate`/`toDate`\nspan for every comparison; passing a four-month range with `periods=4` returns five rolling\nfour-month totals rather than four single-month totals.\n\n**`fromDate` and `toDate` must be within one calendar month.** Multi-month base ranges are\nrejected because Xero returns plausible-looking rolling totals under monthly column labels.\nFor N reliable completed monthly columns, request the current calendar month with `periods=N`\nand ignore column 0 (the current month-to-date column); the remaining comparison columns are\nthe completed prior months. The tool returns `comparisonColumnMetadata` so consumers can verify\neach column's actual `fromDate`, `toDate`, and `isMonthToDate` state. Use `periods=0` when making\none call per completed month.\n\n### Bank account movement for a period (GL-level)\n```\nlist-report-bank-summary: fromDate=<start>, toDate=<end>\n```\nGives Xero's own opening balance, cash received, cash spent, and closing balance per bank\naccount — computed by Xero, not reconstructed. Prefer this over summing\n`list-bank-transactions` for account movement: a plain BankTransactions sum can miss transfers\nbetween accounts and other postings that this report already accounts for.\n\n### Drilling into what actually posted to an account\n```\nlist-journals: fromDate=<start>, toDate=<end>, accountId=<id>\n```\nReturns the actual double-entry GL lines for that account — the same data Xero's UI shows\nwhen you click into a P&L/Balance Sheet line. Omitting `accountId` returns every journal in\nthe range across all accounts. **Always pass `fromDate` when filtering by account** — without\nit the tool starts scanning from the very beginning of the ledger (oldest first), which is\nalmost never what's wanted. Note: cross-check `list-journals` totals against\n`list-report-bank-summary`/`list-trial-balance` for the same account/period rather than trusting\neither in isolation — on at least one tested org, a single bank account's per-journal activity\nfor a month did not reconcile with that same account's Bank Summary figures for the same period,\nand the cause wasn't resolved. Treat a mismatch as a signal to investigate that account's\ntransaction history, not as one tool being definitively wrong.\n\n---\n\n## Terminology\n\n| Xero term | Meaning |\n|---|---|\n| `ACCREC` | Accounts Receivable — sales invoices, money owed TO you |\n| `ACCPAY` | Accounts Payable — purchase invoices / bills, money you OWE |\n| `AUTHORISED` | Invoice approved and outstanding (not yet fully paid) |\n| `PAID` | Invoice fully paid |\n| `IsReconciled` | Bank transaction matched to an invoice or spend/receive rule |\n\n---\n\n## Read-only mode\n\nBy default this server runs in **read-only mode** — only list, get, and report tools are\nregistered. Create, update, and delete tools are absent unless the server is started with\n`XERO_READWRITE=true`.\n\nIf a user asks you to create, update, or delete something and those tools are not available,\nexplain that the server is running in read-only mode and direct them to set\n`XERO_READWRITE=true` in their MCP server configuration.\n\n---\n\n## API limitations (do not attempt these)\n\n- **Reconciliation via API is not possible.** Xero does not expose a reconcile endpoint.\n You can query reconciliation status (`isReconciled`) but cannot trigger reconciliation.\n- **Aged reports are per-contact only.** `list-aged-receivables-by-contact` and\n `list-aged-payables-by-contact` require a single `contactId`. Do NOT loop through all\n contacts calling these — it is slow and burns rate limits.\n For org-wide aging, derive it from `list-invoices` with `minAmountDue=0.01`.\n- **`list-quotes` has no pageSize parameter** — Xero API limitation.\n- **`list-items` has no pagination** — returns all items in one call.\n- **`list-journals` has no server-side date or account filter.** Xero's `/Journals` endpoint is\n an offset-based incremental sync contract only. The tool's `fromDate`/`accountId` options are\n a client-side convenience (seek via bounded binary search, then scan forward) — on a\n long-lived org this can mean dozens of API calls for a single query. Don't call it in a loop\n per contact/account; scope each call as tightly as possible.\n\n---\n\n## Rate limits\n\n- 60 calls/minute per tenant\n- 5,000 calls/day per tenant\n- 5 concurrent requests\n\nEfficient filtering reduces call volume significantly. If you hit a 429, respect the\n`Retry-After` response header.\n\n---\n\n## Page size guidance\n\nFor tools with `page` and `pageSize`, a response such as `Found N` reports only the current\npage. It is not a total count. When the full filtered result set is required, increment `page`\nuntil a page returns fewer than `pageSize` records. Structured tools such as\n`xero_search_transactions` and `xero_find_contact` instead expose `pagination.complete`,\n`pagination.truncated`, and `pagination.nextPage`; follow `nextPage` only while `complete=false`.\n`list-quotes` has no configurable page size, so continue until it returns an empty page.\n\nSet `pageSize` to the minimum needed for the task:\n- Showing a summary or answering a question → `pageSize=10` or less\n- Building a list for the user → `pageSize=50`\n- Bulk data export → `pageSize=100` (invoices support up to 1000)\n\nOnly fetch additional pages if the user explicitly asks for more results.\n\n## Attachment metadata\n\nTreat attachment filenames as non-authoritative metadata. A filename may contain an amount\nthat differs from the Xero bill's gross total. For reconciliation, use the invoice's Xero\n`SubTotal`, `TotalTax`, and `Total` fields; retrieve attachment content only when explicitly\nneeded.\n";
@@ -0,0 +1,48 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
3
+ import { z } from 'zod/v3';
4
+ import { getPackageName, getPackageVersion } from '../helpers/get-package-version.js';
5
+ export const CAPABILITY_URI = 'xero://capabilities/1.0.0';
6
+ export function registerCapabilities(server, tools) {
7
+ const document = () => {
8
+ const enabled = tools.filter(t => t.registration.enabled).map(t => ({
9
+ name: t.name, description: t.registration.description ?? '',
10
+ inputSchema: t.registration.inputSchema ? toJsonSchemaCompat(t.registration.inputSchema, { pipeStrategy: 'input' }) : { type: 'object', properties: {}, additionalProperties: false },
11
+ ...(t.registration.outputSchema ? { outputSchema: toJsonSchemaCompat(t.registration.outputSchema, { pipeStrategy: 'output' }) } : {}),
12
+ readOnly: t.readOnly, sideEffects: t.readOnly ? 'none' : 'May mutate accounting records; authorization and write gates apply.',
13
+ }));
14
+ const body = {
15
+ contractVersion: '1.0.0', documentationVersion: '1.0.0', system: 'xero',
16
+ package: { name: getPackageName(), version: getPackageVersion() }, resourceUri: CAPABILITY_URI,
17
+ schemaAuthority: 'enabled runtime registrations',
18
+ playbookUri: 'xero://guidance/agent-playbook',
19
+ knowledgeService: { role: 'Cross-system relationships and workflow advice; no configured endpoint is implied.' },
20
+ fields: [
21
+ { entity: 'contact', field: 'ContactID', meaning: 'Xero contact UUID, scoped to an organisation.', type: 'string', identityRole: 'record_id' },
22
+ { entity: 'contact', field: 'AccountNumber', meaning: 'User-defined account reference. Its external-system meaning is configuration-specific.', type: 'string', identityRole: 'external_reference' },
23
+ { entity: 'invoice', field: 'InvoiceID', meaning: 'Xero invoice UUID; use for subsequent detail and settlement queries.', type: 'string', identityRole: 'record_id' },
24
+ { entity: 'invoice', field: 'InvoiceNumber', meaning: 'Invoice or purchase-bill number; preserve as a string. It is distinct from Reference.' },
25
+ { entity: 'invoice', field: 'Type', values: { ACCREC: 'Sales invoice; money owed to the organisation.', ACCPAY: 'Purchase bill; money owed to a supplier.' } },
26
+ ],
27
+ rules: [
28
+ 'Filter before paginating. Contact role does not determine invoice direction; set invoice type when direction matters.',
29
+ 'For structured lookup tools follow pagination.complete, pagination.truncated and pagination.nextPage. Errors and truncated results are not NOT_FOUND.',
30
+ 'For page/pageSize list tools, Found N is the current page count. list-quotes has no pageSize; list-items has no pagination.',
31
+ 'Payments exclude overpayments and prepayments; include the separate resources when reconstructing a contact balance.',
32
+ 'There is no API reconciliation operation; querying reconciliation status does not reconcile transactions.',
33
+ 'For monthly P&L comparisons use a single-calendar-month base range; periods counts prior comparison periods.',
34
+ 'Attachment filenames are not authoritative amounts; use invoice SubTotal, TotalTax and Total.',
35
+ ],
36
+ response: { default: 'May be formatted text; outputFormat=json requests JSON text. Structured lookup tools also return structuredContent.', outputSchemas: 'Only included where actually registered.' },
37
+ access: { scope: 'Organisation and credentials selected by server configuration; never infer access from a contact mapping.', writes: 'Mutation tools depend on explicit write-mode configuration. Availability is not authorization.' },
38
+ tools: enabled,
39
+ };
40
+ return { ...body, contentSha256: createHash('sha256').update(JSON.stringify(body)).digest('hex') };
41
+ };
42
+ server.registerResource('capabilities-v1', CAPABILITY_URI, { mimeType: 'application/json', description: 'Versioned Xero implementation schemas, field semantics, query rules and limitations.' }, async () => ({ contents: [{ uri: CAPABILITY_URI, mimeType: 'application/json', text: JSON.stringify(document()) }] }));
43
+ const registration = server.registerTool('get_capabilities', {
44
+ description: 'Read versioned Xero capability documentation and enabled tool schemas; use the playbook resource for detailed local query patterns.',
45
+ inputSchema: z.object({}).strict(), annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
46
+ }, async () => ({ content: [{ type: 'text', text: JSON.stringify(document()) }] }));
47
+ tools.push({ name: 'get_capabilities', registration, readOnly: true });
48
+ }
@@ -1,17 +1,7 @@
1
- import { readFileSync } from "fs";
2
- import { fileURLToPath } from "url";
3
- import { join, dirname } from "path";
1
+ import { agentPlaybook } from './agent-playbook-content.js';
4
2
  const PLAYBOOK_URI = "xero://guidance/agent-playbook";
5
3
  export function registerResources(server) {
6
- // Resolve AGENTS.md relative to the dist output (../../ = project root)
7
- const agentsPath = join(dirname(fileURLToPath(import.meta.url)), "../../AGENTS.md");
8
- let content;
9
- try {
10
- content = readFileSync(agentsPath, "utf-8");
11
- }
12
- catch {
13
- content = "Agent playbook not found. See AGENTS.md in the package repository.";
14
- }
4
+ const content = agentPlaybook;
15
5
  server.resource("agent-playbook", PLAYBOOK_URI, {
16
6
  description: "Query patterns, common tasks, API limitations, and efficiency rules for using this Xero MCP server. Read this before performing bulk or multi-step Xero operations.",
17
7
  mimeType: "text/markdown",
@@ -0,0 +1,130 @@
1
+ // Canonical fleet response policy. Keep packaged src/response-policy.ts copies identical.
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { mkdir, mkdtemp, readFile, unlink, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+ import { z } from 'zod/v3';
8
+ const installed = new WeakSet();
9
+ export function responseByteLimit(env) {
10
+ const raw = env.MCP_MAX_RESPONSE_BYTES ?? '0';
11
+ if (!/^\d+$/.test(raw.trim()) || !Number.isSafeInteger(Number(raw)) || Number(raw) < 0) {
12
+ throw new Error('MCP_MAX_RESPONSE_BYTES must be a non-negative safe integer (0 disables the inline threshold)');
13
+ }
14
+ return Number(raw);
15
+ }
16
+ /** Only explicit upstream signals establish completeness; a short page is not proof. */
17
+ export function datasetComplete(value) {
18
+ if (!value || typeof value !== 'object' || Array.isArray(value))
19
+ return null;
20
+ const data = value;
21
+ if (data.truncated === true || data.has_more === true || data.hasMore === true)
22
+ return false;
23
+ if (data.nextPageToken || data.nextPage || data.nextCursor || data['@odata.nextLink'])
24
+ return false;
25
+ if (typeof data.complete === 'boolean')
26
+ return data.complete;
27
+ const pagination = data.pagination;
28
+ if (pagination && typeof pagination === 'object')
29
+ return datasetComplete(pagination);
30
+ return null;
31
+ }
32
+ function resultValue(result) {
33
+ if (result.structuredContent !== undefined)
34
+ return result.structuredContent;
35
+ const content = result.content;
36
+ if (content?.length === 1) {
37
+ const item = content[0];
38
+ if (item?.type === 'text' && typeof item.text === 'string') {
39
+ try {
40
+ return JSON.parse(item.text);
41
+ }
42
+ catch { /* Formatted text has unknown completeness. */ }
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ /** Install before the strict-tools adapter; serialization then sees its final formatted result. */
48
+ export function installResponsePolicy(server) {
49
+ if (installed.has(server))
50
+ return;
51
+ const limitBytes = responseByteLimit(process.env);
52
+ installed.add(server);
53
+ const exports = new Map();
54
+ let directory;
55
+ const exportDirectory = () => directory ??= (async () => {
56
+ const base = process.env.MCP_EXPORT_DIR ? resolve(process.env.MCP_EXPORT_DIR) : tmpdir();
57
+ await mkdir(base, { recursive: true });
58
+ return mkdtemp(join(base, 'mcp-export-'));
59
+ })();
60
+ async function expire() {
61
+ for (const [id, file] of exports) {
62
+ if (file.expires <= Date.now()) {
63
+ exports.delete(id);
64
+ await unlink(file.path).catch(() => undefined);
65
+ }
66
+ }
67
+ }
68
+ server.registerResource('mcp-response-export', new ResourceTemplate('mcp-export://response/{id}', { list: undefined }), { description: 'Complete tool response saved as JSON. Session scoped; expires after 24 hours. Read with resources/read.', mimeType: 'application/json' }, async (uri, variables) => {
69
+ await expire();
70
+ const file = exports.get(String(variables.id));
71
+ if (!file)
72
+ throw new Error('Export is unknown or expired; repeat the original query if safe.');
73
+ return { contents: [{ uri: uri.href, mimeType: 'application/json', text: await readFile(file.path, 'utf8') }] };
74
+ });
75
+ const mutable = server;
76
+ const register = mutable._createRegisteredTool.bind(server);
77
+ mutable._createRegisteredTool = (...args) => {
78
+ // Same SDK registration boundary used by the fleet's strict-tools adapter.
79
+ const schema = args[3];
80
+ const shape = { responseMode: z.enum(['inline', 'file']).optional().describe('inline (default) returns the full result; file saves the full MCP response as a JSON resource. A configured byte threshold also selects file delivery.') };
81
+ args[3] = schema && typeof schema.extend === 'function'
82
+ ? schema.extend(shape)
83
+ : schema && schema._def ? schema : z.object({ ...(schema ?? {}), ...shape }).strict();
84
+ const handler = args[8];
85
+ if (typeof handler === 'function') {
86
+ args[8] = async (input, ...rest) => {
87
+ const { responseMode, ...toolArgs } = (input ?? {});
88
+ const result = await handler(toolArgs, ...rest);
89
+ if (!result || result.isError || !Array.isArray(result.content))
90
+ return result;
91
+ // Serialize only after the tool's existing redaction, access checks and formatting.
92
+ const serialized = JSON.stringify(result);
93
+ const originalBytes = Buffer.byteLength(serialized, 'utf8');
94
+ const value = resultValue(result);
95
+ const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
96
+ const pagination = source.pagination && typeof source.pagination === 'object' ? source.pagination : undefined;
97
+ const sourceTruncated = typeof source.truncated === 'boolean' ? source.truncated : typeof pagination?.truncated === 'boolean' ? pagination.truncated : null;
98
+ const response = {
99
+ inlineComplete: true, truncated: false, datasetComplete: datasetComplete(value),
100
+ originalBytes, sourceTruncated,
101
+ ...(pagination ? { sourcePagination: pagination } : {}),
102
+ };
103
+ if (responseMode !== 'file' && (limitBytes === 0 || originalBytes <= limitBytes)) {
104
+ return { ...result, _meta: { ...result._meta, response } };
105
+ }
106
+ try {
107
+ await expire();
108
+ const id = randomUUID();
109
+ const path = join(await exportDirectory(), `${id}.json`);
110
+ await writeFile(path, serialized, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
111
+ const expires = Date.now() + 24 * 60 * 60 * 1000;
112
+ exports.set(id, { path, expires });
113
+ const uri = `mcp-export://response/${id}`;
114
+ const metadata = {
115
+ response: { ...response, inlineComplete: false, delivery: 'file', reason: responseMode === 'file' ? 'requested' : 'configured_inline_threshold', limitBytes },
116
+ export: { uri, mimeType: 'application/json', bytes: originalBytes, sha256: createHash('sha256').update(serialized).digest('hex'), expiresAt: new Date(expires).toISOString(), scope: 'current MCP server session', format: 'Complete MCP tool result; content and structuredContent are preserved.' },
117
+ advice: 'Read the export resource for the complete returned result. It contains this call only; follow the original vendor pagination to retrieve additional pages. No records were cut for delivery.',
118
+ };
119
+ return { ...result, content: [{ type: 'text', text: JSON.stringify(metadata) }, { type: 'resource_link', uri, name: 'Complete tool response', mimeType: 'application/json', size: originalBytes }], structuredContent: metadata, _meta: { ...result._meta, response: metadata.response } };
120
+ }
121
+ catch {
122
+ // Never hide a successful mutation/result behind a filesystem failure or invite a retry.
123
+ directory = undefined;
124
+ return { ...result, _meta: { ...result._meta, response: { ...response, delivery: 'inline', exportError: 'EXPORT_UNAVAILABLE', advice: 'Full result returned inline because export failed. Do not retry a successful mutation.' } } };
125
+ }
126
+ };
127
+ }
128
+ return register(...args);
129
+ };
130
+ }
@@ -1,3 +1,4 @@
1
+ import { installResponsePolicy } from "./response-policy.js";
1
2
  import { z } from "zod/v3";
2
3
  function isSchema(value) {
3
4
  return typeof value === "object" && value !== null && "_def" in value;
@@ -37,6 +38,7 @@ function toJsonValue(text) {
37
38
  }
38
39
  /** Make every tool object reject undeclared arguments, including no-argument tools. */
39
40
  export function enforceStrictToolInputs(server) {
41
+ installResponsePolicy(server);
40
42
  const mutable = server;
41
43
  const createRegisteredTool = mutable._createRegisteredTool.bind(server);
42
44
  mutable._createRegisteredTool = (...args) => {
@@ -21,5 +21,11 @@ export function ToolFactory(server) {
21
21
  ...(enablePayroll && enableReadWrite ? PayrollUpdateTools : []),
22
22
  ...(enablePayroll && enableReadWrite ? PayrollDeleteTools : []),
23
23
  ];
24
- allTools.map((tool) => tool()).forEach((tool) => server.tool(tool.name, tool.description, tool.schema, tool.handler));
24
+ const writeFactories = new Set([...CoreCreateTools, ...CoreUpdateTools, ...CoreDeleteTools,
25
+ ...PayrollCreateTools, ...PayrollUpdateTools, ...PayrollDeleteTools]);
26
+ return allTools.map((factory) => {
27
+ const tool = factory();
28
+ const registration = server.tool(tool.name, tool.description, tool.schema, tool.handler);
29
+ return { name: tool.name, registration, readOnly: !writeFactories.has(factory) };
30
+ });
25
31
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/xero-mcp-server",
3
- "version": "1.16.2",
3
+ "version": "1.17.0",
4
4
  "description": "MCP server implementation for Xero integration - TEAMnetwork",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -14,7 +14,7 @@
14
14
  ".env.example"
15
15
  ],
16
16
  "scripts": {
17
- "build": "tsc && shx chmod +x dist/*.js",
17
+ "build": "node scripts/generate-playbook.mjs && tsc && shx chmod +x dist/*.js",
18
18
  "test": "npm run build && node --test debug/tests/*.test.js",
19
19
  "prepare": "npm run build",
20
20
  "watch": "tsc --watch",