v2rmp 0.4.5

rmpca — Route Optimization TUI & Agent Engine
Documentation
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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
//! rmpca-mcp-server — MCP server exposing the route optimization pipeline.
//!
//! Tools: extract_overture, extract_osm, compile, optimize,
//!        clean, vrp_solve, elevation_query, elevation_profile,
//!        list_solvers, haversine_distance,
//!        elevation_stats, dem_info, fuel_estimate, inspect_rmp,
//!        pipeline, get_valhalla_matrix
//!
//! Runs over stdio with JSON-RPC 2.0 framing (one line per message).
//!
//! Connect from any MCP client by adding to the client config:
//!
//! ```json
//! {
//!   "mcpServers": {
//!     "rmpca": {
//!       "command": "cargo",
//!       "args": ["run", "--bin", "rmpca-mcp-server", "--release"]
//!     }
//!   }
//! }
//! ```

use anyhow::Result;
use serde::Deserialize;
use serde_json::{json, Value};
use std::io::{BufRead, Write};
use std::path::Path;
use v2rmp::core::clean::{clean_geojson, CleanOptions};
use v2rmp::core::compile::{CompileRequest, CompileResult};
use v2rmp::core::elevation::local::LocalDem;
use v2rmp::core::extract::{BBoxRequest, ExtractRequest, ExtractResult, ExtractSource, RoadClass};
use v2rmp::core::optimize::{
    OnewayMode, OptimizeRequest, OptimizeResult, SolverMode, TurnPenalties,
};
use v2rmp::core::vrp::registry::solve_with;
use v2rmp::core::vrp::types::{
    VRPSolverInput, VRPSolverStop, VrpObjective,
};
use v2rmp::core::vrp::utils::{build_haversine_matrix, get_valhalla_matrix};
use v2rmp::core::elevation::{FuelCalculator};

// ── JSON-RPC / MCP types ───────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct Request {
    jsonrpc: String,
    method: String,
    #[serde(default)]
    params: Value,
    #[serde(default)]
    id: Value,
}

#[derive(Debug)]
struct ToolDef {
    name: &'static str,
    description: &'static str,
    input_schema: Value,
}

// ── Protocol helpers ────────────────────────────────────────────────────────

fn send(id: &Value, result: Value) {
    let out = json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": result
    });
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(stdout, "{out}");
    let _ = stdout.flush();
}

fn send_err(id: &Value, code: i64, msg: &str) {
    let out = json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": msg }
    });
    let mut stdout = std::io::stdout().lock();
    let _ = writeln!(stdout, "{out}");
    let _ = stdout.flush();
}

fn tool_success(id: &Value, result: &Result<Value>) {
    match result {
        Ok(val) => send(
            id,
            json!({
                "content": [{
                    "type": "text",
                    "text": serde_json::to_string_pretty(val).unwrap_or_default()
                }]
            }),
        ),
        Err(e) => send(
            id,
            json!({
                "content": [{
                    "type": "text",
                    "text": format!("Error: {e:#}")
                }],
                "isError": true
            }),
        ),
    }
}

// ── Tool definitions ────────────────────────────────────────────────────────

