///|
/// Reserved `_meta` key constants for MCP 2026-07-28 per-request envelopes and results.
pub let meta_key_protocol_version : String = "io.modelcontextprotocol/protocolVersion"

///|
pub let meta_key_client_info : String = "io.modelcontextprotocol/clientInfo"

///|
pub let meta_key_server_info : String = "io.modelcontextprotocol/serverInfo"

///|
pub let meta_key_client_capabilities : String = "io.modelcontextprotocol/clientCapabilities"

///|
pub let meta_key_subscription_id : String = "io.modelcontextprotocol/subscriptionId"

///|
pub let meta_key_log_level : String = "io.modelcontextprotocol/logLevel"

///|
/// Reserved `_meta` keys for W3C Trace Context / Baggage propagation (SEP-414).
pub let meta_key_traceparent : String = "traceparent"

///|
pub let meta_key_tracestate : String = "tracestate"

///|
pub let meta_key_baggage : String = "baggage"

///|
/// First protocol revision of the modern (2026-07-28+) era.
pub let first_modern_protocol_version : String = "2026-07-28"

///|
fn is_valid_protocol_date(ver : String) -> Bool {
  if ver.length() != 10 {
    return false
  }
  let mut idx = 0
  let mut month = 0
  let mut day = 0
  for ch in ver {
    if idx == 4 || idx == 7 {
      if ch != '-' {
        return false
      }
    } else {
      if ch < '0' || ch > '9' {
        return false
      }
      let d = ch.to_int() - '0'.to_int()
      if idx == 5 || idx == 6 {
        month = month * 10 + d
      } else if idx == 8 || idx == 9 {
        day = day * 10 + d
      }
    }
    idx = idx + 1
  }
  month >= 1 && month <= 12 && day >= 1 && day <= 31
}

///|
/// Returns true if `ver` belongs to the modern (2026-07-28+) protocol era.
pub fn is_modern_protocol_version(ver : String) -> Bool {
  is_valid_protocol_date(ver) && ver >= first_modern_protocol_version
}

///|
/// Returns true if `ver` is in `modern_protocol_versions` (supported modern revisions).
pub fn is_supported_modern_version(ver : String) -> Bool {
  for v in modern_protocol_versions {
    if v == ver {
      return true
    }
  }
  false
}

///|
/// Returns true if `ver` is in `supported_protocol_versions` (legacy revisions).
pub fn is_supported_legacy_version(ver : String) -> Bool {
  for v in supported_protocol_versions {
    if v == ver {
      return true
    }
  }
  false
}

///|
/// Exact 10 request methods defined in the 2026-07-28 protocol revision.
pub fn is_rev2026_request_method(meth : String) -> Bool {
  match meth {
    "tools/call"
    | "tools/list"
    | "prompts/get"
    | "prompts/list"
    | "resources/list"
    | "resources/templates/list"
    | "resources/read"
    | "completion/complete"
    | "server/discover"
    | "subscriptions/listen" => true
    _ => false
  }
}

///|
/// Exact 8 notification methods defined in the 2026-07-28 protocol revision.
pub fn is_rev2026_notification_method(meth : String) -> Bool {
  match meth {
    "notifications/cancelled"
    | "notifications/progress"
    | "notifications/message"
    | "notifications/resources/updated"
    | "notifications/resources/list_changed"
    | "notifications/tools/list_changed"
    | "notifications/prompts/list_changed"
    | "notifications/subscriptions/acknowledged" => true
    _ => false
  }
}

///|
/// Extracts `params._meta` object when present.
pub fn extract_params_meta(
  params_opt : Map[String, Json]?,
) -> Map[String, Json]? {
  match params_opt {
    Some(p) =>
      match p.get("_meta") {
        Some(Object(m)) => Some(m)
        _ => None
      }
    None => None
  }
}

///|
/// Returns true if `params._meta` carries the 2026 per-request envelope claim key
/// (`io.modelcontextprotocol/protocolVersion`).
pub fn has_envelope_claim(params_opt : Map[String, Json]?) -> Bool {
  match extract_params_meta(params_opt) {
    Some(m) => m.contains(meta_key_protocol_version)
    None => false
  }
}

///|
/// Returns the string value of `params._meta["io.modelcontextprotocol/protocolVersion"]` if present and a string.
pub fn envelope_claim_version(params_opt : Map[String, Json]?) -> String? {
  match extract_params_meta(params_opt) {
    Some(m) =>
      match m.get(meta_key_protocol_version) {
        Some(String(v)) => Some(v)
        _ => None
      }
    None => None
  }
}

