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
//! GPIO ToolDefs: `gpio_set`, `gpio_get`, `gpio_set_dir`.
//!
//! ## Pin identifier encoding
//!
//! The firmware accepts two forms:
//! - **Bare int** `1`–`8` → passed as a raw integer literal (`gpio_set(3, True)`).
//! - **Named constant** — `"GPIO_1"`–`"GPIO_8"`, `"UART_TX"`, `"UART_RX"`,
//!   `"D0"`–`"D13"`, `"A0"`–`"A7"` — passed as a bare identifier, not a quoted
//!   string (`gpio_set(D5, True)`).  These are module-level MicroPython constants.
//!
//! Any other string is rejected pre-flight (must be alphanumeric + underscore,
//! max 16 chars) to prevent code injection.
//!
//! ## GPIO device responses
//!
//! - `gpio_get(pin)` returns one of exactly `"HIGH"`, `"LOW"`, or `"FLOATING"`.
//!   Any other response → `Err(McpError::Protocol)`.
//! - `gpio_set(pin, value)` and `gpio_set_dir(pin, dir)` produce no meaningful
//!   stdout; we execute and ignore the output.

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

use crate::library::exec_with_cleanup;

// ── Pin encoding ──────────────────────────────────────────────────────────────

/// Whitelist of valid GPIO/UART/Arduino pin string identifiers.
///
/// Defense-in-depth pattern matching analog.rs::DAC_STRING_CHANNELS and
/// wavegen.rs::WAVEGEN_STRING_CHANNELS. Without this whitelist, shape validation
/// alone would let arbitrary firmware-internal identifiers (`os`, `__import__`,
/// etc.) through as bare Python expressions. Code-reviewer flagged CRITICAL
/// 2026-05-12.
const PIN_STRING_IDENTIFIERS: &[&str] = &[
    "GPIO_1", "GPIO_2", "GPIO_3", "GPIO_4", "GPIO_5", "GPIO_6", "GPIO_7", "GPIO_8", "UART_TX",
    "UART_RX", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "D11", "D12",
    "D13", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7",
];

/// Encode a JSON pin value (`int` or `string`) into a Python expression fragment.
///
/// - `Value::Number` integer 1–8 → `"3"` (bare int literal).
/// - `Value::String` matching `PIN_STRING_IDENTIFIERS` → bare identifier emit.
/// - Anything else → `Err` (shape AND whitelist both enforced).
fn encode_pin(pin: &Value) -> Result<String, McpError> {
    match pin {
        Value::Number(n) => {
            let i = n.as_i64().ok_or_else(|| {
                McpError::Protocol("pin must be an integer 1-8 or a string identifier".into())
            })?;
            if !(1..=8).contains(&i) {
                return Err(McpError::Protocol(format!(
                    "pin integer must be 1-8; got {i}"
                )));
            }
            Ok(i.to_string())
        }
        Value::String(s) => {
            if s.is_empty() {
                return Err(McpError::Protocol("pin string must not be empty".into()));
            }
            if s.len() > 16 {
                return Err(McpError::Protocol(format!(
                    "pin identifier too long (max 16 chars): '{s}'"
                )));
            }
            // Shape filter first — protects against any non-ASCII identifier characters
            // before we hit the whitelist check (cheap rejection of obvious garbage).
            if !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
                return Err(McpError::Protocol(format!(
                    "pin identifier contains invalid characters (must be alphanumeric + '_'): '{s}'"
                )));
            }
            // Whitelist check — defense in depth. Only documented pin names are accepted.
            if !PIN_STRING_IDENTIFIERS.contains(&s.as_str()) {
                return Err(McpError::Protocol(format!(
                    "unknown pin identifier '{s}'; valid: GPIO_1-GPIO_8, UART_TX, UART_RX, D0-D13, A0-A7"
                )));
            }
            // Emit as bare identifier — firmware resolves it as a module-level constant.
            Ok(s.clone())
        }
        _ => Err(McpError::Protocol(
            "pin must be an integer 1-8 or a string identifier".into(),
        )),
    }
}

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

/// Pin schema shared across gpio_set, gpio_get, gpio_set_dir.
fn pin_schema() -> Value {
    json!({
        "oneOf": [
            {
                "type": "integer",
                "minimum": 1,
                "maximum": 8,
                "description": "GPIO pin number 1-8"
            },
            {
                "type": "string",
                "description": "Named GPIO constant: GPIO_1-GPIO_8, UART_TX, UART_RX, D0-D13, A0-A7"
            }
        ]
    })
}