fn tool_definitions() -> Vec<ToolDef> {
    vec![
        ToolDef {
            name: "extract_overture",
            description: "Extract road network data from Overture Maps S3 Parquet files. \
                Downloads road segments within a bounding box and writes a GeoJSON file. \
                Can take significant time for large bounding boxes.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "bbox": {
                        "type": "object",
                        "description": "Bounding box: {min_lon, min_lat, max_lon, max_lat}",
                        "properties": {
                            "min_lon": { "type": "number" },
                            "min_lat": { "type": "number" },
                            "max_lon": { "type": "number" },
                            "max_lat": { "type": "number" }
                        },
                        "required": ["min_lon", "min_lat", "max_lon", "max_lat"]
                    },
                    "road_classes": {
                        "type": "array",
                        "description": "Road classes to include (e.g. ['residential','tertiary','secondary']). Default: all vehicle-accessible roads.",
                        "items": { "type": "string" }
                    },
                    "output_path": {
                        "type": "string",
                        "description": "Output GeoJSON file path (default: extract-output.geojson)",
                        "default": "extract-output.geojson"
                    }
                },
                "required": ["bbox"]
            }),
        },
        ToolDef {
            name: "extract_osm",
            description: "Extract road network data from OpenStreetMap. Uses a local PBF file \
                if available, otherwise falls back to the Overpass API. Writes a GeoJSON file.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "bbox": {
                        "type": "object",
                        "description": "Bounding box: {min_lon, min_lat, max_lon, max_lat}",
                        "properties": {
                            "min_lon": { "type": "number" },
                            "min_lat": { "type": "number" },
                            "max_lon": { "type": "number" },
                            "max_lat": { "type": "number" }
                        },
                        "required": ["min_lon", "min_lat", "max_lon", "max_lat"]
                    },
                    "road_classes": {
                        "type": "array",
                        "description": "Road classes to include. Default: all vehicle-accessible roads.",
                        "items": { "type": "string" }
                    },
                    "pbf_path": {
                        "type": "string",
                        "description": "Path to local OSM PBF file. If omitted, falls back to Overpass API."
                    },
                    "output_path": {
                        "type": "string",
                        "description": "Output GeoJSON file path (default: extract-output.geojson)",
                        "default": "extract-output.geojson"
                    }
                },
                "required": ["bbox"]
            }),
        },
        ToolDef {
            name: "compile",
            description: "Compile a GeoJSON road network file into the binary .rmp format. \
                Optionally runs a cleaning pipeline and prunes disconnected subgraphs.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Path to input GeoJSON file"
                    },
                    "output": {
                        "type": "string",
                        "description": "Path to output .rmp binary file"
                    },
                    "clean": {
                        "type": "boolean",
                        "description": "Run cleaning pipeline before compilation (default: false)",
                        "default": false
                    },
                    "prune_disconnected": {
                        "type": "boolean",
                        "description": "Prune disconnected subgraphs, keeping only the largest (default: false)",
                        "default": false
                    }
                },
                "required": ["input", "output"]
            }),
        },
        ToolDef {
            name: "optimize",
            description: "Run route optimization on a .rmp binary network file. \
                Supports CPP (Chinese Postman — edge coverage) and VRP (Vehicle Routing Problem) modes. \
                Outputs route statistics and optionally writes a GPX file.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Path to input .rmp binary network file"
                    },
                    "output": {
                        "type": "string",
                        "description": "Optional output GPX route file path"
                    },
                    "depot": {
                        "type": "object",
                        "description": "Depot coordinates {lat, lon}. Solver snaps to nearest node.",
                        "properties": {
                            "lat": { "type": "number" },
                            "lon": { "type": "number" }
                        }
                    },
                    "oneway_mode": {
                        "type": "string",
                        "enum": ["respect", "ignore", "reverse"],
                        "description": "How to handle one-way streets (default: respect)",
                        "default": "respect"
                    },
                    "mode": {
                        "type": "string",
                        "enum": ["cpp", "vrp"],
                        "description": "Solver: cpp for edge coverage, vrp for stop visits (default: cpp)",
                        "default": "cpp"
                    },
                    "left_penalty": {
                        "type": "number",
                        "description": "Left turn penalty (default: 1.0)",
                        "default": 1.0
                    },
                    "right_penalty": {
                        "type": "number",
                        "description": "Right turn penalty (default: 0.0)",
                        "default": 0.0
                    },
                    "uturn_penalty": {
                        "type": "number",
                        "description": "U-turn penalty (default: 5.0)",
                        "default": 5.0
                    },
                    "num_vehicles": {
                        "type": "integer",
                        "description": "Number of vehicles — VRP mode only (default: 1)",
                        "default": 1
                    },
                    "solver_id": {
                        "type": "string",
                        "description": "VRP solver algorithm: default, clarke_wright, sweep, two_opt, or_opt",
                        "default": "default"
                    }
                },
                "required": ["input"]
            }),
        },
        // ── New tools ──────────────────────────────────────────────────────────
        ToolDef {
            name: "clean",
            description: "Clean a GeoJSON road network with full control over all cleaning parameters. \
                Runs the 11-stage cleaning pipeline: repair → build graph → remove self-loops → \
                remove short edges → merge nearby nodes → deduplicate edges → remove edges missing attrs → \
                merge parallel edges → remove isolates → keep largest components → export. \
                Returns cleaned GeoJSON plus detailed statistics.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Path to input GeoJSON file"
                    },
                    "output": {
                        "type": "string",
                        "description": "Path to output cleaned GeoJSON file"
                    },
                    "make_valid": {
                        "type": "boolean",
                        "description": "Repair invalid geometries (default: true)"
                    },
                    "drop_invalid": {
                        "type": "boolean",
                        "description": "Drop features that cannot be repaired (default: true)"
                    },
                    "remove_selfloops": {
                        "type": "boolean",
                        "description": "Remove self-loop edges (default: true)"
                    },
                    "min_length_m": {
                        "type": "number",
                        "description": "Remove edges shorter than this in metres (default: 0.1)"
                    },
                    "node_snap_m": {
                        "type": "number",
                        "description": "Merge nodes within this distance in metres (default: 1.0)"
                    },
                    "node_precision_decimals": {
                        "type": "integer",
                        "description": "Decimal places for node ID generation (default: 6)"
                    },
                    "merge_node_positions": {
                        "type": "boolean",
                        "description": "Average coordinates when merging nodes (default: true)"
                    },
                    "dedupe_edges": {
                        "type": "boolean",
                        "description": "Remove duplicate edges (default: true)"
                    },
                    "remove_isolates": {
                        "type": "boolean",
                        "description": "Remove isolated nodes (default: true)"
                    },
                    "max_components": {
                        "type": "integer",
                        "description": "Keep only the N largest connected components (0 = keep all, default: 1)"
                    },
                    "required_attrs": {
                        "type": "array",
                        "description": "Remove edges missing any of these property names",
                        "items": { "type": "string" }
                    },
                    "merge_parallel_edges": {
                        "type": "boolean",
                        "description": "Merge parallel edges between same nodes (default: false)"
                    },
                    "merge_parallel_edge_properties": {
                        "type": "boolean",
                        "description": "When merging parallel edges, also merge their properties (default: false)"
                    },
                    "property_merge_strategy": {
                        "type": "string",
                        "enum": ["first", "merge"],
                        "description": "How to merge properties on parallel edges: 'first' keeps first edge's props, 'merge' combines them (default: first)"
                    },
                    "simplify_tolerance_m": {
                        "type": "number",
                        "description": "Douglas-Peucker simplification tolerance in metres (0 = no simplification, default: 0)"
                    },
                    "include_polygons": {
                        "type": "boolean",
                        "description": "Include polygon features in output (default: false)"
                    },
                    "include_points": {
                        "type": "boolean",
                        "description": "Include point features in output (default: false)"
                    }
                },
                "required": ["input", "output"]
            }),
        },
        ToolDef {
            name: "vrp_solve",
            description: "Solve a Vehicle Routing Problem (VRP) with explicit stop coordinates. \
                Unlike the 'optimize' tool (which operates on .rmp files), this tool takes an array \
                of stop coordinates, builds a haversine distance matrix, and dispatches to the chosen \
                solver algorithm. Returns per-vehicle routes with stop assignments and statistics.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "stops": {
                        "type": "array",
                        "description": "Array of stops. The first stop is the depot.",
                        "items": {
                            "type": "object",
                            "properties": {
                                "lat": { "type": "number", "description": "Latitude" },
                                "lon": { "type": "number", "description": "Longitude" },
                                "label": { "type": "string", "description": "Label for this stop (optional)" },
                                "demand": { "type": "number", "description": "Demand at this stop (default: 1.0)" }
                            },
                            "required": ["lat", "lon"]
                        }
                    },
                    "num_vehicles": {
                        "type": "integer",
                        "description": "Number of vehicles (default: 1)"
                    },
                    "vehicle_capacity": {
                        "type": "number",
                        "description": "Vehicle capacity (default: 100.0)"
                    },
                    "solver_id": {
                        "type": "string",
                        "description": "VRP solver algorithm: default, clarke_wright, sweep, two_opt, or_opt",
                        "default": "default"
                    },
                    "avg_speed_kmh": {
                        "type": "number",
                        "description": "Average speed in km/h for time estimation (default: 40.0)"
                    },
                    "objective": {
                        "type": "string",
                        "enum": ["min_distance", "min_time", "balance_load", "min_vehicles"],
                        "description": "Optimization objective (default: min_distance)"
                    }
                },
                "required": ["stops"]
            }),
        },
        ToolDef {
            name: "elevation_query",
            description: "Query elevation at one or more lat/lon points from a local DEM GeoTIFF file. \
                Uses bilinear interpolation with nearest-neighbor fallback for nodata pixels. \
                Returns an array of elevations (or null for points outside coverage).",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "dem_path": {
                        "type": "string",
                        "description": "Path to the DEM GeoTIFF file"
                    },
                    "points": {
                        "type": "array",
                        "description": "Array of {lon, lat} points to query",
                        "items": {
                            "type": "object",
                            "properties": {
                                "lon": { "type": "number" },
                                "lat": { "type": "number" }
                            },
                            "required": ["lon", "lat"]
                        }
                    }
                },
                "required": ["dem_path", "points"]
            }),
        },
        ToolDef {
            name: "elevation_profile",
            description: "Sample elevation along a route at fixed intervals from a local DEM GeoTIFF file. \
                Returns per-sample points with distance and elevation, plus total ascent, descent, \
                min/max/avg elevation, and total distance.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "dem_path": {
                        "type": "string",
                        "description": "Path to the DEM GeoTIFF file"
                    },
                    "route": {
                        "type": "array",
                        "description": "Ordered array of {lon, lat} waypoints forming the route",
                        "items": {
                            "type": "object",
                            "properties": {
                                "lon": { "type": "number" },
                                "lat": { "type": "number" }
                            },
                            "required": ["lon", "lat"]
                        }
                    },
                    "sample_interval_m": {
                        "type": "number",
                        "description": "Distance between elevation samples in metres (default: 100.0)"
                    }
                },
                "required": ["dem_path", "route"]
            }),
        },
        ToolDef {
            name: "list_solvers",
            description: "List available VRP solvers and their labels.",
            input_schema: json!({
                "type": "object",
                "properties": {}
            }),
        },
        // ── Medium-priority tools ──────────────────────────────────────────
        ToolDef {
            name: "elevation_stats",
            description: "Compute elevation statistics (min, max, avg, coverage %) within a bounding box \
                from a DEM GeoTIFF file. Samples on a grid with configurable step size.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "dem_path": {
                        "type": "string",
                        "description": "Path to the DEM GeoTIFF file"
                    },
                    "bbox": {
                        "type": "object",
                        "description": "Bounding box: {min_lon, min_lat, max_lon, max_lat}",
                        "properties": {
                            "min_lon": { "type": "number" },
                            "min_lat": { "type": "number" },
                            "max_lon": { "type": "number" },
                            "max_lat": { "type": "number" }
                        },
                        "required": ["min_lon", "min_lat", "max_lon", "max_lat"]
                    },
                    "grid_step": {
                        "type": "integer",
                        "description": "Pixel skip for sampling (1 = every pixel, 10 = every 10th). Default: 1",
                        "default": 1
                    }
                },
                "required": ["dem_path", "bbox"]
            }),
        },
        ToolDef {
            name: "dem_info",
            description: "Return metadata about a DEM GeoTIFF file: width, height, bounding box, \
                nodata value, and pixel size in degrees.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "dem_path": {
                        "type": "string",
                        "description": "Path to the DEM GeoTIFF file"
                    }
                },
                "required": ["dem_path"]
            }),
        },
        ToolDef {
            name: "fuel_estimate",
            description: "Calculate fuel consumption from an elevation profile. Takes an array of \
                {distance_m, elevation_m} samples (the same shape returned by 'elevation_profile') \
                and a base consumption rate (L/km). Null/missing elevation values are skipped. \
                Applies grade-based adjustments: +15% per 1% uphill grade, -5% per 1% downhill grade (capped at -20%).",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "samples": {
                        "type": "array",
                        "description": "Array of {distance_m, elevation_m} points. elevation_m may be null (nodata pixels are skipped).",
                        "items": {
                            "type": "object",
                            "properties": {
                                "distance_m": { "type": "number", "description": "Cumulative distance in metres" },
                                "elevation_m": { "type": "number", "description": "Elevation in metres (null for nodata)" }
                            },
                            "required": ["distance_m"]
                        }
                    },
                    "base_consumption": {
                        "type": "number",
                        "description": "Base fuel consumption in L/km on flat terrain (default: 0.08, ~8L/100km)",
                        "default": 0.08
                    }
                },
                "required": ["samples"]
            }),
        },
        ToolDef {
            name: "inspect_rmp",
            description: "Parse a .rmp binary network file and return node count, edge count, and \
                bounding box without running optimization. Useful for validating files and inspecting \
                network geometry.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "Path to the .rmp binary file"
                    }
                },
                "required": ["input"]
            }),
        },
        ToolDef {
            name: "pipeline",
            description: "End-to-end route optimization pipeline: extract road network → clean → \
                compile to .rmp binary → optimize. Runs all four stages in sequence and returns \
                combined statistics. Intermediate files (extract.geojson, cleaned.geojson, network.rmp, \
                route.gpx) are written to the output_dir. Can take significant time for large bounding boxes.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "bbox": {
                        "type": "object",
                        "description": "Bounding box: {min_lon, min_lat, max_lon, max_lat}",
                        "properties": {
                            "min_lon": { "type": "number" },
                            "min_lat": { "type": "number" },
                            "max_lon": { "type": "number" },
                            "max_lat": { "type": "number" }
                        },
                        "required": ["min_lon", "min_lat", "max_lon", "max_lat"]
                    },
                    "output_dir": {
                        "type": "string",
                        "description": "Directory for intermediate and output files (default: ./pipeline-output)",
                        "default": "./pipeline-output"
                    },
                    "source": {
                        "type": "string",
                        "enum": ["overture", "osm"],
                        "description": "Data source for extraction (default: overture)"
                    },
                    "pbf_path": {
                        "type": "string",
                        "description": "Path to local OSM PBF file (OSM source only)"
                    },
                    "depot": {
                        "type": "object",
                        "description": "Depot coordinates {lat, lon}",
                        "properties": {
                            "lat": { "type": "number" },
                            "lon": { "type": "number" }
                        }
                    },
                    "mode": {
                        "type": "string",
                        "enum": ["cpp", "vrp"],
                        "description": "Solver mode: cpp for edge coverage, vrp for stop visits (default: cpp)"
                    },
                    "prune_disconnected": {
                        "type": "boolean",
                        "description": "Prune disconnected subgraphs during compilation (default: false)"
                    }
                },
                "required": ["bbox"]
            }),
        },
        ToolDef {
            name: "haversine_distance",
            description: "Calculate the great-circle distance between two WGS-84 lat/lon points \
                using the haversine formula. Returns distance in metres and kilometres.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "from": {
                        "type": "object",
                        "description": "Origin point",
                        "properties": {
                            "lat": { "type": "number", "description": "Latitude in degrees" },
                            "lon": { "type": "number", "description": "Longitude in degrees" }
                        },
                        "required": ["lat", "lon"]
                    },
                    "to": {
                        "type": "object",
                        "description": "Destination point",
                        "properties": {
                            "lat": { "type": "number", "description": "Latitude in degrees" },
                            "lon": { "type": "number", "description": "Longitude in degrees" }
                        },
                        "required": ["lat", "lon"]
                    }
                },
                "required": ["from", "to"]
            }),
        },
        ToolDef {
            name: "get_valhalla_matrix",
            description: "Fetch a real-road distance/time matrix from the public Valhalla/OSRM API. \
                Takes an array of stop coordinates and returns an NxN matrix with distance (km) and \
                time (seconds) for each pair. Requires internet connectivity.",
            input_schema: json!({
                "type": "object",
                "properties": {
                    "locations": {
                        "type": "array",
                        "description": "Array of {lat, lon} coordinates",
                        "items": {
                            "type": "object",
                            "properties": {
                                "lat": { "type": "number" },
                                "lon": { "type": "number" }
                            },
                            "required": ["lat", "lon"]
                        }
                    }
                },
                "required": ["locations"]
            }),
        },
    ]
}

