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
//! Overlay ToolDefs: `jumperless.overlay.*`
//!
//! Four tools for inspecting and clearing graphic overlay state on the
//! Jumperless V5. These wrap the `overlay_*` Python bindings in
//! `JumperlessMicroPythonAPI.cpp`.
//!
//! ## Gotchas baked in (from contract sheet):
//! - `overlay_serialize` returns a pointer to a 4096-byte **static** buffer.
//!   The device MicroPython returns the JSON as stdout. Copy immediately.
//! - `overlay_count` is accurate but slot layout may be sparse after removals.
//! - `overlay_clear_all` always calls `markDirty()` even if no overlays exist.

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 ───────────────────────────────────────────────────────────

/// Serialize current overlay state as structured JSON.
///
/// Wraps `overlay_serialize()`. Returns the parsed JSON, or the raw string if
/// parsing fails. The device uses a 4096-byte static buffer — truncation is
/// possible with >8 large overlays; the `warning` field flags this.
pub fn overlay_serialize_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "overlay_serialize",
        "Serialize the current overlay state from the Jumperless V5 as structured JSON. \
         Returns an array of overlay objects, each with name, row, col, width, height, and \
         colors fields. Colors are 6-char hex strings in row-major order; '000000' = off. \
         The _DIRECT_PIXELS_ overlay appears here if any pixels were set via overlay_set_pixel. \
         NOTE: device uses a 4096-byte static buffer — large overlay sets (approaching 8) \
         may be silently truncated.",
        no_args(),
        2_000,
    )
}

/// List named overlays with their bounds.
///
/// Synthesized from `overlay_count()` + `overlay_serialize()`. Returns count
/// and a list of overlay names and bounding boxes.
pub fn overlay_list_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "overlay_list",
        "List all active overlays on the Jumperless V5 with their names and bounding boxes. \
         Returns overlay count and a summary array. Uses overlay_count() + overlay_serialize(). \
         NOTE: count is accurate but slot layout may be sparse after removals (slots are not \
         compacted after overlay_clear). Max 8 overlays; approaching that cap will cause \
         overlay_set and overlay_set_pixel to fail silently.",
        no_args(),
        2_000,
    )
}

/// Clear a single named overlay.
///
/// Wraps `overlay_clear(name: str)`. Returns `{"removed": bool}`.
pub fn overlay_clear_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "overlay_clear",
        "Remove a single named overlay from the Jumperless V5. \
         Requires the exact name (case-sensitive, max 31 chars). \
         Returns {\"removed\": true} if the overlay was found and removed, \
         {\"removed\": false} if not found. Triggers markDirty() → autosave within ~2s. \
         Passing the special name '_DIRECT_PIXELS_' clears all overlay_set_pixel pixels.",
        json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Exact overlay name (case-sensitive, max 31 chars)"
                }
            },
            "required": ["name"],
            "additionalProperties": false
        }),
        2_000,
    )
}

/// Clear all overlays.
///
/// Wraps `overlay_clear_all()`. Returns `{"cleared": true}`.
pub fn overlay_clear_all_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "overlay_clear_all",
        "Clear all graphic overlays from the Jumperless V5, including the implicit \
         _DIRECT_PIXELS_ overlay created by overlay_set_pixel. Always succeeds. \
         Triggers markDirty() → autosave within ~2s even if no overlays existed. \
         For guaranteed persistence call jumperless.slot.save after this tool.",
        no_args(),
        2_000,
    )
}

/// Return all four overlay ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![
        overlay_serialize_descriptor(),
        overlay_list_descriptor(),
        overlay_clear_descriptor(),
        overlay_clear_all_descriptor(),
    ]
}

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

