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
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
//! Slot persistence ToolDefs: `jumperless.slot.*`
//!
//! Five tools for managing slot save/discard/load/query state on the Jumperless V5.
//! These wrap `nodes_*` and slot-management Python bindings in `JumperlessMicroPythonAPI.cpp`.
//!
//! ## Gotchas baked in (from contract sheet):
//! - `nodes_save()` saves the FULL state (connections + overlays + power + config),
//!   not just nodes. The name is misleading.
//! - `nodes_save()` pauses Core2 internally — callers must NOT wrap it in an
//!   additional pause_core2 call (would cause double-pause behavior).
//! - `nodes_discard()` is destructive: it restores Python-entry state AND saves
//!   that reverted state to disk. Not a soft in-RAM undo.
//! - `nodes_has_changes()` compares against Python-entry backup, NOT the last
//!   saved slot file. Always returns False if called outside a Python session.

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

use crate::library::exec_with_cleanup;

/// Empty input schema for zero-arg tools.
fn no_args() -> Value {
    json!({"type": "object", "properties": {}, "additionalProperties": false})
}

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

/// Check for unsaved changes vs. Python-entry backup.
///
/// Wraps `nodes_has_changes()`. Returns `{"has_changes": bool}`.
pub fn slot_has_changes_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "slot_has_changes",
        "Check whether the current Jumperless V5 state differs from the Python-session-entry \
         backup. NOTE: always returns false if no Python session backup exists \
         (e.g., called outside a Python session or at boot). \
         Returns {\"has_changes\": true|false}.",
        no_args(),
        2_000,
    )
}

/// Save current state to a slot.
///
/// Wraps `nodes_save(slot=-1)`. Returns `{"saved_to_slot": int}`.
pub fn slot_save_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "slot_save",
        "Save the complete Jumperless V5 state (connections, nets, power, config, AND overlays) \
         to a slot file. Slot -1 (default) saves to the currently active slot. Valid explicit \
         slots: 0-7. IMPORTANT: this tool pauses Core2 internally during the filesystem write \
         (~50-200ms); do NOT wrap it in jumperless.core.pause — that would double-pause. \
         Bypasses the 2-second autosave timer for guaranteed immediate persistence. \
         Returns {\"saved_to_slot\": int, \"pause_was_applied_by_firmware\": true, \"do_not_wrap_in_core_pause\": true}.",
        json!({
            "type": "object",
            "properties": {
                "slot": {
                    "type": "integer",
                    "minimum": -1,
                    "maximum": 7,
                    "description": "Slot to save to. -1 = current active slot (default). Valid: -1 or 0-7."
                }
            },
            "additionalProperties": false
        }),
        3_000,
    )
}

/// Load state from a slot.
///
/// Wraps `switch_slot(slot)`. Returns `{"loaded_from_slot": int}`.
pub fn slot_load_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "slot_load",
        "Load the Jumperless V5 state from a slot file (connections, nets, power, config, and \
         overlays). Slot must be 0-7. The device will immediately switch to the specified slot, \
         replacing the current live state. NOTE: this is the same underlying primitive as manually \
         rotating slots on the device — it does NOT create a backup first. If the target slot \
         is empty, the board will clear to a default state. \
         Returns {\"loaded_from_slot\": int}.",
        json!({
            "type": "object",
            "properties": {
                "slot": {
                    "type": "integer",
                    "minimum": 0,
                    "maximum": 7,
                    "description": "Slot to load from. Required. Valid: 0-7."
                }
            },
            "required": ["slot"],
            "additionalProperties": false
        }),
        2_000,
    )
}

/// Query the currently active slot number.
///
/// Reads the `CURRENT_SLOT` constant. Returns `{"current_slot": int}`.
pub fn slot_get_current_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "slot_get_current",
        "Return the currently active slot number on the Jumperless V5 (0-7). Reads the \
         CURRENT_SLOT firmware constant — this is the slot whose state is presently loaded in \
         memory. Useful before a slot_load call to record where you are, or after a slot_save \
         call to confirm the active slot. Returns {\"current_slot\": int}.",
        no_args(),
        1_000,
    )
}