///|
/// Validates a 2026-07-28 per-request `_meta` envelope object.
/// Returns `Some((key, problem))` on the first violation, or `None` when valid.
pub fn validate_envelope_meta(meta : Map[String, Json]) -> (String, String)? {
  // Required: io.modelcontextprotocol/protocolVersion (non-empty string)
  match meta.get(meta_key_protocol_version) {
    None => return Some((meta_key_protocol_version, "missing"))
    Some(String(s)) if !s.is_empty() => ()
    Some(_) =>
      return Some(
        (meta_key_protocol_version, "expected a protocol version string"),
      )
  }
  // Required: io.modelcontextprotocol/clientCapabilities (object)
  match meta.get(meta_key_client_capabilities) {
    None => return Some((meta_key_client_capabilities, "missing"))
    Some(Object(_)) => ()
    Some(_) => return Some((meta_key_client_capabilities, "expected an object"))
  }
  // Optional: io.modelcontextprotocol/clientInfo (Implementation object: name + version strings)
  match meta.get(meta_key_client_info) {
    None => ()
    Some(Object(ci)) => {
      match ci.get("name") {
        Some(String(_)) => ()
        _ =>
          return Some(
            (meta_key_client_info, "clientInfo.name must be a string"),
          )
      }
      match ci.get("version") {
        Some(String(_)) => ()
        _ =>
          return Some(
            (meta_key_client_info, "clientInfo.version must be a string"),
          )
      }
    }
    Some(_) => return Some((meta_key_client_info, "expected an object"))
  }
  // Optional: io.modelcontextprotocol/logLevel (valid RFC-5424 level string)
  match meta.get(meta_key_log_level) {
    None => ()
    Some(String(lvl)) =>
      if McpLogLevel::parse(lvl) is None {
        return Some((meta_key_log_level, "invalid log level: \{lvl}"))
      }
    Some(_) => return Some((meta_key_log_level, "expected a log level string"))
  }
  None
}

///|
/// Returns true if `params` carries a valid modern (`>= 2026-07-28`) per-request `_meta` envelope claim.
pub fn carries_valid_modern_envelope_claim(
  params_opt : Map[String, Json]?,
) -> Bool {
  if !has_envelope_claim(params_opt) {
    return false
  }
  match envelope_claim_version(params_opt) {
    Some(v) if is_modern_protocol_version(v) =>
      match extract_params_meta(params_opt) {
        Some(m) => validate_envelope_meta(m) is None
        None => false
      }
    _ => false
  }
}

///|
/// Strips HTTP optional whitespace (SP / HTAB) from both ends of a header value.
pub fn strip_http_ows(s : String) -> String {
  let chars = s.to_array()
  let mut start = 0
  let mut end = chars.length()
  while start < end && (chars[start] == ' ' || chars[start] == '\t') {
    start = start + 1
  }
  while end > start && (chars[end - 1] == ' ' || chars[end - 1] == '\t') {
    end = end - 1
  }
  if start == 0 && end == chars.length() {
    return s
  }
  let sb = StringBuilder()
  for i = start; i < end; i = i + 1 {
    sb.write_char(chars[i])
  }
  sb.to_string()
}