/// Execute `overlay_serialize()` and return parsed or raw JSON.
///
/// ## Why NOT `json.dumps(overlay_serialize())`
///
/// `overlay_serialize()` already returns a Python `str` (the raw C buffer, per
/// modjumperless.c:5800-5803). Wrapping it in `json.dumps` double-encodes it
/// into a JSON-quoted blob. Additionally, the C function (`serializeOverlaysToJSON`,
/// GraphicOverlays.cpp:469-503) emits a JSON *fragment* starting with
/// `  "overlays": [...]` — no outer braces. We add the braces on the Python side
/// via `print('{' + overlay_serialize() + '}')` to produce a parseable document.
pub fn handle_overlay_serialize<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    // Do NOT use json.dumps here — overlay_serialize() already returns a str.
    // Add outer braces to convert the firmware fragment into a parseable JSON document.
    let code = "print('{' + overlay_serialize() + '}')";
    let resp = exec_with_cleanup(port, code, "overlay_serialize")?;
    let raw = resp.stdout.trim().to_string();

    // Strict parse — failure is a protocol error, NOT a silent {raw, parse_error}
    // fallback. The previous fallback masked 4096-byte buffer truncations and made
    // the get_state synthesizer's overlay-fold path lossy. Flagged CRITICAL by
    // SF-hunter review 2026-05-12.
    let parsed = serde_json::from_str::<Value>(&raw).map_err(|e| {
        McpError::Protocol(format!(
            "overlay_serialize: device returned non-JSON (possible 4096-byte buffer truncation; \
             parse error: {e}); raw: '{raw}'"
        ))
    })?;

    // Missing 'overlays' key is a schema violation, not a soft fallback to []
    // (SF-hunter R2 finding 2026-05-12). Without this Err, a firmware response
    // shape change that drops the key would silently report empty state.
    let overlays = parsed
        .get("overlays")
        .and_then(|v| v.as_array())
        .ok_or_else(|| {
            McpError::Protocol(format!(
                "overlay_serialize: parsed JSON missing 'overlays' key — possible firmware \
             response shape change; raw: '{raw}'"
            ))
        })?;

    // Warn if approaching the 8-overlay cap.
    let count = overlays.len();
    let warning = if count >= 7 {
        Some(format!(
            "overlay count is {count}; approaching MAX_GRAPHIC_OVERLAYS (8) — \
             overlay_set and overlay_set_pixel will fail silently when full"
        ))
    } else {
        None
    };
    Ok(json!({
        "overlays": overlays,
        "warning": warning
    }))
}

/// Execute `overlay_count()` + `overlay_serialize()` and return a list summary.
///
/// Both the count parse and the serialize parse are STRICT — a parse failure
/// returns Err rather than silently producing `count=0` / `overlays=[]`. The
/// silent-fallback pattern was flagged CRITICAL by SF-hunter review 2026-05-12:
/// it made a truncated overlay payload indistinguishable from an empty overlay
/// slate, which could let consumers clobber state they thought was empty.
pub fn handle_overlay_list<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    // Get count first — strict parse.
    let count_code = "print(overlay_count())";
    let count_resp = exec_with_cleanup(port, count_code, "overlay_list:count")?;
    let count: u64 = count_resp.stdout.trim().parse().map_err(|_| {
        McpError::Protocol(format!(
            "overlay_list: unexpected count response: '{}'",
            count_resp.stdout.trim()
        ))
    })?;

    // Get serialized state for names/bounds.
    // Same firmware-fragment wrapping as handle_overlay_serialize — see that fn's doc comment.
    let serialize_code = "print('{' + overlay_serialize() + '}')";
    let serialize_resp = exec_with_cleanup(port, serialize_code, "overlay_list:serialize")?;
    let raw = serialize_resp.stdout.trim().to_string();

    let parsed = serde_json::from_str::<Value>(&raw).map_err(|e| {
        McpError::Protocol(format!(
            "overlay_list: serialize-stage parse failed (possible 4096-byte buffer truncation; \
             parse error: {e}); raw: '{raw}'"
        ))
    })?;
    let overlays: Vec<Value> = parsed
        .get("overlays")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default()
        .into_iter()
        .map(|o| {
            json!({
                "name": o.get("name").cloned().unwrap_or(json!("")),
                "row": o.get("row").cloned().unwrap_or(json!(0)),
                "col": o.get("col").cloned().unwrap_or(json!(0)),
                "width": o.get("width").cloned().unwrap_or(json!(0)),
                "height": o.get("height").cloned().unwrap_or(json!(0)),
            })
        })
        .collect();

    let at_cap = count >= 8;
    Ok(json!({
        "count": count,
        "at_cap": at_cap,
        "cap_warning": if at_cap {
            Some("overlay cap reached (8); overlay_set and overlay_set_pixel will fail silently")
        } else {
            None
        },
        "overlays": overlays
    }))
}

