serial-mcp 0.9.3

MCP server for serial port communication. 25 tools (list/open/read/write/transact/capture_boot/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/configure/rollback_profile/get_log/clear_log/export_log/reconnect/compute_checksum/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
Documentation
//! Data encoding/decoding between MCP tool strings and raw bytes.
//!
//! MCP tool arguments carry serial payloads as strings tagged with an
//! `encoding` field. This module converts in both directions and reports
//! a typed error per failure mode.

use std::fmt;
use std::str::FromStr;

use base64::{engine::general_purpose, Engine as _};
use thiserror::Error;

/// Wire-format used to represent serial bytes inside an MCP tool string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Encoding {
    /// Raw UTF-8 text. Bytes that are not valid UTF-8 cannot be encoded.
    Utf8,
    /// Lowercase hex pairs. Decoder accepts upper or lower case and ignores spaces.
    Hex,
    /// Standard Base64. Decoder also accepts URL-safe / no-padding input.
    Base64,
}

impl FromStr for Encoding {
    type Err = CodecError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "utf8" | "utf-8" => Ok(Encoding::Utf8),
            "hex" => Ok(Encoding::Hex),
            "base64" | "b64" => Ok(Encoding::Base64),
            _ => Err(CodecError::UnknownEncoding(s.to_string())),
        }
    }
}

impl fmt::Display for Encoding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Encoding::Utf8 => "utf8",
            Encoding::Hex => "hex",
            Encoding::Base64 => "base64",
        };
        f.write_str(name)
    }
}

#[derive(Debug, Error)]
pub enum CodecError {
    #[error("Unknown encoding: {0}")]
    UnknownEncoding(String),

