jumperless-mcp 0.1.0

MCP server for the Jumperless V5 — persistent USB-serial bridge exposing the firmware API to LLMs
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
//! INA current/power sensor ToolDefs: `ina_get_current`, `ina_get_voltage`, `ina_get_power`
//!
//! Wraps the Jumperless V5 INA219 current/power monitor Python bindings.
//!
//! ## Sensor mapping
//! - Sensor 0 = DAC0 / Probe rail
//! - Sensor 1 = TOP_RAIL
//!
//! Both sensors are validated pre-flight. Any value outside {0, 1} is rejected
//! with `McpError::Protocol` before any bytes are sent to the device.
//!
//! ## Firmware note
//! `ina_get_voltage` reads the **shunt voltage** (across the current-sense
//! resistor), not the INA bus voltage. The bus voltage is available via
//! `ina_get_bus_voltage(sensor)`, which is a separate firmware call not wrapped
//! here. The task spec names the field `"voltage"` and the device call
//! `ina_get_voltage`, so we mirror that verbatim.

use crate::base::{McpError, ToolDescriptor};
use serde_json::{json, Value};
use std::io::{Read, Write};

use crate::library::exec_with_cleanup;

// ── Sensor validation ─────────────────────────────────────────────────────────

/// Validate an INA sensor argument: must be an integer in {0, 1}.
///
/// Returns the validated `i64` on success, or a `McpError::Protocol` describing
/// the violation on failure. No bytes are sent to the device before this passes.
fn validate_sensor(v: &Value) -> Result<i64, McpError> {
    let i = v
        .as_i64()
        .ok_or_else(|| McpError::Protocol("sensor must be an integer (0 or 1)".into()))?;
    if !(0..=1).contains(&i) {
        return Err(McpError::Protocol(format!(
            "sensor must be 0 (DAC0/Probe) or 1 (TOP_RAIL); got {i}"
        )));
    }
    Ok(i)
}

// ── ToolDescriptors ───────────────────────────────────────────────────────────

/// Build the `ina_get_current` [`ToolDescriptor`].
pub fn ina_get_current_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "ina_get_current",
        "Read the current in Amps from an INA219 current sensor on the Jumperless V5. \
         sensor: 0 = DAC0/Probe rail, 1 = TOP_RAIL. \
         Returns {\"current_amps\": float, \"sensor\": int}.",
        json!({
            "type": "object",
            "properties": {
                "sensor": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 1,
                    "description": "INA sensor index: 0 = DAC0/Probe, 1 = TOP_RAIL."
                }
            },
            "required": ["sensor"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Build the `ina_get_voltage` [`ToolDescriptor`].
pub fn ina_get_voltage_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "ina_get_voltage",
        "Read the shunt voltage in Volts from an INA219 sensor on the Jumperless V5. \
         sensor: 0 = DAC0/Probe rail, 1 = TOP_RAIL. \
         NOTE: This reads the shunt (sense-resistor) voltage, not the bus voltage. \
         For bus voltage use ina_get_bus_voltage (separate tool). \
         Returns {\"voltage\": float, \"sensor\": int}.",
        json!({
            "type": "object",
            "properties": {
                "sensor": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 1,
                    "description": "INA sensor index: 0 = DAC0/Probe, 1 = TOP_RAIL."
                }
            },
            "required": ["sensor"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Build the `ina_get_power` [`ToolDescriptor`].
pub fn ina_get_power_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "ina_get_power",
        "Read the power in Watts from an INA219 sensor on the Jumperless V5. \
         sensor: 0 = DAC0/Probe rail, 1 = TOP_RAIL. \
         Returns {\"power_watts\": float, \"sensor\": int}.",
        json!({
            "type": "object",
            "properties": {
                "sensor": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 1,
                    "description": "INA sensor index: 0 = DAC0/Probe, 1 = TOP_RAIL."
                }
            },
            "required": ["sensor"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Return all three INA ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![
        ina_get_current_descriptor(),
        ina_get_voltage_descriptor(),
        ina_get_power_descriptor(),
    ]
}

// ── Handlers ─────────────────────────────────────────────────────────────────

/// Read current in Amps from an INA219 sensor.
///
/// Validates `sensor` ∈ {0, 1} before contacting the device.
/// Calls `ina_get_current(sensor)`. Parses the response as f64.
/// Returns `{"current_amps": float, "sensor": int}`.
pub fn handle_ina_get_current<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let sensor_val = args
        .get("sensor")
        .ok_or_else(|| McpError::Protocol("missing required arg: sensor".into()))?;
    let sensor = validate_sensor(sensor_val)?;
    let code = format!("print(ina_get_current({sensor}))");
    let resp = exec_with_cleanup(port, &code, "ina_get_current")?;
    let current: f64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "ina_get_current: unexpected device response: '{}'",
            resp.stdout.trim()
        ))
    })?;
    Ok(json!({ "current_amps": current, "sensor": sensor }))
}

