use super::*;
#[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)
}
#[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)
}
#[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)
}
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))
}
#[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()
}
#[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)
}
#[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()
}
#[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()
}
#[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))
}