DeepLedger
Menu

For developers

Connect LangChain and LangGraph to Xero: MCP Setup

Connect LangChain or LangGraph to Xero with LangChain's MCPAdapter, a DeepLedger API key and a first profit and loss that checks the organisation first.

Published by DeepLedger9 min read

Connect LangChain to Xero by pointing LangChain's built-in MCPAdapter at DeepLedger's hosted MCP server, https://mcp.deepledger.ai/mcp, with a DeepLedger API key. The same tools work in LangGraph, because create_agent returns a LangGraph graph. The script below exposes only two Xero tools: it checks the organisation and runs one profit and loss without writing to Xero.

This guide is for Python developers building a Xero agent with LangChain or LangGraph.

How do I connect LangChain to Xero?

  1. Connect the Xero organisation. In DeepLedger, open Companies, select the company, open its Connections tab and choose Connect to Xero. Approve DeepLedger on Xero's sign-in page and pick only this company's organisation.
  2. Install LangChain with its MCP extra. Install langchain with the mcp extra, version 1.4.0 or newer, and the LangChain package for your model provider.
  3. Create a DeepLedger API key. In DeepLedger, open Settings → API keys and choose Create key. Choose an Expiration and All my companies or One company, then copy the key; it is shown once.
  4. Set the environment variables. Export the DeepLedger key, your model provider's key and the name of the Xero organisation you expect.
pip install "langchain[mcp]>=1.4.0" langchain-openai

export DEEPLEDGER_API_KEY="dl_live_..."      # DeepLedger: Settings → API keys → Create key
export OPENAI_API_KEY="..."
export LANGCHAIN_MODEL="openai:gpt-5.5"      # any model string your provider package supports
export EXPECTED_XERO_ORG="Demo Company (NZ)"
  1. Run the script and compare the report. Save the script below, run python xero_langchain.py and compare the totals with the same profit and loss in Xero.
# xero_langchain.py
import asyncio
import os

from fastmcp.client import Client
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter

MCP_URL = "https://mcp.deepledger.ai/mcp"
WANTED = {"xeroOrganisation", "xeroReports"}


async def main():
    expected = os.environ["EXPECTED_XERO_ORG"]
    client = Client(MCP_URL, auth=os.environ["DEEPLEDGER_API_KEY"])

    async with MCPAdapter(client) as adapter:
        tools = [t for t in await adapter.list_tools() if t.name in WANTED]
        missing = WANTED - {t.name for t in tools}
        if missing:
            raise RuntimeError(f"DeepLedger tools not found: {sorted(missing)}")

        agent = create_agent(os.environ.get("LANGCHAIN_MODEL", "openai:gpt-5.5"), tools)
        result = await agent.ainvoke({"messages": [{"role": "user", "content": f"""
Call xeroOrganisation with operation "profile".
The expected Xero organisation is "{expected}".
If the company named in the result does not match, stop and explain.

If it matches, call xeroReports with reportType "profitAndLoss",
fromDate "2026-10-01" and toDate "2026-10-31". Leave paymentsOnly
unset, so the report is on the accrual basis.

Return the organisation name, base currency, report dates, basis,
total income, total operating expenses and net profit. Do not call
any other tool.
""".strip()}]})

    print(result["messages"][-1].content)


asyncio.run(main())

In a notebook, use await main() instead of asyncio.run(main()). Use the same dates and basis when you compare in Xero.

The LangChain calls follow LangChain's MCP overview and MCP authentication pages. FastMCP's auth argument takes the bare key and adds the Bearer prefix itself. The langchain.mcp namespace is beta in LangChain 1.4.0 and prints a LangChainBetaWarning once per process (as of November 2026).

What are you connecting?

Two separate authorisations sit behind the agent:

  1. An admin connects the Xero organisation to DeepLedger through Xero's own sign-in. DeepLedger keeps that connection and renews it.
  2. Your Python process sends a DeepLedger API key to https://mcp.deepledger.ai/mcp.

The LangChain process never receives a Xero token. LangChain turns DeepLedger's MCP tools into tools its agent loop can call. The Xero MCP server guide covers the wider options, including running your own server.

You need Python 3.10 or newer, a DeepLedger account with the organisation connected, and a model-provider key. Use a demo organisation while you test.

A DeepLedger API key acts as the person who created it, with that person's access. Any team member can create one. A One company key works only in that organisation and cannot switch. A key has no read-only switch, so keep it in an environment variable or secret manager, never in source control.

How does the code work?

Packages. langchain[mcp] installs the built-in langchain.mcp namespace. Older examples use langchain-mcp-adapters and MultiServerMCPClient; LangChain documents MCPAdapter as the replacement. Use one API, not both.

The tool filter. The script keeps xeroOrganisation and xeroReports and stops if either is missing. Do not rely on a fixed tool count, because catalogs change. xeroOrganisation reads the profile (base currency, tax basis, year end and lock dates) and can also list and switch Xero companies; none of these writes to the books. The filter limits the agent, not the key.

The report. xeroReports takes a reportType. For the profit and loss, pass fromDate and toDate; add periods and timeframe (MONTH, QUARTER or YEAR) for comparison columns, or trackingCategoryId to split by a tracking category. Set paymentsOnly to true for a cash basis report. The balance sheet and trial balance take a single date.

Aged reports. Xero runs aged receivables and payables one contact at a time, so contactId is required. For everyone's open items, an agent searches open invoices or bills with xeroFetchTransactions.

langchain.mcp (MCPAdapter)langchain-mcp-adapters (MultiServerMCPClient)
StatusCurrent, beta in langchain 1.4.0Older package
Installpip install "langchain[mcp]>=1.4.0"Separate package
Used in this guideYesNo

How do I connect Xero to LangGraph?