/// Discard changes and restore Python-entry state.
///
/// Wraps `nodes_discard()`. Returns `{"discarded": true}`.
pub fn slot_discard_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "slot_discard",
        "DESTRUCTIVE: Revert the Jumperless V5 state to the Python-session-entry backup AND \
         immediately save the reverted state to disk. This is NOT a soft undo — it overwrites \
         the slot file with the pre-session state. If no backup exists (boot-time script, or \
         never entered Python normally), returns {\"discarded\": false, \"reason\": str} instead \
         of performing a silent no-op. After discard, slot_has_changes() will return false. \
         Returns {\"discarded\": true} on success.",
        no_args(),
        3_000,
    )
}

/// Return all five slot ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![
        slot_has_changes_descriptor(),
        slot_save_descriptor(),
        slot_discard_descriptor(),
        slot_load_descriptor(),
        slot_get_current_descriptor(),
    ]
}

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

/// Execute `nodes_has_changes()` and return `{"has_changes": bool}`.
///
/// Validates the device response strictly — accepts ONLY `"True"` or `"False"`.
/// Anything else (empty string, unexpected output, firmware version difference)
/// returns Err rather than silently coercing to a false negative.
/// Mirrors the validation pattern in `handle_context_get` (tools/context.rs:71-75).
pub fn handle_slot_has_changes<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    let code = "print(nodes_has_changes())";
    let resp = exec_with_cleanup(port, code, "slot_has_changes")?;
    let trimmed = resp.stdout.trim();
    let has_changes = match trimmed {
        "True" => true,
        "False" => false,
        other => {
            return Err(McpError::Protocol(format!(
                "slot_has_changes: unexpected device response: '{other}'"
            )));
        }
    };
    Ok(json!({ "has_changes": has_changes }))
}

/// Execute `nodes_save(slot)` and return `{"saved_to_slot": int}`.
pub fn handle_slot_save<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    // Slot arg: -1 for current (default), 0-7 for explicit.
    let slot = match args.get("slot") {
        Some(v) => {
            let n = v
                .as_i64()
                .ok_or_else(|| McpError::Protocol("slot must be an integer".into()))?;
            if n != -1 && !(0..=7).contains(&n) {
                return Err(McpError::Protocol(format!(
                    "slot must be -1 (current) or 0-7; got {n}"
                )));
            }
            n
        }
        None => -1,
    };

    let code = format!("print(nodes_save({slot}))");
    let resp = exec_with_cleanup(port, &code, "slot_save")?;
    let saved_to: i64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "slot_save: unexpected response: '{}'",
            resp.stdout.trim()
        ))
    })?;

    // R6: nodes_save() pauses Core2 internally. Callers who also call
    // core_pause before slot_save will double-pause and get deadlock/crash.
    // Make this machine-readable so clients can detect the footgun.
    Ok(json!({
        "saved_to_slot": saved_to,
        "pause_was_applied_by_firmware": true,
        "do_not_wrap_in_core_pause": true
    }))
}

/// Execute `nodes_discard()` with pre-flight backup check.
///
/// The tool description says: "If no backup exists (boot-time script, or never
/// entered Python normally), this is a silent no-op." The handler now surfaces
/// that distinction: we call `nodes_has_changes()` first to determine if a backup
/// exists. If there is no backup, we return `{"discarded": false}` rather than
/// reporting `{"discarded": true}` for a no-op that did nothing.
///
/// This also prevents the surprising footgun of getting a success confirmation
/// for a silent no-op that left state unchanged.
pub fn handle_slot_discard<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    // Pre-flight: check if a Python-session backup exists to revert to.
    let check_code = "print(nodes_has_changes())";
    let check_resp = exec_with_cleanup(port, check_code, "slot_discard:has_changes")?;
    let trimmed = check_resp.stdout.trim();
    let has_backup = match trimmed {
        "True" => true,
        "False" => false,
        other => {
            return Err(McpError::Protocol(format!(
                "slot_discard: unexpected response from nodes_has_changes(): '{other}'"
            )));
        }
    };

    if !has_backup {
        // No backup → discard would be a silent no-op. Report honestly.
        return Ok(json!({
            "discarded": false,
            "reason": "no backup available; not entered via Python session (boot-time script or called outside a Python session)"
        }));
    }

    // Backup exists → proceed with the destructive revert.
    let code = "nodes_discard()";
    exec_with_cleanup(port, code, "slot_discard")?;
    Ok(json!({ "discarded": true }))
}