    #[error("Invalid UTF-8: {0}")]
    InvalidUtf8(#[from] std::string::FromUtf8Error),

    #[error("Invalid hex: {0}")]
    InvalidHex(#[from] hex::FromHexError),

    #[error("Invalid base64: {0}")]
    InvalidBase64(#[from] base64::DecodeError),

    #[error("Hex string must have even length")]
    HexOddLength,
}

/// Decode a tool-supplied string into raw bytes.
pub fn decode(encoding: Encoding, input: &str) -> Result<Vec<u8>, CodecError> {
    match encoding {
        Encoding::Utf8 => Ok(input.as_bytes().to_vec()),
        Encoding::Hex => decode_hex(input),
        Encoding::Base64 => decode_base64(input),
    }
}

/// Encode raw bytes into a string suitable for an MCP tool response.
pub fn encode(encoding: Encoding, bytes: &[u8]) -> Result<String, CodecError> {
    match encoding {
        Encoding::Utf8 => Ok(String::from_utf8(bytes.to_vec())?),
        Encoding::Hex => Ok(encode_hex_spaced(bytes)),
        Encoding::Base64 => Ok(general_purpose::STANDARD.encode(bytes)),
    }
}

/// Result of [`encode_or_hex`]: the encoded string plus the effective
/// encoding actually used to produce it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedPayload {
    pub data: String,
    pub encoding: Encoding,
    /// `Some(original error text)` when `requested` could not represent the
    /// bytes and the payload was re-encoded as hex; `None` on direct success.
    pub fallback_reason: Option<String>,
}

/// Try `requested`, then fall back to exact lowercase spaced hex when the
/// requested encoding cannot represent `bytes`.
///
/// A successful fallback returns the hex payload with
/// `encoding == Encoding::Hex` and `fallback_reason` set to the original
/// error text; it is NOT an error — callers own warning/drop semantics and
/// must not count a successful fallback as a dropped payload. Only a true
/// hex-encoding failure returns `Err`.
///
/// Never lossy: invalid UTF-8 bytes are preserved exactly in hex form.
pub fn encode_or_hex(requested: Encoding, bytes: &[u8]) -> Result<EncodedPayload, CodecError> {
    match encode(requested, bytes) {
        Ok(data) => Ok(EncodedPayload {
            data,
            encoding: requested,
            fallback_reason: None,
        }),
        Err(e) => {
            let data = encode(Encoding::Hex, bytes)?;
            Ok(EncodedPayload {
                data,
                encoding: Encoding::Hex,
                fallback_reason: Some(e.to_string()),
            })
        }
    }
}

fn decode_hex(input: &str) -> Result<Vec<u8>, CodecError> {
    let stripped = input.trim().replace(' ', "");
    if !stripped.len().is_multiple_of(2) {
        return Err(CodecError::HexOddLength);
    }
    Ok(hex::decode(&stripped)?)
}

fn decode_base64(input: &str) -> Result<Vec<u8>, CodecError> {
    let trimmed = input.trim();
    general_purpose::STANDARD
        .decode(trimmed)
        .or_else(|_| general_purpose::URL_SAFE_NO_PAD.decode(trimmed))
        .map_err(CodecError::InvalidBase64)
}

fn encode_hex_spaced(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encoding_from_str_accepts_aliases() {
        assert_eq!("utf8".parse::<Encoding>().unwrap(), Encoding::Utf8);
        assert_eq!("UTF-8".parse::<Encoding>().unwrap(), Encoding::Utf8);
        assert_eq!("Hex".parse::<Encoding>().unwrap(), Encoding::Hex);
        assert_eq!("b64".parse::<Encoding>().unwrap(), Encoding::Base64);
    }

    #[test]
    fn encoding_from_str_rejects_unknown() {
        assert!("rot13".parse::<Encoding>().is_err());
    }

    #[test]
    fn utf8_roundtrip() {
        let bytes = decode(Encoding::Utf8, "Hello, 世界!").unwrap();
        assert_eq!(encode(Encoding::Utf8, &bytes).unwrap(), "Hello, 世界!");
    }

    #[test]
    fn utf8_encode_rejects_invalid_bytes() {
        assert!(encode(Encoding::Utf8, &[0xFF, 0xFE]).is_err());
    }

    #[test]
    fn hex_roundtrip() {
        assert_eq!(decode(Encoding::Hex, "48656c6c6f").unwrap(), b"Hello");
        assert_eq!(decode(Encoding::Hex, "48 65 6c 6c 6f").unwrap(), b"Hello");
        assert_eq!(decode(Encoding::Hex, "48656C6C6F").unwrap(), b"Hello");
        assert_eq!(encode(Encoding::Hex, b"Hello").unwrap(), "48 65 6c 6c 6f");
    }

    #[test]
    fn hex_odd_length_rejected() {
        assert!(matches!(
            decode(Encoding::Hex, "48656c6c6"),
            Err(CodecError::HexOddLength)
        ));
    }

    #[test]
    fn hex_invalid_chars_rejected() {
        assert!(matches!(
            decode(Encoding::Hex, "48656cXY"),
            Err(CodecError::InvalidHex(_))
        ));
    }

    #[test]
    fn base64_roundtrip_and_padding_variants() {
        assert_eq!(
            decode(Encoding::Base64, "SGVsbG8gV29ybGQ=").unwrap(),
            b"Hello World"
        );
        assert_eq!(
            decode(Encoding::Base64, "SGVsbG8gV29ybGQ").unwrap(),
            b"Hello World"
        );
        assert_eq!(
            encode(Encoding::Base64, b"Hello World").unwrap(),
            "SGVsbG8gV29ybGQ="
        );
    }

    #[test]
    fn binary_roundtrips_via_hex_and_base64() {
        let data: &[u8] = b"Hello, World! 123 \x00\xFF";
        let hex = encode(Encoding::Hex, data).unwrap();
        assert_eq!(decode(Encoding::Hex, &hex).unwrap(), data);
        let b64 = encode(Encoding::Base64, data).unwrap();
        assert_eq!(decode(Encoding::Base64, &b64).unwrap(), data);
    }

    // ── encode_or_hex ─────────────────────────────────────────────────────

    #[test]
    fn encode_or_hex_valid_utf8_stays_requested_encoding() {
        // "Hello, 世界!" as explicit UTF-8 bytes (byte strings are ASCII-only).
        let bytes: &[u8] = b"Hello, \xE4\xB8\x96\xE7\x95\x8C!";
        let p = encode_or_hex(Encoding::Utf8, bytes).unwrap();
        assert_eq!(p.data, "Hello, 世界!");
        assert_eq!(p.encoding, Encoding::Utf8);
        assert!(p.fallback_reason.is_none());
    }

    #[test]
    fn encode_or_hex_invalid_utf8_falls_back_to_exact_hex() {
        let bytes: &[u8] = &[0x48, 0x69, 0xFF, 0xFE, 0x00];
        let p = encode_or_hex(Encoding::Utf8, bytes).unwrap();
        assert_eq!(p.data, "48 69 ff fe 00");
        assert_eq!(p.encoding, Encoding::Hex);
        let reason = p.fallback_reason.expect("fallback reason present");
        assert!(
            reason.contains("UTF-8"),
            "reason should name UTF-8: {reason}"
        );
    }

    #[test]
    fn encode_or_hex_requested_hex_has_no_fallback() {
        let p = encode_or_hex(Encoding::Hex, &[0x00, 0x01, 0x02, 0xFF]).unwrap();
        assert_eq!(p.data, "00 01 02 ff");
        assert_eq!(p.encoding, Encoding::Hex);
        assert!(p.fallback_reason.is_none());
    }

    #[test]
    fn encode_or_hex_requested_base64_has_no_fallback() {
        let p = encode_or_hex(Encoding::Base64, b"Hello World").unwrap();
        assert_eq!(p.data, "SGVsbG8gV29ybGQ=");
        assert_eq!(p.encoding, Encoding::Base64);
        assert!(p.fallback_reason.is_none());
    }

    #[test]
    fn encode_or_hex_empty_bytes() {
        let p = encode_or_hex(Encoding::Utf8, b"").unwrap();
        assert_eq!(p.data, "");
        assert_eq!(p.encoding, Encoding::Utf8);
        assert!(p.fallback_reason.is_none());
    }

    #[test]
    fn encode_or_hex_fallback_bytes_roundtrip() {
        let bytes: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0xFF];
        let p = encode_or_hex(Encoding::Utf8, bytes).unwrap();
        assert_eq!(p.encoding, Encoding::Hex);
        assert_eq!(decode(Encoding::Hex, &p.data).unwrap(), bytes);
    }
}