# Instinct serve: HTTP framing for MCP Streamable HTTP (2025-06-18) [GAMMA-Codon/S] v0.1.0
# Pure functions over bytes and strings: parse a request head, decide whether to admit it, frame a response.
# No sockets, no clock, no bank. src/serve.rs owns the loopback listener and hands every JSON-RPC body to the same
# function the stdio server uses.
AAC # pub const MAX_BODY: usize = 1 << 20
AAC # pub const MAX_HEAD: usize = 16 * 1024
AAC # const VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]
TAG # #[derive(Debug, Default)]
GCA # pub struct Head
GCC # pub method: String
GCC # pub path: String
GCC # pub headers: Vec<(String, String)>
GCC # pub length: Option<usize>
TTT # end
# Offset just past the blank line that ends the head, or None while the head is still arriving.
AAA # pub fn head_end(buf: &[u8]) -> Option<usize>
TAC # buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)
TTT # end
# Parse the head (request line + headers). The Err value is the HTTP status to answer with.
AAA # pub fn parse_head(raw: &[u8]) -> Result<Head, u16>
AAC # let text = std::str::from_utf8(raw).map_err(|_| 400u16)?
AAC # let mut lines = text.trim_end_matches("\r\n").split("\r\n")
AAC # let request = lines.next().unwrap_or("")
AAC # let mut parts = request.split(' ')
AAC # let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return Err(400) }
CAA # if !version.starts_with("HTTP/1.") || method.is_empty() || !target.starts_with('/')
AAC # return Err(400)
TTT # end
AAC # let mut head = Head { method: method.to_string(), path: target.split('?').next().unwrap_or("").to_string(), ..Head::default() }
AGA # for line in lines
CAA # if line.starts_with(' ') || line.starts_with('\t')
AAC # return Err(400)
TTT # end
AAC # let Some((name, value)) = line.split_once(':') else { return Err(400) }
AAC # let name = name.to_ascii_lowercase()
CAA # if name.is_empty() || name.contains(' ')
AAC # return Err(400)
TTT # end
CAA # if name == "transfer-encoding"
AAC # return Err(501)
TTT # end
CAA # if name == "content-length"
AAC # let n = value.trim().parse::<usize>().map_err(|_| 400u16)?
CAA # if head.length.is_some()
AAC # return Err(400)
TTT # end
AAC # head.length = Some(n)
TTT # end
AAC # head.headers.push((name, value.trim().to_string()))
TTT # end
TAC # Ok(head)
TTT # end
AAA # pub fn header<'a>(head: &'a Head, name: &str) -> Option<&'a str>
TAC # head.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
TTT # end
# Compare two secrets without stopping at the first difference. The length is not secret (a key is 64 hex digits).
AAA # pub fn same_secret(a: &[u8], b: &[u8]) -> bool
CAA # if a.len() != b.len()
AAC # return false
TTT # end
AAC # let mut diff = 0u8
AGA # for (x, y) in a.iter().zip(b.iter())
AAC # diff |= x ^ y
TTT # end
TAC # std::hint::black_box(diff) == 0
TTT # end
# A browser origin must be https and listed exactly; an origin with a path, query or trailing slash never matches.
AAA # pub fn origin_ok(origin: &str, allow: &[String]) -> bool
TAC # origin.starts_with("https://") && allow.iter().any(|a| a.eq_ignore_ascii_case(origin))
TTT # end
AAA # pub fn version_ok(value: &str) -> bool
TAC # VERSIONS.contains(&value)
TTT # end
# Decide whether a request may reach the MCP handler. Order: path, origin, key, method, version, length.
AAA # pub fn admit(head: &Head, key: &str, allow: &[String]) -> Result<(), u16>
CAA # if head.path != "/mcp"
AAC # return Err(404)
TTT # end
CAA # if let Some(origin) = header(head, "origin")
CAA # if !origin_ok(origin, allow)
AAC # return Err(403)
TTT # end
TTT # end
AAC # let sent = header(head, "x-api-key").unwrap_or("")
CAA # if key.is_empty() || !same_secret(sent.as_bytes(), key.as_bytes())
AAC # return Err(401)
TTT # end
CAA # if head.method != "POST"
AAC # return Err(405)
TTT # end
CAA # if let Some(v) = header(head, "mcp-protocol-version")
CAA # if !version_ok(v)
AAC # return Err(400)
TTT # end
TTT # end
CAA # match head.length
TAC # None => return Err(411),
TAC # Some(n) if n > MAX_BODY => return Err(413),
TAC # Some(_) => {}
TTT # end
TAC # Ok(())
TTT # end
AAA # pub fn reason(status: u16) -> &'static str
TAC # match status { 200 => "OK", 202 => "Accepted", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 408 => "Request Timeout", 411 => "Length Required", 413 => "Content Too Large", 431 => "Request Header Fields Too Large", 501 => "Not Implemented", 503 => "Service Unavailable", _ => "Internal Server Error" }
TTT # end
# Frame a response. A 202 carries no body; every other status carries a JSON body. The connection always closes.
AAA # pub fn reply(status: u16, body: &str) -> Vec<u8>
AAC # let none = status == 202
AAC # let mut out = format!("HTTP/1.1 {status} {}\r\nConnection: close\r\nCache-Control: no-store\r\n", reason(status))
CAA # if status == 405
AAC # out.push_str("Allow: POST\r\n")
TTT # end
CAA # if none
AAC # out.push_str("Content-Length: 0\r\n\r\n")
CAC # else
AAC # out.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len()))
TTT # end
TAC # out.into_bytes()
TTT # end
# The JSON error body for a refused request. Never echoes any request header or secret.
AAA # pub fn refusal(status: u16) -> Vec<u8>
TAC # reply(status, &format!("{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32000,\"message\":\"{}\"}}}}", reason(status)))
TTT # end