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
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
//! Connection routing ToolDefs: `jumperless.connect.*`
//!
//! Four tools for driving the Jumperless V5 crossbar routing engine:
//! `connect`, `disconnect`, `nodes_clear`, `is_connected`.
//!
//! ## Node identifier encoding (Python-side)
//! The Jumperless firmware exposes rows as integers and rail/pin names as
//! module-level Python identifiers.  When emitting a call we must distinguish:
//!
//! - Integer rows: `"5"` → emitted as `5` (bare int literal)
//! - Named rails:  `"TOP_RAIL"` → emitted as `TOP_RAIL` (bare identifier)
//!
//! See [`python_node_repr`] for the sanitizing helper.
//!
//! ## Gotchas baked in (from the LLM-tools spec):
//! - `connect(node1, node2, duplicates=-1)` — firmware default is `-1` (allow
//!   duplicates).  The spec names the parameter but does not define the semantics
//!   of positive values; we accept it and forward it verbatim (see SPEC NOTE in
//!   `connect_descriptor`).
//! - `nodes_clear()` removes ALL connections immediately.  Unlike the overlay
//!   equivalents there is no per-connection version — the caller should
//!   `slot_save` to slot 7 first.
//! - `is_connected` returns the Python boolean `True` or `False` over the REPL.
//!   We parse strictly; anything else is Err.

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

use crate::library::exec_with_cleanup;

// ── Node identifier helper ────────────────────────────────────────────────────

/// Convert a caller-supplied node string into safe Python source text.
///
/// Rules:
/// - If the string parses as `i32`, return the decimal representation
///   (e.g. `"5"` → `"5"`).  This becomes a Python integer literal in the call.
/// - Otherwise validate as an identifier: ASCII alphanumeric + underscore,
///   must start with a letter or underscore, max 16 chars.  Returns the string
///   unchanged to be emitted as a bare Python name.
/// - Anything else (empty, spaces, semicolons, too long, starts with digit
///   but not a plain integer) is rejected with `McpError::Protocol`.
///
/// NEVER quote identifiers as Python strings — `'TOP_RAIL'` would be a string
/// literal and the firmware's constant binding would not resolve.
pub fn python_node_repr(raw: &str) -> Result<String, McpError> {
    if raw.is_empty() {
        return Err(McpError::Protocol(
            "node identifier must not be empty".into(),
        ));
    }

    // Fast path: integer row numbers.
    if let Ok(n) = raw.parse::<i32>() {
        return Ok(n.to_string());
    }

    // Identifier path: alphanumeric + underscore, letter/underscore start.
    if raw.len() > 16 {
        return Err(McpError::Protocol(format!(
            "node identifier too long (max 16 chars): '{raw}'"
        )));
    }

    let mut chars = raw.chars();
    let first = chars.next().expect("non-empty checked above");
    if !first.is_ascii_alphabetic() && first != '_' {
        return Err(McpError::Protocol(format!(
            "node identifier must start with a letter or underscore: '{raw}'"
        )));
    }
    for ch in chars {
        if !ch.is_ascii_alphanumeric() && ch != '_' {
            return Err(McpError::Protocol(format!(
                "node identifier contains invalid character '{}': '{raw}'",
                ch
            )));
        }
    }

    Ok(raw.to_string())
}

// ── Empty input schema ────────────────────────────────────────────────────────

fn no_args() -> Value {
    json!({"type": "object", "properties": {}, "additionalProperties": false})
}

// ── Two-node schema ───────────────────────────────────────────────────────────

fn two_node_schema() -> Value {
    json!({
        "type": "object",
        "properties": {
            "node1": {
                "type": "string",
                "description": "First node. Row numbers '1'-'60', rail names (TOP_RAIL, BOTTOM_RAIL, GND, DAC0, DAC1), Arduino pins (D0-D13, A0-A7, AREF, RESET), GPIO (GPIO_1-GPIO_8, UART_TX, UART_RX), ADC (ADC0-ADC3, ISENSE_PLUS, ISENSE_MINUS)."
            },
            "node2": {
                "type": "string",
                "description": "Second node. Same identifier space as node1."
            }
        },
        "required": ["node1", "node2"],
        "additionalProperties": false
    })
}

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