/// Read shunt voltage in Volts from an INA219 sensor.
///
/// Validates `sensor` ∈ {0, 1} before contacting the device.
/// Calls `ina_get_voltage(sensor)`. Parses the response as f64.
/// Returns `{"voltage": float, "sensor": int}`.
pub fn handle_ina_get_voltage<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let sensor_val = args
        .get("sensor")
        .ok_or_else(|| McpError::Protocol("missing required arg: sensor".into()))?;
    let sensor = validate_sensor(sensor_val)?;
    let code = format!("print(ina_get_voltage({sensor}))");
    let resp = exec_with_cleanup(port, &code, "ina_get_voltage")?;
    let voltage: f64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "ina_get_voltage: unexpected device response: '{}'",
            resp.stdout.trim()
        ))
    })?;
    Ok(json!({ "voltage": voltage, "sensor": sensor }))
}

/// Read power in Watts from an INA219 sensor.
///
/// Validates `sensor` ∈ {0, 1} before contacting the device.
/// Calls `ina_get_power(sensor)`. Parses the response as f64.
/// Returns `{"power_watts": float, "sensor": int}`.
pub fn handle_ina_get_power<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let sensor_val = args
        .get("sensor")
        .ok_or_else(|| McpError::Protocol("missing required arg: sensor".into()))?;
    let sensor = validate_sensor(sensor_val)?;
    let code = format!("print(ina_get_power({sensor}))");
    let resp = exec_with_cleanup(port, &code, "ina_get_power")?;
    let power: f64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "ina_get_power: unexpected device response: '{}'",
            resp.stdout.trim()
        ))
    })?;
    Ok(json!({ "power_watts": power, "sensor": sensor }))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use std::io::{self, Read, Write};

    // ── MockPort ──────────────────────────────────────────────────────────────

    struct MockPort {
        read_data: VecDeque<u8>,
        pub write_data: Vec<u8>,
    }

    impl MockPort {
        fn with_responses(responses: &[&[u8]]) -> Self {
            let mut buf = Vec::new();
            for r in responses {
                buf.extend_from_slice(r);
            }
            MockPort {
                read_data: VecDeque::from(buf),
                write_data: Vec::new(),
            }
        }

        fn ok_with_stdout(line: &str) -> Vec<u8> {
            let mut v = b"OK".to_vec();
            v.extend_from_slice(line.as_bytes());
            v.push(b'\n');
            v.extend_from_slice(b"\x04\x04>");
            v
        }
    }

    impl Read for MockPort {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = buf.len().min(self.read_data.len());
            if n == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "MockPort: no more scripted bytes",
                ));
            }
            for (dst, src) in buf[..n].iter_mut().zip(self.read_data.drain(..n)) {
                *dst = src;
            }
            Ok(n)
        }
    }

    impl Write for MockPort {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.write_data.extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    // ── Descriptor: names + additionalProperties ──────────────────────────────

    #[test]
    fn all_descriptors_have_correct_names() {
        let descs = descriptors();
        let names: Vec<&str> = descs.iter().map(|d| d.name.as_str()).collect();
        assert!(
            names.contains(&"ina_get_current"),
            "missing ina_get_current"
        );
        assert!(
            names.contains(&"ina_get_voltage"),
            "missing ina_get_voltage"
        );
        assert!(names.contains(&"ina_get_power"), "missing ina_get_power");
        assert_eq!(descs.len(), 3);
    }

    #[test]
    fn all_descriptors_have_object_schema_with_additional_properties_false() {
        for d in descriptors() {
            assert!(
                matches!(d.input_schema, Value::Object(_)),
                "descriptor '{}' must have object input_schema",
                d.name
            );
            assert_eq!(
                d.input_schema.get("additionalProperties"),
                Some(&Value::Bool(false)),
                "descriptor '{}' must have additionalProperties=false",
                d.name
            );
        }
    }

    // ── ina_get_current: happy path ───────────────────────────────────────────

    #[test]
    fn ina_get_current_sensor0_happy() {
        let frame = MockPort::ok_with_stdout("0.045");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 0});
        let result = handle_ina_get_current(&mut port, &args).unwrap();
        assert!((result["current_amps"].as_f64().unwrap() - 0.045).abs() < 1e-9);
        assert_eq!(result["sensor"], 0);
        let sent = String::from_utf8_lossy(&port.write_data);
        assert!(
            sent.contains("ina_get_current(0)"),
            "expected ina_get_current(0) in command; got: {sent}"
        );
    }

    #[test]
    fn ina_get_current_sensor1_happy() {
        let frame = MockPort::ok_with_stdout("0.123");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 1});
        let result = handle_ina_get_current(&mut port, &args).unwrap();
        assert!((result["current_amps"].as_f64().unwrap() - 0.123).abs() < 1e-9);
        assert_eq!(result["sensor"], 1);
        let sent = String::from_utf8_lossy(&port.write_data);
        assert!(
            sent.contains("ina_get_current(1)"),
            "expected ina_get_current(1) in command; got: {sent}"
        );
    }

    // ── ina_get_voltage: happy path ───────────────────────────────────────────

    #[test]
    fn ina_get_voltage_sensor0_happy() {
        let frame = MockPort::ok_with_stdout("0.00125");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 0});
        let result = handle_ina_get_voltage(&mut port, &args).unwrap();
        assert!((result["voltage"].as_f64().unwrap() - 0.00125).abs() < 1e-12);
        assert_eq!(result["sensor"], 0);
        let sent = String::from_utf8_lossy(&port.write_data);
        assert!(
            sent.contains("ina_get_voltage(0)"),
            "expected ina_get_voltage(0) in command; got: {sent}"
        );
    }

    #[test]
    fn ina_get_voltage_sensor1_happy() {
        let frame = MockPort::ok_with_stdout("3.3");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 1});
        let result = handle_ina_get_voltage(&mut port, &args).unwrap();
        assert!((result["voltage"].as_f64().unwrap() - 3.3).abs() < 1e-9);
        assert_eq!(result["sensor"], 1);
    }

    // ── ina_get_power: happy path ─────────────────────────────────────────────

    #[test]
    fn ina_get_power_sensor0_happy() {
        let frame = MockPort::ok_with_stdout("0.1485");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 0});
        let result = handle_ina_get_power(&mut port, &args).unwrap();
        assert!((result["power_watts"].as_f64().unwrap() - 0.1485).abs() < 1e-9);
        assert_eq!(result["sensor"], 0);
        let sent = String::from_utf8_lossy(&port.write_data);
        assert!(
            sent.contains("ina_get_power(0)"),
            "expected ina_get_power(0) in command; got: {sent}"
        );
    }

    #[test]
    fn ina_get_power_sensor1_happy() {
        let frame = MockPort::ok_with_stdout("0.4059");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 1});
        let result = handle_ina_get_power(&mut port, &args).unwrap();
        assert!((result["power_watts"].as_f64().unwrap() - 0.4059).abs() < 1e-9);
        assert_eq!(result["sensor"], 1);
    }

    // ── Sensor=2 rejected pre-flight (one per tool) ───────────────────────────

    #[test]
    fn ina_get_current_sensor2_rejected_before_device() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"sensor": 2});
        let result = handle_ina_get_current(&mut port, &args);
        assert!(result.is_err(), "sensor=2 must be rejected");
        assert!(
            port.write_data.is_empty(),
            "no bytes must be sent for out-of-range sensor"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("0") && msg.contains("1"),
                    "error must mention valid range; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn ina_get_voltage_sensor2_rejected_before_device() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"sensor": 2});
        let result = handle_ina_get_voltage(&mut port, &args);
        assert!(result.is_err(), "sensor=2 must be rejected");
        assert!(
            port.write_data.is_empty(),
            "no bytes must be sent for out-of-range sensor"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("0") && msg.contains("1"),
                    "error must mention valid range; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn ina_get_power_sensor2_rejected_before_device() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"sensor": 2});
        let result = handle_ina_get_power(&mut port, &args);
        assert!(result.is_err(), "sensor=2 must be rejected");
        assert!(
            port.write_data.is_empty(),
            "no bytes must be sent for out-of-range sensor"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("0") && msg.contains("1"),
                    "error must mention valid range; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    // ── Float parse error for each tool ───────────────────────────────────────

    #[test]
    fn ina_get_current_bad_device_response_returns_error() {
        let frame = MockPort::ok_with_stdout("ERROR: sensor timeout");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 0});
        let result = handle_ina_get_current(&mut port, &args);
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must describe unexpected response; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn ina_get_voltage_bad_device_response_returns_error() {
        let frame = MockPort::ok_with_stdout("not_a_float");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"sensor": 1});
        let result = handle_ina_get_voltage(&mut port, &args);
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must describe unexpected response; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn ina_get_power_bad_device_response_returns_error() {
        // Note: "nan" is actually a valid f64 parse in Rust (f64::NAN).
        // Use a truly unparseable string to test the error path.
        let frame2 = MockPort::ok_with_stdout("oops");
        let mut port2 = MockPort::with_responses(&[&frame2]);
        let result = handle_ina_get_power(&mut port2, &json!({"sensor": 1}));
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must describe unexpected response; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    // ── Negative sensor rejected ───────────────────────────────────────────────

    #[test]
    fn ina_get_current_negative_sensor_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"sensor": -1});
        let result = handle_ina_get_current(&mut port, &args);
        assert!(result.is_err(), "negative sensor must be rejected");
        assert!(
            port.write_data.is_empty(),
            "no bytes sent for invalid sensor"
        );
    }

    // ── Non-integer sensor rejected ───────────────────────────────────────────

    #[test]
    fn ina_get_power_float_sensor_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"sensor": 0.5});
        let result = handle_ina_get_power(&mut port, &args);
        assert!(result.is_err(), "float sensor must be rejected");
        assert!(port.write_data.is_empty(), "no bytes sent for float sensor");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("integer"),
                    "error must require integer; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }
}