mashrur950's picture
feat: Implement FastAPI root endpoint with usage instructions and server status
3d451f2
raw
history blame
8.77 kB
"""
FleetMind MCP Server - Hugging Face Space Entry Point (Track 1)
This file serves as the entry point for HuggingFace Space deployment.
Exposes 18 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
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import uvicorn
# ============================================================================
# HUGGING FACE SPACE CONFIGURATION
# ============================================================================
# HuggingFace Space default port
HF_SPACE_PORT = int(os.getenv("PORT", 7860))
HF_SPACE_HOST = os.getenv("HOST", "0.0.0.0")
# Create FastAPI app with root endpoint
app = FastAPI(title="FleetMind MCP Server")
@app.get("/", response_class=HTMLResponse)
async def root():
"""Root endpoint with usage instructions"""
return """
<!DOCTYPE html>
<html>
<head>
<title>FleetMind MCP Server</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; line-height: 1.6; }
h1 { color: #2c3e50; }
h2 { color: #34495e; margin-top: 30px; }
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }
pre { background: #2c3e50; color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; }
.status { color: #27ae60; font-weight: bold; }
.endpoint { background: #3498db; color: white; padding: 10px; border-radius: 5px; margin: 10px 0; }
ul { margin-left: 20px; }
</style>
</head>
<body>
<h1>🚚 FleetMind MCP Server</h1>
<p class="status">βœ… Server Status: RUNNING</p>
<h2>πŸ“‘ MCP Endpoint</h2>
<div class="endpoint">
<strong>SSE Endpoint:</strong> <code>https://huggingface.co/spaces/MCP-1st-Birthday/fleetmind-dispatch-ai/sse</code>
</div>
<h2>πŸ”§ How to Connect</h2>
<h3>From Claude Desktop:</h3>
<p>Add this to your <code>claude_desktop_config.json</code>:</p>
<pre>{
"mcpServers": {
"fleetmind": {
"command": "npx",
"args": [
"mcp-remote",
"https://huggingface.co/spaces/MCP-1st-Birthday/fleetmind-dispatch-ai/sse"
]
}
}
}</pre>
<h3>From Continue (VS Code):</h3>
<ol>
<li>Install Continue extension</li>
<li>Add FleetMind MCP server in settings</li>
<li>Use the SSE endpoint URL above</li>
</ol>
<h2>πŸ› οΈ Available Tools (18 Total)</h2>
<h3>Order Management:</h3>
<ul>
<li><code>geocode_address</code> - Convert addresses to GPS coordinates</li>
<li><code>calculate_route</code> - Find shortest route between locations</li>
<li><code>create_order</code> - Create new delivery orders</li>
<li><code>count_orders</code> - Count orders with filters</li>
<li><code>fetch_orders</code> - Retrieve orders with pagination</li>
<li><code>get_order_details</code> - Get complete order information</li>
<li><code>search_orders</code> - Search by customer/ID</li>
<li><code>get_incomplete_orders</code> - List active deliveries</li>
<li><code>update_order</code> - Update order details</li>
<li><code>delete_order</code> - Remove orders</li>
</ul>
<h3>Driver Management:</h3>
<ul>
<li><code>create_driver</code> - Onboard new drivers</li>
<li><code>count_drivers</code> - Count drivers with filters</li>
<li><code>fetch_drivers</code> - Retrieve drivers with pagination</li>
<li><code>get_driver_details</code> - Get driver info + location</li>
<li><code>search_drivers</code> - Search by name/plate/ID</li>
<li><code>get_available_drivers</code> - List available drivers</li>
<li><code>update_driver</code> - Update driver information</li>
<li><code>delete_driver</code> - Remove drivers</li>
</ul>
<h2>πŸ“Š Real-Time Resources (2 Total)</h2>
<ul>
<li><code>orders://all</code> - Live orders dataset (last 30 days)</li>
<li><code>drivers://all</code> - Live drivers dataset with locations</li>
</ul>
<h2>πŸ“– Example Usage</h2>
<p>After connecting via Claude Desktop, try:</p>
<ul>
<li>"Create an urgent delivery order for Sarah at 456 Oak Ave, San Francisco"</li>
<li>"Show me all available drivers"</li>
<li>"Calculate route from downtown SF to Oakland Airport"</li>
<li>"How many pending orders do we have?"</li>
</ul>
<h2>πŸ”— Links</h2>
<ul>
<li><a href="https://github.com/mashrur-rahman-fahim/fleetmind-mcp">GitHub Repository</a></li>
<li><a href="https://huggingface.co/MCP-1st-Birthday">MCP 1st Birthday Hackathon</a></li>
<li><a href="https://modelcontextprotocol.io">Model Context Protocol Docs</a></li>
</ul>
<footer style="margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d;">
<p>πŸ† <strong>Track 1: Building MCP Servers - Enterprise Category</strong></p>
<p>Built with ❀️ using <a href="https://github.com/jlowin/fastmcp">FastMCP</a></p>
</footer>
</body>
</html>
"""
# Mount MCP SSE endpoint
# FastMCP will handle the /sse endpoint when we call mcp.run()
# ============================================================================
# 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"Endpoint: http://{HF_SPACE_HOST}:{HF_SPACE_PORT}/sse")
logger.info("=" * 70)
logger.info("Features:")
logger.info(" βœ“ 18 AI Tools (Order + Driver Management)")
logger.info(" βœ“ 2 Real-Time Resources (orders://all, drivers://all)")
logger.info(" βœ“ Google Maps API Integration (Geocoding + Routes)")
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(f"Starting SSE server on {HF_SPACE_HOST}:{HF_SPACE_PORT}...")
logger.info("Waiting for MCP client connections...")
logger.info("=" * 70)
try:
# Run MCP server in SSE mode for HuggingFace Space
# This will automatically mount the /sse endpoint to our FastAPI app
mcp.run(
transport="sse",
host=HF_SPACE_HOST,
port=HF_SPACE_PORT,
custom_app=app # Use our custom FastAPI app with root endpoint
)
except TypeError:
# Fallback if FastMCP doesn't support custom_app
# Run both servers (not ideal but works)
logger.warning("Running without custom root endpoint")
mcp.run(
transport="sse",
host=HF_SPACE_HOST,
port=HF_SPACE_PORT
)
except Exception as e:
logger.error(f"Failed to start MCP 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