/// Build the `gpio_set` [`ToolDescriptor`].
pub fn gpio_set_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "gpio_set",
        "Set a Jumperless V5 digital GPIO pin HIGH (3.3 V) or LOW (0 V). \
         Pin must first be configured as OUTPUT via gpio_set_dir. \
         Pin can be an integer 1-8 or a named constant (GPIO_1-GPIO_8, UART_TX, UART_RX, D0-D13, A0-A7). \
         Returns {\"set\": true, \"pin\": <as-passed>, \"value\": bool}.",
        json!({
            "type": "object",
            "properties": {
                "pin": pin_schema(),
                "value": {
                    "type": "boolean",
                    "description": "true = 3.3 V (HIGH), false = 0 V (LOW)"
                }
            },
            "required": ["pin", "value"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Build the `gpio_get` [`ToolDescriptor`].
pub fn gpio_get_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "gpio_get",
        "Read the current level of a Jumperless V5 GPIO pin. \
         Returns {\"value\": \"HIGH\" | \"LOW\" | \"FLOATING\", \"pin\": <as-passed>}. \
         FLOATING is reported when the pin is INPUT with no driver. \
         Pin can be an integer 1-8 or a named constant (GPIO_1-GPIO_8, UART_TX, UART_RX, D0-D13, A0-A7).",
        json!({
            "type": "object",
            "properties": {
                "pin": pin_schema()
            },
            "required": ["pin"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Build the `gpio_set_dir` [`ToolDescriptor`].
pub fn gpio_set_dir_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "gpio_set_dir",
        "Set the direction of a Jumperless V5 GPIO pin. \
         \"OUTPUT\" drives the pin; \"INPUT\" puts it in high-impedance input mode. \
         Pin can be an integer 1-8 or a named constant (GPIO_1-GPIO_8, UART_TX, UART_RX, D0-D13, A0-A7). \
         Returns {\"set\": true, \"pin\": <as-passed>, \"direction\": <as-passed>}.",
        json!({
            "type": "object",
            "properties": {
                "pin": pin_schema(),
                "direction": {
                    "type": "string",
                    "enum": ["OUTPUT", "INPUT"],
                    "description": "\"OUTPUT\" = drive pin; \"INPUT\" = high-impedance"
                }
            },
            "required": ["pin", "direction"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Return all three GPIO ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![
        gpio_set_descriptor(),
        gpio_get_descriptor(),
        gpio_set_dir_descriptor(),
    ]
}

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

/// Execute `gpio_set(pin, value)`.
///
/// Returns `{"set": true, "pin": <as-passed>, "value": <bool>}`.
pub fn handle_gpio_set<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let pin_raw = args
        .get("pin")
        .ok_or_else(|| McpError::Protocol("gpio_set requires 'pin'".into()))?;
    let pin_expr = encode_pin(pin_raw)?;

    let value = args
        .get("value")
        .and_then(|v| v.as_bool())
        .ok_or_else(|| McpError::Protocol("gpio_set requires 'value' (bool)".into()))?;

    let py_bool = if value { "True" } else { "False" };
    let code = format!("gpio_set({pin_expr}, {py_bool})");
    exec_with_cleanup(port, &code, "gpio_set")?;

    Ok(json!({
        "set": true,
        "pin": pin_raw,
        "value": value
    }))
}

/// Execute `gpio_get(pin)` and return `{"value": "HIGH"|"LOW"|"FLOATING", "pin": <as-passed>}`.
///
/// Validates strictly — any response other than `"HIGH"`, `"LOW"`, or `"FLOATING"`
/// returns `Err(McpError::Protocol)`.
pub fn handle_gpio_get<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let pin_raw = args
        .get("pin")
        .ok_or_else(|| McpError::Protocol("gpio_get requires 'pin'".into()))?;
    let pin_expr = encode_pin(pin_raw)?;

    let code = format!("print(gpio_get({pin_expr}))");
    let resp = exec_with_cleanup(port, &code, "gpio_get")?;
    let trimmed = resp.stdout.trim();

    let level = match trimmed {
        "HIGH" | "LOW" | "FLOATING" => trimmed,
        other => {
            return Err(McpError::Protocol(format!(
                "gpio_get: unexpected device response: '{other}'"
            )));
        }
    };

    Ok(json!({
        "value": level,
        "pin": pin_raw
    }))
}

/// Execute `gpio_set_dir(pin, direction)`.
///
/// Translates `"OUTPUT"` → `True`, `"INPUT"` → `False`. Any other direction
/// value is rejected before the device is contacted.
///
/// Returns `{"set": true, "pin": <as-passed>, "direction": <as-passed>}`.
pub fn handle_gpio_set_dir<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let pin_raw = args
        .get("pin")
        .ok_or_else(|| McpError::Protocol("gpio_set_dir requires 'pin'".into()))?;
    let pin_expr = encode_pin(pin_raw)?;

    let direction = args
        .get("direction")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("gpio_set_dir requires 'direction' (string)".into()))?;

    let py_bool = match direction {
        "OUTPUT" => "True",
        "INPUT" => "False",
        other => {
            return Err(McpError::Protocol(format!(
                "gpio_set_dir: direction must be \"OUTPUT\" or \"INPUT\"; got \"{other}\""
            )));
        }
    };

    let code = format!("gpio_set_dir({pin_expr}, {py_bool})");
    exec_with_cleanup(port, &code, "gpio_set_dir")?;

    Ok(json!({
        "set": true,
        "pin": pin_raw,
        "direction": direction
    }))
}

// ── 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(&"gpio_set"));
        assert!(names.contains(&"gpio_get"));
        assert!(names.contains(&"gpio_set_dir"));
        assert_eq!(descs.len(), 3);
    }

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

    // ── encode_pin ────────────────────────────────────────────────────────────

    #[test]
    fn encode_pin_int_roundtrip() {
        assert_eq!(encode_pin(&json!(3)).unwrap(), "3");
        assert_eq!(encode_pin(&json!(1)).unwrap(), "1");
        assert_eq!(encode_pin(&json!(8)).unwrap(), "8");
    }

    #[test]
    fn encode_pin_int_out_of_range_rejected() {
        assert!(encode_pin(&json!(0)).is_err());
        assert!(encode_pin(&json!(9)).is_err());
        assert!(encode_pin(&json!(-1)).is_err());
    }

    #[test]
    fn encode_pin_string_identifier_roundtrip() {
        assert_eq!(encode_pin(&json!("GPIO_1")).unwrap(), "GPIO_1");
        assert_eq!(encode_pin(&json!("UART_TX")).unwrap(), "UART_TX");
        assert_eq!(encode_pin(&json!("D13")).unwrap(), "D13");
        assert_eq!(encode_pin(&json!("A7")).unwrap(), "A7");
    }

    #[test]
    fn encode_pin_string_too_long_rejected() {
        // 17 chars — exceeds max 16
        let long = "A".repeat(17);
        assert!(encode_pin(&Value::String(long)).is_err());
    }

    #[test]
    fn encode_pin_string_injection_rejected() {
        // Single quote — would escape into Python string context
        assert!(encode_pin(&json!("GPIO'1")).is_err());
        // Semicolon
        assert!(encode_pin(&json!("GPIO;DROP")).is_err());
        // Space
        assert!(encode_pin(&json!("GPIO 1")).is_err());
    }

    #[test]
    fn encode_pin_empty_string_rejected() {
        assert!(encode_pin(&json!("")).is_err());
    }

    #[test]
    fn encode_pin_non_whitelisted_identifier_rejected() {
        // Post-fix (CRITICAL from code-reviewer 2026-05-12): shape-only validation
        // is not enough — encode_pin must whitelist against PIN_STRING_IDENTIFIERS.
        // Shape-valid but not-a-real-pin identifiers must Err.
        for bad in &[
            "os",
            "exec",
            "__import__",
            "print",
            "open",
            "eval",
            "GPIO_9",
            "D14",
            "A8",
        ] {
            let result = encode_pin(&json!(bad));
            assert!(
                result.is_err(),
                "non-whitelisted identifier '{bad}' must be rejected (shape-valid but not a real pin)"
            );
            match result.unwrap_err() {
                McpError::Protocol(msg) => assert!(
                    msg.contains("unknown pin"),
                    "error must say 'unknown pin'; got: {msg}"
                ),
                other => panic!("expected Protocol err, got: {other:?}"),
            }
        }
    }

    #[test]
    fn encode_pin_whitelisted_identifiers_accepted() {
        // Spot-check the whitelist boundaries.
        for ok in &[
            "GPIO_1", "GPIO_8", "UART_TX", "UART_RX", "D0", "D13", "A0", "A7",
        ] {
            assert!(
                encode_pin(&json!(ok)).is_ok(),
                "whitelisted identifier '{ok}' must be accepted"
            );
        }
    }

    // ── Handler: gpio_set ─────────────────────────────────────────────────────

    #[test]
    fn gpio_set_high_int_pin() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 3, "value": true});
        let result = handle_gpio_set(&mut port, &args).unwrap();
        assert_eq!(result["set"], true);
        assert_eq!(result["value"], true);
        // Verify command sent to device
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("gpio_set(3, True)"), "cmd was: {cmd}");
    }

    #[test]
    fn gpio_set_low_string_pin() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": "D5", "value": false});
        let result = handle_gpio_set(&mut port, &args).unwrap();
        assert_eq!(result["set"], true);
        assert_eq!(result["value"], false);
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("gpio_set(D5, False)"), "cmd was: {cmd}");
    }

    #[test]
    fn gpio_set_invalid_pin_int_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"pin": 99, "value": true});
        assert!(handle_gpio_set(&mut port, &args).is_err());
    }

    #[test]
    fn gpio_set_invalid_pin_string_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"pin": "bad'pin", "value": true});
        assert!(handle_gpio_set(&mut port, &args).is_err());
    }

    #[test]
    fn gpio_set_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: gpio_set");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"pin": 1, "value": true});
        let result = handle_gpio_set(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: gpio_get ─────────────────────────────────────────────────────

    #[test]
    fn gpio_get_high_response() {
        let frame = MockPort::ok_with_stdout("HIGH");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 2});
        let result = handle_gpio_get(&mut port, &args).unwrap();
        assert_eq!(result["value"], "HIGH");
        assert_eq!(result["pin"], 2);
    }

    #[test]
    fn gpio_get_low_response() {
        let frame = MockPort::ok_with_stdout("LOW");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": "GPIO_3"});
        let result = handle_gpio_get(&mut port, &args).unwrap();
        assert_eq!(result["value"], "LOW");
        assert_eq!(result["pin"], "GPIO_3");
    }

    #[test]
    fn gpio_get_floating_response() {
        let frame = MockPort::ok_with_stdout("FLOATING");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 7});
        let result = handle_gpio_get(&mut port, &args).unwrap();
        assert_eq!(result["value"], "FLOATING");
    }

    #[test]
    fn gpio_get_unexpected_response_returns_err() {
        // Anything not HIGH/LOW/FLOATING must be an Err, not a silent coercion.
        let frame = MockPort::ok_with_stdout("UNKNOWN");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 1});
        let result = handle_gpio_get(&mut port, &args);
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(msg.contains("unexpected"), "error must say 'unexpected'");
                assert!(
                    msg.contains("UNKNOWN"),
                    "error must include the actual response"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn gpio_get_empty_response_returns_err() {
        let frame = MockPort::ok_with_stdout("");
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 1});
        assert!(handle_gpio_get(&mut port, &args).is_err());
    }

    #[test]
    fn gpio_get_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: gpio_get");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"pin": 1});
        let result = handle_gpio_get(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: gpio_set_dir ─────────────────────────────────────────────────

    #[test]
    fn gpio_set_dir_output() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": 4, "direction": "OUTPUT"});
        let result = handle_gpio_set_dir(&mut port, &args).unwrap();
        assert_eq!(result["set"], true);
        assert_eq!(result["direction"], "OUTPUT");
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("gpio_set_dir(4, True)"), "cmd was: {cmd}");
    }

    #[test]
    fn gpio_set_dir_input() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"pin": "UART_RX", "direction": "INPUT"});
        let result = handle_gpio_set_dir(&mut port, &args).unwrap();
        assert_eq!(result["set"], true);
        assert_eq!(result["direction"], "INPUT");
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(
            cmd.contains("gpio_set_dir(UART_RX, False)"),
            "cmd was: {cmd}"
        );
    }

    #[test]
    fn gpio_set_dir_invalid_direction_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"pin": 1, "direction": "TRISTATE"});
        let result = handle_gpio_set_dir(&mut port, &args);
        assert!(result.is_err());
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("TRISTATE"),
                    "error must include the bad value; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    #[test]
    fn gpio_set_dir_lowercase_direction_rejected() {
        // "output" (lowercase) must not be silently accepted — must match exact case.
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"pin": 1, "direction": "output"});
        assert!(handle_gpio_set_dir(&mut port, &args).is_err());
    }

    #[test]
    fn gpio_set_dir_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: gpio_set_dir");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"pin": 1, "direction": "OUTPUT"});
        let result = handle_gpio_set_dir(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }
}