portainer-mcp/run_server.py
Adolfo Delorenzo be1e05c382 Simplify authentication to require URL and API key only
Major configuration and tooling updates:

Authentication Changes:
- Remove username/password authentication support
- Require PORTAINER_URL and PORTAINER_API_KEY (both mandatory)
- Simplify PortainerConfig class and validation logic
- Update all documentation to reflect API key requirement

Multiple Runtime Support:
- Add uvx support for running without installation
- Add uv support with dedicated wrapper script
- Add npx support with Node.js wrapper script
- Maintain backward compatibility with direct Python execution

Documentation Updates:
- Comprehensive README.md with all execution methods
- Detailed USAGE.md with step-by-step instructions
- Updated .env.example with clear required vs optional sections
- Enhanced docstrings in server.py and config.py

Tooling Support:
- package.json for npm/npx support with cross-platform wrapper
- scripts/run-with-uv.py for uv integration
- bin/portainer-core-mcp Node.js wrapper for npx
- test_uvx.py for uvx functionality testing

Configuration Improvements:
- Clear separation of required vs optional environment variables
- Better validation error messages
- Simplified authentication flow
- Enhanced project metadata in pyproject.toml

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-18 07:48:23 -06:00

110 lines
3.8 KiB
Python

#!/usr/bin/env python3
"""
Portainer Core MCP Server - Entry Point Script.
This script serves as the main entry point for the Portainer Core MCP Server,
providing authentication and user management functionality for Portainer Business Edition.
It handles environment setup, configuration validation, and server startup.
Usage:
python run_server.py
Environment Variables:
PORTAINER_URL: The base URL of your Portainer instance (required)
PORTAINER_API_KEY: API key for authentication (required)
Example:
export PORTAINER_URL=https://portainer.example.com
export PORTAINER_API_KEY=your-api-key-here
python run_server.py
Architecture:
- Environment setup and validation
- Configuration loading from environment variables
- Async server initialization and startup
- Graceful error handling and shutdown
"""
import os
import sys
import asyncio
from portainer_core.server import main
def setup_environment():
"""
Set up environment variables with fallback values for demo/testing.
This function ensures the required environment variables are set for the server
to start properly. It provides fallback values for demo purposes when specific
configuration is not provided.
Environment Variables Handled:
PORTAINER_URL: Sets default demo URL if not provided
PORTAINER_API_KEY: Sets placeholder if no authentication is configured
Raises:
None: This function doesn't raise exceptions but prints warnings for
missing configuration.
Side Effects:
- Modifies os.environ with default values
- Prints configuration messages to stdout
- Ensures minimum viable configuration for server startup
Note:
In production environments, always provide proper authentication
credentials rather than relying on demo/placeholder values.
"""
# Configure Portainer URL with fallback to demo instance
if not os.environ.get('PORTAINER_URL'):
os.environ['PORTAINER_URL'] = 'https://demo.portainer.io'
print("🔧 Using demo Portainer URL: https://demo.portainer.io")
# Configure authentication - requires API key
has_api_key = os.environ.get('PORTAINER_API_KEY')
if not has_api_key:
print("⚠️ No API key configured. Set PORTAINER_API_KEY")
print(" For demo purposes, using placeholder API key")
os.environ['PORTAINER_API_KEY'] = 'demo-api-key'
if __name__ == "__main__":
"""
Main execution block for the Portainer Core MCP Server.
This block handles the complete server lifecycle:
1. Environment setup and configuration validation
2. Async server initialization
3. Graceful error handling and shutdown
4. User-friendly status messages
Exit Codes:
0: Successful shutdown (user interrupt)
1: Server failure or configuration error
Flow:
1. Print startup messages and configuration requirements
2. Setup environment variables with fallbacks
3. Start async server using asyncio.run()
4. Handle interrupts and exceptions gracefully
"""
print("🚀 Starting Portainer Core MCP Server...")
print(" Configuration will be loaded from environment variables")
print(" Set PORTAINER_URL and PORTAINER_API_KEY before running")
print("")
# Initialize environment with fallback values for demo/testing
setup_environment()
try:
# Start the async MCP server - this blocks until shutdown
asyncio.run(main())
except KeyboardInterrupt:
# Handle graceful shutdown on Ctrl+C
print("\n👋 Server stopped by user")
sys.exit(0)
except Exception as e:
# Handle any startup or runtime errors
print(f"\n❌ Server failed: {e}")
sys.exit(1)