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
//! USB device discovery helpers.
//!
//! Reusable across all USB-based subsystem MCPs. Provides three public
//! discovery functions, each backed by a private pure helper for testability.

use crate::base::errors::DiscoveryError;
use serialport::{SerialPortInfo, SerialPortType};

/// USB Vendor ID + Product ID pair.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VidPid(pub u16, pub u16);

// ── Private pure helpers (testable without touching the host USB stack) ───────

/// Filter `ports` to those matching `target` VID:PID, then return the entry at
/// `port_index` after sorting by `interface` ascending.
///
/// Sorting rule: ports with `interface: Some(n)` sort by `n` ascending.
/// Ports with `interface: None` sort last. (Note: Rust's `Option<T: Ord>`
/// default puts `None < Some(_)`, so we use a custom `(is_none, interface)`
/// key to achieve None-last ordering.) In practice, composite CDC devices
/// always populate `interface`; None-last ensures they don't silently claim
/// an index that an interface-numbered port would otherwise occupy.
///
/// This is the pure core extracted from `discover_composite_port_by_index` so
/// tests can inject synthetic `SerialPortInfo` values without hitting the OS.
fn select_composite_port(
    ports: Vec<SerialPortInfo>,
    target: VidPid,
    port_index: usize,
) -> Result<SerialPortInfo, DiscoveryError> {
    let mut matched: Vec<SerialPortInfo> = ports
        .into_iter()
        .filter(|p| match &p.port_type {
            SerialPortType::UsbPort(info) => info.vid == target.0 && info.pid == target.1,
            _ => false,
        })
        .collect();

    // Sort by interface number ascending; None sorts last.
    //
    // Rust's Option<T: Ord> orders None < Some(_), so a naive sort_by_key on
    // interface would put None-interface ports first. We want None last, because
    // an interface-less entry on a composite device is anomalous and should not
    // claim an index that a numbered interface would otherwise occupy.
    //
    // Key: (is_none, interface) — false < true, so Some(_) entries sort before
    // None entries; within the Some(_) group they sort by interface value ascending.
    matched.sort_by_key(|p| match &p.port_type {
        SerialPortType::UsbPort(info) => (info.interface.is_none(), info.interface),
        _ => (true, None),
    });

    if matched.is_empty() {
        return Err(DiscoveryError::NotFound {
            message: format!(
                "no device found with VID {:04x}:PID {:04x}. Is the device plugged in?",
                target.0, target.1
            ),
        });
    }

    if port_index >= matched.len() {
        return Err(DiscoveryError::IndexOutOfRange {
            requested: port_index,
            found: matched.len(),
            vid: target.0,
            pid: target.1,
        });
    }

    Ok(matched.remove(port_index))
}

/// Pure core for `discover_by_vid_pid`: filter a pre-enumerated list.
///
/// Separated from the public function so tests can inject synthetic ports.
fn filter_by_vid_pid(
    ports: Vec<SerialPortInfo>,
    target: VidPid,
) -> Result<SerialPortInfo, DiscoveryError> {
    let mut matched: Vec<SerialPortInfo> = ports
        .into_iter()
        .filter(|p| match &p.port_type {
            SerialPortType::UsbPort(info) => info.vid == target.0 && info.pid == target.1,
            _ => false,
        })
        .collect();

    match matched.len() {
        0 => Err(DiscoveryError::NotFound {
            message: format!(
                "no device found with VID {:04x}:PID {:04x}. Is the device plugged in?",
                target.0, target.1
            ),
        }),
        1 => Ok(matched.remove(0)),
        n => Err(DiscoveryError::Ambiguous {
            count: n,
            hint: "use discover_composite_port_by_index(vid_pid, index) to select \
                   a specific port on a composite device, or --port to override"
                .to_string(),
        }),
    }
}

