""" FleetMind MCP Server - Hugging Face Space Entry Point (Track 1) This file serves as the entry point for HuggingFace Space deployment. Exposes 29 MCP tools via Server-Sent Events (SSE) endpoint for AI clients. Architecture: User → MCP Client (Claude Desktop, Continue, etc.) → SSE Endpoint (this file) → FleetMind MCP Server (server.py) → Tools (chat/tools.py) → Database (PostgreSQL) For Track 1: Building MCP Servers - Enterprise Category https://huggingface.co/MCP-1st-Birthday Compatible with: - Claude Desktop (via SSE transport) - Continue.dev (VS Code extension) - Cline (VS Code extension) - Any MCP client supporting SSE protocol """ import os import sys import logging from pathlib import Path # Add project root to path sys.path.insert(0, str(Path(__file__).parent)) # Configure logging for HuggingFace Space logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler()] ) logger = logging.getLogger(__name__) # Import the MCP server instance from server import mcp # ============================================================================ # HUGGING FACE SPACE CONFIGURATION # ============================================================================ # HuggingFace Space default port # NOTE: When using proxy.py, FastMCP runs on 7861 (internal port) # The proxy runs on 7860 (public) and forwards requests here HF_SPACE_PORT = int(os.getenv("PORT", 7861)) HF_SPACE_HOST = os.getenv("HOST", "0.0.0.0") # ============================================================================ # MAIN ENTRY POINT # ============================================================================ if __name__ == "__main__": logger.info("=" * 70) logger.info("FleetMind MCP Server - HuggingFace Space (Track 1)") logger.info("=" * 70) logger.info("MCP Server: FleetMind Dispatch Coordinator v1.0.0") logger.info("Protocol: Model Context Protocol (MCP)") logger.info("Transport: Server-Sent Events (SSE)") logger.info(f"SSE Endpoint: https://mcp-1st-birthday-fleetmind-dispatch-ai.hf.space/sse") logger.info("=" * 70) logger.info("Features:") logger.info(" ✓ 29 AI Tools (Order + Driver + Assignment Management)") logger.info(" ✓ 2 Real-Time Resources (orders://all, drivers://all)") logger.info(" ✓ Gemini 2.0 Flash AI - Intelligent Assignment") logger.info(" ✓ Google Maps API Integration (Routes + Geocoding)") logger.info(" ✓ Weather-Aware Routing (OpenWeatherMap)") logger.info(" ✓ PostgreSQL Database (Neon)") logger.info("=" * 70) logger.info("Compatible Clients:") logger.info(" • Claude Desktop") logger.info(" • Continue.dev (VS Code)") logger.info(" • Cline (VS Code)") logger.info(" • Any MCP-compatible client") logger.info("=" * 70) logger.info("How to Connect (Claude Desktop):") logger.info(' Add to claude_desktop_config.json:') logger.info(' {') logger.info(' "mcpServers": {') logger.info(' "fleetmind": {') logger.info(' "command": "npx",') logger.info(' "args": [') logger.info(' "mcp-remote",') logger.info(' "https://mcp-1st-birthday-fleetmind-dispatch-ai.hf.space/sse"') logger.info(' ]') logger.info(' }') logger.info(' }') logger.info(' }') logger.info("=" * 70) logger.info(f"Starting SSE server on {HF_SPACE_HOST}:{HF_SPACE_PORT}...") logger.info("Waiting for MCP client connections...") logger.info("=" * 70) try: # Add web routes for landing page and API key generation from starlette.responses import HTMLResponse, JSONResponse from starlette.requests import Request from database.api_keys import generate_api_key as db_generate_api_key # ===================================================================== # PROXY-BASED AUTHENTICATION # Authentication is handled by proxy.py (port 7860) # The proxy captures API keys from SSE connections and injects them # into tool requests before forwarding to FastMCP (port 7861) # ===================================================================== logger.info("[Auth] Using proxy-based authentication") logger.info("[Auth] Proxy captures API keys and injects into tool requests") @mcp.custom_route("/", methods=["GET"]) async def landing_page(request): """Landing page with MCP connection information""" return HTMLResponse(""" FleetMind MCP Server

🚚 FleetMind MCP Server

Enterprise Model Context Protocol Server for AI-Powered Delivery Dispatch

MCP 1st Birthday Hackathon Track 1: Building MCP Enterprise Category


🔌 MCP Server Connection

SSE Endpoint URL:
https://mcp-1st-birthday-fleetmind-dispatch-ai.hf.space/sse

🔑 Step 1: Get Your API Key

Generate API Key →

Click the button above to generate your unique API key. You'll need this to authenticate with the server.

⚙️ Step 2: Configure Claude Desktop

Add this to your claude_desktop_config.json file:

{
  "mcpServers": {
    "fleetmind": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp-1st-birthday-fleetmind-dispatch-ai.hf.space/sse?api_key=fm_your_api_key_here"
      ]
    }
  }
}

💡 Important: Add your API key as a query parameter (?api_key=...) in the URL, not in the env section!

📋 Step 3: Connect

  1. Generate your API key using the button above
  2. Install Claude Desktop
  3. Locate your claude_desktop_config.json file
  4. Add the configuration, replacing fm_your_api_key_here with your actual API key in the URL
  5. Restart Claude Desktop
  6. Look for "FleetMind" in the 🔌 tools menu

