v2rmp 0.5.0

rmpca — Route Optimization TUI
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
use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::io::{self, BufRead, Write};
use v2rmp::core::r2::R2Storage;
use v2rmp::core::extract::{ExtractRequest, ExtractSource, BBoxRequest, RoadClass};
use v2rmp::core::compile::{CompileRequest, run_compile};
use v2rmp::core::optimize::{OptimizeRequest, OnewayMode, run_optimize, TurnPenalties};
use v2rmp::core::postgis_cpp::{PostGisCppRequest, run_postgis_cpp};

fn main() -> Result<()> {
    let stdin = io::stdin();
    let mut stdout = io::stdout();

    for line in stdin.lock().lines() {
        let line = line?;
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let Ok(message) = serde_json::from_str::<Value>(trimmed) else {
            continue;
        };

        if let Some(response) = handle_message(message) {
            let payload = serde_json::to_string(&response)?;
            writeln!(stdout, "{}", payload)?;
            stdout.flush()?;
        }
    }

    Ok(())
}

fn handle_message(message: Value) -> Option<Value> {
    let method = message.get("method").and_then(Value::as_str)?;
    let id = message.get("id").cloned();

    match method {
        "initialize" => respond(id.as_ref(), json!({
            "protocolVersion": "2024-11-05",
            "serverInfo": {
                "name": "v2rmp-mcp-server",
                "version": env!("CARGO_PKG_VERSION"),
            },
            "capabilities": {
                "tools": {},
            }
        })),
        "tools/list" => respond(id.as_ref(), json!({
            "tools": [
                {
                    "name": "list_r2_bucket",
                    "description": "List all objects available in the configured Cloudflare R2 bucket.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "bucket": { "type": "string" },
                            "prefix": { "type": "string" }
                        }
                    }
                },
                {
                    "name": "upload_to_r2",
                    "description": "Upload a local file to the R2 bucket.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "local_path": { "type": "string" },
                            "r2_path": { "type": "string" },
                            "bucket": { "type": "string" }
                        },
                        "required": ["local_path", "r2_path"]
                    }
                },
                {
                    "name": "download_from_r2",
                    "description": "Download an object from the R2 bucket to a local file.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "r2_path": { "type": "string" },
                            "local_path": { "type": "string" },
                            "bucket": { "type": "string" }
                        },
                        "required": ["r2_path", "local_path"]
                    }
                },
                {
                    "name": "query_supabase",
                    "description": "Execute a SQL query against the Supabase database.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "query": { "type": "string" }
                        },
                        "required": ["query"]
                    }
                },
                {
                    "name": "v2rmp_extract",
                    "description": "Extract road network data from Overture or OSM.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "source": { "type": "string", "enum": ["overture", "osm"] },
                            "min_lon": { "type": "number" },
                            "min_lat": { "type": "number" },
                            "max_lon": { "type": "number" },
                            "max_lat": { "type": "number" },
                            "output_path": { "type": "string" }
                        },
                        "required": ["source", "min_lon", "min_lat", "max_lon", "max_lat", "output_path"]
                    }
                },
                {
                    "name": "v2rmp_compile",
                    "description": "Compile GeoJSON into .rmp binary format with optional cleaning.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "input_geojson": { "type": "string" },
                            "output_rmp": { "type": "string" },
                            "remove_isolates": { "type": "boolean" }
                        },
                        "required": ["input_geojson", "output_rmp"]
                    }
                },
                {
                    "name": "v2rmp_optimize",
                    "description": "Optimize a route on an .rmp map using classical algorithms.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "map_path": { "type": "string" },
                            "u_turn_penalty": { "type": "number" },
                            "depot_lat": { "type": "number" },
                            "depot_lon": { "type": "number" },
                            "output_route": { "type": "string" }
                        },
                        "required": ["map_path", "output_route"]
                    }
                },
                {
                    "name": "v2rmp_postgis_cpp",
                    "description": "Solve Chinese Postman Problem directly from a PostGIS road_edges table.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "bbox_min_lon": { "type": "number" },
                            "bbox_min_lat": { "type": "number" },
                            "bbox_max_lon": { "type": "number" },
                            "bbox_max_lat": { "type": "number" },
                            "road_classes": { "type": "array", "items": { "type": "string" } },
                            "oneway_mode": { "type": "string", "enum": ["ignore", "respect", "reverse"] },
                            "left_turn_penalty": { "type": "number" },
                            "right_turn_penalty": { "type": "number" },
                            "u_turn_penalty": { "type": "number" },
                            "depot_lat": { "type": "number" },
                            "depot_lon": { "type": "number" },
                            "database_url": { "type": "string" },
                            "table_name": { "type": "string" },
                            "output_path": { "type": "string" }
                        },
                        "required": ["bbox_min_lon", "bbox_min_lat", "bbox_max_lon", "bbox_max_lat"]
                    }
                },
                {
                    "name": "v2rmp_neural_optimize",
                    "description": "Optimize a route using a Neural Network model (ONNX). Best for complex VRP problems with capacity constraints.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "model_path": { "type": "string", "description": "Path to the .onnx model file" },
                            "locations": { 
                                "type": "array", 
                                "items": { 
                                    "type": "array", 
                                    "items": { "type": "number" },
                                    "minItems": 2,
                                    "maxItems": 2
                                },
                                "description": "List of [lat, lon] coordinates. Index 0 is the depot."
                            },
                            "demands": { "type": "array", "items": { "type": "number" }, "description": "Demands for each location (0 for depot)" },
                            "capacity": { "type": "number", "description": "Vehicle capacity" }
                        },
                        "required": ["model_path", "locations", "demands", "capacity"]
                    }
                }
            ]
        })),
        "resources/list" => respond(id.as_ref(), json!({ "resources": [] })),
        "resources/templates/list" => respond(id.as_ref(), json!({ "resourceTemplates": [] })),
        "notifications/initialized" => None,
        "tools/call" => {
            let params = message.get("params").cloned().unwrap_or_else(|| json!({}));
            match handle_tool_call(params) {
                Ok(result) => respond(id.as_ref(), result),
                Err(err) => respond_error(id.as_ref(), -32000, err.to_string()),
            }
        }
        "ping" => respond(id.as_ref(), json!({})),
        _ => respond_error(id.as_ref(), -32601, format!("Method not found: {}", method)),
    }
}