/// Pure core for `discover_by_name_pattern`: case-insensitive substring match
/// on `product` field of USB ports. Non-USB ports are filtered out.
///
/// Separated from the public function so tests can inject synthetic ports
/// without hitting the OS (same pattern as `select_composite_port` and
/// `filter_by_vid_pid`).
fn filter_by_name_pattern(ports: Vec<SerialPortInfo>, pattern: &str) -> Vec<SerialPortInfo> {
    let pattern_lower = pattern.to_ascii_lowercase();
    ports
        .into_iter()
        .filter(|p| match &p.port_type {
            SerialPortType::UsbPort(info) => info
                .product
                .as_deref()
                .map(|prod| prod.to_ascii_lowercase().contains(&pattern_lower))
                .unwrap_or(false),
            _ => false,
        })
        .collect()
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Discover a single device by exact VID:PID match.
///
/// Returns `Err(DiscoveryError::NotFound)` if no device matches.
/// Returns `Err(DiscoveryError::Ambiguous)` if multiple devices match (e.g.,
/// two identical devices attached, or a composite device exposing multiple
/// ports — use [`discover_composite_port_by_index`] in that case).
pub fn discover_by_vid_pid(target: VidPid) -> Result<SerialPortInfo, DiscoveryError> {
    let ports = serialport::available_ports()?;
    filter_by_vid_pid(ports, target)
}

/// Discover devices whose USB product name contains `pattern`.
///
/// `pattern` is matched as a case-insensitive substring of the port's `product`
/// field. Returns all matching ports (empty vec is a valid result — caller
/// decides how to handle no-match).
///
/// Prefer [`discover_by_vid_pid`] when you have the exact VID:PID; this
/// function is for cases where only the product name string is known.
///
/// Returns `Err(DiscoveryError::Serial)` if the OS port enumeration itself fails.
pub fn discover_by_name_pattern(pattern: &str) -> Result<Vec<SerialPortInfo>, DiscoveryError> {
    let ports = serialport::available_ports()?;
    Ok(filter_by_name_pattern(ports, pattern))
}

/// Discover a specific port on a composite USB device by interface index.
///
/// Composite devices (like the Jumperless V5) expose multiple CDC serial ports
/// from a single VID:PID. This function selects the one at `port_index` after
/// sorting all matching ports by their USB `interface` field ascending.
///
/// **Sorting rule:** ports are sorted by `interface: Option<u8>` ascending,
/// with `None` last. (Rust's default `Option<T: Ord>` puts `None < Some(_)`,
/// so a custom key is used to achieve None-last ordering.) Composite CDC
/// devices always populate `interface`; `None`-last prevents interface-less
/// anomalies from displacing numbered entries.
///
/// # Example — Jumperless V5
///
/// ```text
/// port_index=0 → MI_00 "JLV5port1" (main Python terminal)
/// port_index=1 → MI_02 "JLV5port3" (Arduino UART passthrough)
/// port_index=2 → MI_04 "JLV5port5" (MicroPython Raw REPL ← target)
/// port_index=3 → MI_06 (debug serial)
/// ```
pub fn discover_composite_port_by_index(
    target: VidPid,
    port_index: usize,
) -> Result<SerialPortInfo, DiscoveryError> {
    let ports = serialport::available_ports()?;
    select_composite_port(ports, target, port_index)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serialport::{SerialPortInfo, SerialPortType, UsbPortInfo};

    /// Build a synthetic USB SerialPortInfo for testing without hardware.
    fn make_usb_port(name: &str, vid: u16, pid: u16, interface: Option<u8>) -> SerialPortInfo {
        SerialPortInfo {
            port_name: name.to_string(),
            port_type: SerialPortType::UsbPort(UsbPortInfo {
                vid,
                pid,
                serial_number: None,
                manufacturer: None,
                product: None,
                interface,
            }),
        }
    }

    /// Build a synthetic USB port with a product string.
    fn make_usb_port_named(
        name: &str,
        vid: u16,
        pid: u16,
        product: &str,
        interface: Option<u8>,
    ) -> SerialPortInfo {
        SerialPortInfo {
            port_name: name.to_string(),
            port_type: SerialPortType::UsbPort(UsbPortInfo {
                vid,
                pid,
                serial_number: None,
                manufacturer: None,
                product: Some(product.to_string()),
                interface,
            }),
        }
    }

    /// Build a non-USB (e.g., Bluetooth/PCI) port for negative testing.
    fn make_non_usb_port(name: &str) -> SerialPortInfo {
        SerialPortInfo {
            port_name: name.to_string(),
            port_type: SerialPortType::BluetoothPort,
        }
    }

    // ── select_composite_port tests ───────────────────────────────────────────

    /// Jumperless V5 scenario: 4 CDC ports with interfaces 0, 2, 4, 6.
    /// port_index=2 (the Raw REPL, MI_04) should be returned.
    #[test]
    fn select_composite_port_picks_correct_index() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![
            make_usb_port("COM5", 0x1d50, 0xacab, Some(0)), // MI_00 — main Python
            make_usb_port("COM6", 0x1d50, 0xacab, Some(2)), // MI_02 — Arduino UART
            make_usb_port("COM7", 0x1d50, 0xacab, Some(4)), // MI_04 — Raw REPL
            make_usb_port("COM8", 0x1d50, 0xacab, Some(6)), // MI_06 — debug
        ];
        let result = select_composite_port(ports, target, 2).unwrap();
        assert_eq!(result.port_name, "COM7");
    }

    /// Mixing matched and unmatched VID:PID — only matched ports are considered.
    #[test]
    fn select_composite_port_filters_by_vid_pid() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![
            make_usb_port("COM1", 0xdead, 0xbeef, Some(0)), // wrong device
            make_usb_port("COM2", 0x1d50, 0xacab, Some(0)), // match
            make_usb_port("COM3", 0x1d50, 0xacab, Some(2)), // match
            make_usb_port("COM4", 0x0403, 0x6001, Some(0)), // FTDI — wrong device
        ];
        // Only COM2 and COM3 match; index=1 should return COM3.
        let result = select_composite_port(ports, target, 1).unwrap();
        assert_eq!(result.port_name, "COM3");
    }

    /// No ports match VID:PID → NotFound (empty match, distinct from IndexOutOfRange).
    #[test]
    fn select_composite_port_not_found_empty_match() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![
            make_usb_port("COM1", 0xdead, 0xbeef, Some(0)),
            make_usb_port("COM2", 0x0403, 0x6001, Some(0)),
        ];
        let err = select_composite_port(ports, target, 0).unwrap_err();
        // MEDIUM-c: when no device matches at all, we get NotFound (not IndexOutOfRange).
        assert!(
            matches!(err, DiscoveryError::NotFound { .. }),
            "no-match should be NotFound, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(msg.contains("1d50"), "message should mention VID: {msg}");
        assert!(msg.contains("acab"), "message should mention PID: {msg}");
    }

    /// 2 matches but port_index=5 → IndexOutOfRange (device found, index wrong).
    /// MEDIUM-c: this is now a distinct variant from NotFound so callers can
    /// distinguish "device not plugged in" from "wrong port_index configured".
    #[test]
    fn select_composite_port_index_out_of_range() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![
            make_usb_port("COM2", 0x1d50, 0xacab, Some(0)),
            make_usb_port("COM3", 0x1d50, 0xacab, Some(2)),
        ];
        let err = select_composite_port(ports, target, 5).unwrap_err();
        assert!(
            matches!(
                err,
                DiscoveryError::IndexOutOfRange {
                    requested: 5,
                    found: 2,
                    ..
                }
            ),
            "index-out-of-range should be IndexOutOfRange{{requested:5, found:2}}, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("port_index 5"),
            "message should mention requested index: {msg}"
        );
        assert!(
            msg.contains("found 2"),
            "message should mention found count: {msg}"
        );
        assert!(msg.contains("1d50"), "message should mention VID: {msg}");
        assert!(msg.contains("acab"), "message should mention PID: {msg}");
    }

    /// Regression: IndexOutOfRange vs NotFound are distinct — a no-match should
    /// NOT produce IndexOutOfRange.
    #[test]
    fn select_composite_port_empty_match_is_not_index_out_of_range() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![];
        let err = select_composite_port(ports, target, 0).unwrap_err();
        assert!(
            !matches!(err, DiscoveryError::IndexOutOfRange { .. }),
            "empty match must be NotFound, not IndexOutOfRange"
        );
    }

    /// Port with `interface: None` should sort last, not steal an early index.
    ///
    /// Rationale: None-interface entries on a composite device are abnormal
    /// (the OS failed to report the interface number). Sorting them last preserves
    /// the interface-numbered entries' expected indices. Note that Rust's natural
    /// `Option<T: Ord>` would put `None < Some(0)` (i.e., None first) — the
    /// implementation explicitly overrides this via a `(is_none, interface)` key.
    #[test]
    fn select_composite_port_handles_missing_interface_field() {
        let target = VidPid(0x1d50, 0xacab);
        let ports = vec![
            make_usb_port("GHOST", 0x1d50, 0xacab, None), // no interface — sorts last
            make_usb_port("COM5", 0x1d50, 0xacab, Some(0)), // index 0
            make_usb_port("COM7", 0x1d50, 0xacab, Some(4)), // index 1 after sort
        ];
        // After sort: COM5 (Some(0)), COM7 (Some(4)), GHOST (None)
        let idx0 = select_composite_port(ports.clone(), target, 0).unwrap();
        assert_eq!(idx0.port_name, "COM5");
        let idx1 = select_composite_port(ports.clone(), target, 1).unwrap();
        assert_eq!(idx1.port_name, "COM7");
        let idx2 = select_composite_port(ports, target, 2).unwrap();
        assert_eq!(idx2.port_name, "GHOST");
    }

    // ── filter_by_vid_pid tests ───────────────────────────────────────────────

    /// No matches → NotFound.
    #[test]
    fn filter_by_vid_pid_no_match_returns_not_found() {
        let ports = vec![
            make_usb_port("COM1", 0xdead, 0xbeef, Some(0)),
            make_non_usb_port("COM2"),
        ];
        let err = filter_by_vid_pid(ports, VidPid(0x1d50, 0xacab)).unwrap_err();
        assert!(matches!(err, DiscoveryError::NotFound { .. }));
    }

    /// Exactly one match → Ok.
    #[test]
    fn filter_by_vid_pid_single_match_returns_ok() {
        let ports = vec![
            make_usb_port("COM1", 0xdead, 0xbeef, Some(0)),
            make_usb_port("COM2", 0x1d50, 0xacab, Some(0)),
        ];
        let result = filter_by_vid_pid(ports, VidPid(0x1d50, 0xacab)).unwrap();
        assert_eq!(result.port_name, "COM2");
    }

    /// More than one match → Ambiguous.
    #[test]
    fn filter_by_vid_pid_multiple_matches_returns_ambiguous() {
        let ports = vec![
            make_usb_port("COM2", 0x1d50, 0xacab, Some(0)),
            make_usb_port("COM3", 0x1d50, 0xacab, Some(2)),
        ];
        let err = filter_by_vid_pid(ports, VidPid(0x1d50, 0xacab)).unwrap_err();
        assert!(matches!(err, DiscoveryError::Ambiguous { count: 2, .. }));
    }

    // ── filter_by_name_pattern tests (pure list, no OS call) ─────────────────

    /// Case-insensitive substring match: uppercase product name matched by
    /// lowercase pattern. Port without a product field is not included.
    #[test]
    fn name_pattern_case_insensitive_match() {
        let ports = vec![
            make_usb_port_named("COM1", 0x1d50, 0xacab, "JLV5PORT", Some(0)),
            make_usb_port_named("COM2", 0x1d50, 0xacab, "JLV5PORT", Some(2)),
            make_usb_port("COM3", 0x0403, 0x6001, None), // no product — must be excluded
        ];
        let matched = filter_by_name_pattern(ports, "jlv5port");
        assert_eq!(matched.len(), 2);
        assert_eq!(matched[0].port_name, "COM1");
        assert_eq!(matched[1].port_name, "COM2");
    }

    /// Non-USB ports (Bluetooth, PCI, etc.) are excluded from name-pattern
    /// matching regardless of pattern.
    #[test]
    fn name_pattern_skips_non_usb_ports() {
        let ports = vec![make_non_usb_port("COM1")];
        let matched = filter_by_name_pattern(ports, "jlv5port");
        assert!(matched.is_empty());
    }
}