// ── Argument parsing helpers ────────────────────────────────────────────────

fn parse_bbox(args: &Value) -> anyhow::Result<BBoxRequest> {
    let bbox = args
        .get("bbox")
        .ok_or_else(|| anyhow::anyhow!("Missing 'bbox' parameter"))?;
    Ok(BBoxRequest {
        min_lon: bbox
            .get("min_lon")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.min_lon required"))?,
        min_lat: bbox
            .get("min_lat")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.min_lat required"))?,
        max_lon: bbox
            .get("max_lon")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.max_lon required"))?,
        max_lat: bbox
            .get("max_lat")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.max_lat required"))?,
    })
}

fn parse_road_classes(args: &Value) -> Vec<RoadClass> {
    let Some(arr) = args.get("road_classes").and_then(|v| v.as_array()) else {
        return RoadClass::all_vehicle();
    };
    if arr.is_empty() {
        return RoadClass::all_vehicle();
    }
    arr.iter()
        .filter_map(|v| v.as_str())
        .filter_map(|s| match s {
            "residential" => Some(RoadClass::Residential),
            "tertiary" => Some(RoadClass::Tertiary),
            "secondary" => Some(RoadClass::Secondary),
            "primary" => Some(RoadClass::Primary),
            "trunk" => Some(RoadClass::Trunk),
            "motorway" => Some(RoadClass::Motorway),
            "unclassified" => Some(RoadClass::Unclassified),
            "living_street" => Some(RoadClass::LivingStreet),
            "service" => Some(RoadClass::Service),
            "secondary_link" => Some(RoadClass::SecondaryLink),
            "primary_link" => Some(RoadClass::PrimaryLink),
            "trunk_link" => Some(RoadClass::TrunkLink),
            "motorway_link" => Some(RoadClass::MotorwayLink),
            _ => None,
        })
        .collect()
}

