ERP集成HTTP服务器

Xentral MCP HTTP服务器是一个用于Xentral ERP集成的Model Context Protocol (MCP)实现,提供100多种工具支持日常ERP工作流程,包括销售、物流、财务等多个模块。

  • by bventures007
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 bventures007/xentral-mcp

使用说明

Xentral MCP HTTP Server

A Model Context Protocol (MCP) HTTP server for Xentral ERP integration, providing 100+ tools for daily ERP workflows. This server implements the MCP specification and automatically generates tool definitions from the comprehensive tool documentation.

🚀 Features

  • Real MCP HTTP Server: Full JSON-RPC 2.0 compatible MCP implementation
  • 100+ Tools: Automatically parsed from mcp-tools-list.md covering all ERP workflows
  • Runtime Configuration: Update API credentials dynamically without restart
  • Console Logging: Detailed logging of all MCP requests and parameters
  • Health Monitoring: Built-in health checks and server information endpoints
  • CORS Support: Compatible with web-based MCP clients
  • Production Ready: Structured codebase with proper error handling

📋 Requirements

  • Python 3.8 or higher
  • Xentral ERP system with API access
  • Valid Xentral API credentials

🛠️ Installation

1. Clone or Download

# If you have the files, ensure you have these files in your directory:
# - mcp_server.py
# - config.py
# - mcp_protocol.py
# - mcp_tools_parser.py
# - mcp-tools-list.md
# - requirements.txt
# - .env.example

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment

# Copy the example environment file
cp .env.example .env

# Edit .env with your Xentral credentials
nano .env  # or use your preferred editor

Required configuration in .env:

XENTRAL_API_URL=https://your-company.xentral.com/api
XENTRAL_API_KEY=your_api_key_here

⚙️ Configuration

Environment Variables

Variable Description Default Required
XENTRAL_API_URL Your Xentral API URL https://api.xentral.com ✅
XENTRAL_API_KEY Your Xentral API key - ✅
MCP_SERVER_HOST Server bind address 0.0.0.0 ❌
MCP_SERVER_PORT Server port 8888 ❌
MCP_DEBUG Debug mode false ❌
LOG_LEVEL Logging level INFO ❌
LOG_REQUESTS Log MCP requests true ❌

Runtime Configuration

You can also update API credentials at runtime:

curl -X POST http://localhost:8888/config/credentials \
  -H "Content-Type: application/json" \
  -d '{
    "api_url": "https://new-api.xentral.com",
    "api_key": "new_api_key_here"
  }'

🏃 Running the Server

Basic Usage

python mcp_server.py

With Custom Configuration

# Set environment variables inline
XENTRAL_API_URL=https://demo.xentral.com MCP_SERVER_PORT=9999 python mcp_server.py

Expected Output

============================================================
🚀 Xentral MCP HTTP Server
============================================================
Server: xentral-mcp-server v1.0.0
API URL: https://your-company.xentral.com
API Key: ✓ Configured
Host: 0.0.0.0
Port: 8888
Debug: False
------------------------------------------------------------
✅ Loaded 120 MCP tools
------------------------------------------------------------
🌐 Starting MCP server on http://0.0.0.0:8888
📋 Available endpoints:
   - POST /mcp - Main MCP JSON-RPC endpoint
   - GET  /health - Health check
   - GET  /info - Server information
   - GET  /tools - List all tools
   - GET  /config - Get configuration
   - POST /config/credentials - Update API credentials
============================================================

🔌 MCP Client Integration

Using with MCP-Compatible Clients

The server implements the standard MCP HTTP transport protocol. Configure your MCP client to connect to:

Endpoint: http://localhost:8888/mcp
Method: POST
Content-Type: application/json

Example MCP Client Request

Initialize the server:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {
      "name": "your-client",
      "version": "1.0.0"
    }
  }
}

List available tools:

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list"
}

Call a tool:

{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "search_customers",
    "arguments": {
      "name": "Miller",
      "city": "Berlin"
    }
  }
}

Search by email address:

{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "tools/call",
  "params": {
    "name": "search_customers",
    "arguments": {
      "email": "mueller@example.com"
    }
  }
}

Search by phone number:

{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "tools/call",
  "params": {
    "name": "search_customers",
    "arguments": {
      "phone": "+49 30 12345678"
    }
  }
}

🛠️ Available Tools

The server automatically loads 100+ tools from mcp-tools-list.md, organized in categories:

Sales & CRM (26 tools)

  • Customer management (search_customers, get_customer_overview, get_customer_history)
  • Quote processing (quick_quote, duplicate_quote, convert_quote_to_order)
  • Order management (get_order_overview, track_order_progress, update_delivery_date)

Service & Support (12 tools)

  • Ticketing (create_ticket_from_call, search_tickets, escalate_ticket)
  • Technical service (get_product_documentation, check_warranty_status, create_rma)

Logistics & Fulfillment (20 tools)

  • Warehouse operations (get_pick_orders, scan_barcode, check_stock_location)
  • Shipping (create_shipment_quick, print_shipping_label, bulk_track_shipments)
  • Returns (process_return, inspect_returned_goods, issue_refund)