///|
fn is_canonical_base64(s : String) -> Bool {
  let chars = s.to_array()
  let len = chars.length()
  if len % 4 != 0 {
    return false
  }
  if len == 0 {
    return true
  }
  let mut i = 0
  while i < len {
    let ch = chars[i]
    let is_b64 = (ch >= 'A' && ch <= 'Z') ||
      (ch >= 'a' && ch <= 'z') ||
      (ch >= '0' && ch <= '9') ||
      ch == '+' ||
      ch == '/'
    if is_b64 {
      i = i + 1
    } else if ch == '=' {
      // Padding is only valid in the last 1 or 2 positions
      if i == len - 1 {
        return true
      } else if i == len - 2 && chars[len - 1] == '=' {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  }
  true
}

///|
fn needs_base64_mcp_param(s : String) -> Bool {
  if s.is_empty() {
    return true
  }
  if s.has_prefix("=?base64?") && s.has_suffix("?=") {
    return true
  }
  let chars = s.to_array()
  let first = chars[0]
  let last = chars[chars.length() - 1]
  if first == ' ' ||
    first == '\t' ||
    first == '\r' ||
    first == '\n' ||
    last == ' ' ||
    last == '\t' ||
    last == '\r' ||
    last == '\n' {
    return true
  }
  for ch in chars {
    let code = ch.to_int()
    if code == 0x09 || (code >= 0x20 && code <= 0x7E) {
      continue
    }
    return true
  }
  false
}

///|
/// Encodes a string value for SEP-2243 `Mcp-Name` / `Mcp-Param-*` headers.
/// Safe plain-ASCII RFC 9110 field values pass through unchanged; all other values
/// (empty, leading/trailing whitespace, non-ASCII, control chars, or values already
/// matching the sentinel pattern) are wrapped as `=?base64?{b64-of-utf8}?=`.
pub fn encode_mcp_param_value(value : String) -> String {
  if needs_base64_mcp_param(value) {
    let b64 = @base64.encode(@utf8.encode(value))
    "=?base64?\{b64}?="
  } else {
    value
  }
}

///|
/// Decodes an SEP-2243 `Mcp-Name` / `Mcp-Param-*` HTTP header value.
/// Handles the `=?base64?{b64}?=` sentinel (canonical padded RFC 4648 Base64 + valid UTF-8).
/// Returns `None` if the sentinel is present but malformed.
pub fn decode_mcp_param_value(value : String) -> String? {
  let prefix = "=?base64?"
  let suffix = "?="
  if !(value.has_prefix(prefix) && value.has_suffix(suffix)) {
    return Some(value)
  }
  if value.length() < prefix.length() + suffix.length() {
    return None
  }
  let b64 = value[prefix.length():value.length() - suffix.length()].to_owned()
  if !is_canonical_base64(b64) {
    return None
  }
  let bytes = @base64.decode(b64) catch { _ => return None }
  let txt = @utf8.decode(bytes) catch { _ => return None }
  Some(txt)
}

///|
fn is_rfc9110_token(s : String) -> Bool {
  if s.is_empty() {
    return false
  }
  for ch in s {
    let ok = (ch >= 'a' && ch <= 'z') ||
      (ch >= 'A' && ch <= 'Z') ||
      (ch >= '0' && ch <= '9') ||
      ch == '!' ||
      ch == '#' ||
      ch == '$' ||
      ch == '%' ||
      ch == '&' ||
      ch == '\'' ||
      ch == '*' ||
      ch == '+' ||
      ch == '-' ||
      ch == '.' ||
      ch == '^' ||
      ch == '_' ||
      ch == '`' ||
      ch == '|' ||
      ch == '~'
    if !ok {
      return false
    }
  }
  true
}

///|
#derive(Debug, Eq)
priv struct XMcpHeaderDecl {
  path : Array[String]
  header_name : String
  schema_type : String
}

///|
priv struct XMcpHeaderScanResult {
  fault : String?
  declarations : Array[XMcpHeaderDecl]
}

///|
let non_reachable_subschema_keywords : Array[String] = [
  "items", "prefixItems", "contains", "additionalProperties", "unevaluatedProperties",
  "unevaluatedItems", "propertyNames", "patternProperties", "dependentSchemas", "oneOf",
  "anyOf", "allOf", "not", "if", "then", "else", "$defs", "definitions",
]

///|
fn is_object_valued_subschema_keyword(k : String) -> Bool {
  k == "patternProperties" ||
  k == "dependentSchemas" ||
  k == "$defs" ||
  k == "definitions"
}

///|
/// Scans a tool's JSON `inputSchema` for SEP-2243 `x-mcp-header` declarations
/// with full static-reachability sweep (rejecting annotations under `items`,
/// `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, `$defs`, etc.)
/// and case-insensitive uniqueness checks (matching `mcpParamHeaders.ts`).
fn scan_x_mcp_headers_full(input_schema : Json) -> XMcpHeaderScanResult {
  let out : Array[XMcpHeaderDecl] = []
  let seen_lower : Map[String, String] = Map([])
  let mut number_fault : String? = None
  fn visit(node : Json, path : Array[String], reachable : Bool) -> String? {
    match node {
      Object(m) => {
        if m.contains("x-mcp-header") {
          let pname = if path.is_empty() { "" } else { path.join(".") }
          if !reachable || path.is_empty() {
            return Some(
              "\{pname}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys",
            )
          }
          let raw_name = match m.get("x-mcp-header") {
            Some(String(s)) if !s.is_empty() => s
            _ =>
              return Some("\{pname}: x-mcp-header MUST be a non-empty string")
          }
          if !is_rfc9110_token(raw_name) {
            return Some(
              "\{pname}: x-mcp-header '\{raw_name}' is not a valid RFC 9110 token",
            )
          }
          let stype = match m.get("type") {
            Some(String(t)) => t
            _ => ""
          }
          if stype != "string" && stype != "integer" && stype != "boolean" {
            let disp_type = if stype.is_empty() { "" } else { stype }
            let f = "\{pname}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got \{disp_type}"
            if stype != "number" {
              return Some(f)
            }
            if number_fault is None {
              number_fault = Some(f)
            }
          }
          let lower = raw_name.to_lower()
          match seen_lower.get(lower) {
            Some(prior) =>
              return Some(
                "x-mcp-header '\{raw_name}' is not case-insensitively unique (also declared as '\{prior}')",
              )
            None => ()
          }
          seen_lower[lower] = raw_name
          out.push({
            path: path.copy(),
            header_name: raw_name,
            schema_type: stype,
          })
        }
        match m.get("properties") {
          Some(Object(props)) => {
            let mut err : String? = None
            props.each((k, child) => {
              if err is None {
                let next_path = path.copy()
                next_path.push(k)
                err = visit(child, next_path, reachable)
              }
            })
            if err is Some(_) {
              return err
            }
          }
          _ => ()
        }
        for kw in non_reachable_subschema_keywords {
          match m.get(kw) {
            None => ()
            Some(Array(branches)) =>
              for branch in branches {
                let next_path = path.copy()
                next_path.push("<\{kw}>")
                match visit(branch, next_path, false) {
                  Some(f) => return Some(f)
                  None => ()
                }
              }
            Some(Object(obj_map)) if is_object_valued_subschema_keyword(kw) => {
              let mut err : String? = None
              obj_map.each((_k, branch) => {
                if err is None {
                  let next_path = path.copy()
                  next_path.push("<\{kw}>")
                  err = visit(branch, next_path, false)
                }
              })
              if err is Some(_) {
                return err
              }
            }
            Some(sub) => {
              let next_path = path.copy()
              next_path.push("<\{kw}>")
              match visit(sub, next_path, false) {
                Some(f) => return Some(f)
                None => ()
              }
            }
          }
        }
        None
      }
      _ => None
    }
  }
  let fault = visit(input_schema, [], true)
  match fault {
    Some(f) => { fault: Some(number_fault.unwrap_or(f)), declarations: [], }
    None => { fault: number_fault, declarations: out, }
  }
}

///|
/// Pre-scanned SEP-2243 `x-mcp-header` declarations cached once per tool at registration time.
#derive(Debug, Eq)
pub struct CompiledXMcpHeaders {
  priv fault : String?
  priv declarations : Array[XMcpHeaderDecl]
}

///|
/// Scans `input_schema` once and returns reusable compiled `x-mcp-header` metadata.
pub fn compile_x_mcp_headers(input_schema : Json) -> CompiledXMcpHeaders {
  let res = scan_x_mcp_headers_full(input_schema)
  { fault: res.fault, declarations: res.declarations, }
}

///|
pub fn CompiledXMcpHeaders::fault(self : CompiledXMcpHeaders) -> String? {
  self.fault
}

///|
pub fn CompiledXMcpHeaders::is_empty(self : CompiledXMcpHeaders) -> Bool {
  self.declarations.is_empty()
}

///|
pub fn CompiledXMcpHeaders::header_count(self : CompiledXMcpHeaders) -> Int32 {
  self.declarations.length()
}

///|
/// Validates a tool's `inputSchema` against SEP-2243 `x-mcp-header` constraints.
/// Returns `None` when compliant, or `Some(reason)` on the first violation.
pub fn validate_x_mcp_headers(input_schema : Json) -> String? {
  scan_x_mcp_headers_full(input_schema).fault
}

///|
fn is_canonical_decimal(s : String) -> Bool {
  let chars = s.to_array()
  let len = chars.length()
  if len == 0 {
    return false
  }
  let mut i = 0
  if chars[0] == '-' {
    i = 1
    if i >= len {
      return false
    }
  }
  let mut has_digit = false
  while i < len && chars[i] >= '0' && chars[i] <= '9' {
    has_digit = true
    i = i + 1
  }
  if !has_digit {
    return false
  }
  if i == len {
    return true
  }
  if chars[i] != '.' {
    return false
  }
  i = i + 1
  let mut has_frac = false
  while i < len && chars[i] >= '0' && chars[i] <= '9' {
    has_frac = true
    i = i + 1
  }
  has_frac && i == len
}

///|
fn json_value_at_path(root : Map[String, Json], path : Array[String]) -> Json? {
  if path.is_empty() {
    return None
  }
  let mut cur : Json = Json::object(root)
  for seg in path {
    match cur {
      Object(m) =>
        match m.get(seg) {
          Some(next) => cur = next
          None => return None
        }
      _ => return None
    }
  }
  Some(cur)
}

///|
fn parse_decimal_double(s : String) -> Double? {
  let parsed : Json? = Some(@json.parse(s)) catch { _ => None }
  match parsed {
    Some(Number(n, ..)) => Some(n)
    _ => None
  }
}

///|
fn is_safe_exact_int64(n : Double) -> Bool {
  if n.is_nan() ||
    n.is_inf() ||
    n >= 9223372036854775808.0 ||
    n < -9223372036854775808.0 ||
    n.abs() > 9007199254740991.0 {
    false
  } else {
    n.to_int64().to_double() == n
  }
}

///|
pub fn json_scalar_to_string(v : Json) -> String {
  match v {
    String(s) => s
    Number(n, ..) =>
      if is_safe_exact_int64(n) {
        n.to_int64().to_string()
      } else {
        n.to_string()
      }
    True => "true"
    False => "false"
    Null => ""
    other => other.stringify()
  }
}

///|
pub fn extract_mime_base(content_type : String) -> String {
  let trimmed = content_type.trim()
  match trimmed.find(";") {
    Some(idx) => trimmed[:idx].trim().to_lower().to_owned()
    None => trimmed.to_lower().to_owned()
  }
}

///|
/// Validates SEP-2243 `Mcp-Param-*` headers using pre-scanned `CompiledXMcpHeaders`
/// (eliminates per-request JSON Schema tree traversal on `tools/call`).
pub fn validate_mcp_param_headers_compiled(
  compiled : CompiledXMcpHeaders,
  args : Map[String, Json],
  headers : @http.Headers,
) -> McpProtocolError? {
  let decls = compiled.declarations
  if decls.is_empty() {
    return None
  }
  for decl in decls {
    let header_key = "Mcp-Param-\{decl.header_name}"
    let header_val_opt = headers.get(header_key.to_lower()).map(strip_http_ows)
    match json_value_at_path(args, decl.path) {
      None | Some(Null) =>
        match header_val_opt {
          Some(hv) =>
            return Some(
              McpProtocolError::header_mismatch(
                "the \{header_key} header is present ('\{hv}') but \{decl.path.join(".")} is absent or null in the body",
                header=header_key,
                body="",
              ),
            )
          None => continue
        }
      Some(Object(_)) | Some(Array(_)) =>
        return Some(
          McpProtocolError::header_mismatch(
            "the body carries a non-primitive value for \{decl.path.join(".")}",
            header=header_key,
            body=decl.path.join("."),
          ),
        )
      Some(body_val) => {
        let header_val = match header_val_opt {
          Some(v) => v
          None =>
            return Some(
              McpProtocolError::header_mismatch(
                "the body carries \{decl.path.join(".")} but the \{header_key} header is absent",
                header=header_key,
                body=body_val.stringify(),
              ),
            )
        }
        let decoded = match decode_mcp_param_value(header_val) {
          Some(d) => d
          None =>
            return Some(
              McpProtocolError::header_mismatch(
                "the \{header_key} header carries an invalid Base64 sentinel value",
                header=header_key,
                body=body_val.stringify(),
              ),
            )
        }
        let equal = match body_val {
          Number(n, ..) if (
              decl.schema_type == "integer" || decl.schema_type == "number"
            ) &&
            is_canonical_decimal(decoded) =>
            match parse_decimal_double(decoded) {
              Some(dn) => dn == n
              None => false
            }
          String(s) => decoded == s
          True => decoded == "true"
          False => decoded == "false"
          other => decoded == json_scalar_to_string(other)
        }
        if !equal {
          return Some(
            McpProtocolError::header_mismatch(
              "the \{header_key} header decodes to '\{decoded}' but the body carries \{body_val.stringify()}",
              header=header_key,
              body=body_val.stringify(),
            ),
          )
        }
      }
    }
  }
  None
}

///|
/// Validates SEP-2243 `Mcp-Param-*` headers against a tool's `inputSchema` and
/// request `arguments`. Returns `Some(McpProtocolError)` (`-32020`) on mismatch.
pub fn validate_mcp_param_headers(
  input_schema : Json,
  args : Map[String, Json],
  headers : @http.Headers,
) -> McpProtocolError? {
  validate_mcp_param_headers_compiled(
    compile_x_mcp_headers(input_schema),
    args,
    headers,
  )
}

///|
/// Extracts the SEP-2243 `Mcp-Name` source field (`params.name` or `params.uri`) for methods that require it.
fn mcp_name_source(
  meth : String,
  params_opt : Map[String, Json]?,
) -> (String, String?)? {
  let field = match meth {
    "tools/call" | "prompts/get" => "name"
    "resources/read" => "uri"
    _ => return None
  }
  let val = match params_opt {
    Some(p) =>
      match p.get(field) {
        Some(String(s)) => Some(s)
        _ => None
      }
    None => None
  }
  Some((field, val))
}

///|
/// Validates SEP-2243 standard headers (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`)
/// on a modern-era HTTP request POST.
pub fn validate_standard_headers_2026(
  meth : String,
  params_opt : Map[String, Json]?,
  claimed_version : String,
  headers : @http.Headers,
) -> McpProtocolError? {
  match headers.get("mcp-protocol-version").map(strip_http_ows) {
    None =>
      return Some(
        McpProtocolError::header_mismatch(
          "the body envelope names protocol version \{claimed_version} but the required MCP-Protocol-Version header is absent",
          header="(missing)",
          body=claimed_version,
        ),
      )
    Some(hv) =>
      if hv != claimed_version {
        return Some(
          McpProtocolError::header_mismatch(
            "the body envelope names protocol version \{claimed_version} but the MCP-Protocol-Version header names \{hv}",
            header=hv,
            body=claimed_version,
          ),
        )
      }
  }
  match headers.get("mcp-method").map(strip_http_ows) {
    None =>
      return Some(
        McpProtocolError::header_mismatch(
          "the body names method \{meth} but the required Mcp-Method header is absent",
          header="(missing)",
          body=meth,
        ),
      )
    Some(hm) =>
      if hm != meth {
        return Some(
          McpProtocolError::header_mismatch(
            "the body names method \{meth} but the Mcp-Method header names \{hm}",
            header=hm,
            body=meth,
          ),
        )
      }
  }
  match mcp_name_source(meth, params_opt) {
    Some((field, Some(body_val))) =>
      match headers.get("mcp-name").map(strip_http_ows) {
        None =>
          return Some(
            McpProtocolError::header_mismatch(
              "the body carries params.\{field}=\"\{body_val}\" but the required Mcp-Name header is absent",
              header="(missing)",
              body=body_val,
            ),
          )
        Some(raw_name) =>
          match decode_mcp_param_value(raw_name) {
            None =>
              return Some(
                McpProtocolError::header_mismatch(
                  "the Mcp-Name header carries an invalid Base64 sentinel value",
                  header=raw_name,
                  body=body_val,
                ),
              )
            Some(decoded) =>
              if decoded != body_val {
                return Some(
                  McpProtocolError::header_mismatch(
                    "the body carries params.\{field}=\"\{body_val}\" but the Mcp-Name header names \"\{decoded}\"",
                    header=raw_name,
                    body=body_val,
                  ),
                )
              }
          }
      }
    Some((field, None)) =>
      match headers.get("mcp-name").map(strip_http_ows) {
        Some(raw_name) =>
          return Some(
            McpProtocolError::header_mismatch(
              "the Mcp-Name header is present ('\{raw_name}') but the body lacks params.\{field}",
              header=raw_name,
              body="",
            ),
          )
        None => ()
      }
    None =>
      match headers.get("mcp-name").map(strip_http_ows) {
        Some(raw_name) =>
          if decode_mcp_param_value(raw_name) is None {
            return Some(
              McpProtocolError::header_mismatch(
                "the Mcp-Name header carries an invalid Base64 sentinel value",
                header=raw_name,
                body="",
              ),
            )
          }
        None => ()
      }
  }
  None
}

///|
/// Computes the missing subset of required client capabilities for embedded `InputRequest`s
/// (2026-07-28 SEP-2322 + `-32021 MissingRequiredClientCapability`).
/// A bare `elicitation: {}` declaration satisfies `elicitation.form` per spec.
pub fn missing_capabilities_for_input_requests(
  input_requests : Map[String, InputRequest],
  declared_opt : Json?,
) -> Json? {
  let declared_map : Map[String, Json] = match declared_opt {
    Some(Object(m)) => m
    _ => Map([])
  }
  let missing : Map[String, Json] = Map([])
  let missing_elicit : Map[String, Json] = Map([])
  let mut missing_sampling_any = false
  let mut missing_sampling_tools = false
  input_requests.each((_key, req) => {
    match req {
      InputRequest::ElicitForm(_) =>
        match declared_map.get("elicitation") {
          None => missing_elicit["form"] = Json::object(Map([]))
          Some(Object(em)) => {
            let has_form = em.contains("form")
            let has_url = em.contains("url")
            // Bare `{}` implies form support; `{ url: {} }` without `form` does not
            if !has_form && has_url {
              missing_elicit["form"] = Json::object(Map([]))
            }
          }
          Some(_) => missing_elicit["form"] = Json::object(Map([]))
        }
      InputRequest::ElicitUrl(..) =>
        match declared_map.get("elicitation") {
          Some(Object(em)) if em.contains("url") => ()
          _ => missing_elicit["url"] = Json::object(Map([]))
        }
      InputRequest::CreateMessage(params) => {
        let needs_tools = !params.tools.is_empty() ||
          params.tool_choice is Some(_)
        match declared_map.get("sampling") {
          None => {
            missing_sampling_any = true
            if needs_tools {
              missing_sampling_tools = true
            }
          }
          Some(Object(sm)) =>
            if needs_tools && !sm.contains("tools") {
              missing_sampling_tools = true
            }
          Some(_) => {
            missing_sampling_any = true
            if needs_tools {
              missing_sampling_tools = true
            }
          }
        }
      }
      InputRequest::ListRoots =>
        match declared_map.get("roots") {
          Some(Object(_)) => ()
          _ => missing["roots"] = Json::object(Map([]))
        }
    }
  })
  if !missing_elicit.is_empty() {
    missing["elicitation"] = Json::object(missing_elicit)
  }
  if missing_sampling_tools {
    missing["sampling"] = Json::object(Map([("tools", Json::object(Map([])))]))
  } else if missing_sampling_any {
    missing["sampling"] = Json::object(Map([]))
  }
  if missing.is_empty() {
    None
  } else {
    Some(Json::object(missing))
  }
}

///|
/// Maps a JSON-RPC error code to the spec-mandated HTTP status code on the modern (2026-07-28) path.
pub fn http_status_for_modern_error(code : Int32, is_ladder : Bool) -> Int32 {
  if !is_ladder {
    return if code == err_missing_required_client_capability {
      400
    } else {
      200
    }
  }
  if code == err_method_not_found {
    404
  } else if code == err_parse_error ||
    code == err_invalid_request ||
    code == err_header_mismatch ||
    code == err_missing_required_client_capability ||
    code == err_unsupported_protocol_version ||
    code == err_invalid_params {
    400
  } else {
    200
  }
}

///|
fn validate_value_with_defs(
  path : String,
  value : Json,
  schema : Json,
  defs : Map[String, Json]?,
  depth_left : Int32,
) -> String? {
  if depth_left <= 0 {
    return None
  }
  let obj = match schema {
    Object(m) => m
    _ => return None
  }
  let eff_defs : Map[String, Json]? = match obj.get("$defs") {
    Some(Object(d)) => Some(d)
    _ => defs
  }
  match obj.get("$ref") {
    Some(String(ref_str)) if ref_str.has_prefix("#/$defs/") => {
      let def_name = ref_str[8:].to_owned()
      match eff_defs {
        Some(d) =>
          match d.get(def_name) {
            Some(target_schema) =>
              return validate_value_with_defs(
                path,
                value,
                target_schema,
                eff_defs,
                depth_left - 1,
              )
            None => ()
          }
        None => ()
      }
    }
    _ => ()
  }
  match obj.get("enum") {
    Some(Array(allowed)) => {
      let mut found = false
      for item in allowed {
        if item == value {
          found = true
          break
        }
      }
      if !found {
        return Some("Field '\{path}' value is not in allowed enum")
      }
    }
    _ => ()
  }
  match obj.get("type") {
    Some(String(expected)) => {
      let ok = match (expected, value) {
        ("string", String(_)) => true
        ("boolean", True) | ("boolean", False) => true
        ("null", Null) => true
        ("number", Number(n, ..)) => !(n.is_nan() || n.is_inf())
        ("integer", Number(n, ..)) => is_safe_exact_int64(n)
        ("array", Array(_)) => true
        ("object", Object(_)) => true
        _ => false
      }
      if !ok {
        return Some("Field '\{path}' expected type '\{expected}'")
      }
    }
    Some(Array(types)) => {
      let mut ok = false
      for t in types {
        match t {
          String(expected) => {
            let matched = match (expected, value) {
              ("string", String(_)) => true
              ("boolean", True) | ("boolean", False) => true
              ("null", Null) => true
              ("number", Number(n, ..)) => !(n.is_nan() || n.is_inf())
              ("integer", Number(n, ..)) => is_safe_exact_int64(n)
              ("array", Array(_)) => true
              ("object", Object(_)) => true
              _ => false
            }
            if matched {
              ok = true
              break
            }
          }
          _ => ()
        }
      }
      if !ok {
        return Some("Field '\{path}' did not match any allowed type")
      }
    }
    _ => ()
  }
  match value {
    Object(val_map) => {
      match obj.get("required") {
        Some(Array(reqs)) =>
          for req in reqs {
            match req {
              String(rname) =>
                if !val_map.contains(rname) {
                  let full = if path.is_empty() {
                    rname
                  } else {
                    "\{path}.\{rname}"
                  }
                  return Some("Missing required argument: \{full}")
                }
              _ => ()
            }
          }
        _ => ()
      }
      let props_opt : Map[String, Json]? = match obj.get("properties") {
        Some(Object(p)) => Some(p)
        _ => None
      }
      if obj.get("additionalProperties") == Some(Json::boolean(false)) {
        let mut extra : String? = None
        val_map.each((k, _v) => {
          if extra is None {
            let known = match props_opt {
              Some(p) => p.contains(k)
              None => false
            }
            if !known {
              extra = Some(k)
            }
          }
        })
        match extra {
          Some(k) => {
            let full = if path.is_empty() { k } else { "\{path}.\{k}" }
            return Some("Unexpected additional property: \{full}")
          }
          None => ()
        }
      }
      match props_opt {
        Some(props) => {
          let mut err : String? = None
          val_map.each((k, v) => {
            if err is None {
              match props.get(k) {
                Some(prop_schema) => {
                  let full = if path.is_empty() { k } else { "\{path}.\{k}" }
                  err = validate_value_with_defs(
                    full,
                    v,
                    prop_schema,
                    eff_defs,
                    depth_left - 1,
                  )
                }
                None => ()
              }
            }
          })
          if err is Some(_) {
            return err
          }
        }
        None => ()
      }
    }
    Array(items) =>
      match obj.get("items") {
        Some(item_schema) =>
          for i = 0; i < items.length(); i = i + 1 {
            match
              validate_value_with_defs(
                "\{path}[\{i}]",
                items[i],
                item_schema,
                eff_defs,
                depth_left - 1,
              ) {
              Some(e) => return Some(e)
              None => ()
            }
          }
        None => ()
      }
    _ => ()
  }
  None
}

///|
/// Lightweight runtime JSON Schema validator for programmatic `register_tool` `input_schema`.
/// Checks `required`, property `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`, `null`),
/// `enum`, local `#/$defs/` `$ref`, and `additionalProperties: false`. Returns `Some(reason)` on first violation.
pub fn validate_value_against_schema(
  path : String,
  value : Json,
  schema : Json,
) -> String? {
  validate_value_with_defs(path, value, schema, None, 32)
}

///|
pub fn validate_tool_arguments(
  args : Map[String, Json],
  input_schema : Json,
) -> String? {
  validate_value_against_schema("", Json::object(args), input_schema)
}

///|
pub fn is_json_content_type_header(ct : String?) -> Bool {
  match ct {
    Some(raw) =>
      !raw.contains(",") && extract_mime_base(raw) == "application/json"
    None => false
  }
}

///|
fn is_ref_data_position_key(k : String) -> Bool {
  k == "const" || k == "enum" || k == "default" || k == "examples"
}

///|
fn is_ref_name_map_key(k : String) -> Bool {
  k == "properties" ||
  k == "patternProperties" ||
  k == "$defs" ||
  k == "definitions" ||
  k == "dependentSchemas" ||
  k == "dependencies"
}

///|
fn establishes_new_schema_base(id_opt : Json?) -> Bool {
  match id_opt {
    None => false
    Some(String(s)) if s.has_prefix("#") => false
    Some(_) => true
  }
}

///|
fn rewrite_schema_refs_for_legacy(
  node : Json,
  parent_is_name_map : Bool,
) -> Json {
  match node {
    Array(items) =>
      Json::array(
        items.map(item => rewrite_schema_refs_for_legacy(item, false)),
      )
    Object(m) => {
      if !parent_is_name_map && establishes_new_schema_base(m.get("$id")) {
        return node
      }
      let out : Map[String, Json] = Map([])
      m.each((k, v) => {
        if parent_is_name_map {
          out[k] = rewrite_schema_refs_for_legacy(v, false)
        } else if k == "$ref" || k == "$dynamicRef" || k == "$recursiveRef" {
          match v {
            String("#") => out[k] = Json::string("#/properties/result")
            String(s) if s.has_prefix("#/") =>
              out[k] = Json::string("#/properties/result\{s[1:].to_owned()}")
            _ => out[k] = v
          }
        } else if is_ref_data_position_key(k) {
          out[k] = v
        } else if is_ref_name_map_key(k) {
          out[k] = rewrite_schema_refs_for_legacy(v, true)
        } else {
          out[k] = rewrite_schema_refs_for_legacy(v, false)
        }
      })
      Json::object(out)
    }
    other => other
  }
}

///|
/// Returns true if `schema` is a JSON Schema object whose root does NOT declare
/// `"type": "object"` (matching SEP-2106 `isNonObjectJsonSchemaRoot`).
pub fn is_non_object_json_schema_root(schema : Json) -> Bool {
  match schema {
    Object(m) => m.get("type") != Some(Json::string("object"))
    _ => false
  }
}

///|
/// SEP-2106 legacy `outputSchema` projection for 2025-era (`2025-11-25`) clients:
/// object-rooted schemas (`type: "object"`) pass through unchanged; non-object roots
/// are wrapped in `{ "type": "object", "properties": { "result":  }, "required": ["result"] }`
/// with `$schema` hoisted and same-document `$ref`/`$dynamicRef`/`$recursiveRef` pointers rewritten.
pub fn wrap_output_schema_for_legacy(schema : Json) -> Json {
  let obj = match schema {
    Object(m) => m
    _ => return schema
  }
  if !is_non_object_json_schema_root(schema) {
    return schema
  }
  let wrapped : Map[String, Json] = Map([])
  match obj.get("$schema") {
    Some(String(s)) => wrapped["$schema"] = Json::string(s)
    _ => ()
  }
  let inner = if establishes_new_schema_base(obj.get("$id")) {
    schema
  } else {
    rewrite_schema_refs_for_legacy(schema, false)
  }
  wrapped["type"] = Json::string("object")
  wrapped["properties"] = Json::object(Map([("result", inner)]))
  wrapped["required"] = Json::array([Json::string("result")])
  Json::object(wrapped)
}

///|
/// Convenience allowlist for localhost DNS rebinding protection (`validate_host_header`).
pub fn localhost_allowed_hostnames() -> Array[String] {
  ["localhost", "127.0.0.1", "[::1]"]
}

///|
/// Convenience allowlist for localhost browser Origin protection (`validate_origin_header`).
pub fn localhost_allowed_origins() -> Array[String] {
  ["localhost", "127.0.0.1", "[::1]"]
}

///|
/// Extracts the lowercase port-stripped hostname from an authority string (`host[:port]` or `[ipv6][:port]`).
/// Returns `None` if malformed (contains userinfo `@`, whitespace, slash, unclosed bracket, or invalid port).
fn extract_hostname_from_authority(authority : String) -> String? {
  if authority.is_empty() {
    return None
  }
  for ch in authority {
    if ch == '@' ||
      ch == '/' ||
      ch == '?' ||
      ch == '#' ||
      ch == ' ' ||
      ch == '\t' {
      return None
    }
  }
  if authority.has_prefix("[") {
    match authority.find("]") {
      Some(close_idx) => {
        let ipv6 = authority[:close_idx + 1].to_owned().to_lower()
        let rest = authority[close_idx + 1:].to_owned()
        if rest.is_empty() {
          Some(ipv6)
        } else if rest.has_prefix(":") {
          let port_str = rest[1:].to_owned()
          if is_valid_tcp_port(port_str) {
            Some(ipv6)
          } else {
            None
          }
        } else {
          None
        }
      }
      None => None
    }
  } else {
    match authority.find(":") {
      Some(colon_idx) => {
        let host_part = authority[:colon_idx].to_owned().to_lower()
        let port_str = authority[colon_idx + 1:].to_owned()
        if host_part.is_empty() || !is_valid_tcp_port(port_str) {
          None
        } else {
          Some(host_part)
        }
      }
      None => Some(authority.to_lower())
    }
  }
}

///|
fn is_valid_tcp_port(port_str : String) -> Bool {
  if port_str.is_empty() {
    return false
  }
  let mut n = 0
  for ch in port_str {
    if ch < '0' || ch > '9' {
      return false
    }
    n = n * 10 + (ch.to_int() - '0'.to_int())
    if n > 65535 {
      return false
    }
  }
  true
}

///|
/// Validates an HTTP `Host` header against a port-agnostic hostname allowlist
/// (matches `@modelcontextprotocol/server` `validateHostHeader`).
/// Returns `None` when allowed, or `Some(message)` on failure.
pub fn validate_host_header(
  host_header : String?,
  allowed_hostnames : Array[String],
) -> String? {
  let raw = match host_header {
    Some(s) if !s.is_empty() => strip_http_ows(s)
    _ => return Some("Missing Host header")
  }
  if raw.is_empty() {
    return Some("Missing Host header")
  }
  let hostname = match extract_hostname_from_authority(raw) {
    Some(h) => h
    None => return Some("Invalid Host header: \{raw}")
  }
  for allowed in allowed_hostnames {
    if allowed.to_lower() == hostname {
      return None
    }
  }
  Some("Invalid Host: \{hostname}")
}

///|
/// Validates an HTTP `Origin` header against a port-agnostic hostname allowlist
/// (matches `@modelcontextprotocol/server` `validateOriginHeader`).
/// Missing/empty `Origin` passes (non-browser clients); opaque `"null"` or unparseable
/// origins fail closed; `://*` (non-http/https) supports browser extensions.
/// Returns `None` when allowed, or `Some(message)` on failure.
pub fn validate_origin_header(
  origin_header : String?,
  allowed_origin_hostnames : Array[String],
) -> String? {
  let raw = match origin_header {
    Some(s) if !s.is_empty() => {
      let trimmed = strip_http_ows(s)
      if trimmed.is_empty() {
        return Some("Invalid Origin header: whitespace-only")
      }
      trimmed
    }
    _ => return None
  }
  // RFC 6454 serialized origins must be `://[:]` with no path, query, or fragment
  if raw.contains("?") || raw.contains("#") {
    return Some("Invalid Origin header: \{raw}")
  }
  match raw.find("://") {
    Some(sep_idx) => {
      let after_scheme = raw[sep_idx + 3:].to_owned()
      if after_scheme.is_empty() || after_scheme.contains("/") {
        return Some("Invalid Origin header: \{raw}")
      }
    }
    None => return Some("Invalid Origin header: \{raw}")
  }
  let parsed = @url.Url::parse(raw) catch {
    _ => return Some("Invalid Origin header: \{raw}")
  }
  if parsed.scheme.is_empty() {
    return Some("Invalid Origin header: \{raw}")
  }
  let hostname = match extract_hostname_from_authority(parsed.host) {
    Some(h) if !h.is_empty() => h
    _ => return Some("Invalid Origin header: \{raw}")
  }
  let scheme = parsed.scheme.to_lower()
  if scheme != "http" && scheme != "https" {
    let wildcard = "\{scheme}://*"
    for allowed in allowed_origin_hostnames {
      if allowed.to_lower() == wildcard {
        return None
      }
    }
    return Some("Invalid Origin scheme: \{scheme}")
  }
  for allowed in allowed_origin_hostnames {
    if allowed.to_lower() == hostname {
      return None
    }
  }
  Some("Invalid Origin: \{hostname}")
}