/// Execute `switch_slot(slot)` and return `{"loaded_from_slot": int}`.
///
/// The device-side primitive is `switch_slot(slot)` which switches the active slot and
/// returns the *previous* slot number. The MCP tool name (`slot_load`) follows our naming
/// convention (verb_noun matching the tool family) rather than the device function name.
///
/// Slot must be 0-7. The `required` schema field enforces presence, but we also validate
/// the range here so callers get a clear error rather than a firmware-level exception.
pub fn handle_slot_load<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let slot = match args.get("slot") {
        Some(v) => {
            let n = v
                .as_i64()
                .ok_or_else(|| McpError::Protocol("slot must be an integer".into()))?;
            if !(0..=7).contains(&n) {
                return Err(McpError::Protocol(format!("slot must be 0-7; got {n}")));
            }
            n
        }
        None => {
            return Err(McpError::Protocol(
                "slot_load: 'slot' argument is required".into(),
            ));
        }
    };

    let code = format!("print(switch_slot({slot}))");
    let resp = exec_with_cleanup(port, &code, "slot_load")?;
    // switch_slot returns the previous slot; we confirm the parse succeeds but
    // our response reports the slot we loaded INTO (the requested slot).
    let _prev_slot: i64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "slot_load: unexpected device response: '{}'",
            resp.stdout.trim()
        ))
    })?;

    Ok(json!({ "loaded_from_slot": slot }))
}

/// Read the current slot index via `CURRENT_SLOT()` and return `{"current_slot": int}`.
///
/// CONTRACT (live-verified V5 5.6.6.2, 2026-05-12): `CURRENT_SLOT` is a FUNCTION,
/// not a constant — `type(CURRENT_SLOT).__name__ == "function"`, and bare
/// `print(CURRENT_SLOT)` emits `<function>`. We call it: `print(CURRENT_SLOT())`
/// which returns the int slot index. Spec doc string (`get_current_slot()`)
/// gestures at a function-shaped getter; the firmware-exposed name happens to be
/// `CURRENT_SLOT` (capitalized like a constant, but callable like a getter).
pub fn handle_slot_get_current<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    let code = "print(CURRENT_SLOT())";
    let resp = exec_with_cleanup(port, code, "slot_get_current")?;
    let current: i64 = resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "slot_get_current: unexpected device response: '{}'",
            resp.stdout.trim()
        ))
    })?;
    Ok(json!({ "current_slot": current }))
}

