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
//! OLED ToolDefs: `oled_print`, `oled_clear`.
//!
//! ## Text escaping for `oled_print`
//!
//! User-supplied text is embedded in a Python single-quoted string literal:
//!
//! ```python
//! oled_print('Hello World', 2)
//! ```
//!
//! Escaping rules applied before emission:
//! - `\` → `\\`  (must happen first to avoid double-escaping)
//! - `'` → `\'`
//!
//! Rejection rules (pre-flight, before the device is contacted):
//! - Contains `\n` or `\r` — OLED doesn't render newlines and they break REPL framing.
//! - Contains `'''` — triple-quote sequence could confuse parsers.
//! - Longer than 64 characters — OLED is 128×32 px; at size=2 (default) the display
//!   can show at most ~64 characters across all lines.
//!
//! ## Size parameter
//!
//! `size` defaults to 2 and must be in the range 1–4 (firmware constraint).
//! Values outside that range are rejected pre-flight.

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

use crate::library::exec_with_cleanup;

// ── Text validation + escaping ────────────────────────────────────────────────

const OLED_MAX_LEN: usize = 64;

/// Validate and escape `text` for embedding in a Python single-quoted string.
///
/// Returns the escaped string on success, or a descriptive `McpError::Protocol`
/// on any rejection condition.
fn escape_oled_text(text: &str) -> Result<String, McpError> {
    if text.len() > OLED_MAX_LEN {
        return Err(McpError::Protocol(format!(
            "oled_print: text too long ({} chars, max {OLED_MAX_LEN})",
            text.len()
        )));
    }

    // Reject newlines — OLED doesn't render them; they would break the REPL framing.
    if text.contains('\n') || text.contains('\r') {
        return Err(McpError::Protocol(
            "oled_print: text must not contain newline characters (\\n or \\r)".into(),
        ));
    }

    // Reject triple-quote sequences as a safety measure.
    if text.contains("'''") || text.contains("\"\"\"") {
        return Err(McpError::Protocol(
            "oled_print: text must not contain triple-quote sequences (''' or \"\"\")".into(),
        ));
    }

    // Escape: backslash first (to avoid double-escaping), then single-quote.
    let escaped = text.replace('\\', "\\\\").replace('\'', "\\'");
    Ok(escaped)
}

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

/// Build the `oled_print` [`ToolDescriptor`].
pub fn oled_print_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "oled_print",
        "Display text on the Jumperless V5 OLED screen (128×32 px). \
         'size' controls the font scale: 1=smallest, 4=largest, default=2. \
         Text is limited to 64 characters (the maximum displayable at size=2). \
         Newlines and triple-quote sequences are not allowed. \
         Call oled_clear first if you want to overwrite the previous content. \
         Returns {\"printed\": true, \"text\": <as-passed>}.",
        json!({
            "type": "object",
            "properties": {
                "text": {
                    "type": "string",
                    "maxLength": 64,
                    "description": "Text to display. No newlines. Max 64 characters."
                },
                "size": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 4,
                    "description": "Font size scale 1-4 (default 2)"
                }
            },
            "required": ["text"],
            "additionalProperties": false
        }),
        1_500,
    )
}

/// Build the `oled_clear` [`ToolDescriptor`].
pub fn oled_clear_descriptor() -> ToolDescriptor {
    ToolDescriptor::with_timeout(
        "oled_clear",
        "Clear the Jumperless V5 OLED display. Returns {\"cleared\": true}.",
        json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        }),
        1_000,
    )
}

/// Return both OLED ToolDescriptors.
pub fn descriptors() -> Vec<ToolDescriptor> {
    vec![oled_print_descriptor(), oled_clear_descriptor()]
}

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

/// Execute `oled_print(text, size)` and return `{"printed": true, "text": <as-passed>}`.
pub fn handle_oled_print<P: Read + Write + ?Sized>(
    port: &mut P,
    args: &Value,
) -> Result<Value, McpError> {
    let text = args
        .get("text")
        .and_then(|v| v.as_str())
        .ok_or_else(|| McpError::Protocol("oled_print requires 'text' (string)".into()))?;

    // Validate and escape before touching the device.
    let escaped = escape_oled_text(text)?;

    // size: default 2, validate range 1-4.
    let size = match args.get("size") {
        Some(v) => {
            let n = v.as_i64().ok_or_else(|| {
                McpError::Protocol("oled_print: 'size' must be an integer".into())
            })?;
            if !(1..=4).contains(&n) {
                return Err(McpError::Protocol(format!(
                    "oled_print: size must be 1-4; got {n}"
                )));
            }
            n
        }
        None => 2,
    };

    let code = format!("oled_print('{escaped}', {size})");
    exec_with_cleanup(port, &code, "oled_print")?;

    Ok(json!({
        "printed": true,
        "text": text
    }))
}