🛠️ Available Tools (29 Total)

📍 Geocoding & Routing (3 tools):
geocode_address, calculate_route, calculate_intelligent_route
📦 Order Management (8 tools):
create_order, count_orders, fetch_orders, get_order_details, search_orders, get_incomplete_orders, update_order, delete_order
👥 Driver Management (8 tools):
create_driver, count_drivers, fetch_drivers, get_driver_details, search_drivers, get_available_drivers, update_driver, delete_driver
🔗 Assignment Management (8 tools):
create_assignment, auto_assign_order, intelligent_assign_order, get_assignment_details, update_assignment, unassign_order, complete_delivery, fail_delivery
🗑️ Bulk Operations (2 tools):
delete_all_orders, delete_all_drivers

⭐ Key Features

🔒 Authentication & Security

How Authentication Works:
1. Generate API key via /generate-key
2. API key hashed (SHA-256) before storage
3. User ID generated: user_{MD5(email)[:12]}
4. Add key to URL: ?api_key=fm_...
5. Server validates on each SSE connection
6. All queries filter by user_id for isolation
Security Features:
✅ One-Time Display (keys shown once)
✅ Hashed Storage (SHA-256, never plaintext)
✅ Database-Level Isolation (all tables have user_id)
✅ Deterministic User IDs (same email → same user_id)
✅ Production Safeguards (ENV-based SKIP_AUTH protection)

📚 Resources


FleetMind v1.0 - Built for MCP 1st Birthday Hackathon
29 AI Tools | 2 Real-Time Resources | Enterprise-Ready

""") @mcp.custom_route("/generate-key", methods=["GET", "POST"]) async def generate_key_page(request): """API Key generation page""" if request.method == "GET": return HTMLResponse(""" Generate FleetMind API Key

🔑 Generate API Key

Create your FleetMind MCP Server API key

📋 What you'll need:
• Your email address (used to generate your unique user_id)
• Your name (optional)

🔐 What you'll get:
• API Key: fm_xxxxx... (show once, copy immediately!)
• User ID: user_xxxxx (deterministic from your email)
• All your data (orders/drivers/assignments) will be isolated by this user_id

← Back to Home

""") # POST - Generate API key else: try: form_data = await request.form() email = form_data.get("email") name = form_data.get("name") or None if not email: return HTMLResponse("

Error: Email is required

", status_code=400) result = db_generate_api_key(email, name) if not result['success']: return HTMLResponse(f"

Error: {result['error']}

", status_code=400) # Success - show the API key (one time only!) return HTMLResponse(f""" Your FleetMind API Key

✅ API Key Generated!

Your API key has been created successfully

📧 Email: {result["email"]}

👤 Name: {result["name"]}

🆔 User ID: {result["user_id"]}

⚠️ SAVE THIS KEY NOW - IT WON'T BE SHOWN AGAIN!

🔑 Your API Key:

{result["api_key"]}

👥 Multi-Tenant Isolation

Your user_id ({result["user_id"]}) ensures complete data isolation:
✅ You will only see your own orders, drivers, and assignments
✅ All database operations automatically filter by your user_id
✅ Your user_id is deterministic - same email always gets same ID
✅ Even if you regenerate your API key, your user_id stays the same

📋 Claude Desktop Setup:

Add this to your claude_desktop_config.json:

{{
  "mcpServers": {{
    "fleetmind": {{
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp-1st-birthday-fleetmind-dispatch-ai.hf.space/sse?api_key={result["api_key"]}"
      ]
    }}
  }}
}}

💡 Important: The API key is included in the URL as a query parameter (?api_key=...)

🚀 Next Steps:

  1. Copy your API key (click the button above)
  2. Add it to your Claude Desktop config
  3. Restart Claude Desktop
  4. Start using FleetMind tools!

🔐 How Authentication Works:

Authentication Flow:

1️⃣ Connection: Claude Desktop connects to SSE endpoint with your API key in URL
2️⃣ Validation: Server hashes your key (SHA-256) and looks it up in database
3️⃣ User Extraction: Server retrieves your user_id: {result["user_id"]}
4️⃣ Data Isolation: All tool calls automatically filter by your user_id
5️⃣ Security: You can only access data associated with your user_id

← Back to Home

""") except Exception as e: return HTMLResponse(f"

Error: {str(e)}

", status_code=500) logger.info("[OK] Landing page added at / route") logger.info("[OK] API key generation page added at /generate-key") logger.info("[OK] MCP SSE endpoint available at /sse") logger.info("[OK] Authentication handled by proxy.py (port 7860)") # Run MCP server with SSE transport # No middleware needed - proxy.py handles API key capture and injection mcp.run( transport="sse", host=HF_SPACE_HOST, port=HF_SPACE_PORT ) except Exception as e: logger.error(f"Failed to start server: {e}") logger.error("Check that:") logger.error(" 1. Database connection is configured (DB_HOST, DB_USER, etc.)") logger.error(" 2. Google Maps API key is set (GOOGLE_MAPS_API_KEY)") logger.error(" 3. Port 7860 is available") raise