// ── 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_frame() -> Vec<u8> {
            b"OK\x04\x04>".to_vec()
        }

        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
        }

        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(())
        }
    }

    // ── 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(&"slot_has_changes"));
        assert!(names.contains(&"slot_save"));
        assert!(names.contains(&"slot_discard"));
        assert!(names.contains(&"slot_load"));
        assert!(names.contains(&"slot_get_current"));
        assert_eq!(descs.len(), 5);
    }

    #[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
            );
        }
    }

    #[test]
    fn slot_discard_description_mentions_destructive() {
        let d = slot_discard_descriptor();
        assert!(
            d.description.to_uppercase().contains("DESTRUCTIVE"),
            "slot_discard description must warn DESTRUCTIVE"
        );
    }

    #[test]
    fn slot_save_description_warns_about_double_pause() {
        let d = slot_save_descriptor();
        assert!(
            d.description.contains("do NOT wrap") || d.description.contains("double-pause"),
            "slot_save description must warn against double-pause"
        );
    }

    // ── Handler: slot_has_changes ─────────────────────────────────────────────

    #[test]
    fn slot_has_changes_returns_true_when_device_says_true() {
        let frame = MockPort::ok_with_stdout("True");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_has_changes(&mut port).unwrap();
        assert_eq!(result["has_changes"], true);
    }

    #[test]
    fn slot_has_changes_returns_false_when_device_says_false() {
        let frame = MockPort::ok_with_stdout("False");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_has_changes(&mut port).unwrap();
        assert_eq!(result["has_changes"], false);
    }

    #[test]
    fn slot_has_changes_unexpected_value_returns_error() {
        // Anything other than "True" or "False" must be an Err — not a silent false.
        // Mirrors context_get_unexpected_value_returns_error.
        let frame = MockPort::ok_with_stdout("maybe");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_has_changes(&mut port);
        assert!(result.is_err(), "unexpected device output must return Err");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must describe the unexpected value; got: {msg}"
                );
                assert!(
                    msg.contains("maybe"),
                    "error must include the actual value; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_has_changes_empty_response_returns_error() {
        // Empty stdout (e.g. firmware returned nothing) must not silently coerce to false.
        let frame = MockPort::ok_with_stdout("");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_has_changes(&mut port);
        assert!(
            result.is_err(),
            "empty device output must return Err, not silent false"
        );
    }

    #[test]
    fn slot_has_changes_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: nodes_has_changes");
        let mut port = MockPort::with_responses(&[&err]);
        let result = handle_slot_has_changes(&mut port);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: slot_save ────────────────────────────────────────────────────

    #[test]
    fn slot_save_default_slot_returns_saved_slot_with_pause_fields() {
        let frame = MockPort::ok_with_stdout("3");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({});
        let result = handle_slot_save(&mut port, &args).unwrap();
        assert_eq!(result["saved_to_slot"], 3);
        // R6: response must include machine-readable double-pause warning fields.
        assert_eq!(
            result["pause_was_applied_by_firmware"], true,
            "must indicate firmware applied pause internally"
        );
        assert_eq!(
            result["do_not_wrap_in_core_pause"], true,
            "must warn against wrapping in core_pause"
        );
    }

    #[test]
    fn slot_save_explicit_slot_0() {
        let frame = MockPort::ok_with_stdout("0");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"slot": 0});
        let result = handle_slot_save(&mut port, &args).unwrap();
        assert_eq!(result["saved_to_slot"], 0);
        // Pause warning fields present on all successful saves.
        assert_eq!(result["pause_was_applied_by_firmware"], true);
        assert_eq!(result["do_not_wrap_in_core_pause"], true);
    }

    #[test]
    fn slot_save_rejects_invalid_slot() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"slot": 99});
        let result = handle_slot_save(&mut port, &args);
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(msg.contains("slot"), "error must mention 'slot'");
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_save_rejects_invalid_slot_8() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"slot": 8});
        let result = handle_slot_save(&mut port, &args);
        assert!(result.is_err());
    }

    #[test]
    fn slot_save_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("IOError: flash write failed");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({});
        let result = handle_slot_save(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: slot_discard ─────────────────────────────────────────────────

    #[test]
    fn slot_discard_happy_path_with_backup() {
        // Handler now does: has_changes check (→ "True") + nodes_discard call.
        let has_changes_frame = MockPort::ok_with_stdout("True");
        let discard_frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&has_changes_frame, &discard_frame]);
        let result = handle_slot_discard(&mut port).unwrap();
        assert_eq!(result["discarded"], true);
    }

    #[test]
    fn slot_discard_no_backup_returns_discarded_false() {
        // If nodes_has_changes() returns False, discard is a documented silent no-op.
        // The handler must return discarded:false with a reason, not discarded:true.
        let has_changes_frame = MockPort::ok_with_stdout("False");
        let mut port = MockPort::with_responses(&[&has_changes_frame]);
        let result = handle_slot_discard(&mut port).unwrap();
        assert_eq!(
            result["discarded"], false,
            "no-backup path must return discarded:false"
        );
        assert!(
            result.get("reason").and_then(|v| v.as_str()).is_some(),
            "no-backup response must include a 'reason' field"
        );
    }

    #[test]
    fn slot_discard_has_changes_unexpected_value_returns_error() {
        // Unexpected response from the pre-flight check must propagate as Err.
        let has_changes_frame = MockPort::ok_with_stdout("unexpected");
        let mut port = MockPort::with_responses(&[&has_changes_frame]);
        let result = handle_slot_discard(&mut port);
        assert!(
            result.is_err(),
            "unexpected has_changes value must return Err"
        );
    }

    #[test]
    fn slot_discard_device_error_sends_ctrl_c() {
        // Error on the has_changes pre-flight → Ctrl-C is sent by exec_with_cleanup.
        let err = MockPort::error_frame("NameError: nodes_has_changes");
        let mut port = MockPort::with_responses(&[&err]);
        let result = handle_slot_discard(&mut port);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    #[test]
    fn slot_discard_discard_call_error_sends_ctrl_c() {
        // Error on the actual nodes_discard() call after pre-flight passes.
        let has_changes_frame = MockPort::ok_with_stdout("True");
        let err = MockPort::error_frame("NameError: nodes_discard");
        let mut port = MockPort::with_responses(&[&has_changes_frame, &err]);
        let result = handle_slot_discard(&mut port);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Descriptor: two new tools appear in descriptors() ────────────────────

    #[test]
    fn descriptors_includes_slot_load_and_slot_get_current() {
        let descs = descriptors();
        let names: Vec<&str> = descs.iter().map(|d| d.name.as_str()).collect();
        assert!(
            names.contains(&"slot_load"),
            "descriptors() must include slot_load; got: {names:?}"
        );
        assert!(
            names.contains(&"slot_get_current"),
            "descriptors() must include slot_get_current; got: {names:?}"
        );
        // Total count is now 5 (was 3).
        assert_eq!(
            descs.len(),
            5,
            "descriptors() must return 5 entries (slot_has_changes, slot_save, slot_discard, slot_load, slot_get_current)"
        );
    }

    // ── Handler: slot_load ────────────────────────────────────────────────────

    #[test]
    fn slot_load_happy_path_returns_loaded_from_slot() {
        // switch_slot(2) → device returns "3" (previous slot). We return {loaded_from_slot: 2}.
        let frame = MockPort::ok_with_stdout("3");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"slot": 2});
        let result = handle_slot_load(&mut port, &args).unwrap();
        assert_eq!(
            result["loaded_from_slot"], 2,
            "loaded_from_slot must reflect the requested slot, not the previous one"
        );
    }

    #[test]
    fn slot_load_slot_zero_accepted() {
        let frame = MockPort::ok_with_stdout("5");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"slot": 0});
        let result = handle_slot_load(&mut port, &args).unwrap();
        assert_eq!(result["loaded_from_slot"], 0);
    }

    #[test]
    fn slot_load_rejects_slot_minus_one() {
        // Unlike slot_save, slot_load does NOT accept -1 as "current slot".
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"slot": -1});
        let result = handle_slot_load(&mut port, &args);
        assert!(result.is_err(), "slot -1 must be rejected by slot_load");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(msg.contains("slot"), "error must mention 'slot'");
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_load_rejects_slot_8() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"slot": 8});
        let result = handle_slot_load(&mut port, &args);
        assert!(result.is_err(), "slot 8 must be rejected");
    }

    #[test]
    fn slot_load_rejects_non_integer_slot() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"slot": "two"});
        let result = handle_slot_load(&mut port, &args);
        assert!(result.is_err(), "non-integer slot must be rejected");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("integer") || msg.contains("slot"),
                    "error must be descriptive; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_load_missing_arg_returns_error() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({});
        let result = handle_slot_load(&mut port, &args);
        assert!(result.is_err(), "missing 'slot' arg must return Err");
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("required") || msg.contains("slot"),
                    "error must describe the missing field; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_load_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("RuntimeError: switch_slot failed");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"slot": 1});
        let result = handle_slot_load(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: slot_get_current ─────────────────────────────────────────────

    #[test]
    fn slot_get_current_happy_path_returns_current_slot() {
        let frame = MockPort::ok_with_stdout("4");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_get_current(&mut port).unwrap();
        assert_eq!(result["current_slot"], 4);
    }

    #[test]
    fn slot_get_current_slot_zero() {
        let frame = MockPort::ok_with_stdout("0");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_get_current(&mut port).unwrap();
        assert_eq!(result["current_slot"], 0);
    }

    #[test]
    fn slot_get_current_malformed_response_returns_error() {
        // Non-integer firmware response must produce Err, not garbage data.
        let frame = MockPort::ok_with_stdout("???");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_get_current(&mut port);
        assert!(
            result.is_err(),
            "non-integer CURRENT_SLOT response must return Err"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must mention 'unexpected'; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn slot_get_current_empty_response_returns_error() {
        let frame = MockPort::ok_with_stdout("");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_slot_get_current(&mut port);
        assert!(
            result.is_err(),
            "empty CURRENT_SLOT response must return Err"
        );
    }

    #[test]
    fn slot_get_current_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: CURRENT_SLOT");
        let mut port = MockPort::with_responses(&[&err]);
        let result = handle_slot_get_current(&mut port);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }
}