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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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# FleetMind MCP Server

**Industry-standard Model Context Protocol server for AI-powered delivery dispatch management**

[![FastMCP](https://img.shields.io/badge/FastMCP-2.13.0-blue)](https://github.com/jlowin/fastmcp)
[![Python](https://img.shields.io/badge/Python-3.10%2B-brightgreen)](https://www.python.org/)
[![License](https://img.shields.io/badge/License-MIT-yellow)](LICENSE)

---

## Overview

FleetMind MCP Server provides 18 AI tools and 2 real-time resources for managing delivery dispatch operations through any MCP-compatible client (Claude Desktop, Continue, Cline, etc.).

**What is MCP?**
The Model Context Protocol (MCP) is an open standard that enables AI assistants to securely connect to external data sources and tools. Think of it as a universal API for AI agents.

---

## Quick Start

### 1. Installation

```bash
# Clone the repository
git clone https://github.com/your-org/fleetmind-mcp.git
cd fleetmind-mcp

# Install dependencies
pip install -r requirements.txt

# Configure environment variables
cp .env.example .env
# Edit .env with your credentials
```

### 2. Configure Environment

Edit `.env` file:

```ini
# Database (required)
DB_HOST=your-postgres-host.com
DB_PORT=5432
DB_NAME=fleetmind
DB_USER=your_db_user
DB_PASSWORD=your_db_password

# Google Maps API (required for geocoding)
GOOGLE_MAPS_API_KEY=your_google_maps_key
```

### 3. Test the Server

```bash
# Test server imports and database connectivity
python -c "import server; print('FleetMind MCP Server ready!')"
```

### 4. Run with Claude Desktop

Add to your Claude Desktop config (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "fleetmind": {
      "command": "python",
      "args": ["F:\\path\\to\\fleetmind-mcp\\server.py"],
      "env": {
        "GOOGLE_MAPS_API_KEY": "your_api_key",
        "DB_HOST": "your-host.com",
        "DB_NAME": "fleetmind",
        "DB_USER": "your_user",
        "DB_PASSWORD": "your_password"
      }
    }
  }
}
```

Restart Claude Desktop. You'll now see FleetMind tools available!

---

## Architecture

### **Before (Gradio UI):**
```
User β†’ Gradio Web UI β†’ ChatEngine β†’ Gemini/Claude API β†’ Tools β†’ Database
```

### **After (MCP Protocol):**
```
User β†’ Claude Desktop (or any MCP client) β†’ MCP Protocol β†’ FleetMind Server β†’ Tools β†’ Database
       β””β†’ Continue.dev β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β””β†’ Cline β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β””β†’ Custom Apps β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Benefits:**
- βœ… Use from multiple clients (Claude Desktop, VS Code, mobile apps)
- βœ… 46% less code (no UI, no provider abstractions)
- βœ… Industry-standard protocol (MCP)
- βœ… Better testing (isolated tools)
- βœ… Scalable architecture

---

## Features

### **18 AI Tools**

#### Order Management (10 tools)
- `geocode_address` - Convert addresses to GPS coordinates
- `calculate_route` - Find shortest route between locations
- `create_order` - Create new delivery orders
- `count_orders` - Count orders with filters
- `fetch_orders` - Retrieve orders with pagination
- `get_order_details` - Get complete order information
- `search_orders` - Search by customer/ID
- `get_incomplete_orders` - List active deliveries
- `update_order` - Update order details (auto-geocoding)
- `delete_order` - Permanently remove orders

#### Driver Management (8 tools)
- `create_driver` - Onboard new drivers
- `count_drivers` - Count drivers with filters
- `fetch_drivers` - Retrieve drivers with pagination
- `get_driver_details` - Get driver info + reverse-geocoded location
- `search_drivers` - Search by name/plate/ID
- `get_available_drivers` - List drivers ready for dispatch
- `update_driver` - Update driver information
- `delete_driver` - Remove drivers from fleet

### **2 Real-Time Resources**

- `orders://all` - Live orders dataset (last 30 days, max 1000)
- `drivers://all` - Live drivers dataset with locations

Resources provide AI assistants with contextual data for smarter responses.

---

## Usage Examples

### Example 1: Create an Order

**User (in Claude Desktop):**
"Create an urgent delivery order for Sarah Johnson at 456 Oak Ave, San Francisco CA. Phone: 555-1234."

**Claude automatically:**
1. Calls `geocode_address("456 Oak Ave, San Francisco CA")`
2. Gets coordinates: `(37.7749, -122.4194)`
3. Calls `create_order(customer_name="Sarah Johnson", delivery_address="456 Oak Ave, SF CA 94103", delivery_lat=37.7749, delivery_lng=-122.4194, customer_phone="555-1234", priority="urgent")`
4. Returns: `"Order ORD-20251114163800 created successfully!"`

### Example 2: Assign Driver

**User:**
"Assign order ORD-20251114163800 to the nearest available driver"

**Claude automatically:**
1. Calls `get_order_details("ORD-20251114163800")` β†’ Gets delivery location
2. Calls `get_available_drivers(limit=10)` β†’ Lists available drivers
3. Calls `calculate_route()` for each driver β†’ Finds nearest
4. Calls `update_order(order_id="ORD-20251114163800", assigned_driver_id="DRV-...", status="assigned")`
5. Returns: `"Order assigned to John Smith (DRV-20251110120000), 5.2 km away, ETA 12 mins"`

### Example 3: Track Orders

**User:**
"Show me all urgent orders that haven't been delivered yet"

**Claude automatically:**
1. Calls `fetch_orders(status="pending", priority="urgent")` OR
2. Calls `fetch_orders(status="in_transit", priority="urgent")`
3. Returns formatted list with customer names, addresses, and deadlines

---

## API Reference

### Tool: `create_order`

Create a new delivery order.

**Parameters:**
- `customer_name` (string, required): Full name
- `delivery_address` (string, required): Complete address
- `delivery_lat` (float, required): Latitude from geocoding
- `delivery_lng` (float, required): Longitude from geocoding
- `customer_phone` (string, optional): Phone number
- `customer_email` (string, optional): Email address
- `priority` (enum, optional): `standard` | `express` | `urgent` (default: `standard`)
- `weight_kg` (float, optional): Package weight (default: 5.0)
- `special_instructions` (string, optional): Delivery notes
- `time_window_end` (string, optional): Deadline in ISO format (default: +6 hours)

**Returns:**
```json
{
  "success": true,
  "order_id": "ORD-20251114163800",
  "status": "pending",
  "customer": "Sarah Johnson",
  "address": "456 Oak Ave, San Francisco CA 94103",
  "deadline": "2025-11-14T22:38:00",
  "priority": "urgent",
  "message": "Order created successfully!"
}
```

### Tool: `calculate_route`

Calculate shortest route between two locations.

**Parameters:**
- `origin` (string, required): Starting location (address or "lat,lng")
- `destination` (string, required): Ending location (address or "lat,lng")
- `mode` (enum, optional): `driving` | `walking` | `bicycling` | `transit` (default: `driving`)
- `alternatives` (boolean, optional): Return multiple routes (default: false)
- `include_steps` (boolean, optional): Include turn-by-turn directions (default: false)

**Returns:**
```json
{
  "success": true,
  "origin": "San Francisco City Hall, CA 94102, USA",
  "destination": "Oakland Airport, CA 94621, USA",
  "distance": {"meters": 25400, "text": "25.4 km"},
  "duration": {"seconds": 1680, "text": "28 mins"},
  "mode": "driving",
  "route_summary": "I-880 N",
  "confidence": "high (Google Maps API)"
}
```

### Resource: `orders://all`

Real-time orders dataset for AI context.

**Contains:** All orders from last 30 days (max 1000)

**Fields:** order_id, customer_name, delivery_address, status, priority, created_at, assigned_driver_id

**Usage:** AI automatically references this when answering questions like "How many pending orders?" or "What's the oldest unassigned order?"

### Resource: `drivers://all`

Real-time drivers dataset with current locations.

**Contains:** All drivers sorted alphabetically

**Fields:** driver_id, name, status, vehicle_type, vehicle_plate, current_lat, current_lng, last_location_update

**Usage:** AI automatically references this for questions like "How many active drivers?" or "Which driver is closest to downtown?"

---

## Database Schema

### `orders` table (26 columns)

```sql
CREATE TABLE orders (
    order_id VARCHAR(50) PRIMARY KEY,
    customer_name VARCHAR(255) NOT NULL,
    customer_phone VARCHAR(20),
    customer_email VARCHAR(255),
    delivery_address TEXT NOT NULL,
    delivery_lat DECIMAL(10,8),
    delivery_lng DECIMAL(11,8),
    status VARCHAR(20) CHECK (status IN ('pending','assigned','in_transit','delivered','failed','cancelled')),
    priority VARCHAR(20) CHECK (priority IN ('standard','express','urgent')),
    time_window_end TIMESTAMP,
    assigned_driver_id VARCHAR(50),
    payment_status VARCHAR(20) CHECK (payment_status IN ('pending','paid','cod')),
    weight_kg DECIMAL(10,2),
    special_instructions TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    -- ... additional fields
);
```

### `drivers` table (15 columns)

```sql
CREATE TABLE drivers (
    driver_id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    phone VARCHAR(20),
    email VARCHAR(255),
    status VARCHAR(20) CHECK (status IN ('active','busy','offline','unavailable')),
    vehicle_type VARCHAR(50),
    vehicle_plate VARCHAR(20),
    capacity_kg DECIMAL(10,2),
    skills JSONB,
    current_lat DECIMAL(10,8),
    current_lng DECIMAL(11,8),
    last_location_update TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

---

## Development

### Project Structure

```
fleetmind-mcp/
β”œβ”€β”€ server.py              # Main MCP server (882 lines)
β”œβ”€β”€ pyproject.toml         # Package configuration
β”œβ”€β”€ mcp_config.json        # MCP metadata
β”œβ”€β”€ requirements.txt       # Dependencies
β”œβ”€β”€ .env                   # Environment variables
β”‚
β”œβ”€β”€ chat/
β”‚   β”œβ”€β”€ tools.py          # 18 tool handlers (2099 lines)
β”‚   └── geocoding.py      # Geocoding service (429 lines)
β”‚
β”œβ”€β”€ database/
β”‚   β”œβ”€β”€ connection.py     # Database layer (221 lines)
β”‚   └── schema.py         # Schema definitions (213 lines)
β”‚
β”œβ”€β”€ logs/                 # Server logs
└── docs/                 # Documentation
```

### Running Tests

```bash
# Install test dependencies
pip install pytest pytest-asyncio

# Run tests
pytest tests/
```

### Testing with MCP Inspector

```bash
# Official MCP protocol testing tool
npx @modelcontextprotocol/inspector python server.py
```

---

## Deployment

### Option 1: Local Development

```bash
python server.py
```

### Option 2: Docker Container

```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "server.py"]
```

```bash
docker build -t fleetmind-mcp .
docker run -d --env-file .env fleetmind-mcp
```

### Option 3: Production Server

For production, use a process manager like `supervisord` or `systemd`:

```ini
# /etc/systemd/system/fleetmind-mcp.service
[Unit]
Description=FleetMind MCP Server
After=network.target

[Service]
Type=simple
User=fleetmind
WorkingDirectory=/opt/fleetmind-mcp
Environment="PATH=/opt/fleetmind-mcp/venv/bin"
EnvironmentFile=/opt/fleetmind-mcp/.env
ExecStart=/opt/fleetmind-mcp/venv/bin/python server.py
Restart=always

[Install]
WantedBy=multi-user.target
```

---

## Troubleshooting

### Error: "Cannot import name 'UserMessage'"

**Solution:** Prompts are currently disabled pending FastMCP API confirmation. Tools and resources work perfectly.

### Error: "Database connection failed"

**Check:**
1. `.env` file has correct credentials
2. PostgreSQL server is running
3. Database `fleetmind` exists
4. Network allows connection (check firewall/security groups)

### Error: "Geocoding failed"

**Check:**
1. `GOOGLE_MAPS_API_KEY` is set in `.env`
2. API key has Geocoding API enabled
3. API key has sufficient quota

**Fallback:** Server automatically uses mock geocoding if API unavailable.

---

## Migration from Gradio UI

### What Changed?

| Component | Gradio Version | MCP Version |
|-----------|----------------|-------------|
| UI | Gradio web interface | Any MCP client |
| AI Provider | Gemini/Claude via API | Client handles AI |
| Tool Execution | chat/tools.py handlers | Same handlers |
| Database | PostgreSQL/Neon | Same database |
| Geocoding | Google Maps API | Same API |

### What Stayed the Same?

- βœ… All 18 tool handlers (unchanged)
- βœ… Database schema (identical)
- βœ… Geocoding logic (same)
- βœ… Business logic (preserved)
- βœ… .env configuration (compatible)

### Migration Steps

1. **Backup your data:** `pg_dump fleetmind > backup.sql`
2. **Install MCP dependencies:** `pip install -r requirements.txt`
3. **Test server:** `python -c "import server"`
4. **Configure Claude Desktop:** Add server to `claude_desktop_config.json`
5. **Test with Claude:** Create a test order
6. **Archive old code:** Move `ui/`, `chat/providers/`, `chat/chat_engine.py` to `archive/`

---

## Contributing

We welcome contributions! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## License

MIT License - see [LICENSE](LICENSE) file for details.

---

## Support

- **Issues:** https://github.com/your-org/fleetmind-mcp/issues
- **Documentation:** https://docs.fleetmind.com
- **Discord:** https://discord.gg/fleetmind

---

## Roadmap

- [x] Convert all 18 tools to MCP format
- [x] Add 2 real-time resources (orders, drivers)
- [ ] Add prompt templates (pending FastMCP API confirmation)
- [ ] Add assignment optimization algorithm
- [ ] Add route optimization for multi-stop deliveries
- [ ] Add real-time driver tracking via WebSocket
- [ ] Add analytics dashboard
- [] Mobile app MCP client

---

**Built with ❀️ using [FastMCP](https://github.com/jlowin/fastmcp)**