mcp-mailu/examples/test_server.py
Ryan Malloy 66d1c0732a Initial commit: FastMCP server for Mailu email API integration
- Complete FastMCP server with OpenAPI integration and fallback tools
- Automatic tool generation from Mailu REST API endpoints
- Bearer token authentication support
- Comprehensive test suite and documentation
- PyPI-ready package configuration with proper metadata
- Environment-based configuration support
- Production-ready error handling and logging
- Examples and publishing scripts included

Features:
- User management (list, create, update, delete)
- Domain management (list, create, update, delete)
- Alias management and email forwarding
- DKIM key generation
- Manager assignment for domains
- Graceful fallback when OpenAPI validation fails

Ready for Claude Desktop integration and PyPI distribution.
2025-07-16 11:55:44 -06:00

164 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""
Example script demonstrating how to test the Mailu MCP server.
This script shows how to use the FastMCP client to connect to
the Mailu MCP server and perform operations.
"""
import asyncio
import os
from fastmcp import FastMCP
from fastmcp.client import Client
async def test_mailu_mcp_server():
"""Test the Mailu MCP server functionality."""
print("🚀 Testing Mailu MCP Server")
print("=" * 50)
# Create a client to connect to our MCP server
# Note: In practice, the server would be running separately
client = Client("stdio")
try:
# Connect to the server
print("📡 Connecting to MCP server...")
await client.connect()
# List available tools
print("\n🔧 Available Tools:")
tools = await client.list_tools()
for tool in tools:
print(f" - {tool.name}: {tool.description}")
# List available resources
print("\n📊 Available Resources:")
resources = await client.list_resources()
for resource in resources:
print(f" - {resource.uri}: {resource.name}")
# Example: List all users (if configured)
print("\n👥 Testing user listing...")
try:
result = await client.call_tool("list_users", {})
print(f"✅ Users retrieved: {len(result.get('content', []))} users")
except Exception as e:
print(f"⚠️ Note: {e} (Expected if not configured)")
# Example: List all domains
print("\n🌐 Testing domain listing...")
try:
result = await client.call_tool("list_domain", {})
print(f"✅ Domains retrieved: {len(result.get('content', []))} domains")
except Exception as e:
print(f"⚠️ Note: {e} (Expected if not configured)")
except Exception as e:
print(f"❌ Error: {e}")
print("\n💡 Tips:")
print(" 1. Make sure you have set MAILU_BASE_URL and MAILU_API_TOKEN")
print(" 2. Ensure your Mailu server is accessible")
print(" 3. Verify your API token has the required permissions")
finally:
await client.close()
async def show_configuration_example():
"""Show example configuration."""
print("\n⚙️ Configuration Example")
print("=" * 50)
example_config = """
# Copy .env.example to .env and update with your values:
MAILU_BASE_URL=https://mail.yourdomain.com
MAILU_API_TOKEN=your_actual_api_token_here
# Then run the server:
uv run mcp-mailu
"""
print(example_config)
# Check current environment
base_url = os.getenv("MAILU_BASE_URL")
api_token = os.getenv("MAILU_API_TOKEN")
print(f"Current MAILU_BASE_URL: {base_url or 'Not set'}")
print(f"Current MAILU_API_TOKEN: {'Set' if api_token else 'Not set'}")
async def demonstrate_api_operations():
"""Demonstrate typical API operations."""
print("\n📋 Common API Operations")
print("=" * 50)
operations = [
{
"name": "Create User",
"tool": "create_user",
"example": {
"email": "john.doe@example.com",
"raw_password": "SecurePassword123!",
"displayed_name": "John Doe",
"quota_bytes": 1000000000, # 1GB
"enabled": True,
"comment": "New employee"
}
},
{
"name": "Create Domain",
"tool": "create_domain",
"example": {
"name": "newcompany.com",
"max_users": 50,
"max_aliases": 100,
"signup_enabled": False,
"comment": "New company domain"
}
},
{
"name": "Create Alias",
"tool": "create_alias",
"example": {
"email": "sales@example.com",
"destination": ["john@example.com", "jane@example.com"],
"comment": "Sales team alias"
}
},
{
"name": "Update User Quota",
"tool": "update_user",
"example": {
"quota_bytes": 2000000000, # 2GB
"comment": "Increased quota for power user"
}
}
]
for op in operations:
print(f"\n🔧 {op['name']}:")
print(f" Tool: {op['tool']}")
print(f" Example parameters:")
for key, value in op['example'].items():
print(f" {key}: {value}")
async def main():
"""Main example function."""
await show_configuration_example()
await demonstrate_api_operations()
# Only try to connect if we have configuration
if os.getenv("MAILU_API_TOKEN"):
await test_mailu_mcp_server()
else:
print("\n💡 Set MAILU_API_TOKEN to test live connection")
if __name__ == "__main__":
asyncio.run(main())