/// Execute `oled_clear()` and return `{"cleared": true}`.
pub fn handle_oled_clear<P: Read + Write + ?Sized>(port: &mut P) -> Result<Value, McpError> {
    exec_with_cleanup(port, "oled_clear()", "oled_clear")?;
    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 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(())
        }
    }

    // ── Text escaping unit tests ──────────────────────────────────────────────

    #[test]
    fn escape_plain_text_unchanged() {
        assert_eq!(escape_oled_text("Hello World").unwrap(), "Hello World");
    }

    #[test]
    fn escape_backslash_doubled() {
        assert_eq!(escape_oled_text("a\\b").unwrap(), "a\\\\b");
    }

    #[test]
    fn escape_single_quote_escaped() {
        assert_eq!(escape_oled_text("it's").unwrap(), "it\\'s");
    }

    #[test]
    fn escape_backslash_then_quote_both_escaped() {
        // Input: \'  → output: \\'  (backslash doubled first, then quote)
        assert_eq!(escape_oled_text("\\'").unwrap(), "\\\\\\'");
    }

    #[test]
    fn escape_text_too_long_rejected() {
        let long = "A".repeat(65);
        assert!(escape_oled_text(&long).is_err());
    }

    #[test]
    fn escape_exactly_64_chars_accepted() {
        let exactly_64 = "A".repeat(64);
        assert!(escape_oled_text(&exactly_64).is_ok());
    }

    #[test]
    fn escape_newline_rejected() {
        assert!(escape_oled_text("line1\nline2").is_err());
    }

    #[test]
    fn escape_carriage_return_rejected() {
        assert!(escape_oled_text("line\r").is_err());
    }

    #[test]
    fn escape_triple_single_quote_rejected() {
        assert!(escape_oled_text("'''").is_err());
    }

    #[test]
    fn escape_triple_double_quote_rejected() {
        assert!(escape_oled_text("\"\"\"").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(&"oled_print"));
        assert!(names.contains(&"oled_clear"));
        assert_eq!(descs.len(), 2);
    }

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

    // ── Handler: oled_print ───────────────────────────────────────────────────

    #[test]
    fn oled_print_happy_path_default_size() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"text": "Hello"});
        let result = handle_oled_print(&mut port, &args).unwrap();
        assert_eq!(result["printed"], true);
        assert_eq!(result["text"], "Hello");
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("oled_print('Hello', 2)"), "cmd was: {cmd}");
    }

    #[test]
    fn oled_print_explicit_size_1() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"text": "Big", "size": 1});
        let result = handle_oled_print(&mut port, &args).unwrap();
        assert_eq!(result["printed"], true);
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("oled_print('Big', 1)"), "cmd was: {cmd}");
    }

    #[test]
    fn oled_print_explicit_size_4() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"text": "X", "size": 4});
        let result = handle_oled_print(&mut port, &args).unwrap();
        assert_eq!(result["printed"], true);
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("oled_print('X', 4)"), "cmd was: {cmd}");
    }

    #[test]
    fn oled_print_size_0_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"text": "Hi", "size": 0});
        assert!(handle_oled_print(&mut port, &args).is_err());
    }

    #[test]
    fn oled_print_size_5_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"text": "Hi", "size": 5});
        assert!(handle_oled_print(&mut port, &args).is_err());
    }

    #[test]
    fn oled_print_text_with_newline_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let args = json!({"text": "line1\nline2"});
        assert!(handle_oled_print(&mut port, &args).is_err());
    }

    #[test]
    fn oled_print_text_too_long_rejected() {
        let mut port = MockPort::with_responses(&[]);
        let long = "A".repeat(65);
        let args = json!({"text": long});
        assert!(handle_oled_print(&mut port, &args).is_err());
    }

    #[test]
    fn oled_print_text_with_single_quote_escaped_in_command() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"text": "it's"});
        let result = handle_oled_print(&mut port, &args).unwrap();
        // Returned text is the original, unescaped form.
        assert_eq!(result["text"], "it's");
        // Command sent to device uses escaped form.
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(
            cmd.contains("oled_print('it\\'s', 2)"),
            "cmd must have escaped quote; cmd was: {cmd}"
        );
    }

    #[test]
    fn oled_print_text_with_backslash_escaped_in_command() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let args = json!({"text": "a\\b"});
        let result = handle_oled_print(&mut port, &args).unwrap();
        assert_eq!(result["text"], "a\\b");
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(
            cmd.contains("oled_print('a\\\\b', 2)"),
            "cmd must have doubled backslash; cmd was: {cmd}"
        );
    }

    #[test]
    fn oled_print_device_error_sends_ctrl_c() {
        let err = MockPort::error_frame("NameError: oled_print");
        let mut port = MockPort::with_responses(&[&err]);
        let args = json!({"text": "Hi"});
        let result = handle_oled_print(&mut port, &args);
        assert!(result.is_err());
        assert!(port.write_data.contains(&0x03));
    }

    // ── Handler: oled_clear ───────────────────────────────────────────────────

    #[test]
    fn oled_clear_happy_path() {
        let frame = MockPort::ok_frame();
        let mut port = MockPort::with_responses(&[&frame]);
        let result = handle_oled_clear(&mut port).unwrap();
        assert_eq!(result["cleared"], true);
        let cmd = String::from_utf8_lossy(&port.write_data);
        assert!(cmd.contains("oled_clear()"), "cmd was: {cmd}");
    }

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