fn handle_tool_call(params: Value) -> Result<Value> {
    let name = params.get("name").and_then(Value::as_str).context("Missing tool name")?;
    let arguments = params.get("arguments").cloned().unwrap_or_else(|| json!({}));

    match name {
        "list_r2_bucket" => {
            let bucket = arguments.get("bucket").and_then(Value::as_str).unwrap_or("v2rmp");
            let prefix = arguments.get("prefix").and_then(Value::as_str);
            let rt = tokio::runtime::Runtime::new()?;
            rt.block_on(async {
                let storage = R2Storage::from_env(bucket)?;
                let objects = storage.list_objects(prefix).await?;
                Ok(json!({ "content": [{ "type": "text", "text": format!("Objects:\n{}", objects.join("\n")) }], "isError": false }))
            })
        }
        "upload_to_r2" => {
            let local_path = arguments.get("local_path").and_then(Value::as_str).context("Missing local_path")?;
            let r2_path = arguments.get("r2_path").and_then(Value::as_str).context("Missing r2_path")?;
            let bucket = arguments.get("bucket").and_then(Value::as_str).unwrap_or("v2rmp");
            let data = std::fs::read(local_path)?;
            let rt = tokio::runtime::Runtime::new()?;
            rt.block_on(async {
                let storage = R2Storage::from_env(bucket)?;
                storage.upload_object(r2_path, data).await?;
                Ok(json!({ "content": [{ "type": "text", "text": format!("Uploaded to {}", r2_path) }], "isError": false }))
            })
        }
        "download_from_r2" => {
            let r2_path = arguments.get("r2_path").and_then(Value::as_str).context("Missing r2_path")?;
            let local_path = arguments.get("local_path").and_then(Value::as_str).context("Missing local_path")?;
            let bucket = arguments.get("bucket").and_then(Value::as_str).unwrap_or("v2rmp");
            let rt = tokio::runtime::Runtime::new()?;
            rt.block_on(async {
                let storage = R2Storage::from_env(bucket)?;
                let data = storage.download_object(r2_path).await?;
                std::fs::write(local_path, data)?;
                Ok(json!({ "content": [{ "type": "text", "text": format!("Downloaded to {}", local_path) }], "isError": false }))
            })
        }
        "query_supabase" => {
            let sql_query = arguments.get("query").and_then(Value::as_str).context("Missing SQL query")?;
            let rt = tokio::runtime::Runtime::new()?;
            rt.block_on(async {
                dotenvy::dotenv().ok();
                let db_url = std::env::var("SUPABASE_DB_URL")?;
                let pool = sqlx::PgPool::connect(&db_url).await?;
                let rows = sqlx::query(sql_query).fetch_all(&pool).await?;
                let mut results = Vec::new();
                for row in rows {
                    use sqlx::{Column, Row, TypeInfo};
                    let mut res_row = serde_json::Map::new();
                    for col in row.columns() {
                        let name = col.name();
                        let val: Value = match col.type_info().name() {
                            "TEXT" | "VARCHAR" | "NAME" => row.get::<Option<String>, _>(name).map(Value::String).unwrap_or(Value::Null),
                            "INT4" | "INTEGER" => row.get::<Option<i32>, _>(name).map(|n| json!(n)).unwrap_or(Value::Null),
                            "INT8" | "BIGINT" => row.get::<Option<i64>, _>(name).map(|n| json!(n)).unwrap_or(Value::Null),
                            _ => json!("<type not displayed>"),
                        };
                        res_row.insert(name.to_string(), val);
                    }
                    results.push(Value::Object(res_row));
                }
                Ok(json!({ "content": [{ "type": "text", "text": serde_json::to_string_pretty(&results)? }], "isError": false }))
            })
        }
        "v2rmp_extract" => {
            let source = match arguments.get("source").and_then(Value::as_str).unwrap_or("overture") {
                "osm" => ExtractSource::Osm,
                _ => ExtractSource::Overture,
            };
            let req = ExtractRequest {
                source,
                bbox: BBoxRequest {
                    min_lon: arguments.get("min_lon").and_then(Value::as_f64).unwrap_or(0.0),
                    min_lat: arguments.get("min_lat").and_then(Value::as_f64).unwrap_or(0.0),
                    max_lon: arguments.get("max_lon").and_then(Value::as_f64).unwrap_or(0.0),
                    max_lat: arguments.get("max_lat").and_then(Value::as_f64).unwrap_or(0.0),
                },
                road_classes: RoadClass::all_vehicle(),
                output_path: arguments.get("output_path").and_then(Value::as_str).unwrap_or("out.geojson").to_string(),
            };
            let res = v2rmp::core::extract::run_extract(&req)?;
            Ok(json!({ "content": [{ "type": "text", "text": format!("Extracted {} nodes", res.nodes) }], "isError": false }))
        }
        "v2rmp_compile" => {
            let mut opts = v2rmp::core::clean::CleanOptions::default();
            opts.remove_isolates = arguments.get("remove_isolates").and_then(Value::as_bool).unwrap_or(true);
            let req = CompileRequest {
                input_geojson: arguments.get("input_geojson").and_then(Value::as_str).context("Missing input")?.to_string(),
                output_rmp: arguments.get("output_rmp").and_then(Value::as_str).context("Missing output")?.to_string(),
                compress: true, road_classes: vec![], clean_options: Some(opts),
            };
            let res = run_compile(&req)?;
            Ok(json!({ "content": [{ "type": "text", "text": format!("Compiled {} nodes", res.node_count) }], "isError": false }))
        }
        "v2rmp_optimize" => {
            let mut penalties = TurnPenalties::default();
            penalties.u_turn = arguments.get("u_turn_penalty").and_then(Value::as_f64).unwrap_or(10.0);
            let depot = if let (Some(lat), Some(lon)) = (arguments.get("depot_lat").and_then(Value::as_f64), arguments.get("depot_lon").and_then(Value::as_f64)) { Some((lat, lon)) } else { None };
            let req = OptimizeRequest {
                cache_file: arguments.get("map_path").and_then(Value::as_str).context("Missing map")?.to_string(),
                route_file: Some(arguments.get("output_route").and_then(Value::as_str).context("Missing output")?.to_string()),
                turn_penalties: penalties,
                depot,
                oneway_mode: OnewayMode::Respect,
            };
            let res = run_optimize(&req)?;
            Ok(json!({ "content": [{ "type": "text", "text": format!("Optimized: {:.2} km", res.total_distance_km) }], "isError": false }))
        }
        "v2rmp_postgis_cpp" => {
            let depot = if let (Some(lat), Some(lon)) = (
                arguments.get("depot_lat").and_then(Value::as_f64),
                arguments.get("depot_lon").and_then(Value::as_f64),
            ) {
                Some((lat, lon))
            } else {
                None
            };

            let road_classes: Vec<String> = arguments
                .get("road_classes")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();

            let oneway_mode = match arguments
                .get("oneway_mode")
                .and_then(Value::as_str)
                .unwrap_or("respect")
            {
                "ignore" => v2rmp::core::postgis_cpp::OneWayMode::Ignore,
                "reverse" => v2rmp::core::postgis_cpp::OneWayMode::Reverse,
                _ => v2rmp::core::postgis_cpp::OneWayMode::Respect,
            };

            let req = PostGisCppRequest {
                bbox: [
                    arguments.get("bbox_min_lon").and_then(Value::as_f64).context("Missing bbox_min_lon")?,
                    arguments.get("bbox_min_lat").and_then(Value::as_f64).context("Missing bbox_min_lat")?,
                    arguments.get("bbox_max_lon").and_then(Value::as_f64).context("Missing bbox_max_lon")?,
                    arguments.get("bbox_max_lat").and_then(Value::as_f64).context("Missing bbox_max_lat")?,
                ],
                road_classes,
                oneway_mode,
                turn_penalties: v2rmp::core::postgis_cpp::TurnPenalties {
                    left: arguments.get("left_turn_penalty").and_then(Value::as_f64).unwrap_or(50.0),
                    right: arguments.get("right_turn_penalty").and_then(Value::as_f64).unwrap_or(0.0),
                    u_turn: arguments.get("u_turn_penalty").and_then(Value::as_f64).unwrap_or(500.0),
                },
                depot,
                database_url: arguments.get("database_url").and_then(Value::as_str).map(|s| s.to_string()),
                table_name: arguments.get("table_name").and_then(Value::as_str).map(|s| s.to_string()),
                output_path: arguments.get("output_path").and_then(Value::as_str).map(|s| s.to_string()),
            };

            let res = run_postgis_cpp(&req)?;
            let json_text = serde_json::to_string_pretty(&res)?;
            Ok(json!({ "content": [{ "type": "text", "text": json_text }], "isError": false }))
        }
        "v2rmp_neural_optimize" => {
            use v2rmp::core::neural_routing::{NeuralRouteRequest, solve_neural};
            
            let locations_raw = arguments.get("locations").and_then(Value::as_array).context("Missing locations")?;
            let mut locations = Vec::with_capacity(locations_raw.len());
            for loc in locations_raw {
                let coords = loc.as_array().context("Invalid coordinate format")?;
                let lat = coords[0].as_f64().context("Invalid latitude")?;
                let lon = coords[1].as_f64().context("Invalid longitude")?;
                locations.push([lat, lon]);
            }

            let demands = arguments.get("demands").and_then(Value::as_array)
                .context("Missing demands")?
                .iter().filter_map(|v| v.as_f64()).collect();

            let req = NeuralRouteRequest {
                model_path: arguments.get("model_path").and_then(Value::as_str).context("Missing model_path")?.to_string(),
                locations,
                demands,
                capacity: arguments.get("capacity").and_then(Value::as_f64).unwrap_or(1.0),
            };

            let res = solve_neural(&req)?;
            Ok(json!({ 
                "content": [{ 
                    "type": "text", 
                    "text": serde_json::to_string_pretty(&res)? 
                }], 
                "isError": false 
            }))
        }
        _ => anyhow::bail!("Tool not found"),
    }
}

fn respond(id: Option<&Value>, result: Value) -> Option<Value> {
    id.map(|id| json!({ "jsonrpc": "2.0", "id": id, "result": result }))
}

fn respond_error(id: Option<&Value>, code: i64, message: String) -> Option<Value> {
    id.map(|id| json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }))
}