///|
/// Latest standard MCP protocol version supported by `unmbt/ciallo-mcp`.
pub let latest_protocol_version : String = "2025-11-25"

///|
/// Protocol versions accepted during `initialize` negotiation (newest first).
pub let supported_protocol_versions : Array[String] = [
  "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07",
]

///|
/// Modern stateless discovery protocol versions (`server/discover`).
pub let modern_protocol_versions : Array[String] = ["2026-07-28"]

///|
/// Standard JSON-RPC 2.0 & MCP protocol error codes.
pub let err_parse_error : Int32 = -32700

///|
pub let err_invalid_request : Int32 = -32600

///|
pub let err_method_not_found : Int32 = -32601

///|
pub let err_invalid_params : Int32 = -32602

///|
pub let err_internal_error : Int32 = -32603

///|
pub let err_server_overloaded : Int32 = -32000

///|
/// Receive-tolerated legacy resource-not-found code (`-32002`).
/// Per 2026-07-28 spec, servers MUST emit `-32602` for `resources/read` misses
/// (see `McpProtocolError::resource_not_found`); kept as a constant for client interop.
pub let err_resource_not_found : Int32 = -32002

///|
/// SEP-2243 HTTP header/body mismatch error code (protocol revision 2026-07-28).
pub let err_header_mismatch : Int32 = -32020

///|
/// Missing required client capability error code (protocol revision 2026-07-28).
pub let err_missing_required_client_capability : Int32 = -32021

///|
/// Unsupported protocol version error code (protocol revision 2026-07-28).
pub let err_unsupported_protocol_version : Int32 = -32022

///|
pub let err_url_elicitation_required : Int32 = -32042

///|
/// Structured MCP JSON-RPC protocol error raised by handlers or client RPCs.
#derive(Debug, Eq)
#non_exhaustive
pub(all) suberror McpProtocolError {
  ProtocolError(code~ : Int32, message~ : String, data~ : Json?)
}

///|
pub fn McpProtocolError::invalid_params(
  message : String,
  data? : Json,
) -> McpProtocolError {
  ProtocolError(code=err_invalid_params, message~, data~)
}

///|
/// MCP 2025-11-25 spec: missing resource emits `-32602` with `data: { "uri": uri }`.
pub fn McpProtocolError::resource_not_found(uri : String) -> McpProtocolError {
  ProtocolError(
    code=err_invalid_params,
    message="Resource not found: \{uri}",
    data=Some(Json::object(Map([("uri", Json::string(uri))]))),
  )
}

///|
pub fn McpProtocolError::method_not_found(meth : String) -> McpProtocolError {
  ProtocolError(
    code=err_method_not_found,
    message="Method not found: \{meth}",
    data=None,
  )
}

///|
pub fn McpProtocolError::internal_error(
  message : String,
  data? : Json,
) -> McpProtocolError {
  ProtocolError(code=err_internal_error, message~, data~)
}

///|
pub fn McpProtocolError::unsupported_protocol_version(
  version : String,
) -> McpProtocolError {
  McpProtocolError::unsupported_protocol_version_list(
    requested=version,
    supported=modern_protocol_versions,
  )
}

///|
/// Emits `-32022` (`UnsupportedProtocolVersion`) with `data: { supported, requested? }`.
pub fn McpProtocolError::unsupported_protocol_version_list(
  requested? : String,
  supported~ : Array[String] = modern_protocol_versions,
) -> McpProtocolError {
  let d : Map[String, Json] = Map([
    ("supported", Json::array(supported.map(v => Json::string(v)))),
  ])
  let msg = match requested {
    Some(ver) => {
      d["requested"] = Json::string(ver)
      "Unsupported protocol version: \{ver}"
    }
    None =>
      "Unsupported protocol version: the request did not name a protocol version"
  }
  ProtocolError(
    code=err_unsupported_protocol_version,
    message=msg,
    data=Some(Json::object(d)),
  )
}

///|
/// Emits `-32020` (`HeaderMismatch`) with `data: { mismatch: { header, body } }`.
pub fn McpProtocolError::header_mismatch(
  detail : String,
  header~ : String,
  body~ : String,
) -> McpProtocolError {
  ProtocolError(
    code=err_header_mismatch,
    message="Bad Request: the request headers and body disagree: \{detail}",
    data=Some(
      Json::object(
        Map([
          (
            "mismatch",
            Json::object(
              Map([
                ("header", Json::string(header)),
                ("body", Json::string(body)),
              ]),
            ),
          ),
        ]),
      ),
    ),
  )
}

///|
/// Emits `-32021` (`MissingRequiredClientCapability`) with `data: { requiredCapabilities }`.
pub fn McpProtocolError::missing_required_client_capability(
  required_capabilities : Json,
) -> McpProtocolError {
  ProtocolError(
    code=err_missing_required_client_capability,
    message="Missing required client capability",
    data=Some(
      Json::object(Map([("requiredCapabilities", required_capabilities)])),
    ),
  )
}

///|
pub fn McpProtocolError::url_elicitation_required(
  message : String,
  elicitations : Array[ElicitUrlParams],
) -> McpProtocolError {
  ProtocolError(
    code=err_url_elicitation_required,
    message~,
    data=Some(
      Json::object(
        Map([("elicitations", Json::array(elicitations.map(e => e.to_json())))]),
      ),
    ),
  )
}

///|
/// Protocol era: `Legacy` (`2025-11-25` and earlier via `initialize`) or
/// `Modern` (`2026-07-28` and later via `server/discover` & per-request `_meta` envelope).
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum McpEra {
  Legacy
  Modern
}