Purchasing & Procurement (14 tools)

  • Order processing (get_purchase_requests, create_purchase_order_fast)
  • Supplier management (get_supplier_performance, negotiate_terms)

Accounting & Finance (14 tools)

  • Bookkeeping (scan_receipt, quick_journal_entry, match_payments)
  • Receivables (get_overdue_invoices, send_reminder, setup_payment_plan)

Administration & Master Data (8 tools)

  • User management (get_user_permissions, delegate_task, set_out_of_office)
  • Product management (create_product_quick, update_product_price)

Communication & Workflow (15 tools)

  • Document management (upload_document, search_documents, approve_document)
  • Workflow (get_pending_approvals, approve_request, escalate_approval)

Analytics & Reporting (20 tools)

  • KPIs (get_daily_sales, get_open_orders, get_stock_alerts)
  • Analytics (get_sales_metrics, get_customer_analytics, get_financial_kpis)

Mobile & Integration (8 tools)

  • Mobile functions (mobile_time_tracking, mobile_expense_report)
  • External integration (sync_bank_data, update_web_shop)

🔍 Testing and Debugging

CLI Testing Tool (Recommended) 🎯

We provide a simple command-line tool for easy testing and exploration:

# Show help and usage
python mcp_client.py --help

# List all available tools (122 tools total)
python mcp_client.py list-tools

# Show detailed help for a specific tool
python mcp_client.py help search_customers
python mcp_client.py help get_order_overview

# Test tools with parameters - Sales & CRM
python mcp_client.py call search_customers --name "Miller" --city "Berlin"
python mcp_client.py call search_customers --email "mueller@example.com"
python mcp_client.py call search_customers --phone "+49 30 12345678"
python mcp_client.py call search_customers --name "Miller" --email "miller@example.com"
python mcp_client.py call get_order_overview --order_number "12345"
python mcp_client.py call get_customer_history --customer_number "C001" --limit "10"

# Test tools with parameters - Logistics
python mcp_client.py call check_product_availability --product_number "P123" --quantity "5"
python mcp_client.py call check_stock_location --product_number "ABC123" --warehouse_id "WH01"

# Test tools with parameters - Service & Support
python mcp_client.py call create_ticket_from_call \
  --customer_number "C001" \
  --product_number "P123" \
  --issue_category "defect" \
  --priority "high" \
  --description "Product not working properly"

# Test with different server
python mcp_client.py --server http://localhost:9999 list-tools

Key Features of the CLI Tool:

  • 🔧 Auto-discovery: Lists all 122 tools with descriptions
  • 📋 Parameter help: Shows detailed parameter information for each tool
  • 🎯 Smart examples: Generates example usage for each tool
  • 📊 Categorized view: Groups tools by functionality (Sales, Logistics, etc.)
  • ⚡ Easy testing: Simple parameter passing with --param value syntax
  • 🔍 Request logging: See exactly what gets sent to the server

Manual Testing with curl

Health Check

curl http://localhost:8888/health

Server Information

curl http://localhost:8888/info

List All Tools

curl http://localhost:8888/tools

Test MCP Communication

curl -X POST http://localhost:8888/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
  }'

View Logs

The server logs all MCP requests with parameters:

2024-01-15 10:30:15 - MCP Request: POST /mcp
2024-01-15 10:30:15 - MCP Method: tools/call
2024-01-15 10:30:15 - Tool Call: search_customers
2024-01-15 10:30:15 - Tool Arguments: {"name": "Miller", "city": "Berlin"}

Logs are written to:

  • Console (stdout)
  • mcp_server.log file

🐛 Troubleshooting

Common Issues

1. Server won't start

❌ Failed to initialize tools. Server will start but may not function properly.
  • Solution: Ensure mcp-tools-list.md is present in the same directory

2. Configuration errors

⚠️ Configuration Issues:
   - XENTRAL_API_KEY is not configured
  • Solution: Set up your .env file or use runtime configuration

3. Tools not loading

⚠️ No tools were parsed from mcp-tools-list.md
  • Solution: Check that mcp-tools-list.md is properly formatted and accessible

4. MCP client connection issues

  • Solution: Ensure the client is connecting to http://localhost:8888/mcp with POST requests
  • Solution: Check CORS settings if using a web-based client

Debug Mode

Enable debug mode for detailed logging:

MCP_DEBUG=true LOG_LEVEL=DEBUG python mcp_server.py

Port Conflicts

If port 8888 is in use:

MCP_SERVER_PORT=9999 python mcp_server.py

📁 Project Structure

xentral-mcp/
├── mcp_server.py           # Main server with configuration section
├── config.py               # Configuration management class
├── mcp_protocol.py         # MCP JSON-RPC protocol implementation
├── mcp_tools_parser.py     # Markdown parser for tool definitions
├── mcp-tools-list.md       # Complete tool documentation (100+ tools)
├── requirements.txt        # Python dependencies
├── .env.example           # Environment configuration template
├── .env                   # Your actual configuration (create this)
├── README.md              # This file
└── mcp_server.log         # Server logs (generated at runtime)

🔧 Development

