hyperlane-plugin-mcp 22.14.0

A Model Context Protocol (MCP) Streamable HTTP server plugin for the Hyperlane framework with tool, resource, and prompt registries, session lifecycle management, DNS-rebinding Origin validation, and an opt-in ServerHook.
Documentation
use super::*;

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &RequestHeadersValue| values.back())
        .map(String::as_str)
}

/// Computes the shard index for an MCP session identifier using `XxHash3_64`.
///
/// # Arguments
///
/// - `&str` - Session identifier.
///
/// # Returns
///
/// - `usize` - Shard index in `0..MCP_SESSION_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn mcp_session_shard_index(session_id: &str) -> usize {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    hasher.write(session_id.as_bytes());
    (hasher.finish() as usize) & (MCP_SESSION_SHARD_COUNT - 1)
}

/// Applies one SplitMix64 avalanche step to `x`.
///
/// # Arguments
///
/// - `u64` - Input state value.
///
/// # Returns
///
/// - `u64` - Mixed 64-bit output.
#[inline(always)]
pub(crate) fn mix_splitmix64(mut x: u64) -> u64 {
    x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
    x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
    x ^ (x >> 31)
}

/// Generates a process-unique 64-bit seed from wall-clock nanoseconds, PID, and stack ASLR entropy.
///
/// # Returns
///
/// - `u64` - Non-trivial per-registry entropy seed.
pub(crate) fn mcp_random_seed() -> u64 {
    let nanos: u128 = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_nanos())
        .unwrap_or(0);
    let pid: u64 = process::id() as u64;
    let stack_probe: u64 = (&nanos as *const u128) as usize as u64;
    let mixed: u64 =
        (nanos as u64) ^ ((nanos >> 64) as u64).rotate_left(17) ^ pid.rotate_left(33) ^ stack_probe;
    mix_splitmix64(mixed.wrapping_add(SPLITMIX_GAMMA))
}

/// Mints an unpredictable 128-bit hexadecimal MCP session identifier using stack hex formatting.
///
/// # Arguments
///
/// - `u64` - Registry entropy seed.
/// - `u64` - Monotonic sequence number.
///
/// # Returns
///
/// - `String` - Session identifier prefixed with [`MCP_SESSION_PREFIX`].
#[inline]
pub(crate) fn mint_mcp_session_id(seed: u64, seq: u64) -> String {
    let nanos: u64 = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_nanos() as u64)
        .unwrap_or(0);
    let hi: u64 =
        mix_splitmix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)) ^ nanos.rotate_left(13));
    let lo: u64 = mix_splitmix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(29));
    let prefix: &[u8] = MCP_SESSION_PREFIX.as_bytes();
    let mut stack: [u8; 41] = [0u8; 41];
    stack[..prefix.len()].copy_from_slice(prefix);
    let mut pos: usize = prefix.len();
    for word in [hi, lo] {
        let mut shift: u32 = 64;
        while shift > 0 {
            shift -= 4;
            let nibble: usize = ((word >> shift) & 0x0F) as usize;
            stack[pos] = MCP_HEX_DIGITS[nibble];
            pos += 1;
        }
    }
    from_utf8(&stack[..pos]).unwrap_or_default().to_owned()
}

/// Builds a standard MCP text content block `{"type": "text", "text": text}`.
///
/// # Arguments
///
/// - `String` - Plain-text content payload.
///
/// # Returns
///
/// - `Value` - Constructed text content JSON object.
#[inline]
pub(crate) fn mcp_text_content(text: String) -> Value {
    let mut map: Map<String, Value> = Map::with_capacity(2);
    map.insert(KEY_TYPE.to_owned(), Value::String(KEY_TEXT.to_owned()));
    map.insert(KEY_TEXT.to_owned(), Value::String(text));
    Value::Object(map)
}

/// Formats a JSON-RPC 2.0 error envelope directly into UTF-8 JSON bytes without intermediate maps.
///
/// # Arguments
///
/// - `&Value` - Request correlation identifier (`Value::Null` if unavailable).
/// - `i64` - JSON-RPC error code.
/// - `&str` - Human-readable error message.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC error response.
#[inline]
pub(crate) fn mcp_json_error(id: &Value, code: i64, message: &str) -> Vec<u8> {
    let envelope: McpRpcError<'_> = McpRpcError {
        jsonrpc: MCP_JSONRPC_VERSION,
        id,
        error: McpRpcErrorBody { code, message },
    };
    to_vec(&envelope).unwrap_or_default()
}

/// Formats a JSON-RPC 2.0 success envelope directly into UTF-8 JSON bytes without intermediate maps.
///
/// # Arguments
///
/// - `&Value` - Request correlation identifier.
/// - `T` - Typed serializable result payload.
///
/// # Returns
///
/// - `Vec<u8>` - Serialized JSON-RPC success response.
#[inline]
pub(crate) fn mcp_json_success<T>(id: &Value, result: T) -> Vec<u8>
where
    T: Serialize,
{
    let envelope: McpRpcSuccess<'_, T> = McpRpcSuccess {
        jsonrpc: MCP_JSONRPC_VERSION,
        id,
        result,
    };
    to_vec(&envelope).unwrap_or_default()
}

/// Validates an incoming `Origin` header against `allowed_origins` to mitigate DNS rebinding.
///
/// # Arguments
///
/// - `Option<&str>` - Incoming `Origin` header value.
/// - `&[String]` - Configured allowed origins (empty allows all origins).
///
/// # Returns
///
/// - `bool` - `true` when the request origin is permitted.
#[inline]
pub(crate) fn is_origin_allowed(origin: Option<&str>, allowed_origins: &[String]) -> bool {
    if allowed_origins.is_empty() {
        return true;
    }
    let Some(value) = origin else {
        return true;
    };
    let trimmed: &str = value.trim();
    allowed_origins
        .iter()
        .any(|allowed: &String| allowed.eq_ignore_ascii_case(trimmed))
}