fn parse_oneway_mode(args: &Value) -> OnewayMode {
    match args
        .get("oneway_mode")
        .and_then(|v| v.as_str())
        .unwrap_or("respect")
    {
        "ignore" => OnewayMode::Ignore,
        "reverse" => OnewayMode::Reverse,
        _ => OnewayMode::Respect,
    }
}

fn parse_solver_mode(args: &Value) -> SolverMode {
    match args
        .get("mode")
        .and_then(|v| v.as_str())
        .unwrap_or("cpp")
    {
        "vrp" => SolverMode::Vrp,
        _ => SolverMode::Cpp,
    }
}

// ── Tool handlers ───────────────────────────────────────────────────────────

async fn handle_extract_overture(args: &Value) -> Result<Value> {
    let bbox = parse_bbox(args)?;
    let road_classes = parse_road_classes(args);
    let output_path = args
        .get("output_path")
        .and_then(|v| v.as_str())
        .unwrap_or("extract-output.geojson")
        .to_string();

    tracing::info!("extract_overture: bbox={:.4},{:.4},{:.4},{:.4}",
        bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat);

    let req = ExtractRequest {
        source: ExtractSource::Overture,
        bbox,
        road_classes,
        output_path,
        pbf_path: None,
    };

    let result: ExtractResult = v2rmp::core::extract::run_extract(&req).await?;
    Ok(serde_json::to_value(result)?)
}

async fn handle_extract_osm(args: &Value) -> Result<Value> {
    let bbox = parse_bbox(args)?;
    let road_classes = parse_road_classes(args);
    let pbf_path = args.get("pbf_path").and_then(|v| v.as_str()).map(String::from);
    let output_path = args
        .get("output_path")
        .and_then(|v| v.as_str())
        .unwrap_or("extract-output.geojson")
        .to_string();

    tracing::info!("extract_osm: bbox={:.4},{:.4},{:.4},{:.4}",
        bbox.min_lon, bbox.min_lat, bbox.max_lon, bbox.max_lat);

    let req = ExtractRequest {
        source: ExtractSource::Osm,
        bbox,
        road_classes,
        output_path,
        pbf_path,
    };

    let result: ExtractResult = v2rmp::core::extract::run_extract(&req).await?;
    Ok(serde_json::to_value(result)?)
}

fn handle_compile(args: &Value) -> Result<Value> {
    let input = args
        .get("input")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'input' parameter"))?
        .to_string();
    let output = args
        .get("output")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'output' parameter"))?
        .to_string();
    let clean = args
        .get("clean")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let prune = args
        .get("prune_disconnected")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    let clean_options = if clean {
        Some(v2rmp::core::clean::CleanOptions::default())
    } else {
        None
    };

    tracing::info!("compile: {} -> {}", input, output);

    let req = CompileRequest {
        input_geojson: input,
        output_rmp: output,
        compress: false,
        road_classes: vec![],
        clean_options,
        prune_disconnected: prune,
    };

    let result: CompileResult = v2rmp::core::compile::run_compile(&req)?;
    Ok(serde_json::to_value(result)?)
}

async fn handle_optimize(args: &Value) -> Result<Value> {
    let input = args
        .get("input")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'input' parameter"))?
        .to_string();
    let route_file = args.get("output").and_then(|v| v.as_str()).map(String::from);
    let depot = args
        .get("depot")
        .and_then(|d| {
            let lat = d.get("lat")?.as_f64()?;
            let lon = d.get("lon")?.as_f64()?;
            Some((lat, lon))
        });
    let oneway_mode = parse_oneway_mode(args);
    let mode = parse_solver_mode(args);
    let left = args
        .get("left_penalty")
        .and_then(|v| v.as_f64())
        .unwrap_or(1.0);
    let right = args
        .get("right_penalty")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.0);
    let u_turn = args
        .get("uturn_penalty")
        .and_then(|v| v.as_f64())
        .unwrap_or(5.0);
    let num_vehicles = args
        .get("num_vehicles")
        .and_then(|v| v.as_u64())
        .unwrap_or(1) as usize;
    let solver_id = args
        .get("solver_id")
        .and_then(|v| v.as_str())
        .unwrap_or("default")
        .to_string();

    tracing::info!("optimize: input={}", input);

    let req = OptimizeRequest {
        cache_file: input,
        route_file,
        turn_penalties: TurnPenalties {
            left,
            right,
            u_turn,
        },
        depot,
        oneway_mode,
        mode,
        num_vehicles,
        solver_id,
    };

    let result: OptimizeResult = v2rmp::core::optimize::run_optimize(&req).await?;
    Ok(serde_json::to_value(result)?)
}