///|
/// How `mount_http` handles legacy (pre-2026-07-28, envelope-less) HTTP requests.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum LegacyHttpMode {
  Stateless
  Reject
}

///|
/// How `mount_http` shapes HTTP responses for modern (2026-07-28) request exchanges
/// (matches `@modelcontextprotocol/server` `PerRequestResponseMode`).
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum HttpResponseMode {
  Auto
  Sse
  Json
}

///|
/// Configuration for `McpServer::mount_http` (Streamable HTTP + dual-era 2026-07-28/2025-11-25).
#derive(Debug, Eq)
pub(all) struct McpHttpOptions {
  legacy_mode : LegacyHttpMode
  response_mode : HttpResponseMode
  max_request_body_size : Int64
  keep_alive_ms : Int32
  allowed_origins : Array[String]?
  allowed_hosts : Array[String]?
}

///|
pub fn McpHttpOptions::McpHttpOptions(
  legacy_mode~ : LegacyHttpMode = LegacyHttpMode::Stateless,
  response_mode~ : HttpResponseMode = HttpResponseMode::Auto,
  max_request_body_size~ : Int64 = 4L * 1024L * 1024L,
  keep_alive_ms~ : Int32 = 15000,
  allowed_origins? : Array[String],
  allowed_hosts? : Array[String],
) -> McpHttpOptions {
  {
    legacy_mode,
    response_mode,
    max_request_body_size: if max_request_body_size > 0L {
      max_request_body_size
    } else {
      4L * 1024L * 1024L
    },
    keep_alive_ms: if keep_alive_ms >= 0 {
      keep_alive_ms
    } else {
      15000
    },
    allowed_origins,
    allowed_hosts,
  }
}

///|
/// SEP-2549 cache scope for 2026-07-28 cacheable results.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum CacheScope {
  Public
  Private
}

///|
pub fn CacheScope::as_str(self : CacheScope) -> String {
  match self {
    Public => "public"
    Private => "private"
  }
}

///|
/// SEP-2549 cache hint (`ttlMs` and `cacheScope`) for 2026-07-28 cacheable results.
#derive(Debug, Eq)
pub(all) struct CacheHint {
  ttl_ms : Int32
  cache_scope : CacheScope
}

///|
pub fn CacheHint::CacheHint(
  ttl_ms~ : Int32 = 0,
  cache_scope~ : CacheScope = CacheScope::Private,
) -> CacheHint {
  { ttl_ms: if ttl_ms < 0 { 0 } else { ttl_ms }, cache_scope, }
}

///|
/// Identifies the active MCP transport executing a request.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum McpTransport {
  Stdio
  StreamableHttp
}

///|
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum IconTheme {
  Light
  Dark
}

///|
pub fn IconTheme::as_str(self : IconTheme) -> String {
  match self {
    Light => "light"
    Dark => "dark"
  }
}

///|
#derive(Debug, Eq)
pub(all) struct McpIcon {
  src : String
  mime_type : String?
  sizes : Array[String]
  theme : IconTheme?
}

///|
pub fn McpIcon::McpIcon(
  src~ : String,
  mime_type? : String,
  sizes~ : Array[String] = [],
  theme? : IconTheme,
) -> McpIcon {
  { src, mime_type, sizes, theme, }
}

///|
pub fn McpIcon::to_json(self : McpIcon) -> Json {
  let m : Map[String, Json] = Map([("src", Json::string(self.src))])
  match self.mime_type {
    Some(mt) => m["mimeType"] = Json::string(mt)
    None => ()
  }
  if !self.sizes.is_empty() {
    m["sizes"] = Json::array(self.sizes.map(s => Json::string(s)))
  }
  match self.theme {
    Some(t) => m["theme"] = Json::string(t.as_str())
    None => ()
  }
  Json::object(m)
}

///|
/// Rich MCP server / client Implementation descriptor (2025-11-25).
#derive(Debug, Eq)
pub(all) struct McpImplementation {
  name : String
  version : String
  title : String?
  description : String?
  website_url : String?
  icons : Array[McpIcon]
}

///|
pub fn McpImplementation::McpImplementation(
  name~ : String,
  version~ : String,
  title? : String,
  description? : String,
  website_url? : String,
  icons~ : Array[McpIcon] = [],
) -> McpImplementation {
  { name, version, title, description, website_url, icons, }
}

///|
pub fn McpImplementation::from_openapi(
  info : @openapi.OpenApiInfo,
) -> McpImplementation {
  {
    name: info.title,
    version: info.version,
    title: Some(info.title),
    description: info.description,
    website_url: None,
    icons: [],
  }
}