/// Create a connection between two nodes.
///
/// SPEC NOTE: `duplicates=-1` is the firmware default (allow duplicates).
/// The spec does not define the semantics of positive values; the parameter
/// is accepted and forwarded verbatim.  If the firmware rejects a value it
/// will surface as a device error.
pub fn connect_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "connect",
        "Create a connection between two nodes on the Jumperless V5 crossbar. \
         Nodes may be row numbers 1-60, power rails (TOP_RAIL, BOTTOM_RAIL, GND, \
         DAC0, DAC1), Arduino pins (D0-D13, A0-A7, AREF, RESET), GPIO \
         (GPIO_1-GPIO_8, UART_TX, UART_RX), or ADC inputs (ADC0-ADC3, \
         ISENSE_PLUS, ISENSE_MINUS). The `duplicates` parameter is passed to the \
         firmware; -1 (default) allows duplicate connections per firmware convention. \
         Firmware validates node names and will error on unknown identifiers. \
         Returns {\"connected\": true} on success.",
        json!({
            "type": "object",
            "properties": {
                "node1": {
                    "type": "string",
                    "description": "First node identifier (row number or named rail/pin)."
                },
                "node2": {
                    "type": "string",
                    "description": "Second node identifier (row number or named rail/pin)."
                },
                "duplicates": {
                    "type": "integer",
                    "description": "Passed to firmware connect(). -1 = allow duplicates (default). Positive values: semantics defined by firmware."
                }
            },
            "required": ["node1", "node2"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Remove a connection between two nodes.
pub fn disconnect_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "disconnect",
        "Remove the connection between two nodes on the Jumperless V5 crossbar. \
         Both nodes must be valid identifiers (row numbers 1-60, named rail/pin). \
         If no connection exists between the two nodes, the firmware treats this \
         as a no-op (no error). \
         Returns {\"disconnected\": true} on success (no-op if no connection existed).",
        two_node_schema(),
        1_500,
    )
}

/// Remove ALL connections from the board.
pub fn nodes_clear_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "nodes_clear",
        "DESTRUCTIVE: Remove ALL connections from the Jumperless V5 crossbar immediately. \
         This cannot be undone without a saved slot. Strongly recommend calling \
         slot_save(7) first to preserve a recovery point. \
         Does NOT clear overlays (use overlay_clear_all for that). \
         Returns {\"cleared\": true}.",
        no_args(),
        2_000,
    )
}

/// Check whether two nodes are currently connected.
pub fn is_connected_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "is_connected",
        "Check whether two nodes on the Jumperless V5 are currently connected through \
         the crossbar. Returns {\"connected\": true} or {\"connected\": false}. \
         Both node identifiers must be valid (row 1-60, named rail/pin). \
         (Internally wraps the device call in bool() because firmware returns a \
         ConnectionState class whose string form is 'CONNECTED'/'DISCONNECTED'; \
         this tool always returns clean booleans.)",
        two_node_schema(),
        1_000,
    )
}

/// Return all four connection ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![
        connect_descriptor(),
        disconnect_descriptor(),
        nodes_clear_descriptor(),
        is_connected_descriptor(),
    ]
}

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

/// Execute `connect(node1, node2, duplicates)` on the device.
///
/// Returns `{"connected": true}` on success (the firmware does not return a
/// meaningful value from `connect()` — we return a fixed confirmation).
pub fn handle_connect<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let n1_raw = args
        .get("node1")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("connect: 'node1' argument required".into()))?;
    let n2_raw = args
        .get("node2")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("connect: 'node2' argument required".into()))?;

    let n1 = python_node_repr(n1_raw)
        .map_err(|e| McpError::Protocol(format!("connect: node1 invalid — {e}")))?;
    let n2 = python_node_repr(n2_raw)
        .map_err(|e| McpError::Protocol(format!("connect: node2 invalid — {e}")))?;

    let duplicates = match args.get("duplicates") {
        Some(v) => v
            .as_i64()
            .ok_or_else(|| McpError::Protocol("connect: 'duplicates' must be an integer".into()))?,
        None => -1,
    };

    let code = format!("connect({n1}, {n2}, {duplicates})");
    exec_with_cleanup(port, &code, "connect")?;
    Ok(json!({ "connected": true }))
}

/// Execute `disconnect(node1, node2)` on the device.
///
/// Returns `{"disconnected": true}` on success.
pub fn handle_disconnect<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let n1_raw = args
        .get("node1")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("disconnect: 'node1' argument required".into()))?;
    let n2_raw = args
        .get("node2")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("disconnect: 'node2' argument required".into()))?;

    let n1 = python_node_repr(n1_raw)
        .map_err(|e| McpError::Protocol(format!("disconnect: node1 invalid — {e}")))?;
    let n2 = python_node_repr(n2_raw)
        .map_err(|e| McpError::Protocol(format!("disconnect: node2 invalid — {e}")))?;

    let code = format!("disconnect({n1}, {n2})");
    exec_with_cleanup(port, &code, "disconnect")?;
    Ok(json!({ "disconnected": true }))
}

/// Execute `nodes_clear()` on the device.
///
/// Returns `{"cleared": true}` on success.
pub fn handle_nodes_clear<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    exec_with_cleanup(port, "nodes_clear()", "nodes_clear")?;
    Ok(json!({ "cleared": true }))
}