// ── Clean handler ─────────────────────────────────────────────────────────

fn handle_clean(args: &Value) -> Result<Value> {
    let input = args
        .get("input")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'input' parameter"))?
        .to_string();
    let output = args
        .get("output")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'output' parameter"))?
        .to_string();

    // Build CleanOptions from args, using defaults where not specified
    let defaults = CleanOptions::default();
    let options = CleanOptions {
        make_valid: args.get("make_valid").and_then(|v| v.as_bool()).unwrap_or(defaults.make_valid),
        drop_invalid: args.get("drop_invalid").and_then(|v| v.as_bool()).unwrap_or(defaults.drop_invalid),
        remove_selfloops: args.get("remove_selfloops").and_then(|v| v.as_bool()).unwrap_or(defaults.remove_selfloops),
        min_length_m: args.get("min_length_m").and_then(|v| v.as_f64()).unwrap_or(defaults.min_length_m),
        node_snap_m: args.get("node_snap_m").and_then(|v| v.as_f64()).unwrap_or(defaults.node_snap_m),
        node_precision_decimals: args.get("node_precision_decimals").and_then(|v| v.as_u64()).map(|v| v as u32).unwrap_or(defaults.node_precision_decimals),
        merge_node_positions: args.get("merge_node_positions").and_then(|v| v.as_bool()).unwrap_or(defaults.merge_node_positions),
        dedupe_edges: args.get("dedupe_edges").and_then(|v| v.as_bool()).unwrap_or(defaults.dedupe_edges),
        remove_isolates: args.get("remove_isolates").and_then(|v| v.as_bool()).unwrap_or(defaults.remove_isolates),
        max_components: args.get("max_components").and_then(|v| v.as_u64()).map(|v| v as usize).unwrap_or(defaults.max_components),
        required_attrs: args.get("required_attrs").and_then(|v| v.as_array()).map(|arr| {
            arr.iter().filter_map(|v| v.as_str().map(String::from)).collect()
        }),
        merge_parallel_edges: args.get("merge_parallel_edges").and_then(|v| v.as_bool()).unwrap_or(defaults.merge_parallel_edges),
        merge_parallel_edge_properties: args.get("merge_parallel_edge_properties").and_then(|v| v.as_bool()).unwrap_or(defaults.merge_parallel_edge_properties),
        property_merge_strategy: args.get("property_merge_strategy").and_then(|v| v.as_str()).map(String::from).unwrap_or(defaults.property_merge_strategy),
        simplify_tolerance_m: args.get("simplify_tolerance_m").and_then(|v| v.as_f64()).unwrap_or(defaults.simplify_tolerance_m),
        include_polygons: args.get("include_polygons").and_then(|v| v.as_bool()).unwrap_or(defaults.include_polygons),
        include_points: args.get("include_points").and_then(|v| v.as_bool()).unwrap_or(defaults.include_points),
    };

    tracing::info!("clean: {} -> {} (min_length={}, node_snap={}, max_components={})",
        input, output, options.min_length_m, options.node_snap_m, options.max_components);

    // Read input GeoJSON
    let input_str = std::fs::read_to_string(&input)
        .map_err(|e| anyhow::anyhow!("Failed to read input file '{}': {}", input, e))?;
    let geojson: geojson::FeatureCollection = serde_json::from_str(&input_str)
        .map_err(|e| anyhow::anyhow!("Failed to parse GeoJSON: {}", e))?;

    // Run clean pipeline
    let (cleaned, stats, warnings) = clean_geojson(&geojson, &options)
        .map_err(|e| anyhow::anyhow!("Clean pipeline failed: {}", e))?;

    // Write output
    let output_str = serde_json::to_string_pretty(&cleaned)
        .map_err(|e| anyhow::anyhow!("Failed to serialize output: {}", e))?;
    std::fs::write(&output, &output_str)
        .map_err(|e| anyhow::anyhow!("Failed to write output file '{}': {}", output, e))?;

    Ok(json!({
        "output_file": output,
        "input_features": stats.input_features,
        "output_features": stats.output_features,
        "invalid_dropped": stats.invalid_dropped,
        "selfloops_removed": stats.selfloops_removed,
        "short_edges_removed": stats.short_edges_removed,
        "nodes_merged": stats.nodes_merged,
        "duplicate_edges_removed": stats.duplicate_edges_removed,
        "incomplete_edges_removed": stats.incomplete_edges_removed,
        "parallel_edges_merged": stats.parallel_edges_merged,
        "isolates_removed": stats.isolates_removed,
        "components_removed": stats.components_removed,
        "total_removed": stats.total_removed(),
        "warnings": warnings,
    }))
}

// ── VRP Solve handler ────────────────────────────────────────────────────

async fn handle_vrp_solve(args: &Value) -> Result<Value> {
    let stops_val = args
        .get("stops")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'stops' parameter"))?;

    if stops_val.is_empty() {
        anyhow::bail!("At least one stop (the depot) is required");
    }

    let stops: Vec<VRPSolverStop> = stops_val
        .iter()
        .enumerate()
        .map(|(i, s)| {
            let lat = s.get("lat").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Stop {} missing 'lat'", i))?;
            let lon = s.get("lon").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Stop {} missing 'lon'", i))?;
            let label = s.get("label").and_then(|v| v.as_str())
                .unwrap_or_else(|| "")
                .to_string();
            let demand = s.get("demand").and_then(|v| v.as_f64());
            Ok(VRPSolverStop {
                lat,
                lon,
                label: if label.is_empty() { format!("Stop {}", i) } else { label },
                demand,
                arrival_time: None,
            })
        })
        .collect::<Result<Vec<_>>>()?;

    let num_vehicles = args.get("num_vehicles").and_then(|v| v.as_u64()).unwrap_or(1) as usize;
    let vehicle_capacity = args.get("vehicle_capacity").and_then(|v| v.as_f64()).unwrap_or(100.0);
    let solver_id = args.get("solver_id").and_then(|v| v.as_str()).unwrap_or("default").to_string();
    let avg_speed_kmh = args.get("avg_speed_kmh").and_then(|v| v.as_f64()).unwrap_or(40.0);
    let objective = match args.get("objective").and_then(|v| v.as_str()).unwrap_or("min_distance") {
        "min_time" => VrpObjective::MinTime,
        "balance_load" => VrpObjective::BalanceLoad,
        "min_vehicles" => VrpObjective::MinVehicles,
        _ => VrpObjective::MinDistance,
    };

    // Build haversine distance matrix
    let matrix = build_haversine_matrix(&stops, avg_speed_kmh);

    let input = VRPSolverInput {
        locations: stops,
        num_vehicles,
        vehicle_capacity,
        objective,
        matrix: Some(matrix),
        service_time_secs: None,
        use_time_windows: false,
        window_open: None,
        window_close: None,
    };

    tracing::info!("vrp_solve: {} stops, {} vehicles, solver={}", 
        input.locations.len(), num_vehicles, solver_id);

    let output = solve_with(&solver_id, &input).await
        .map_err(|e| anyhow::anyhow!("VRP solver failed: {}", e))?;

    // Convert routes to JSON
    let routes_json: Vec<Value> = output.routes.iter().flatten().enumerate().map(|(vi, route)| {
        let stops_json: Vec<Value> = route.iter().map(|s| {
            json!({
                "lat": s.lat,
                "lon": s.lon,
                "label": s.label,
                "demand": s.demand,
            })
        }).collect();
        json!({
            "vehicle": vi,
            "stops": stops_json,
        })
    }).collect();

    Ok(json!({
        "total_distance_km": output.total_distance_km,
        "total_time_min": output.total_time_min,
        "routes": routes_json,
        "unassigned": output.unassigned,
    }))
}

