Xero Model Context Protocol (MCP) Server

repository·main·Indexed 43 days ago

https://github.com/xeroapi/xero-mcp-server

A Model Context Protocol implementation that provides a standardized bridge between AI agents and Xero's accounting and business APIs. It enables agents to manage contacts, invoices, bank transactions, and payroll data through a set of specialized commands. Version 0.0.16 supports custom connections via client IDs and secrets or bearer token authentication for multi-account runtime support.

Tokens
8.6K
Snippets
23
Records
24
Agent score
56%

What's inside Xero MCP Server

  1. Configure Custom Connections for Xero MCP

    main

    Custom Connections are recommended for testing, development, and integration with 3rd party MCP clients like Claude Desktop. This mode allows you to specify a XERO_CLIENT_ID and XERO_CLIENT_SECRET for a specific organisation.

    Required Scopes

    Custom connections require specific scopes. The MCP server attempts to use V1 (bundled) scopes first and falls back to V2 (granular) if needed. You can override this behavior by setting the XERO_SCOPES environment variable to a space-separated list.

    Connection CreatedRequired Scopes
    Before Apr 29, 2026SCOPES_V1 (bundled)
    From Apr 29, 2026SCOPES_V2 (granular)

    Claude Desktop Configuration

    Add the following to your claude_desktop_config.json:

    {
      "mcpServers": {
        "xero": {
          "command": "npx",
          "args": ["-y", "@xeroapi/xero-mcp-server@latest"],
          "env": {
            "XERO_CLIENT_ID": "your_client_id_here",
            "XERO_CLIENT_SECRET": "your_client_secret_here",
            "XERO_SCOPES": "accounting.invoices accounting.contacts accounting.settings"
          }
        }
      }
    }

    Note for NVM users: If using Node Version Manager, change the command from npx to the absolute path of your npx executable (e.g., /home/user/.nvm/versions/node/v22.14.0/bin/npx).

  2. Use Xero MCP Server with OpenAI agents SDK

    main

    This example demonstrates how to integrate the Xero MCP Server with OpenAI's agents SDK to allow an AI agent to interact with Xero data.

    To use this example, you must install the openai-agents package and configure your environment with the necessary credentials for both Xero and OpenAI.

    # Install the OpenAI agents SDK
    pip install openai-agents
    
    # Set required environment variables
    export XERO_CLIENT_ID=your_xero_client_id
    export XERO_CLIENT_SECRET=your_xero_client_secret
    export OPENAI_API_KEY=your_openai_api_key
  3. Install the Xero MCP Server

    main

    You can install the Xero MCP server using npm or pnpm. This is required if you are developing on the package or running it locally.

    Using npm

    npm install

    Using pnpm

    pnpm install
    # Using npm
    npm install
    
    # Using pnpm
    pnpm install
  4. Develop and Debug the Xero MCP Server

    main

    If you are working on the Xero MCP server source code, follow these steps to build and link it to Claude Desktop for development.

    Build the project

    npm run build
    # or
    pnpm build

    Add the following to your claude_desktop_config.json.

    Windows Users: Ensure you escape the backslashes in the file path (e.g., C:\projects\xero-mcp-server\dist\index.js).

    {
      "mcpServers": {
        "xero": {
          "command": "node",
          "args": ["/absolute/path/to/xero-mcp-server/dist/index.js"],
          "env": {
            "XERO_CLIENT_ID": "your_client_id_here",
            "XERO_CLIENT_SECRET": "your_client_secret_here"
          }
        }
      }
    }
    {
      "mcpServers": {
        "xero": {
          "command": "node",
          "args": ["insert-your-file-path-here/xero-mcp-server/dist/index.js"],
          "env": {
            "XERO_CLIENT_ID": "your_client_id_here",
            "XERO_CLIENT_SECRET": "your_client_secret_here"
          }
        }
      }
    }
  5. Configure Bearer Token Authentication for Xero MCP

    main

    Bearer Token authentication is ideal for supporting multiple Xero accounts at runtime by allowing the MCP client to execute an auth flow (like PKCE).

    Note: XERO_CLIENT_BEARER_TOKEN takes precedence over XERO_CLIENT_ID if both are defined.

    Claude Desktop Configuration

    Add the following to your claude_desktop_config.json:

    {
      "mcpServers": {
        "xero": {
          "command": "npx",
          "args": ["-y", "@xeroapi/xero-mcp-server@latest"],
          "env": {
            "XERO_CLIENT_BEARER_TOKEN": "your_bearer_token"
          }
        }
      }
    }

    Required Scopes

    When obtaining a bearer token, you must request the appropriate scopes. Examples include:

    • accounting.invoices / accounting.invoices.read
    • accounting.contacts
    • accounting.settings
    • payroll.employees
    • payroll.timesheets
    • (and others listed in the documentation)
  6. Initialize and run the Xero MCP Server

    main

    The Xero MCP Server is initialized by creating a server instance via XeroMcpServer.GetServer(), registering tools using the ToolFactory, and connecting it to a StdioServerTransport. This allows the server to communicate with MCP clients (like Claude Desktop or other AI agents) via standard input and output.

    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
    import { XeroMcpServer } from "./server/xero-mcp-server.js";
    import { ToolFactory } from "./tools/tool-factory.js";
    
    const main = async () => {
      // Create an MCP server
      const server = XeroMcpServer.GetServer();
    
      // Register tools
      ToolFactory(server);
    
      // Start receiving messages on stdin and sending messages on stdout
      const transport = new StdioServerTransport();
      await server.connect(transport);
    };
    
    main().catch((error) => {
      console.error("Error:", error);
      process.exit(1);
    });
  7. Reference: Available MCP Commands

    main

    The Xero MCP server provides a wide range of commands to interact with Xero's accounting and payroll features. These commands are categorized by their action (list, create, update, delete, etc.).

    Accounting Commands

    • list-accounts: Retrieve a list of accounts
    • list-contacts: Retrieve a list of contacts
    • list-credit-notes: Retrieve a list of credit notes
    • list-invoices: Retrieve a list of invoices
    • list-items: Retrieve a list of items
    • list-manual-journals: Retrieve a list of manual journals
    • list-organisation-details: Retrieve details about an organisation
    • list-profit-and-loss: Retrieve a profit and loss report
    • list-quotes: Retrieve a list of quotes
    • list-tax-rates: Retrieve a list of tax rates
    • list-payments: Retrieve a list of payments
    • list-trial-balance: Retrieve a trial balance report
    • list-bank-transactions: Retrieve a list of bank account transactions
    • list-report-balance-sheet: Retrieve a balance sheet report
    • list-aged-receivables-by-contact: Retrieves aged receivables for a contact
    • list-aged-payables-by-contact: Retrieves aged payables for a contact
    • list-contact-groups: Retrieve a list of contact groups
    • list-tracking-categories: Retrieve a list of tracking categories
    • create-bank-transaction: Create a new bank transaction
    • create-contact: Create a new contact
    • create-credit-note: Create a new credit note
    • create-invoice: Create a new invoice
    • create-item: Create a new item
    • create-manual-journal: Create a new manual journal
    • create-payment: Create a new payment
    • create-quote: Create a new quote
    • create-tracking-category: Create a new tracking category
    • create-tracking-option: Create a new tracking option
    • update-bank-transaction: Update an existing bank transaction
    • update-contact: Update a new contact
    • update-invoice: Update an existing draft invoice
    • update-item: Update an existing item
    • update-manual-journal: Update an existing manual journal
    • update-quote: Update an existing draft quote
    • update-credit-note: Update an existing draft credit note
    • update-tracking-category: Update an existing tracking category
    • update-tracking-options: Update tracking options

    Payroll Commands

    • list-payroll-employees: Retrieve a list of Payroll Employees
    • list-payroll-employee-leave: Retrieve a Payroll Employee's leave records
    • list-payroll-employee-leave-balances: Retrieve a Payroll Employee's leave balances
    • list-payroll-employee-leave-types: Retrieve a list of Payroll leave types
    • list-payroll-leave-periods: Retrieve a list of a Payroll Employee's leave periods
    • list-payroll-leave-types: Retrieve a list of all available leave types in Xero Payroll
    • list-timesheets: Retrieve a list of Payroll Timesheets
    • create-payroll-timesheet: Create a new Payroll Timesheet
    • update-payroll-timesheet-line: Update a line on an existing Payroll Timesheet
    • approve-payroll-timesheet: Approve a Payroll Timesheet
    • revert-payroll-timesheet: Revert an approved Payroll Timesheet
    • add-payroll-timesheet-line: Add new line on an existing Payroll Timesheet
    • delete-payroll-timesheet: Delete an existing Payroll Timesheet
    • get-payroll-timesheet: Retrieve an existing Payroll Timesheet
  8. Create a Xero credit note with createXeroCreditNote

    main

    Use the createXeroCreditNote function to generate a new credit note in Xero. The credit note is created with a DRAFT status and uses the current date.

    Parameters

    • contactId: The unique identifier of the Xero contact.
    • lineItems: An array of CreditNoteLineItem objects defining the items being credited.
    • reference (optional): A string to serve as the credit note reference.

    CreditNoteLineItem Schema

    Each item in the lineItems array must include:

    • description: string
    • quantity: number
    • unitAmount: number
    • accountCode: string
    • taxType: string

    Return Value

    The function returns a XeroClientResponse<CreditNote> object containing:

    • result: The created CreditNote object (if successful) or null (if failed).
    • isError: A boolean indicating if the operation failed.
    • error: A formatted error message if isError is true.
    import { createXeroCreditNote } from './path-to-handler';
    
    const lineItems = [
      {
        description: 'Refund for service',
        quantity: 1,
        unitAmount: 50.00,
        accountCode: '200',
        taxType: 'OUTPUT'
      }
    ];
    
    const response = await createXeroCreditNote('CONTACT_ID_HERE', lineItems, 'REF-123');
    
    if (response.isError) {
      console.error('Failed to create credit note:', response.error);
    } else {
      console.log('Created Credit Note:', response.result);
    }
  9. List Xero trial balance reports with listXeroTrialBalance

    main

    The listXeroTrialBalance function retrieves trial balance report data from Xero. It returns a XeroClientResponse containing either the report data or an error message.

    Parameters

    • date (optional): A string representing the date for the trial balance in YYYY-MM-DD format.
    • paymentsOnly (optional): A boolean. If set to true, the report will include only accounts with payments.

    Return Value

    Returns a Promise<XeroClientResponse<ReportWithRow>>. The response object contains:

    • result: The ReportWithRow object if successful, or null if the fetch failed.
    • isError: A boolean indicating if the operation failed.
    • error: A string containing the error message if isError is true, otherwise null.
    import { listXeroTrialBalance } from '@xeroapi/xero-mcp-server';
    
    // Example: Fetch trial balance for a specific date
    const response = await listXeroTrialBalance('2023-12-31', true);
    
    if (response.isError) {
      console.error('Error:', response.error);
    } else {
      console.log('Trial Balance Data:', response.result);
    }
  10. List Xero Payroll leave types

    main

    Use the listXeroPayrollLeaveTypes function to retrieve a list of all leave types configured in Xero Payroll (New Zealand). The function handles authentication automatically via the xeroClient.

    Returns a XeroClientResponse object containing an array of LeaveType objects on success, or an error object if the request fails.

    import { listXeroPayrollLeaveTypes } from "@xeroapi/xero-mcp-server";
    
    const response = await listXeroPayrollLeaveTypes();
    
    if (response.isError) {
      console.error("Error fetching leave types:", response.error);
    } else {
      console.log("Leave Types:", response.result);
    }
  11. Create a Xero invoice with createXeroInvoice

    main

    Use the createXeroInvoice function to programmatically create a new invoice in Xero. The function handles authentication via the xeroClient and returns a standardized XeroClientResponse containing either the created Invoice or a formatted error.

    Parameters

    • contactId (string): The unique identifier of the Xero contact associated with the invoice.
    • lineItems (InvoiceLineItem[]): An array of line items for the invoice. Each item must include description, quantity, unitAmount, accountCode, and taxType.
    • type (Invoice.TypeEnum, optional): The type of invoice. Defaults to Invoice.TypeEnum.ACCREC (Accounts Receivable). Use Invoice.TypeEnum.ACCPAY for Accounts Payable.
    • reference (string, optional): A reference string. For ACCREC, this maps to the reference field; for ACCPAY, this maps to the invoiceNumber field.
    • date (string, optional): The invoice date in YYYY-MM-DD format. If omitted, the current date is used.

    Behavior

    • Due Date: Automatically set to 30 days from the current date if not specified.
    • Status: All invoices are created with a status of DRAFT.
    • Error Handling: If creation fails, the function returns an object with isError: true and a formatted error message.
    import { createXeroInvoice } from "@xeroapi/xero-mcp-server";
    import { Invoice } from "xero-node";
    
    const lineItems = [
      {
        description: "Consulting Services",
        quantity: 1,
        unitAmount: 500,
        accountCode: "200",
        taxType: "OUTPUT",
        tracking: []
      }
    ];
    
    const response = await createXeroInvoice(
      "CONTACT_ID_HERE",
      lineItems,
      Invoice.TypeEnum.ACCREC,
      "REF-123",
      "2023-10-27"
    );
    
    if (response.isError) {
      console.error("Failed to create invoice:", response.error);
    } else {
      console.log("Created Invoice:", response.result);
    }
  12. List Xero payroll employee leave balances

    main

    Use the listXeroPayrollEmployeeLeaveBalances function to retrieve the leave balances for a specific employee from Xero Payroll (NZ).

    Parameters:

    • employeeId (string): The unique identifier of the employee.

    Returns: Returns a XeroClientResponse containing an array of EmployeeLeaveBalance objects. If no balances are found, it returns an empty array with isError: false. If the request fails, it returns isError: true with a formatted error message.

    import { listXeroPayrollEmployeeLeaveBalances } from './path-to-handler';
    
    const response = await listXeroPayrollEmployeeLeaveBalances('EMPLOYEE_ID_HERE');
    
    if (response.isError) {
      console.error('Error:', response.error);
    } else {
      console.log('Leave Balances:', response.result);
    }