/// Execute `is_connected(node1, node2)` and parse the boolean response.
///
/// Firmware `is_connected` returns a `ConnectionState` object whose `__repr__`
/// emits `CONNECTED` / `DISCONNECTED` (NOT `True` / `False`). We wrap the call
/// in `bool()` so the printed output is `"True"` / `"False"` for clean strict
/// parsing — the ConnectionState class IS truthy/falsy via Python coercion.
/// Confirmed live 2026-05-12 on V5 firmware 5.6.6.2.
pub fn handle_is_connected<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let n1_raw = args
        .get("node1")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("is_connected: 'node1' argument required".into()))?;
    let n2_raw = args
        .get("node2")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("is_connected: 'node2' argument required".into()))?;

    let n1 = python_node_repr(n1_raw)
        .map_err(|e| McpError::Protocol(format!("is_connected: node1 invalid — {e}")))?;
    let n2 = python_node_repr(n2_raw)
        .map_err(|e| McpError::Protocol(format!("is_connected: node2 invalid — {e}")))?;

    // bool() coerces ConnectionState → True/False; print emits literal "True" / "False".
    let code = format!("print(bool(is_connected({n1}, {n2})))");
    let resp = exec_with_cleanup(port, &code, "is_connected")?;

    let trimmed = resp.stdout.trim();
    let connected = match trimmed {
        "True" => true,
        "False" => false,
        other => {
            return Err(McpError::Protocol(format!(
                "is_connected: unexpected device response: '{other}'"
            )));
        }
    };
    Ok(json!({ "connected": connected }))
}