// ── Elevation Query handler ──────────────────────────────────────────────

fn handle_elevation_query(args: &Value) -> Result<Value> {
    let dem_path = args
        .get("dem_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'dem_path' parameter"))?;
    let points_val = args
        .get("points")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'points' parameter"))?;

    let dem = LocalDem::open(Path::new(dem_path))
        .map_err(|e| anyhow::anyhow!("Failed to open DEM file '{}': {}", dem_path, e))?;

    let points: Vec<(f64, f64)> = points_val
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let lon = p.get("lon").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Point {} missing 'lon'", i))?;
            let lat = p.get("lat").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Point {} missing 'lat'", i))?;
            Ok((lon, lat))
        })
        .collect::<Result<Vec<_>>>()?;

    let elevations = dem.get_elevations(&points)
        .map_err(|e| anyhow::anyhow!("Elevation query failed: {}", e))?;

    let results: Vec<Value> = points.iter().zip(elevations.iter()).enumerate().map(|(i, ((lon, lat), elev))| {
        json!({
            "index": i,
            "lon": *lon,
            "lat": *lat,
            "elevation_m": elev,
        })
    }).collect();

    Ok(json!({
        "dem_path": dem_path,
        "results": results,
    }))
}

// ── Elevation Profile handler ───────────────────────────────────────────

fn handle_elevation_profile(args: &Value) -> Result<Value> {
    let dem_path = args
        .get("dem_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'dem_path' parameter"))?;
    let route_val = args
        .get("route")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'route' parameter"))?;
    let sample_interval_m = args.get("sample_interval_m").and_then(|v| v.as_f64()).unwrap_or(100.0);

    let dem = LocalDem::open(Path::new(dem_path))
        .map_err(|e| anyhow::anyhow!("Failed to open DEM file '{}': {}", dem_path, e))?;

    let route: Vec<(f64, f64)> = route_val
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let lon = p.get("lon").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Route point {} missing 'lon'", i))?;
            let lat = p.get("lat").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Route point {} missing 'lat'", i))?;
            Ok((lon, lat))
        })
        .collect::<Result<Vec<_>>>()?;

    if route.len() < 2 {
        anyhow::bail!("Route must have at least 2 waypoints");
    }

    let profile = dem.route_profile(&route, sample_interval_m)
        .map_err(|e| anyhow::anyhow!("Elevation profile failed: {}", e))?;

    let points_json: Vec<Value> = profile.points.iter().map(|p| {
        json!({
            "distance_m": p.distance_m,
            "elevation_m": p.elevation_m,
            "lon": p.point.lon,
            "lat": p.point.lat,
        })
    }).collect();

    Ok(json!({
        "total_ascent_m": profile.total_ascent,
        "total_descent_m": profile.total_descent,
        "max_elevation_m": profile.max_elevation,
        "min_elevation_m": profile.min_elevation,
        "avg_elevation_m": profile.avg_elevation,
        "distance_km": profile.distance_km,
        "sample_interval_m": sample_interval_m,
        "num_samples": profile.points.len(),
        "points": points_json,
    }))
}

// ── List Solvers handler ───────────────────────────────────────────────────

fn handle_list_solvers(_args: &Value) -> Result<Value> {
    let options = v2rmp::core::vrp::registry::get_algorithm_options();
    let results: Vec<Value> = options.into_iter().map(|(id, label)| {
        json!({
            "id": id,
            "label": label
        })
    }).collect();

    Ok(json!({
        "solvers": results
    }))
}

// ── Haversine Distance handler ────────────────────────────────────────────

fn handle_haversine_distance(args: &Value) -> Result<Value> {
    let from = args
        .get("from")
        .ok_or_else(|| anyhow::anyhow!("Missing 'from' parameter"))?;
    let to = args
        .get("to")
        .ok_or_else(|| anyhow::anyhow!("Missing 'to' parameter"))?;

    let lat1 = from.get("lat").and_then(|v| v.as_f64())
        .ok_or_else(|| anyhow::anyhow!("from.lat required"))?;
    let lon1 = from.get("lon").and_then(|v| v.as_f64())
        .ok_or_else(|| anyhow::anyhow!("from.lon required"))?;
    let lat2 = to.get("lat").and_then(|v| v.as_f64())
        .ok_or_else(|| anyhow::anyhow!("to.lat required"))?;
    let lon2 = to.get("lon").and_then(|v| v.as_f64())
        .ok_or_else(|| anyhow::anyhow!("to.lon required"))?;

    let dist_m = v2rmp::core::haversine_m(lat1, lon1, lat2, lon2);

    Ok(json!({
        "from": { "lat": lat1, "lon": lon1 },
        "to":   { "lat": lat2, "lon": lon2 },
        "distance_m": dist_m,
        "distance_km": dist_m / 1000.0,
    }))
}

// ── Elevation Stats handler ──────────────────────────────────────────────

