This project demonstrates advanced integration between LangChain and the Xero MCP (Model Context Protocol) Server, providing a powerful framework for building AI agents that can interact with Xero accounting data.
The langchain.py file contains several specialized agents and workflows that showcase different use cases for integrating LangChain with Xero through the MCP protocol. This integration allows you to build intelligent agents that can perform complex accounting operations, analyze financial data, and automate business processes.
- Invoice Specialist Agent: Focuses on invoice operations, creation, and management
- Contact Manager Agent: Handles customer and supplier contact management
- Interactive Chat Agent: Provides a conversational interface for Xero operations
- Multi-step Workflows: Complex business processes like monthly invoicing
- Invoice Analysis: Intelligent analysis of invoice data with recommendations
- Organization Insights: Comprehensive business intelligence and reporting
- Automatic tool discovery and integration via MCP
- Async/await support for optimal performance
- Error handling and robust exception management
- Environment-based configuration
Create a .env file in the project directory with the following variables:
# OpenAI API Configuration
OPENAI_API_KEY=your_openai_api_key_here
# Xero API Configuration
XERO_CLIENT_ID=your_xero_client_id
XERO_CLIENT_SECRET=your_xero_client_secret- Create a Xero Developer Account at developer.xero.com
- Create a new app and obtain your Client ID and Client Secret
- Configure the appropriate scopes for your use case
-
Install Python dependencies:
pip install -r requirements.txt
-
Install the Xero MCP Server:
npm install -g @xeroapi/xero-mcp-server@latest
-
Set up environment variables: Create a
.envfile with your API keys (see Prerequisites section)
Execute the main script to access the interactive demo menu:
python langchain.pyYou'll be presented with the following options:
- Invoice Specialist Agent - Demonstrates invoice-focused operations
- Contact Manager Agent - Shows contact management capabilities
- Multi-step Workflow - Complex business process automation
- Invoice Analysis - Intelligent financial data analysis
- Interactive Chat - Conversational interface with your Xero data
- Organization Insights - Business intelligence and reporting
from langchain.py import create_xero_mcp_agent
from langchain_core.messages import HumanMessage
async def example_usage():
# Create the agent
agent, client = await create_xero_mcp_agent()
# Use the agent
response = await agent.ainvoke({
"messages": [HumanMessage(content="Find all draft invoices")]
})
# Process the response
if response and "messages" in response:
result = response["messages"][-1].content
print(f"Agent response: {result}")async def custom_workflow():
agent, client = await create_xero_mcp_agent()
workflow_steps = [
"List all customers",
"Find overdue invoices",
"Calculate total outstanding amount"
]
for step in workflow_steps:
response = await agent.ainvoke({
"messages": [HumanMessage(content=step)]
})
# Process each step...The project uses the langchain-mcp-adapters library to seamlessly integrate with the Xero MCP Server. This provides:
- Automatic Tool Discovery: Tools are automatically discovered from the MCP server
- Type Safety: Proper typing and validation for all Xero API operations
- Error Handling: Robust error handling and retry mechanisms
The agents are built using LangGraph's create_react_agent pattern, providing:
- ReAct Framework: Reasoning and Acting capabilities
- Tool Integration: Seamless integration with Xero MCP tools
- Context Management: Proper conversation context and memory
The integration provides access to comprehensive Xero functionality including:
- Create, update, and search contacts
- Manage customer and supplier information
- Contact group management
- Create and update invoices
- Process payments
- Invoice analysis and reporting
- Profit & Loss statements
- Balance sheets
- Trial balance
- Aged receivables/payables
- Bank transaction management
- Reconciliation support
- Employee management
- Timesheet processing
- Leave management
The project includes comprehensive error handling:
try:
response = await agent.ainvoke({"messages": [HumanMessage(content=query)]})
# Process response...
except Exception as e:
print(f"❌ Error: {e}")
# Handle error appropriately...python/langchain/
├── langchain.py # Main integration file
├── requirements.txt # Python dependencies
└── README.md # This file
To add new functionality:
- Create Custom Agents: Follow the pattern in existing demo functions
- Add New Workflows: Implement multi-step business processes
- Custom Tools: Extend with additional MCP tools if needed
Before running the integration:
- Ensure all environment variables are set
- Verify Xero API credentials are valid
- Test with a Xero sandbox environment first
-
Missing Environment Variables
Error: OPENAI_API_KEY not set in environmentSolution: Create a
.envfile with all required variables -
Xero Authentication Errors
Error: Xero credentials not set in environmentSolution: Verify your Xero Client ID and Secret are correct
-
MCP Server Connection Issues
Error connecting to MCP serverSolution: Ensure the Xero MCP server is installed:
npm install -g @xeroapi/xero-mcp-server@latest
For additional debugging information, set the environment variable:
export DEBUG=1To contribute to this project:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is part of the Xero Agent Toolkit. Please refer to the main repository for licensing information.
For support and questions:
- Check the Xero Developer Documentation
- Review the LangChain Documentation
- Open an issue in the main repository