Adding New Tools

  1. Add tool definition to mcp-tools-list.md following the existing format:
- **`new_tool_name`** - Tool description
  - **Xentral MCP Status:** ❌ Not implemented
  - Parameter: `param1`, `param2` (required), `param3`
  1. Restart the server - tools are automatically parsed and loaded (skeleton response)

Implementing Tool Logic

Once tools are defined in mcp-tools-list.md, you can implement actual Xentral API calls:

1. Create Tool Implementation

Create a new file in the xentral/ directory:

# Create your tool implementation file
touch xentral/your_tool_name.py

2. Tool Implementation Template

"""Xentral API implementation for your_tool_name tool."""

from typing import Dict, Any
from .base import XentralAPIBase, XentralAPIError

class YourToolName(XentralAPIBase):
    """Handle your_tool_name with Xentral API"""
    
    def execute(self, arguments: Dict[str, Any]) -> str:
        """Execute your_tool_name API call"""
        try:
            # 1. Build API URL
            url = self.build_api_url('api/v2/your-endpoint')
            
            # 2. Build request parameters
            params = {}
            
            # Add filters (if applicable)
            filter_params = self._build_filters(arguments)
            params.update(filter_params)
            
            # Add pagination
            pagination_params = self.build_pagination(arguments)
            params.update(pagination_params)
            
            # Add sorting
            sorting_params = self.build_sorting(arguments)
            params.update(sorting_params)
            
            # 3. Make API request
            response_data = self.make_request('GET', url, params=params)
            
            # 4. Format and return response
            return self._format_response(response_data)
            
        except XentralAPIError as e:
            return self.format_error_response(e)
        except Exception as e:
            return self.format_error_response(e)
    
    def _build_filters(self, arguments: Dict[str, Any]) -> Dict[str, str]:
        """Build API filters from MCP arguments"""
        # Map MCP parameters to Xentral API filter keys
        param_mapping = {
            'your_param': 'xentral_field_name',
            'name': 'name',
            'email': 'email',
            # ... add more mappings
        }
        
        return self.build_filters(arguments, param_mapping)
    
    def _format_response(self, api_data: Dict[str, Any]) -> str:
        """Format API response for readable output"""
        if not api_data.get('data'):
            return "No results found."
        
        items = api_data['data']
        total = api_data.get('meta', {}).get('total', len(items))
        
        output = [f"🔍 Found {total} results:\n"]
        
        for i, item in enumerate(items[:10], 1):
            # Format each item - customize based on your data
            output.append(f"{i}. **{item.get('name', 'N/A')}**")
            output.append(f"   ID: {item.get('id', 'N/A')}")
            # Add more fields as needed
            output.append("")
        
        return "\n".join(output)

3. Common Implementation Patterns

For search/list endpoints:

def _build_filters(self, arguments):
    """Build Xentral API filters from MCP arguments"""
    param_mapping = {
        'customer_id': 'id',
        'name': 'name',
        'email': 'email',
        'city': 'city'
    }
    
    return self.build_filters(arguments, param_mapping)

For create/update endpoints:

def execute(self, arguments):
    url = self.build_api_url('api/v2/customers')
    
    # Build request data
    data = {
        'name': arguments.get('name'),
        'email': arguments.get('email'),
        # ... map other fields
    }
    
    response = self.make_request('POST', url, data=data)
    return f"✅ Created customer #{response.get('data', {}).get('number')}"

For single item retrieval:

def execute(self, arguments):
    # Extract ID from arguments
    customer_id = arguments.get('customer_id') or arguments.get('customer_number')
    
    if not customer_id:
        return "❌ Error: customer_id or customer_number is required"
    
    url = self.build_api_url(f'api/v2/customers/{customer_id}')
    response = self.make_request('GET', url)
    
    return self._format_single_customer(response.get('data', {}))

4. Testing Your Implementation

# Test with the CLI client
python mcp_client.py call your_tool_name --param1 "value1" --param2 "value2"

# Or test with curl
curl -X POST http://localhost:8888/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "your_tool_name",
      "arguments": {"param1": "value1"}
    }
  }'

5. Implementation Status

  • ✅ search_customers - Fully implemented with Xentral API v2/customers
  • ❌ All other tools - Skeleton responses (implementation needed)

To implement more tools, follow the same pattern:

  1. Create xentral/tool_name.py
  2. Implement the class inheriting from XentralAPIBase
  3. Add proper API endpoint mapping and response formatting
  4. Test with the CLI client

Extending the Server

  • Add new endpoints: Extend the Flask app in mcp_server.py
  • Modify protocol: Update mcp_protocol.py for MCP spec changes
  • Custom parsing: Enhance mcp_tools_parser.py for complex parameter handling
  • Configuration: Add new settings to config.py
  • New tools: Create files in xentral/ directory following the pattern above

📜 License

This project implements the Model Context Protocol (MCP) specification for Xentral ERP integration.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

📞 Support

For issues and questions:

  1. Check the troubleshooting section above
  2. Review server logs in mcp_server.log
  3. Test with debug mode enabled
  4. Verify your Xentral API credentials and permissions

Happy ERP automation with MCP! 🚀