fn handle_elevation_stats(args: &Value) -> Result<Value> {
    let dem_path = args
        .get("dem_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'dem_path' parameter"))?;

    let bbox_val = args
        .get("bbox")
        .ok_or_else(|| anyhow::anyhow!("Missing 'bbox' parameter"))?;
    let bbox = v2rmp::core::geo_types::BBox {
        min_lon: bbox_val.get("min_lon").and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.min_lon required"))?,
        min_lat: bbox_val.get("min_lat").and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.min_lat required"))?,
        max_lon: bbox_val.get("max_lon").and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.max_lon required"))?,
        max_lat: bbox_val.get("max_lat").and_then(|v| v.as_f64())
            .ok_or_else(|| anyhow::anyhow!("bbox.max_lat required"))?,
    };

    let grid_step = args.get("grid_step").and_then(|v| v.as_u64()).unwrap_or(1) as usize;

    let dem = LocalDem::open(Path::new(dem_path))
        .map_err(|e| anyhow::anyhow!("Failed to open DEM file '{}': {}", dem_path, e))?;

    let stats = dem.bbox_stats(bbox, grid_step)
        .map_err(|e| anyhow::anyhow!("Elevation stats failed: {}", e))?;

    Ok(json!({
        "min_elevation_m": stats.min_elevation,
        "max_elevation_m": stats.max_elevation,
        "avg_elevation_m": stats.avg_elevation,
        "coverage_percent": stats.coverage_percent,
        "pixel_count": stats.pixel_count,
    }))
}

// ── DEM Info handler ─────────────────────────────────────────────────────

fn handle_dem_info(args: &Value) -> Result<Value> {
    let dem_path = args
        .get("dem_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'dem_path' parameter"))?;

    let dem = LocalDem::open(Path::new(dem_path))
        .map_err(|e| anyhow::anyhow!("Failed to open DEM file '{}': {}", dem_path, e))?;

    let info = dem.info();

    Ok(json!({
        "width": info.width,
        "height": info.height,
        "bbox": {
            "min_lon": info.bbox.min_lon,
            "min_lat": info.bbox.min_lat,
            "max_lon": info.bbox.max_lon,
            "max_lat": info.bbox.max_lat,
        },
        "nodata": info.nodata,
        "pixel_size_x": info.pixel_size_x,
        "pixel_size_y": info.pixel_size_y,
    }))
}

// ── Fuel Estimate handler ────────────────────────────────────────────────

fn handle_fuel_estimate(args: &Value) -> Result<Value> {
    let samples_val = args
        .get("samples")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'samples' parameter"))?;

    if samples_val.len() < 2 {
        anyhow::bail!("At least 2 samples are required for fuel estimation");
    }

    let base_consumption = args
        .get("base_consumption")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.08);

    // Build an ElevationProfile from the samples
    let points: Vec<v2rmp::core::elevation::RouteElevationPoint> = samples_val
        .iter()
        .enumerate()
        .map(|(i, s)| {
            let distance_m = s.get("distance_m").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Sample {} missing 'distance_m'", i))?;
            let elevation_m = s.get("elevation_m").and_then(|v| v.as_f64());
            Ok(v2rmp::core::elevation::RouteElevationPoint {
                distance_m,
                elevation_m,
                point: v2rmp::core::elevation::Point { lon: 0.0, lat: 0.0 },
            })
        })
        .collect::<Result<Vec<_>>>()?;

    let total_distance_km = points.last().map(|p| p.distance_m / 1000.0).unwrap_or(0.0);

    let profile = v2rmp::core::elevation::ElevationProfile {
        points,
        total_ascent: 0.0, // Not needed for fuel calc
        total_descent: 0.0,
        max_elevation: 0.0,
        min_elevation: 0.0,
        avg_elevation: 0.0,
        distance_km: total_distance_km,
    };

    let consumption = FuelCalculator::calculate(&profile, base_consumption);

    Ok(json!({
        "total_fuel_l": consumption.total_fuel_l,
        "avg_consumption_l_per_km": consumption.avg_consumption_l_per_km,
        "elevation_penalty_l": consumption.elevation_penalty_l,
        "elevation_benefit_l": consumption.elevation_benefit_l,
        "base_consumption_l_per_km": base_consumption,
        "distance_km": total_distance_km,
    }))
}

// ── Inspect RMP handler ──────────────────────────────────────────────────

fn handle_inspect_rmp(args: &Value) -> Result<Value> {
    let input = args
        .get("input")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing 'input' parameter"))?;

    let file_data = std::fs::read(input)
        .map_err(|e| anyhow::anyhow!("Failed to read .rmp file: {}", e))?;

    let (nodes, edges) = v2rmp::core::optimize::read_rmp_file(&file_data)?;

    // Compute bounding box from nodes
    let (min_lat, max_lat, min_lon, max_lon) = if nodes.is_empty() {
        (0.0, 0.0, 0.0, 0.0)
    } else {
        nodes.iter().fold(
            (f64::MAX, f64::MIN, f64::MAX, f64::MIN),
            |(mn_lat, mx_lat, mn_lon, mx_lon), n| {
                (mn_lat.min(n.lat), mx_lat.max(n.lat), mn_lon.min(n.lon), mx_lon.max(n.lon))
            },
        )
    };

    let total_edge_length_km: f64 = edges.iter().map(|e| e.weight_m / 1000.0).sum();

    Ok(json!({
        "node_count": nodes.len(),
        "edge_count": edges.len(),
        "bbox": {
            "min_lon": min_lon,
            "min_lat": min_lat,
            "max_lon": max_lon,
            "max_lat": max_lat,
        },
        "total_edge_length_km": total_edge_length_km,
        "file_size_bytes": file_data.len(),
    }))
}

// ── Pipeline handler ─────────────────────────────────────────────────────