// ── 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(),
            }
        }

        /// OK frame with no stdout (used when the function returns None/void).
        fn ok_frame() -> Vec<u8> {
            b"OK\x04\x04>".to_vec()
        }

        /// OK frame with one line of stdout.
        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
        }

        /// Error frame — stdout empty, stderr has message.
        fn error_frame(msg: &str) -> Vec<u8> {
            let mut v = b"OK\x04".to_vec();
            v.extend_from_slice(msg.as_bytes());
            v.push(b'\n');
            v.push(b'\x04');
            v.push(b'>');
            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(())
        }
    }

    // ── python_node_repr unit tests ───────────────────────────────────────────

    #[test]
    fn node_repr_integer_row() {
        assert_eq!(python_node_repr("5").unwrap(), "5");
        assert_eq!(python_node_repr("1").unwrap(), "1");
        assert_eq!(python_node_repr("60").unwrap(), "60");
    }

    #[test]
    fn node_repr_named_rail() {
        assert_eq!(python_node_repr("TOP_RAIL").unwrap(), "TOP_RAIL");
        assert_eq!(python_node_repr("GND").unwrap(), "GND");
        assert_eq!(python_node_repr("DAC0").unwrap(), "DAC0");
        assert_eq!(python_node_repr("ISENSE_PLUS").unwrap(), "ISENSE_PLUS");
    }

    #[test]
    fn node_repr_arduino_pins() {
        assert_eq!(python_node_repr("D13").unwrap(), "D13");
        assert_eq!(python_node_repr("A0").unwrap(), "A0");
        assert_eq!(python_node_repr("AREF").unwrap(), "AREF");
        assert_eq!(python_node_repr("RESET").unwrap(), "RESET");
    }

    #[test]
    fn node_repr_gpio() {
        assert_eq!(python_node_repr("GPIO_1").unwrap(), "GPIO_1");
        assert_eq!(python_node_repr("UART_TX").unwrap(), "UART_TX");
    }

    #[test]
    fn node_repr_rejects_empty() {
        assert!(python_node_repr("").is_err());
    }

    #[test]
    fn node_repr_rejects_injection_attempt() {
        // Semicolons, spaces, newlines — injection vectors must all fail.
        assert!(python_node_repr("5;import os").is_err());
        assert!(python_node_repr("foo bar").is_err());
        assert!(python_node_repr("A0\n").is_err());
        assert!(python_node_repr("GND;").is_err());
    }

    #[test]
    fn node_repr_rejects_too_long_identifier() {
        let long = "A".repeat(17);
        assert!(python_node_repr(&long).is_err());
    }

    #[test]
    fn node_repr_rejects_identifier_starting_with_digit() {
        // "5abc" is not parseable as i32 and starts with digit — must be Err.
        assert!(python_node_repr("5abc").is_err());
    }

    // ── Descriptor tests ──────────────────────────────────────────────────────

    #[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(&"connect"), "must have 'connect'");
        assert!(names.contains(&"disconnect"), "must have 'disconnect'");
        assert!(names.contains(&"nodes_clear"), "must have 'nodes_clear'");
        assert!(names.contains(&"is_connected"), "must have 'is_connected'");
        assert_eq!(descs.len(), 4);
    }

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

    #[test]
    fn nodes_clear_description_mentions_destructive() {
        let d = nodes_clear_descriptor();
        assert!(
            d.description.to_uppercase().contains("DESTRUCTIVE"),
            "nodes_clear description must warn DESTRUCTIVE; got: '{}'",
            d.description
        );
    }

    // ── Handler: connect ──────────────────────────────────────────────────────

    #[test]
    fn connect_happy_path_row_to_row() {
        // connect(1, 5, -1) — both integer rows, default duplicates.
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "1", "node2": "5"});
        let result = handle_connect(&mut port, &args).unwrap();
        assert_eq!(result["connected"], true);
        // Verify the emitted Python contains integer literals (no quotes).
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(written.contains("connect(1, 5, -1)"), "got: {written}");
    }

    #[test]
    fn connect_happy_path_row_to_rail() {
        // connect(5, TOP_RAIL, -1) — int row + bare identifier.
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "5", "node2": "TOP_RAIL"});
        let result = handle_connect(&mut port, &args).unwrap();
        assert_eq!(result["connected"], true);
        let written = String::from_utf8_lossy(&port.write_data);
        // Rail name must NOT be quoted in the Python source.
        assert!(
            written.contains("connect(5, TOP_RAIL, -1)"),
            "rail must be bare identifier; got: {written}"
        );
        assert!(
            !written.contains("'TOP_RAIL'"),
            "rail must not be quoted; got: {written}"
        );
    }

    #[test]
    fn connect_explicit_duplicates_arg() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "10", "node2": "20", "duplicates": 0});
        handle_connect(&mut port, &args).unwrap();
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(written.contains("connect(10, 20, 0)"), "got: {written}");
    }

    #[test]
    fn connect_rejects_invalid_node() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"node1": "5;import os", "node2": "10"});
        let result = handle_connect(&mut port, &args);
        assert!(result.is_err(), "injection attempt must be rejected");
    }

    #[test]
    fn connect_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: connect");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"node1": "1", "node2": "2"});
        let result = handle_connect(&mut port, &args);
        assert!(result.is_err());
        assert!(
            port.write_data.contains(&0x03),
            "Ctrl-C must be sent on error"
        );
    }

    // ── Handler: disconnect ───────────────────────────────────────────────────

    #[test]
    fn disconnect_happy_path() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "1", "node2": "5"});
        let result = handle_disconnect(&mut port, &args).unwrap();
        assert_eq!(result["disconnected"], true);
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(written.contains("disconnect(1, 5)"), "got: {written}");
    }

    #[test]
    fn disconnect_rejects_invalid_node() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"node1": "GND", "node2": "bad node"});
        let result = handle_disconnect(&mut port, &args);
        assert!(result.is_err());
    }

    // ── Handler: nodes_clear ──────────────────────────────────────────────────

    #[test]
    fn nodes_clear_happy_path() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_nodes_clear(&mut port).unwrap();
        assert_eq!(result["cleared"], true);
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(written.contains("nodes_clear()"), "got: {written}");
    }

    #[test]
    fn nodes_clear_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("RuntimeError: crossbar fault");
        let mut port = MockPort::with_responses(&[&err]);
        let result = handle_nodes_clear(&mut port);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: is_connected ─────────────────────────────────────────────────

    #[test]
    fn is_connected_returns_true() {
        let frame = MockPort::ok_with_stdout("True");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "1", "node2": "5"});
        let result = handle_is_connected(&mut port, &args).unwrap();
        assert_eq!(result["connected"], true);
    }

    #[test]
    fn is_connected_returns_false() {
        let frame = MockPort::ok_with_stdout("False");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "1", "node2": "60"});
        let result = handle_is_connected(&mut port, &args).unwrap();
        assert_eq!(result["connected"], false);
    }

    #[test]
    fn is_connected_unexpected_response_is_err() {
        let frame = MockPort::ok_with_stdout("maybe");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "1", "node2": "5"});
        let result = handle_is_connected(&mut port, &args);
        assert!(result.is_err(), "unexpected response must be Err");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must say 'unexpected': {msg}"
                );
                assert!(
                    msg.contains("maybe"),
                    "error must include actual value: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn is_connected_emits_bool_print_call() {
        // is_connected must wrap in bool() because firmware returns
        // ConnectionState (repr=CONNECTED/DISCONNECTED). bool() coerces
        // it to True/False which our strict parser accepts.
        let frame = MockPort::ok_with_stdout("True");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"node1": "5", "node2": "GND"});
        handle_is_connected(&mut port, &args).unwrap();
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(
            written.contains("print(bool(is_connected(5, GND)))"),
            "must use print(bool(...)) wrapper for ConnectionState coercion; got: {written}"
        );
    }

    #[test]
    fn is_connected_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: is_connected");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"node1": "1", "node2": "2"});
        let result = handle_is_connected(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }
}