File size: 8,769 Bytes
d69447e
6eba330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69447e
 
6eba330
d69447e
6eba330
d69447e
 
6eba330
d69447e
 
6eba330
 
 
 
 
 
 
 
 
 
6ac5ff6
 
 
6eba330
 
 
 
 
 
 
 
 
6ac5ff6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eba330
 
 
d69447e
 
6eba330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ac5ff6
 
 
 
 
 
 
 
 
 
 
6eba330
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""
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