/// Execute `overlay_clear(name)` and return `{"removed": bool}`.
pub fn handle_overlay_clear<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let name = args
        .get("name")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            McpError::Protocol("overlay_clear requires a non-empty 'name' argument".into())
        })?;

    // Escape for Python single-quoted string (name is max 31 chars, validated device-side).
    let safe_name = name.replace('\\', "\\\\").replace('\'', "\\'");
    let code = format!("print(overlay_clear('{safe_name}'))");
    let resp = exec_with_cleanup(port, &code, "overlay_clear")?;

    // R7: accept "1"/"0" and "True"/"False" (both plausible C-binding return values).
    // Anything else → Err with the actual stdout included for diagnostics.
    let trimmed = resp.stdout.trim();
    let removed = match trimmed {
        "1" | "True" => true,
        "0" | "False" => false,
        other => {
            return Err(McpError::Protocol(format!(
                "overlay_clear: unexpected device response: '{other}'"
            )));
        }
    };
    Ok(json!({ "removed": removed }))
}

/// Execute `overlay_clear_all()` and return `{"cleared": true}`.
pub fn handle_overlay_clear_all<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    let code = "overlay_clear_all()";
    exec_with_cleanup(port, code, "overlay_clear_all")?;
    Ok(json!({ "cleared": true }))
}