Use the same code. create_agent returns a compiled LangGraph graph, so the example already runs as a LangGraph application.

For fixed steps before or after the model, the tools from MCPAdapter.list_tools() are ordinary LangChain tools. Put them in a ToolNode, add routing, or run the created agent as a subgraph. Keep the organisation check ahead of any branch that can write.

LangChain's HumanInTheLoopMiddleware can pause chosen tool calls for approval. It needs a checkpointer and a real person who resumes or rejects the call.

How does the agent pick the right Xero organisation?

With an All my companies key, call xeroOrganisation with operation: "list", switch by the returned organizationId rather than a guessed name, and read the profile again before the report.

A switch changes the person's active company in every AI app they use. Two jobs running on keys from the same person share that one active company and can pull each other into the wrong books. For parallel jobs, give each a One company key, or send an X-Organization-Id header with the company id on every request; DeepLedger checks it against the person's access. The multiple-company guide explains the shared state, which works the same way for Xero.

What do you need before adding Xero write tools?

The tool filter is a limit on the model, not a permission on the key. Before exposing tools such as xeroBill, xeroInvoice or xeroManualJournal:

  1. Name the exact write tools the workflow needs. Do not pass the whole catalog.
  2. Keep new documents as drafts. DeepLedger saves invoices, bills, credit notes and manual journals as drafts unless the request asks to approve them.
  3. Treat xeroPayment, xeroBankTransaction and xeroBankTransfer with more care: payments, spend and receive money and transfers post straight away.
  4. Add HumanInTheLoopMiddleware for those tool names and persist the interrupted state with a checkpointer.
  5. Check the organisation again just before the approved write, and pass its companyId on every write.
  6. Revoke the key when the job ends or the person running it changes.

DeepLedger refuses a write aimed at the wrong company. With an All my companies key, a write without companyId fails with COMPANY_REQUIRED. A One company key or an X-Organization-Id header fixes the company, so the field is optional there. A write that names a different company fails with COMPANY_MISMATCH. Either way, nothing is written. Nothing dated on or before the organisation's lock date can change, and voids need confirmation. Uncertain items can go to a person through the tasks tool.

If you run the agent from cron, that is your code acting as the key's owner; DeepLedger does not start anything on its own.

Next step: verify one organisation and one report

Start with a demo organisation. When the script prints its result:

  1. Check the organisation name against EXPECTED_XERO_ORG.
  2. In Xero, open Reporting → All reports → Profit and Loss for the same organisation, October 1 to 31, 2026, accrual basis. The Xero profit and loss walkthrough lists what to compare.
  3. Compare total income, operating expenses and net profit.

If the figures differ, fix the dates, basis or layout and rerun before you rely on the agent.

Troubleshooting

ImportError: cannot import name 'MCPAdapter'. Confirm the environment has langchain[mcp]>=1.4.0. The older adapter package uses different import paths.

401 Unauthorized. The DeepLedger key may be mistyped, expired or revoked. Create a new one under Settings → API keys, and do not log the full key.

NO_ACTIVE_COMPANY. Call xeroOrganisation with operation: "list", switch by the returned id and read the profile again.

COMPANY_MISMATCH. The write named a different company from the active one. Nothing was written. Confirm the organisation, then retry.

"Switch not allowed." The key was created for One company, or the request carries an X-Organization-Id header. That is by design.

A reconnect message. That organisation's Xero authorisation has lapsed. An admin reconnects it from the company's Connections tab; retrying the script does not fix it.

"Rate limited." Xero limits calls per organisation per minute. Narrow the date range and retry. More fixes are in Xero MCP troubleshooting.

Current primary documentation

The LangChain calls match our QuickBooks Online guide, which was checked against LangChain's documentation on November 2, 2026. The Xero tool names and fields were checked against DeepLedger's Xero tools in November 2026. We did not run this script against a live organisation.

Frequently asked questions

How do I connect LangChain to Xero?

Install langchain with its MCP extra, create a DeepLedger API key, build a FastMCP Client for https://mcp.deepledger.ai/mcp with that key, and pass it to LangChain's MCPAdapter. Keep only the Xero tools your agent needs from list_tools() and pass them to create_agent.

How do I connect Xero to LangGraph?

Use the same code. LangChain's create_agent returns a compiled LangGraph graph, and the tools from MCPAdapter are standard LangChain tools, so you can place them in a ToolNode in your own graph. Keep the organisation check before any branch that can write.

Do I need a Xero developer app for LangChain?

Not for this setup. An admin connects the Xero organisation to DeepLedger once through Xero's sign-in, and your Python process authenticates to DeepLedger with a DeepLedger API key. A direct Xero API integration is a different design and needs your own Xero app.

Does filtering the LangChain tool list make the API key read-only?

No. The filter limits which tools this agent can choose, but a DeepLedger API key carries the access of the person who created it, with no read-only switch of its own. Keep the key in a secret store, revoke it when the job ends, and add a human approval step before exposing a write tool.

Can one LangChain agent work across several Xero organisations?

Yes, with an All my companies key. Call xeroOrganisation with list, switch by the returned organizationId, and check the company named in each result. A switch moves the person's shared active company, so parallel jobs should use One company keys or an X-Organization-Id header.

Will the agent's Xero invoices and bills post straight away?

Not by default. DeepLedger saves new Xero invoices, bills, credit notes and manual journals as drafts unless the request asks to approve them. Payments, spend and receive money and transfers post straight away, so expose those tools only with an approval step.

Browse all AI platforms and integrations.

Ready to get started?

Connect QuickBooks and try your first task with an AI agent.

Start free trial

With your permission, Google Analytics measures visits to our public website and blog. Essential cookies work either way. Change your choice in Cookie settings. Privacy policy