///|
pub fn McpImplementation::to_json(self : McpImplementation) -> Json {
  let m : Map[String, Json] = Map([
    ("name", Json::string(self.name)),
    ("version", Json::string(self.version)),
  ])
  match self.title {
    Some(t) => m["title"] = Json::string(t)
    None => ()
  }
  match self.description {
    Some(d) => m["description"] = Json::string(d)
    None => ()
  }
  match self.website_url {
    Some(u) => m["websiteUrl"] = Json::string(u)
    None => ()
  }
  if !self.icons.is_empty() {
    m["icons"] = Json::array(self.icons.map(i => i.to_json()))
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum PromptRole {
  User
  Assistant
}

///|
pub fn PromptRole::as_str(self : PromptRole) -> String {
  match self {
    User => "user"
    Assistant => "assistant"
  }
}

///|
pub fn PromptRole::parse(s : StringView) -> PromptRole? {
  match s {
    "user" => Some(User)
    "assistant" => Some(Assistant)
    _ => None
  }
}

///|
/// MCP content / resource annotations (`audience`, `priority`, `lastModified`).
#derive(Debug, Eq)
pub(all) struct McpAnnotations {
  audience : Array[PromptRole]?
  priority : Double?
  last_modified : String?
}

///|
pub fn McpAnnotations::McpAnnotations(
  audience? : Array[PromptRole],
  priority? : Double,
  last_modified? : String,
) -> McpAnnotations {
  { audience, priority, last_modified, }
}

///|
pub fn McpAnnotations::to_json(self : McpAnnotations) -> Json {
  let m : Map[String, Json] = Map([])
  match self.audience {
    Some(aud) =>
      m["audience"] = Json::array(aud.map(r => Json::string(r.as_str())))
    None => ()
  }
  match self.priority {
    Some(p) => m["priority"] = Json::number(p)
    None => ()
  }
  match self.last_modified {
    Some(lm) => m["lastModified"] = Json::string(lm)
    None => ()
  }
  Json::object(m)
}

///|
/// MCP 2025-11-25 ToolAnnotations behavioral hints for LLM hosts.
#derive(Debug, Eq)
pub(all) struct ToolAnnotations {
  title : String?
  read_only_hint : Bool?
  destructive_hint : Bool?
  idempotent_hint : Bool?
  open_world_hint : Bool?
}

///|
pub fn ToolAnnotations::ToolAnnotations(
  title? : String,
  read_only_hint? : Bool,
  destructive_hint? : Bool,
  idempotent_hint? : Bool,
  open_world_hint? : Bool,
) -> ToolAnnotations {
  { title, read_only_hint, destructive_hint, idempotent_hint, open_world_hint, }
}

///|
pub fn ToolAnnotations::to_json(self : ToolAnnotations) -> Json {
  let m : Map[String, Json] = Map([])
  match self.title {
    Some(t) => m["title"] = Json::string(t)
    None => ()
  }
  match self.read_only_hint {
    Some(v) => m["readOnlyHint"] = Json::boolean(v)
    None => ()
  }
  match self.destructive_hint {
    Some(v) => m["destructiveHint"] = Json::boolean(v)
    None => ()
  }
  match self.idempotent_hint {
    Some(v) => m["idempotentHint"] = Json::boolean(v)
    None => ()
  }
  match self.open_world_hint {
    Some(v) => m["openWorldHint"] = Json::boolean(v)
    None => ()
  }
  Json::object(m)
}

///|
/// Text or Base64-encoded binary resource contents.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum ResourceContents {
  Text(
    uri~ : String,
    mime_type~ : String?,
    text~ : String,
    meta~ : Map[String, Json]?,
  )
  Blob(
    uri~ : String,
    mime_type~ : String?,
    blob~ : String,
    meta~ : Map[String, Json]?,
  )
}

///|
pub fn ResourceContents::text(
  uri~ : String,
  text~ : String,
  mime_type? : String,
  meta? : Map[String, Json],
) -> ResourceContents {
  Text(uri~, mime_type~, text~, meta~)
}

///|
pub fn ResourceContents::blob(
  uri~ : String,
  blob~ : String,
  mime_type? : String,
  meta? : Map[String, Json],
) -> ResourceContents {
  Blob(uri~, mime_type~, blob~, meta~)
}

///|
pub fn ResourceContents::blob_bytes(
  uri~ : String,
  bytes~ : Bytes,
  mime_type? : String,
  meta? : Map[String, Json],
) -> ResourceContents {
  Blob(uri~, mime_type~, blob=@base64.encode(bytes), meta~)
}

///|
pub fn ResourceContents::to_json(self : ResourceContents) -> Json {
  match self {
    Text(uri~, mime_type~, text~, meta~) => {
      let m : Map[String, Json] = Map([
        ("uri", Json::string(uri)),
        ("text", Json::string(text)),
      ])
      match mime_type {
        Some(mt) => m["mimeType"] = Json::string(mt)
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
    Blob(uri~, mime_type~, blob~, meta~) => {
      let m : Map[String, Json] = Map([
        ("uri", Json::string(uri)),
        ("blob", Json::string(blob)),
      ])
      match mime_type {
        Some(mt) => m["mimeType"] = Json::string(mt)
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
  }
}

///|
/// Static or listed MCP Resource metadata descriptor.
#derive(Debug, Eq)
pub(all) struct McpResourceInfo {
  uri : String
  name : String
  title : String?
  description : String?
  mime_type : String?
  size : Int64?
  icons : Array[McpIcon]
  annotations : McpAnnotations?
  meta : Map[String, Json]?
}

///|
pub fn McpResourceInfo::McpResourceInfo(
  uri~ : String,
  name~ : String,
  title? : String,
  description? : String,
  mime_type? : String,
  size? : Int64,
  icons~ : Array[McpIcon] = [],
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> McpResourceInfo {
  { uri, name, title, description, mime_type, size, icons, annotations, meta, }
}

///|
pub fn McpResourceInfo::to_json(self : McpResourceInfo) -> Json {
  let m : Map[String, Json] = Map([
    ("uri", Json::string(self.uri)),
    ("name", Json::string(self.name)),
  ])
  match self.title {
    Some(t) => m["title"] = Json::string(t)
    None => ()
  }
  match self.description {
    Some(d) => m["description"] = Json::string(d)
    None => ()
  }
  match self.mime_type {
    Some(mt) => m["mimeType"] = Json::string(mt)
    None => ()
  }
  match self.size {
    Some(sz) => m["size"] = Json::number(sz.to_double())
    None => ()
  }
  if !self.icons.is_empty() {
    m["icons"] = Json::array(self.icons.map(i => i.to_json()))
  }
  match self.annotations {
    Some(a) => m["annotations"] = a.to_json()
    None => ()
  }
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
/// RFC 6570 Resource Template metadata descriptor.
#derive(Debug, Eq)
pub(all) struct McpResourceTemplateInfo {
  uri_template : String
  name : String
  title : String?
  description : String?
  mime_type : String?
  icons : Array[McpIcon]
  annotations : McpAnnotations?
  meta : Map[String, Json]?
}

///|
pub fn McpResourceTemplateInfo::McpResourceTemplateInfo(
  uri_template~ : String,
  name~ : String,
  title? : String,
  description? : String,
  mime_type? : String,
  icons~ : Array[McpIcon] = [],
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> McpResourceTemplateInfo {
  {
    uri_template,
    name,
    title,
    description,
    mime_type,
    icons,
    annotations,
    meta,
  }
}

///|
pub fn McpResourceTemplateInfo::to_json(self : McpResourceTemplateInfo) -> Json {
  let m : Map[String, Json] = Map([
    ("uriTemplate", Json::string(self.uri_template)),
    ("name", Json::string(self.name)),
  ])
  match self.title {
    Some(t) => m["title"] = Json::string(t)
    None => ()
  }
  match self.description {
    Some(d) => m["description"] = Json::string(d)
    None => ()
  }
  match self.mime_type {
    Some(mt) => m["mimeType"] = Json::string(mt)
    None => ()
  }
  if !self.icons.is_empty() {
    m["icons"] = Json::array(self.icons.map(i => i.to_json()))
  }
  match self.annotations {
    Some(a) => m["annotations"] = a.to_json()
    None => ()
  }
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct ReadResourceResult {
  contents : Array[ResourceContents]
  meta : Map[String, Json]?
}

///|
pub fn ReadResourceResult::ReadResourceResult(
  contents : Array[ResourceContents],
  meta? : Map[String, Json],
) -> ReadResourceResult {
  { contents, meta, }
}

///|
pub fn ReadResourceResult::to_json(self : ReadResourceResult) -> Json {
  let m : Map[String, Json] = Map([
    ("contents", Json::array(self.contents.map(c => c.to_json()))),
  ])
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
/// Multimodal MCP 2025-11-25 ContentBlock union (`text`, `image`, `audio`, `resource_link`, `resource`).
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum ContentBlock {
  Text(
    text~ : String,
    annotations~ : McpAnnotations?,
    meta~ : Map[String, Json]?,
  )
  Image(
    data~ : String,
    mime_type~ : String,
    annotations~ : McpAnnotations?,
    meta~ : Map[String, Json]?,
  )
  Audio(
    data~ : String,
    mime_type~ : String,
    annotations~ : McpAnnotations?,
    meta~ : Map[String, Json]?,
  )
  ResourceLink(
    uri~ : String,
    name~ : String,
    title~ : String?,
    description~ : String?,
    mime_type~ : String?,
    size~ : Int64?,
    icons~ : Array[McpIcon],
    annotations~ : McpAnnotations?,
    meta~ : Map[String, Json]?,
  )
  EmbeddedResource(
    resource~ : ResourceContents,
    annotations~ : McpAnnotations?,
    meta~ : Map[String, Json]?,
  )
}

///|
pub fn ContentBlock::text(
  text : String,
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> ContentBlock {
  Text(text~, annotations~, meta~)
}

///|
pub fn ContentBlock::image_bytes(
  bytes : Bytes,
  mime_type~ : String,
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> ContentBlock {
  Image(data=@base64.encode(bytes), mime_type~, annotations~, meta~)
}

///|
pub fn ContentBlock::audio_bytes(
  bytes : Bytes,
  mime_type~ : String,
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> ContentBlock {
  Audio(data=@base64.encode(bytes), mime_type~, annotations~, meta~)
}

///|
pub fn ContentBlock::resource_link(
  uri~ : String,
  name~ : String,
  title? : String,
  description? : String,
  mime_type? : String,
  size? : Int64,
  icons~ : Array[McpIcon] = [],
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> ContentBlock {
  ResourceLink(
    uri~,
    name~,
    title~,
    description~,
    mime_type~,
    size~,
    icons~,
    annotations~,
    meta~,
  )
}

///|
pub fn ContentBlock::embedded_resource(
  resource : ResourceContents,
  annotations? : McpAnnotations,
  meta? : Map[String, Json],
) -> ContentBlock {
  EmbeddedResource(resource~, annotations~, meta~)
}

///|
pub fn ContentBlock::to_json(self : ContentBlock) -> Json {
  match self {
    Text(text~, annotations~, meta~) => {
      let m : Map[String, Json] = Map([
        ("type", Json::string("text")),
        ("text", Json::string(text)),
      ])
      match annotations {
        Some(a) => m["annotations"] = a.to_json()
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
    Image(data~, mime_type~, annotations~, meta~) => {
      let m : Map[String, Json] = Map([
        ("type", Json::string("image")),
        ("data", Json::string(data)),
        ("mimeType", Json::string(mime_type)),
      ])
      match annotations {
        Some(a) => m["annotations"] = a.to_json()
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
    Audio(data~, mime_type~, annotations~, meta~) => {
      let m : Map[String, Json] = Map([
        ("type", Json::string("audio")),
        ("data", Json::string(data)),
        ("mimeType", Json::string(mime_type)),
      ])
      match annotations {
        Some(a) => m["annotations"] = a.to_json()
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
    ResourceLink(
      uri~,
      name~,
      title~,
      description~,
      mime_type~,
      size~,
      icons~,
      annotations~,
      meta~,
    ) => {
      let m : Map[String, Json] = Map([
        ("type", Json::string("resource_link")),
        ("uri", Json::string(uri)),
        ("name", Json::string(name)),
      ])
      match title {
        Some(t) => m["title"] = Json::string(t)
        None => ()
      }
      match description {
        Some(d) => m["description"] = Json::string(d)
        None => ()
      }
      match mime_type {
        Some(mt) => m["mimeType"] = Json::string(mt)
        None => ()
      }
      match size {
        Some(sz) => m["size"] = Json::number(sz.to_double())
        None => ()
      }
      if !icons.is_empty() {
        m["icons"] = Json::array(icons.map(i => i.to_json()))
      }
      match annotations {
        Some(a) => m["annotations"] = a.to_json()
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
    EmbeddedResource(resource~, annotations~, meta~) => {
      let m : Map[String, Json] = Map([
        ("type", Json::string("resource")),
        ("resource", resource.to_json()),
      ])
      match annotations {
        Some(a) => m["annotations"] = a.to_json()
        None => ()
      }
      match meta {
        Some(mt) => m["_meta"] = Json::object(mt)
        None => ()
      }
      Json::object(m)
    }
  }
}

///|
/// Result of executing a tool (`tools/call`).
#derive(Debug, Eq)
pub(all) struct CallToolResult {
  content : Array[ContentBlock]
  structured_content : Json?
  is_error : Bool
  meta : Map[String, Json]?
}

///|
pub fn CallToolResult::CallToolResult(
  content : Array[ContentBlock],
  structured_content? : Json,
  is_error~ : Bool = false,
  meta? : Map[String, Json],
) -> CallToolResult {
  { content, structured_content, is_error, meta, }
}

///|
pub fn CallToolResult::text(
  text : String,
  is_error~ : Bool = false,
  structured_content? : Json,
) -> CallToolResult {
  {
    content: [ContentBlock::text(text)],
    structured_content,
    is_error,
    meta: None,
  }
}

///|
pub fn CallToolResult::json(
  value : Json,
  is_error~ : Bool = false,
) -> CallToolResult {
  {
    content: [ContentBlock::text(value.stringify())],
    structured_content: Some(value),
    is_error,
    meta: None,
  }
}

///|
pub fn CallToolResult::to_json(self : CallToolResult) -> Json {
  self.to_json_for_era(is_modern=true)
}

///|
/// Serializes `CallToolResult` respecting era wire rules (SEP-2106):
/// - 搂4.3 TextContent auto-append (both eras): when `structuredContent` is a non-object
///   value (array/primitive/null) and `content` carries no `Text` block, appends
///   `{ "type": "text", "text": structuredContent.stringify() }`.
/// - On `2025-11-25` (`is_modern=false`), `structuredContent` MUST be a JSON object
///   (non-object values are wrapped as `{ "result": value }`).
/// - On `2026-07-28` (`is_modern=true`), any JSON value is emitted verbatim.
pub fn CallToolResult::to_json_for_era(
  self : CallToolResult,
  is_modern~ : Bool,
  output_schema? : Json,
) -> Json {
  let content_blocks = self.content.copy()
  match self.structured_content {
    Some(sc) => {
      let is_non_object = match sc {
        Object(_) => false
        _ => true
      }
      if is_non_object {
        let mut has_text = false
        for blk in content_blocks {
          match blk {
            ContentBlock::Text(..) => {
              has_text = true
              break
            }
            _ => ()
          }
        }
        if !has_text {
          content_blocks.push(ContentBlock::text(sc.stringify()))
        }
      }
    }
    None => ()
  }
  let m : Map[String, Json] = Map([
    ("content", Json::array(content_blocks.map(b => b.to_json()))),
    ("isError", Json::boolean(self.is_error)),
  ])
  match self.structured_content {
    Some(sc) =>
      if is_modern {
        m["structuredContent"] = sc
      } else {
        let value_is_non_object = match sc {
          Object(_) => false
          _ => true
        }
        let schema_wrapped = match output_schema {
          Some(s) => is_non_object_json_schema_root(s)
          None => false
        }
        if value_is_non_object || schema_wrapped {
          m["structuredContent"] = Json::object(Map([("result", sc)]))
        } else {
          m["structuredContent"] = sc
        }
      }
    None => ()
  }
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct PromptArgument {
  name : String
  description : String?
  required : Bool
}

///|
pub fn PromptArgument::PromptArgument(
  name~ : String,
  description? : String,
  required~ : Bool = false,
) -> PromptArgument {
  { name, description, required, }
}

///|
pub fn PromptArgument::to_json(self : PromptArgument) -> Json {
  let m : Map[String, Json] = Map([("name", Json::string(self.name))])
  match self.description {
    Some(d) => m["description"] = Json::string(d)
    None => ()
  }
  if self.required {
    m["required"] = Json::boolean(true)
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct PromptMessage {
  role : PromptRole
  content : ContentBlock
}

///|
pub fn PromptMessage::PromptMessage(
  role~ : PromptRole,
  content~ : ContentBlock,
) -> PromptMessage {
  { role, content, }
}

///|
pub fn PromptMessage::user_text(text : String) -> PromptMessage {
  { role: PromptRole::User, content: ContentBlock::text(text), }
}

///|
pub fn PromptMessage::assistant_text(text : String) -> PromptMessage {
  { role: PromptRole::Assistant, content: ContentBlock::text(text), }
}

///|
pub fn PromptMessage::to_json(self : PromptMessage) -> Json {
  Json::object(
    Map([
      ("role", Json::string(self.role.as_str())),
      ("content", self.content.to_json()),
    ]),
  )
}

///|
#derive(Debug, Eq)
pub(all) struct GetPromptResult {
  description : String?
  messages : Array[PromptMessage]
  meta : Map[String, Json]?
}

///|
pub fn GetPromptResult::GetPromptResult(
  messages : Array[PromptMessage],
  description? : String,
  meta? : Map[String, Json],
) -> GetPromptResult {
  { description, messages, meta, }
}

///|
pub fn GetPromptResult::to_json(self : GetPromptResult) -> Json {
  let m : Map[String, Json] = Map([
    ("messages", Json::array(self.messages.map(msg => msg.to_json()))),
  ])
  match self.description {
    Some(d) => m["description"] = Json::string(d)
    None => ()
  }
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct CompleteContext {
  arguments : Map[String, String]
}

///|
pub fn CompleteContext::CompleteContext(
  arguments~ : Map[String, String] = Map([]),
) -> CompleteContext {
  { arguments, }
}

///|
#derive(Debug, Eq)
pub(all) struct CompleteResult {
  values : Array[String]
  total : Int32?
  has_more : Bool?
}

///|
pub fn CompleteResult::CompleteResult(
  values : Array[String],
  total? : Int32,
  has_more? : Bool,
) -> CompleteResult {
  { values, total, has_more, }
}

///|
/// MCP spec caps `completion.values` at 100 items and adjusts `total` / `hasMore`.
pub fn CompleteResult::to_json(self : CompleteResult) -> Json {
  let total_count = match self.total {
    Some(t) => t
    None => self.values.length()
  }
  let capped : Array[String] = []
  let limit = if self.values.length() > 100 {
    100
  } else {
    self.values.length()
  }
  for i = 0; i < limit; i = i + 1 {
    capped.push(self.values[i])
  }
  let effective_has_more = match self.has_more {
    Some(hm) => hm || self.values.length() > 100
    None => total_count > capped.length()
  }
  let comp : Map[String, Json] = Map([
    ("values", Json::array(capped.map(v => Json::string(v)))),
    ("total", Json::number(total_count.to_double())),
    ("hasMore", Json::boolean(effective_has_more)),
  ])
  Json::object(Map([("completion", Json::object(comp))]))
}

///|
/// RFC-5424 8-level MCP Logging severity.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum McpLogLevel {
  Debug
  Info
  Notice
  Warning
  Error
  Critical
  Alert
  Emergency
}

///|
pub fn McpLogLevel::as_str(self : McpLogLevel) -> String {
  match self {
    Debug => "debug"
    Info => "info"
    Notice => "notice"
    Warning => "warning"
    Error => "error"
    Critical => "critical"
    Alert => "alert"
    Emergency => "emergency"
  }
}

///|
pub fn McpLogLevel::rank(self : McpLogLevel) -> Int32 {
  match self {
    Debug => 0
    Info => 1
    Notice => 2
    Warning => 3
    Error => 4
    Critical => 5
    Alert => 6
    Emergency => 7
  }
}

///|
pub fn McpLogLevel::parse(s : StringView) -> McpLogLevel? {
  match s {
    "debug" => Some(Debug)
    "info" => Some(Info)
    "notice" => Some(Notice)
    "warning" => Some(Warning)
    "error" => Some(Error)
    "critical" => Some(Critical)
    "alert" => Some(Alert)
    "emergency" => Some(Emergency)
    _ => None
  }
}

///|
/// Client filesystem / workspace root returned by `roots/list`.
#derive(Debug, Eq)
pub(all) struct McpRoot {
  uri : String
  name : String?
}

///|
pub fn McpRoot::McpRoot(uri~ : String, name? : String) -> McpRoot {
  { uri, name, }
}

///|
pub fn McpRoot::to_json(self : McpRoot) -> Json {
  let m : Map[String, Json] = Map([("uri", Json::string(self.uri))])
  match self.name {
    Some(n) => m["name"] = Json::string(n)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct ModelHint {
  name : String?
}

///|
pub fn ModelHint::ModelHint(name? : String) -> ModelHint {
  { name, }
}

///|
pub fn ModelHint::to_json(self : ModelHint) -> Json {
  let m : Map[String, Json] = Map([])
  match self.name {
    Some(n) => m["name"] = Json::string(n)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct ModelPreferences {
  hints : Array[ModelHint]
  cost_priority : Double?
  speed_priority : Double?
  intelligence_priority : Double?
}

///|
pub fn ModelPreferences::ModelPreferences(
  hints~ : Array[ModelHint] = [],
  cost_priority? : Double,
  speed_priority? : Double,
  intelligence_priority? : Double,
) -> ModelPreferences {
  { hints, cost_priority, speed_priority, intelligence_priority, }
}

///|
pub fn ModelPreferences::to_json(self : ModelPreferences) -> Json {
  let m : Map[String, Json] = Map([])
  if !self.hints.is_empty() {
    m["hints"] = Json::array(self.hints.map(h => h.to_json()))
  }
  match self.cost_priority {
    Some(v) => m["costPriority"] = Json::number(v)
    None => ()
  }
  match self.speed_priority {
    Some(v) => m["speedPriority"] = Json::number(v)
    None => ()
  }
  match self.intelligence_priority {
    Some(v) => m["intelligencePriority"] = Json::number(v)
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct SamplingMessage {
  role : PromptRole
  content : ContentBlock
}

///|
pub fn SamplingMessage::SamplingMessage(
  role~ : PromptRole,
  content~ : ContentBlock,
) -> SamplingMessage {
  { role, content, }
}

///|
pub fn SamplingMessage::to_json(self : SamplingMessage) -> Json {
  Json::object(
    Map([
      ("role", Json::string(self.role.as_str())),
      ("content", self.content.to_json()),
    ]),
  )
}

///|
#derive(Debug, Eq)
pub(all) struct CreateMessageParams {
  messages : Array[SamplingMessage]
  max_tokens : Int32
  system_prompt : String?
  model_preferences : ModelPreferences?
  temperature : Double?
  stop_sequences : Array[String]
  include_context : String?
  metadata : Json?
  tools : Array[Json]
  tool_choice : Json?
}

///|
pub fn CreateMessageParams::CreateMessageParams(
  messages~ : Array[SamplingMessage],
  max_tokens~ : Int32,
  system_prompt? : String,
  model_preferences? : ModelPreferences,
  temperature? : Double,
  stop_sequences~ : Array[String] = [],
  include_context? : String,
  metadata? : Json,
  tools~ : Array[Json] = [],
  tool_choice? : Json,
) -> CreateMessageParams {
  {
    messages,
    max_tokens,
    system_prompt,
    model_preferences,
    temperature,
    stop_sequences,
    include_context,
    metadata,
    tools,
    tool_choice,
  }
}

///|
pub fn CreateMessageParams::to_json(self : CreateMessageParams) -> Json {
  let m : Map[String, Json] = Map([
    ("messages", Json::array(self.messages.map(msg => msg.to_json()))),
    ("maxTokens", Json::number(self.max_tokens.to_double())),
  ])
  match self.system_prompt {
    Some(sp) => m["systemPrompt"] = Json::string(sp)
    None => ()
  }
  match self.model_preferences {
    Some(mp) => m["modelPreferences"] = mp.to_json()
    None => ()
  }
  match self.temperature {
    Some(t) => m["temperature"] = Json::number(t)
    None => ()
  }
  if !self.stop_sequences.is_empty() {
    m["stopSequences"] = Json::array(
      self.stop_sequences.map(s => Json::string(s)),
    )
  }
  match self.include_context {
    Some(ic) => m["includeContext"] = Json::string(ic)
    None => ()
  }
  match self.metadata {
    Some(md) => m["metadata"] = md
    None => ()
  }
  if !self.tools.is_empty() {
    m["tools"] = Json::array(self.tools)
  }
  match self.tool_choice {
    Some(tc) => m["toolChoice"] = tc
    None => ()
  }
  Json::object(m)
}

///|
#derive(Debug, Eq)
pub(all) struct CreateMessageResult {
  role : PromptRole
  content : ContentBlock
  model : String
  stop_reason : String?
}

///|
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum ElicitAction {
  Accept
  Decline
  Cancel
}

///|
pub fn ElicitAction::as_str(self : ElicitAction) -> String {
  match self {
    Accept => "accept"
    Decline => "decline"
    Cancel => "cancel"
  }
}

///|
pub fn ElicitAction::parse(s : StringView) -> ElicitAction? {
  match s {
    "accept" => Some(Accept)
    "decline" => Some(Decline)
    "cancel" => Some(Cancel)
    _ => None
  }
}

///|
#derive(Debug, Eq)
pub(all) struct ElicitFormParams {
  message : String
  requested_schema : Json
}

///|
pub fn ElicitFormParams::ElicitFormParams(
  message~ : String,
  requested_schema~ : Json,
) -> ElicitFormParams {
  { message, requested_schema, }
}

///|
pub fn ElicitFormParams::to_json(self : ElicitFormParams) -> Json {
  Json::object(
    Map([
      ("mode", Json::string("form")),
      ("message", Json::string(self.message)),
      ("requestedSchema", self.requested_schema),
    ]),
  )
}

///|
#derive(Debug, Eq)
pub(all) struct ElicitUrlParams {
  message : String
  elicitation_id : String
  url : String
}

///|
pub fn ElicitUrlParams::ElicitUrlParams(
  message~ : String,
  elicitation_id~ : String,
  url~ : String,
) -> ElicitUrlParams {
  { message, elicitation_id, url, }
}

///|
pub fn ElicitUrlParams::to_json(self : ElicitUrlParams) -> Json {
  Json::object(
    Map([
      ("mode", Json::string("url")),
      ("message", Json::string(self.message)),
      ("elicitationId", Json::string(self.elicitation_id)),
      ("url", Json::string(self.url)),
    ]),
  )
}

///|
#derive(Debug, Eq)
pub(all) struct ElicitResult {
  action : ElicitAction
  content : Map[String, Json]?
}

///|
/// Embedded client input request for MCP 2026-07-28 multi-round-trip requests (SEP-2322).
/// Works seamlessly across both eras: emitted as `resultType: "input_required"` on 2026-07-28,
/// and automatically shimmed over bidirectional Server鈫扖lient JSON-RPC requests on 2025-11-25.
#derive(Debug, Eq)
#non_exhaustive
pub(all) enum InputRequest {
  ElicitForm(ElicitFormParams)
  ElicitUrl(message~ : String, url~ : String, elicitation_id~ : String?)
  CreateMessage(CreateMessageParams)
  ListRoots
}

///|
pub fn InputRequest::elicit_form(params : ElicitFormParams) -> InputRequest {
  ElicitForm(params)
}

///|
pub fn InputRequest::elicit_url(
  message~ : String,
  url~ : String,
  elicitation_id? : String,
) -> InputRequest {
  ElicitUrl(message~, url~, elicitation_id~)
}

///|
pub fn InputRequest::create_message(
  params : CreateMessageParams,
) -> InputRequest {
  CreateMessage(params)
}

///|
pub fn InputRequest::list_roots() -> InputRequest {
  ListRoots
}

///|
/// Serializes an `InputRequest` into the 2026-07-28 de-JSON-RPC'd wire format.
pub fn InputRequest::to_json(self : InputRequest) -> Json {
  match self {
    ElicitForm(p) =>
      Json::object(
        Map([
          ("method", Json::string("elicitation/create")),
          ("params", p.to_json()),
        ]),
      )
    ElicitUrl(message~, url~, ..) =>
      // 2026-07-28 URL-mode elicitation does not include `elicitationId`
      Json::object(
        Map([
          ("method", Json::string("elicitation/create")),
          (
            "params",
            Json::object(
              Map([
                ("mode", Json::string("url")),
                ("message", Json::string(message)),
                ("url", Json::string(url)),
              ]),
            ),
          ),
        ]),
      )
    CreateMessage(p) =>
      Json::object(
        Map([
          ("method", Json::string("sampling/createMessage")),
          ("params", p.to_json()),
        ]),
      )
    ListRoots => Json::object(Map([("method", Json::string("roots/list"))]))
  }
}

///|
/// Raised by a `tools/call`, `prompts/get`, or `resources/read` handler to pause
/// execution and request client input (SEP-2322 multi-round-trip).
#derive(Debug, Eq)
#non_exhaustive
pub(all) suberror InputRequired {
  InputRequired(
    input_requests~ : Map[String, InputRequest]?,
    request_state~ : String?,
    meta~ : Map[String, Json]?,
  )
}

///|
fn parse_content_block(raw : Json) -> ContentBlock raise McpProtocolError {
  match raw {
    Array(items) =>
      if items.is_empty() {
        ContentBlock::text("")
      } else {
        parse_content_block(items[0])
      }
    Object(m) =>
      match m.get("type") {
        Some(String("text")) => {
          let text = match m.get("text") {
            Some(String(s)) => s
            _ => ""
          }
          ContentBlock::text(text)
        }
        Some(String("image")) => {
          let data = match m.get("data") {
            Some(String(s)) => s
            _ => ""
          }
          let mime_type = match m.get("mimeType") {
            Some(String(s)) => s
            _ => "application/octet-stream"
          }
          ContentBlock::Image(data~, mime_type~, annotations=None, meta=None)
        }
        Some(String("audio")) => {
          let data = match m.get("data") {
            Some(String(s)) => s
            _ => ""
          }
          let mime_type = match m.get("mimeType") {
            Some(String(s)) => s
            _ => "application/octet-stream"
          }
          ContentBlock::Audio(data~, mime_type~, annotations=None, meta=None)
        }
        _ => ContentBlock::text(raw.stringify())
      }
    _ =>
      raise McpProtocolError::internal_error(
        "Invalid ContentBlock in client response",
      )
  }
}

///|
pub fn parse_roots_result(
  result : Json,
) -> Array[McpRoot] raise McpProtocolError {
  match result {
    Object(m) =>
      match m.get("roots") {
        Some(Array(items)) => {
          let out : Array[McpRoot] = []
          for item in items {
            match item {
              Object(ro) =>
                match ro.get("uri") {
                  Some(String(uri)) => {
                    let name = match ro.get("name") {
                      Some(String(n)) => Some(n)
                      _ => None
                    }
                    out.push({ uri, name, })
                  }
                  _ => ()
                }
              _ => ()
            }
          }
          out
        }
        _ => []
      }
    _ =>
      raise McpProtocolError::internal_error(
        "Invalid roots/list response from client",
      )
  }
}

///|
pub fn parse_create_message_result(
  result : Json,
) -> CreateMessageResult raise McpProtocolError {
  match result {
    Object(m) => {
      let role = match m.get("role") {
        Some(String(r)) => PromptRole::parse(r).unwrap_or(PromptRole::Assistant)
        _ => PromptRole::Assistant
      }
      let content = match m.get("content") {
        Some(c) => parse_content_block(c)
        None => ContentBlock::text("")
      }
      let model = match m.get("model") {
        Some(String(s)) => s
        _ => ""
      }
      let stop_reason = match m.get("stopReason") {
        Some(String(s)) => Some(s)
        _ => None
      }
      { role, content, model, stop_reason, }
    }
    _ =>
      raise McpProtocolError::internal_error(
        "Invalid sampling/createMessage response from client",
      )
  }
}

///|
pub fn parse_elicit_result(
  result : Json,
) -> ElicitResult raise McpProtocolError {
  match result {
    Object(m) => {
      let action = match m.get("action") {
        Some(String(a)) =>
          match ElicitAction::parse(a) {
            Some(parsed) => parsed
            None =>
              raise McpProtocolError::internal_error(
                "Unknown elicitation action: \{a}",
              )
          }
        _ =>
          raise McpProtocolError::internal_error(
            "Missing action in elicitation/create response",
          )
      }
      let content = match m.get("content") {
        Some(Object(c)) => Some(c)
        _ => None
      }
      { action, content, }
    }
    _ =>
      raise McpProtocolError::internal_error(
        "Invalid elicitation/create response from client",
      )
  }
}