async fn handle_pipeline(args: &Value) -> Result<Value> {
    let bbox = parse_bbox(args)?;
    let output_dir = args
        .get("output_dir")
        .and_then(|v| v.as_str())
        .unwrap_or("./pipeline-output")
        .to_string();
    let source = match args.get("source").and_then(|v| v.as_str()).unwrap_or("overture") {
        "osm" => ExtractSource::Osm,
        _ => ExtractSource::Overture,
    };
    let pbf_path = args.get("pbf_path").and_then(|v| v.as_str()).map(String::from);
    let depot = args.get("depot").and_then(|d| {
        let lat = d.get("lat")?.as_f64()?;
        let lon = d.get("lon")?.as_f64()?;
        Some((lat, lon))
    });
    let mode = parse_solver_mode(args);
    let prune_disconnected = args.get("prune_disconnected").and_then(|v| v.as_bool()).unwrap_or(false);

    // Ensure output directory exists
    std::fs::create_dir_all(&output_dir)?;

    let extract_path = format!("{}/extract.geojson", output_dir);
    let cleaned_path = format!("{}/cleaned.geojson", output_dir);
    let rmp_path = format!("{}/network.rmp", output_dir);
    let route_path = format!("{}/route.gpx", output_dir);

    // Stage 1: Extract
    tracing::info!("pipeline stage 1: extract");
    let extract_req = ExtractRequest {
        source,
        bbox,
        road_classes: RoadClass::all_vehicle(),
        output_path: extract_path.clone(),
        pbf_path,
    };
    let extract_result = v2rmp::core::extract::run_extract(&extract_req).await?;

    // Stage 2: Clean
    tracing::info!("pipeline stage 2: clean");
    let input_data = std::fs::read_to_string(&extract_path)?;
    let geojson: geojson::FeatureCollection = serde_json::from_str(&input_data)?;
    let (cleaned, clean_stats, _warnings) = clean_geojson(&geojson, &CleanOptions::default())?;
    let cleaned_str = serde_json::to_string_pretty(&cleaned)?;
    std::fs::write(&cleaned_path, &cleaned_str)?;

    // Stage 3: Compile
    tracing::info!("pipeline stage 3: compile");
    let compile_req = CompileRequest {
        input_geojson: cleaned_path.clone(),
        output_rmp: rmp_path.clone(),
        compress: false,
        road_classes: vec![],
        clean_options: None,
        prune_disconnected,
    };
    let compile_result = v2rmp::core::compile::run_compile(&compile_req)?;

    // Stage 4: Optimize
    tracing::info!("pipeline stage 4: optimize");
    let optimize_req = OptimizeRequest {
        cache_file: rmp_path.clone(),
        route_file: Some(route_path.clone()),
        turn_penalties: TurnPenalties::default(),
        depot,
        oneway_mode: OnewayMode::default(),
        mode,
        num_vehicles: 1,
        solver_id: "clarke_wright".to_string(),
    };
    let optimize_result = v2rmp::core::optimize::run_optimize(&optimize_req).await?;

    Ok(json!({
        "output_dir": output_dir,
        "extract": {
            "nodes": extract_result.nodes,
            "edges": extract_result.edges,
            "total_km": extract_result.total_km,
        },
        "clean": {
            "input_features": clean_stats.input_features,
            "output_features": clean_stats.output_features,
            "total_removed": clean_stats.total_removed(),
        },
        "compile": {
            "node_count": compile_result.node_count,
            "edge_count": compile_result.edge_count,
            "output_size_bytes": compile_result.output_size_bytes,
        },
        "optimize": {
            "total_distance_km": optimize_result.total_distance_km,
            "total_segments": optimize_result.total_segments,
            "deadhead_distance_km": optimize_result.deadhead_distance_km,
            "efficiency_pct": optimize_result.efficiency_pct,
            "num_routes": optimize_result.num_routes,
        },
    }))
}

// ── Get Valhalla Matrix handler ──────────────────────────────────────────

async fn handle_get_valhalla_matrix(args: &Value) -> Result<Value> {
    let locs_val = args
        .get("locations")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing 'locations' parameter"))?;

    if locs_val.is_empty() {
        anyhow::bail!("At least one location is required");
    }

    let locations: Vec<VRPSolverStop> = locs_val
        .iter()
        .enumerate()
        .map(|(i, l)| {
            let lat = l.get("lat").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Location {} missing 'lat'", i))?;
            let lon = l.get("lon").and_then(|v| v.as_f64())
                .ok_or_else(|| anyhow::anyhow!("Location {} missing 'lon'", i))?;
            Ok(VRPSolverStop {
                lat,
                lon,
                label: format!("Loc {}", i),
                demand: None,
                arrival_time: None,
            })
        })
        .collect::<Result<Vec<_>>>()?;

    tracing::info!("get_valhalla_matrix: {} locations", locations.len());

    let matrix = get_valhalla_matrix(&locations).await
        .map_err(|e| anyhow::anyhow!("Valhalla matrix fetch failed: {}", e))?;

    let matrix_json: Vec<Vec<Value>> = matrix.iter().map(|row| {
        row.iter().map(|cell| {
            json!({
                "distance_km": cell.distance,
                "time_seconds": cell.time,
            })
        }).collect()
    }).collect();

    Ok(json!({
        "size": locations.len(),
        "matrix": matrix_json,
    }))
}

// ── Main loop ───────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() -> Result<()> {
    eprintln!(
        "rmpca-mcp-server starting (v{})",
        env!("CARGO_PKG_VERSION")
    );

    let tools = tool_definitions();
    let tool_list_json: Vec<Value> = tools
        .iter()
        .map(|t| {
            json!({
                "name": t.name,
                "description": t.description,
                "inputSchema": t.input_schema
            })
        })
        .collect();

    let stdin = std::io::stdin().lock();
    for line in stdin.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }

        let req: Request = match serde_json::from_str(&line) {
            Ok(r) => r,
            Err(e) => {
                send_err(&Value::Null, -32700, &format!("Parse error: {e}"));
                continue;
            }
        };

        if req.jsonrpc != "2.0" {
            send_err(&req.id, -32600, "Invalid Request: jsonrpc must be 2.0");
            continue;
        }

        match req.method.as_str() {
            "initialize" => {
                send(
                    &req.id,
                    json!({
                        "protocolVersion": "2024-11-05",
                        "capabilities": { "tools": {} },
                        "serverInfo": {
                            "name": "rmpca-mcp-server",
                            "version": env!("CARGO_PKG_VERSION")
                        }
                    }),
                );
            }

            "tools/list" => {
                send(&req.id, json!({ "tools": tool_list_json }));
            }

            "tools/call" => {
                let name = req
                    .params
                    .get("name")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let args = req
                    .params
                    .get("arguments")
                    .cloned()
                    .unwrap_or(Value::Null);

                let result = match name {
                    "extract_overture" => handle_extract_overture(&args).await,
                    "extract_osm" => handle_extract_osm(&args).await,
                    "compile" => handle_compile(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "optimize" => handle_optimize(&args).await,
                    "clean" => handle_clean(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "vrp_solve" => handle_vrp_solve(&args).await,
                    "elevation_query" => handle_elevation_query(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "elevation_profile" => handle_elevation_profile(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "list_solvers" => handle_list_solvers(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "haversine_distance" => handle_haversine_distance(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "elevation_stats" => handle_elevation_stats(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "dem_info" => handle_dem_info(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "fuel_estimate" => handle_fuel_estimate(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "inspect_rmp" => handle_inspect_rmp(&args)
                        .map_err(|e| anyhow::anyhow!("{e}"))
                        .map(|v| v),
                    "pipeline" => handle_pipeline(&args).await,
                    "get_valhalla_matrix" => handle_get_valhalla_matrix(&args).await,
                    other => {
                        send_err(&req.id, -32602, &format!("Unknown tool: {other}"));
                        continue;
                    }
                };

                tool_success(&req.id, &result);
            }

            "notifications/initialized" | "initialized" => {}

            other => {
                send_err(&req.id, -32601, &format!("Method not found: {other}"));
            }
        }
    }

    Ok(())
}