// ── 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(&"overlay_serialize"));
        assert!(names.contains(&"overlay_list"));
        assert!(names.contains(&"overlay_clear"));
        assert!(names.contains(&"overlay_clear_all"));
        assert_eq!(descs.len(), 4);
    }

    #[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 overlay_clear_descriptor_requires_name_field() {
        let d = overlay_clear_descriptor();
        let required = d.input_schema.get("required").unwrap();
        let arr = required.as_array().unwrap();
        assert!(
            arr.iter().any(|v| v.as_str() == Some("name")),
            "overlay_clear descriptor must require 'name'"
        );
    }

    // ── Handler: overlay_serialize ────────────────────────────────────────────
    //
    // Mock output shape note:
    // The firmware's serializeOverlaysToJSON (GraphicOverlays.cpp:469-503) emits:
    //   `  "overlays": [...]`
    // (a fragment, not a document). The handler wraps it with outer braces via
    // `print('{' + overlay_serialize() + '}')`, so the device's stdout is:
    //   `{  "overlays": [...]}`
    // These mocks simulate THAT output — the post-wrap bytes the device sends.

    #[test]
    fn overlay_serialize_happy_path_returns_parsed_json() {
        // Simulate real device output: outer-brace-wrapped firmware fragment.
        let payload = r#"{  "overlays": [{"name":"test","row":0,"col":0,"width":5,"height":3,"colors":["FF0000","000000"]}
  ]}"#;
        let frame = MockPort::ok_with_stdout(payload);
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port).unwrap();
        assert!(result.get("overlays").is_some());
        let overlays = result["overlays"].as_array().unwrap();
        assert_eq!(overlays.len(), 1);
        assert_eq!(overlays[0]["name"], "test");
    }

    #[test]
    fn overlay_serialize_empty_returns_empty_array() {
        // Real device output when no overlays exist: `{  "overlays": [
        //   ]}`
        let payload = "{  \"overlays\": [\n  ]}";
        let frame = MockPort::ok_with_stdout(payload);
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port).unwrap();
        let overlays = result["overlays"].as_array().unwrap();
        assert!(overlays.is_empty());
    }

    #[test]
    fn overlay_serialize_warns_at_cap() {
        // 7 overlays → should set warning. Use outer-brace-wrapped fragment shape.
        let overlay_entries = (0..7)
            .map(|i| {
                format!(r#"{{"name":"o{i}","row":0,"col":0,"width":1,"height":1,"colors":[]}}"#)
            })
            .collect::<Vec<_>>()
            .join(",");
        let payload = format!("{{  \"overlays\": [{overlay_entries}\n  ]}}");
        let frame = MockPort::ok_with_stdout(&payload);
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port).unwrap();
        assert!(
            result.get("warning").and_then(|v| v.as_str()).is_some(),
            "should warn when count >= 7"
        );
    }

    #[test]
    fn overlay_serialize_truncated_returns_err() {
        // Post-fix contract (CRITICAL finding from SF-hunter 2026-05-12): truncated
        // device output is a PROTOCOL ERROR, not a silent {raw, parse_error} Ok.
        // Previously this absorbed the parse failure into an Ok response, making
        // 4096-byte buffer truncations indistinguishable from valid empty state to
        // downstream consumers (including the get_state synthesizer's overlay fold).
        let frame = MockPort::ok_with_stdout("not-valid-json");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port);
        assert!(result.is_err(), "truncated/non-JSON output must Err");
        match result.unwrap_err() {
            McpError::Protocol(msg) => assert!(
                msg.contains("non-JSON") || msg.contains("truncation"),
                "error must mention non-JSON/truncation; got: {msg}"
            ),
            other => panic!("expected Protocol err, got: {other:?}"),
        }
    }

    #[test]
    fn overlay_serialize_firmware_fragment_shape_regression() {
        // Regression: verify the handler handles the EXACT firmware fragment shape.
        // Before R1 fix, `json.dumps(overlay_serialize())` would have double-encoded
        // the string into a quoted blob that failed to parse as {"overlays":[...]}.
        // This test uses the raw fragment output (with outer braces added by the handler's
        // print statement) to confirm we parse correctly.
        let firmware_fragment = "  \"overlays\": [\n    {\"name\":\"bracket\",\"row\":0,\"col\":0,\"width\":2,\"height\":2,\"colors\":[\"FF0000\",\"00FF00\",\"0000FF\",\"FFFFFF\"]}\n  ]";
        // This is what `print('{' + overlay_serialize() + '}')` produces on device:
        let payload = format!("{{{firmware_fragment}}}");
        let frame = MockPort::ok_with_stdout(&payload);
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port).unwrap();
        let overlays = result["overlays"].as_array().unwrap();
        assert_eq!(overlays.len(), 1, "must parse firmware fragment correctly");
        assert_eq!(overlays[0]["name"], "bracket");
    }

    #[test]
    fn overlay_serialize_truncated_buffer_regression() {
        // Regression: 4096-byte static buffer can truncate large overlay sets.
        // Post-fix contract: truncated fragment → Err (NOT silent raw fallback).
        let truncated = "{  \"overlays\": [{\"name\":\"partial\",\"row\":0,\"col\":0,\"wid";
        let frame = MockPort::ok_with_stdout(truncated);
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port);
        assert!(
            result.is_err(),
            "truncated output must Err — not silently degrade"
        );
    }

    #[test]
    fn overlay_serialize_missing_overlays_key_returns_err() {
        // R2 fix (SF-hunter): valid JSON without an 'overlays' key is a schema
        // violation, not a soft fallback to []. Defends against firmware response
        // shape changes that would otherwise silently report empty state.
        let frame = MockPort::ok_with_stdout("{\"something_else\": []}");
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_serialize(&mut port);
        assert!(
            result.is_err(),
            "JSON missing 'overlays' key must Err — schema violation"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => assert!(
                msg.contains("missing 'overlays' key") || msg.contains("overlays"),
                "error must mention missing key; got: {msg}"
            ),
            other => panic!("expected Protocol err, got: {other:?}"),
        }
    }

    #[test]
    fn overlay_serialize_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: overlay_serialize");
        let mut port = MockPort::with_responses(&[&err]);
        let result = handle_overlay_serialize(&mut port);
        assert!(result.is_err(), "device exception must propagate as Err");
        // Ctrl-C (0x03) must have been written
        assert!(
            port.write_data.contains(&0x03),
            "Ctrl-C must be sent on error"
        );
    }

    // ── Handler: overlay_list ─────────────────────────────────────────────────
    //
    // Same mock shape note as overlay_serialize: use outer-brace-wrapped fragment.

    #[test]
    fn overlay_list_happy_path_returns_count_and_names() {
        let count_frame = MockPort::ok_with_stdout("2");
        // Real firmware fragment shape: outer braces added by print('{' + ... + '}')
        let payload = "{  \"overlays\": [\n    {\"name\":\"alpha\",\"row\":0,\"col\":0,\"width\":3,\"height\":2,\"colors\":[]},\n    {\"name\":\"beta\",\"row\":1,\"col\":1,\"width\":2,\"height\":2,\"colors\":[]}\n  ]}";
        let serialize_frame = MockPort::ok_with_stdout(payload);
        let mut port = MockPort::with_responses(&[&count_frame, &serialize_frame]);
        let result = handle_overlay_list(&mut port).unwrap();
        assert_eq!(result["count"], 2);
        let overlays = result["overlays"].as_array().unwrap();
        assert_eq!(overlays.len(), 2);
        assert_eq!(overlays[0]["name"], "alpha");
    }

    #[test]
    fn overlay_list_at_cap_sets_flag() {
        let count_frame = MockPort::ok_with_stdout("8");
        let overlay_entries = (0..8)
            .map(|i| {
                format!(r#"{{"name":"o{i}","row":0,"col":0,"width":1,"height":1,"colors":[]}}"#)
            })
            .collect::<Vec<_>>()
            .join(",");
        // Use outer-brace-wrapped fragment shape.
        let payload = format!("{{  \"overlays\": [{overlay_entries}\n  ]}}");
        let serialize_frame = MockPort::ok_with_stdout(&payload);
        let mut port = MockPort::with_responses(&[&count_frame, &serialize_frame]);
        let result = handle_overlay_list(&mut port).unwrap();
        assert_eq!(result["at_cap"], true);
    }

    // ── Handler: overlay_clear ────────────────────────────────────────────────

    #[test]
    fn overlay_clear_happy_path_found() {
        let frame = MockPort::ok_with_stdout("1");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"name": "my_overlay"});
        let result = handle_overlay_clear(&mut port, &args).unwrap();
        assert_eq!(result["removed"], true);
    }

    #[test]
    fn overlay_clear_not_found_returns_false() {
        let frame = MockPort::ok_with_stdout("0");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"name": "nonexistent"});
        let result = handle_overlay_clear(&mut port, &args).unwrap();
        assert_eq!(result["removed"], false);
    }

    #[test]
    fn overlay_clear_unexpected_response_returns_error() {
        // R7: anything other than "1"/"0"/"True"/"False" must be Err.
        let frame = MockPort::ok_with_stdout("maybe");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"name": "test"});
        let result = handle_overlay_clear(&mut port, &args);
        assert!(
            result.is_err(),
            "unexpected device response must return Err"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("unexpected"),
                    "error must describe unexpected value"
                );
                assert!(msg.contains("maybe"), "error must include actual value");
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn overlay_clear_accepts_true_as_found() {
        // R7: "True" (Python-style) must also be accepted as found=true.
        let frame = MockPort::ok_with_stdout("True");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"name": "my_overlay"});
        let result = handle_overlay_clear(&mut port, &args).unwrap();
        assert_eq!(result["removed"], true);
    }

    #[test]
    fn overlay_clear_accepts_false_as_not_found() {
        // R7: "False" (Python-style) must also be accepted as found=false.
        let frame = MockPort::ok_with_stdout("False");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"name": "nonexistent"});
        let result = handle_overlay_clear(&mut port, &args).unwrap();
        assert_eq!(result["removed"], false);
    }

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

    #[test]
    fn overlay_clear_empty_name_returns_error() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"name": ""});
        let result = handle_overlay_clear(&mut port, &args);
        assert!(result.is_err());
    }

    #[test]
    fn overlay_clear_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: overlay_clear");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"name": "test"});
        let result = handle_overlay_clear(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: overlay_clear_all ────────────────────────────────────────────

    #[test]
    fn overlay_clear_all_happy_path() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_overlay_clear_all(&mut port).unwrap();
        assert_eq!(result["cleared"], true);
    }

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