colmugx/mcp/transport does not have a README file

    Transport

    pub(open) trait Transport {
    fn receive(Self) -> String? raise
    TransportError

    fn send(Self, String) -> Unit raise
    TransportError

    fn send_notification(Self,
    Notification
    ) -> Unit raise
    TransportError

    fn close(Self) -> Unit
    }

    AnyTransport

    pub(all) enum AnyTransport {
    Stdio(StdioTransport)
    StdioClient(StdioClientTransport)
    Http(HttpTransport)
    HttpClient(HttpClientTransport)
    }

    AnyTransport::close

    fn AnyTransport::close(self : AnyTransport) -> Unit

    AnyTransport::receive

    async fn AnyTransport::receive(self : AnyTransport) -> String?

    AnyTransport::receive_decoded

    async fn AnyTransport::receive_decoded(self : AnyTransport) -> (String,
    Json
    )?

    Receive both the original wire text and its decoded JSON value. HTTP client transports validate and decode responses while collecting their body, so this path reuses that value instead of parsing the same event a second time.

    AnyTransport::send

    async fn AnyTransport::send(self : AnyTransport, message : String) -> Unit

    AnyTransport::send_json

    async fn AnyTransport::send_json(self : AnyTransport, message :
    Json
    ) -> Unit

    Send a structured JSON-RPC message. Serialization happens once, at the transport boundary; client code can keep the request as a Json value.

    AnyTransport::send_notification

    async fn AnyTransport::send_notification(self : AnyTransport, notification :
    Notification
    ) -> Unit

    AuthConfig

    pub struct AuthConfig {
    authenticate : (String) ->
    Principal
    ?
    resource_metadata_url : String
    authorization_servers : Array[String]
    required_scopes : String?
    allowed_origins : Array[String]?
    }

    Server-side Bearer authentication. The hook must validate credentials and scopes and return a stable identity; request metadata is never an identity source.

    AuthConfig::AuthConfig

    fn AuthConfig::AuthConfig(authenticate~ : (String) ->
    Principal
    ?, resource_metadata_url~ : String, authorization_servers? : Array[String], required_scopes? : String, allowed_origins? : Array[String]) -> AuthConfig

    AuthenticatedRequest

    pub(all) struct AuthenticatedRequest {
    message : String
    reply :
    Queue
    [String]
    principal :
    Principal
    ?
    cancellation_token :
    CancellationToken

    }

    Authenticated per-request transport envelope. Identity and cancellation do not enter JSON.

    DecodedHttpRequest

    pub(all) struct DecodedHttpRequest {
    envelope : AuthenticatedRequest
    parsed :
    Json

    }

    Parsed HTTP request coupled with its authenticated transport envelope. Internal server runtimes consume this directly; legacy transport adapters can still receive the original request string from the envelope.

    HeaderSchemaValidation

    pub(all) enum HeaderSchemaValidation {
    Valid(Array[(Array[String], String)])
    Invalid(String)
    }

    Result of validating one tool's x-mcp-header mirror schema.

    HttpClientTransport

    pub struct HttpClientTransport {
    base_url : String
    auth_token : String?
    closed : Bool
    pending_responses :
    Queue
    [(String,
    Json
    )]
    extra_headers : Array[(String, String)]
    tool_header_schemas : Map[String, Array[(Array[String], String)]]
    }

    HttpClientTransport — MCP client connecting to a remote HTTP server.

    Implements the stateless 2026-07-28 Streamable HTTP transport: every JSON-RPC request is its own POST, carrying the required request-metadata headers (MCP-Protocol-Version, Mcp-Method, Mcp-Name). A POST may be answered with either a single JSON object or an SSE stream scoped to that request; both are collected into pending_responses and surfaced one at a time by receive.

    The legacy session model (Mcp-Session-Id, GET long-poll SSE, Last-Event-ID resumability, DELETE close) is removed. Server→client notifications now flow on per-request SSE response streams (progress) or subscriptions/listen (change events), not a standalone GET channel.

    HttpClientTransport::HttpClientTransport

    fn HttpClientTransport::HttpClientTransport(base_url : String, auth_token? : String, extra_headers? : Array[(String, String)]) -> HttpClientTransport

    HttpClientTransport::close

    fn HttpClientTransport::close(self : HttpClientTransport) -> Unit

    HttpClientTransport::receive

    async fn HttpClientTransport::receive(self : HttpClientTransport) -> String?

    Drain the next response message (single JSON or one SSE event) queued by send. Blocks asynchronously until a message is available. Returns None when the transport is closed or the underlying queue is closed/empty.

    HttpClientTransport::receive_decoded

    async fn HttpClientTransport::receive_decoded(self : HttpClientTransport) -> (String,
    Json
    )?

    Drain the next response with its already-decoded JSON value. The raw text remains available for compatibility callers and diagnostics.

    HttpClientTransport::send

    async fn HttpClientTransport::send(self : HttpClientTransport, message : String) -> Unit

    POST a JSON-RPC request to the server. Sets the required request-metadata headers (MCP-Protocol-Version, Mcp-Method, Mcp-Name) and accepts either a single JSON object or an SSE stream as the response. All response messages are pushed onto pending_responses for receive to drain. Cancellation note: every error-translating catch below re-raises when @async.is_being_cancelled() — otherwise a with_timeout cancellation injected at a suspension point would be re-labeled as WriteError/ReadError, losing its identity to the enclosing task group's timeout fallback.

    HttpClientTransport::send_json

    async fn HttpClientTransport::send_json(self : HttpClientTransport, parsed :
    Json
    ) -> Unit

    Structured request entry point: stringify once at the HTTP wire boundary, then reuse the original JSON value for routing headers and parameter mirrors.

    HttpClientTransport::send_notification

    async fn HttpClientTransport::send_notification(self : HttpClientTransport, notification :
    Notification
    ) -> Unit

    Send a JSON-RPC notification (no id, fire-and-forget). Per spec basic/transports/streamable-http#sending-messages, a notification POST is answered with 202 Accepted and no body.

    HttpClientTransport::set_tool_header_schemas

    fn HttpClientTransport::set_tool_header_schemas(self : HttpClientTransport, schemas : Map[String, Array[(Array[String], String)]]) -> Unit

    Install the x-mcp-header mirror schema set (called by the client layer after validating tools/list tool definitions). Emission itself is done by send when building tools/call request headers.

    HttpTransport

    pub struct HttpTransport {
    port : Int
    endpoint_path : String
    auth : AuthConfig?
    keepalive_interval_ms : Int
    tool_schema_resolver :
    Ref
    [(String) ->
    Json
    ?]
    pending_requests :
    Queue
    [DecodedHttpRequest]
    pending_reply_queues : Map[String,
    Queue
    [String]]
    }

    HttpTransport::HttpTransport

    fn HttpTransport::HttpTransport(port? : Int, endpoint_path? : String, keepalive_interval_ms? : Int) -> HttpTransport

    HttpTransport::close

    fn HttpTransport::close(self : HttpTransport) -> Unit

    HttpTransport::receive

    HttpTransport::receive_authenticated_request

    Preserve the existing string-based authenticated transport API.

    HttpTransport::receive_decoded_request

    HttpTransport::receive_request

    Low-level compatibility adapter. Runtime consumers should retain the authenticated envelope.

    HttpTransport::send

    async fn HttpTransport::send(self : HttpTransport, message : String) -> Unit raise
    TransportError

    HttpTransport::send_notification

    fn HttpTransport::send_notification(self : HttpTransport, _notification :
    Notification
    ) -> Unit

    Trait-required stub. Server→client notifications over HTTP flow through MCPServer's per-subscription reply handles (subscriptions/listen), not through this transport; the legacy GET-SSE event queue is gone.

    HttpTransport::set_tool_schema_resolver

    fn HttpTransport::set_tool_schema_resolver(self : HttpTransport, resolver : (String) ->
    Json
    ?) -> Unit

    Attach a live tool-schema lookup before serving calls; MCPServer installs its registry.

    HttpTransport::start

    HttpTransport::with_auth

    fn HttpTransport::with_auth(self : HttpTransport, auth : AuthConfig) -> HttpTransport

    JsonRpcKind

    pub(all) enum JsonRpcKind {
    Notification
    FinalResponse
    Other
    } derive(Eq,
    Debug
    )

    Classification of JSON-RPC messages arriving on the server-side reply queue. Used to decide whether a POST response is a single JSON object or an SSE stream.

    JsonRpcKind::equal

    fn JsonRpcKind::equal(JsonRpcKind, JsonRpcKind) -> Bool

    Explicit trait method promotion for current MoonBit toolchains.

    JsonRpcKind::not_equal

    fn JsonRpcKind::not_equal(x : JsonRpcKind, y : JsonRpcKind) -> Bool

    Explicit trait method promotion for current MoonBit toolchains.

    SseEventReader

    pub struct SseEventReader {
    buf :
    AsyncLexbuf

    decode_failed :
    Ref
    [Bool]
    }

    SSE (Server-Sent Events) scanner for streamable HTTP transports.

    SseEventReader consumes one event per next call — or detects EOF — from a streaming HTTP response body. Tokenization runs through lexscan over an @lexbuf.AsyncLexbuf, so the per-line matching stays on the compiler-optimized regex path and patterns may span refill-chunk boundaries. The lexbuf persists across next calls: when one refill chunk carries a keepalive event plus the start of the next event, the leftover bytes stay buffered and are scanned by the following next, instead of being discarded with a per-call lexbuf.

    Semantics follow the WHATWG SSE spec: lines end with \n, \r\n, or \r; a blank line dispatches the accumulated event; data:/id: values strip a single leading space; comments and unknown fields are ignored; consecutive data: lines join with \n; an unterminated final line at EOF is dispatched as if the terminator were present.

    SseEventReader::new

    Build a reader over one streaming response body. The refill closure is created once here; every next call scans the same lexbuf it fills.

    SseEventReader::next

    async fn SseEventReader::next(self : SseEventReader) -> (String?, String?)

    Scan the next event from the response stream, reusing the reader's persistent lexbuf so bytes buffered by earlier next calls are not lost.

    SseEventVerdict

    pub enum SseEventVerdict {
    Message(String)
    Skip
    Eof
    } derive(Eq,
    Debug
    )

    What a response-stream consumer should do with one scanned SSE event.

    SseEventVerdict::equal

    Explicit trait method promotion for current MoonBit toolchains.

    SseEventVerdict::not_equal

    fn SseEventVerdict::not_equal(x : SseEventVerdict, y : SseEventVerdict) -> Bool

    Explicit trait method promotion for current MoonBit toolchains.

    StdioClientTransport

    StdioClientTransport — MCP host/client connecting to a local MCP server via spawned child process.

    Follows the MCP specification: the host spawns the server as a subprocess, communicates via newline-delimited JSON-RPC over stdin/stdout pipes. Stderr passes through to the parent for server-side logging.

    Two-phase initialization:
    1. new() stores configuration (command, arguments, env)
    2. start(group) creates pipes and spawns the child process

    Graceful shutdown (per MCP spec):
    1. Close stdin pipe → signals EOF to child
    2. Child detects EOF and exits
    3. TaskGroup cancel_handler (SIGTERM → 5s → SIGKILL) handles stubborn processes

    StdioClientTransport::StdioClientTransport

    fn StdioClientTransport::StdioClientTransport(cmd~ : String, args? : Array[String], extra_env? : Map[String, String]) -> StdioClientTransport

    StdioClientTransport::close

    fn StdioClientTransport::close(self : StdioClientTransport) -> Unit

    Graceful shutdown per MCP spec:
    1. Close stdin writer → signals EOF to child process
    2. Close stdout reader → release pipe resources
    3. Mark transport as closed The TaskGroup's cancel_handler handles forced termination if needed.

    StdioClientTransport::receive

    async fn StdioClientTransport::receive(self : StdioClientTransport) -> String?

    Read one JSON-RPC message from the child's stdout. Returns None on EOF (child closed stdout / process exited).

    StdioClientTransport::send

    async fn StdioClientTransport::send(self : StdioClientTransport, message : String) -> Unit

    Send a JSON-RPC message to the child's stdin. Validates the message, writes it with a newline, and flushes immediately.

    StdioClientTransport::send_json

    async fn StdioClientTransport::send_json(self : StdioClientTransport, parsed :
    Json
    ) -> Unit

    Structured entry point: validate the decoded envelope and serialize only once for the stdio wire frame.

    StdioClientTransport::send_notification

    async fn StdioClientTransport::send_notification(self : StdioClientTransport, notification :
    Notification
    ) -> Unit

    Send a JSON-RPC notification (no id, fire-and-forget) to the child's stdin.

    StdioClientTransport::start

    Spawn the child process inside the given TaskGroup. Creates stdin/stdout pipes, spawns the process, and wraps the writer in a BufferedWriter (8KB) for efficient I/O.

    Must be called before send() / receive().

    StdioTransport

    StdioTransport with buffered I/O for improved performance. Buffering reduces the number of syscalls and context switches, which is critical for high-frequency request/response patterns.

    StdioTransport::StdioTransport

    fn StdioTransport::StdioTransport() -> StdioTransport

    StdioTransport::close

    fn StdioTransport::close(self : StdioTransport) -> Unit

    StdioTransport::receive

    StdioTransport::send

    async fn StdioTransport::send(self : StdioTransport, message : String) -> Unit raise
    TransportError

    StdioTransport::send_notification

    classify_jsonrpc_message

    fn classify_jsonrpc_message(message : String) -> JsonRpcKind

    Classify a serialized JSON-RPC message for response-mode selection.

    decode_base64

    fn decode_base64(s : String) -> Bytes?

    Decode a standard Base64 string back to raw bytes. Returns None on invalid input (fail-closed).

    decode_base64_sentinel

    fn decode_base64_sentinel(value : String) -> String?

    Decode a Base64 sentinel value. Returns None if the value is not in sentinel form or if decoding fails (fail-closed).

    encode_base64

    fn encode_base64(bytes : Bytes) -> String

    Encode raw bytes to a standard Base64 string (with padding).

    encode_base64_sentinel

    fn encode_base64_sentinel(value : String) -> String

    Encode a string as a Base64 sentinel value: =?base64?<b64>?=. The input is first encoded as UTF-8 bytes.

    encode_header_value

    fn encode_header_value(value : String) -> String

    Encode a header value according to the spec: plain when safe, otherwise Base64-sentinel encoded.

    extract_argument_value

    fn extract_argument_value(body : String, path : Array[String]) -> String?

    Extract the value at a property path inside params.arguments for tools/call requests. Returns None when the path is absent or the final value is null. Converts string, safe integer, and boolean values to their header string representations.

    header_mismatch_error

    fn header_mismatch_error(detail : String, body~ : String) -> String

    Build a HeaderMismatch (-32020) JSON-RPC error response body. The request id is echoed when readable from body.

    invalid_params_error

    fn invalid_params_error(detail : String, body~ : String) -> String

    Build an Invalid params (-32602) JSON-RPC error response body for a malformed request rejected at transport entry (e.g. a request whose params._meta is missing required fields). The request id is echoed when readable from body.

    is_header_safe

    fn is_header_safe(value : String) -> Bool

    Returns true if value can be transmitted as a plain HTTP header value: every character is visible ASCII (0x21–0x7E), space (0x20), or tab (0x09); it has no leading/trailing whitespace; and it does not match the sentinel pattern (to avoid ambiguity).

    is_notification

    fn is_notification(body :
    Json
    ) -> Bool

    Returns true when the JSON body is a JSON-RPC notification (method present, id absent).

    is_valid_header_characters

    fn is_valid_header_characters(value : String) -> Bool

    Returns true if value contains only characters permitted in a non- sentinel HTTP header value: visible ASCII (0x21–0x7E), space (0x20), or tab (0x09). CR and LF are implicitly rejected because they are not in the allowed range.

    jsonrpc_error_code

    fn jsonrpc_error_code(message : String) -> Int?

    Extract the JSON-RPC error code from a serialized response, if any.

    looks_like_sentinel

    fn looks_like_sentinel(value : String) -> Bool

    Returns true if the value matches the Base64 sentinel pattern.

    origin_allowed

    fn origin_allowed(origin : String, allowed_origins : Array[String]?) -> Bool

    Decide whether a request Origin value may reach the MCP endpoint.

    • allowed_origins = Some(list) (auth configured with an allowlist): the value must match one entry exactly; the allowlist replaces, not extends, the default policy.
    • allowed_origins = None (no auth, or auth without an allowlist): the default policy admits only loopback origins — http/https with host 127.0.0.1, localhost, or [::1] on any port — so a page served from a rebound public DNS name cannot pass. Malformed values and every other host fail closed.

    Requests carrying no Origin header are non-browser clients; the caller allows them without consulting this function.

    read_sse_event

    async fn read_sse_event(client :
    ClientConnection
    ) -> (String?, String?)

    One-shot wrapper over SseEventReader: consume exactly one event from a streaming response body. Looping consumers should build one reader per response stream and call next repeatedly instead — each read_sse_event call starts a fresh lexbuf, dropping any trailing bytes buffered from its own scan.

    request_id_from_body

    fn request_id_from_body(body : String) ->
    Json
    ?

    request_id_from_json

    Extract the JSON-RPC id member from a serialized request body, for echoing in transport-level error responses. Returns None when the body is not a JSON object or carries no id — JSON-RPC allows omitting id when it cannot be determined from the (possibly malformed) request.

    sse_event_line

    fn sse_event_line(json : String) -> String

    Format a JSON-RPC payload as one SSE event line.

    sse_event_verdict

    fn sse_event_verdict(data : String?, id : String?) -> SseEventVerdict

    Classify one read_sse_event result for a response stream.

    Servers may open or interleave keepalive events: an event dispatched with an empty or whitespace-only data: payload (some servers open every stream with data: (empty) + id: + retry: heartbeat events), or a comment-only heartbeat that carries an id but no data lines. None of those are JSON-RPC messages — queueing an empty payload desyncs response matching (initialize would parse the empty string), and treating a heartbeat as EOF ends the scan before the real reply arrives. The scanner absorbs comment-only events without data or id internally; (None, None) therefore signals EOF.

    unsupported_protocol_version_error

    fn unsupported_protocol_version_error(requested : String, body~ : String) -> String

    Build an UnsupportedProtocolVersion (-32022) JSON-RPC error response body. The request id is echoed when readable from body; the error is transport-level, so unreadable ids are simply omitted.

    validate_jsonrpc_message

    fn validate_jsonrpc_message(message : String) -> Unit raise
    MCPError

    Validate raw JSON-RPC input by decoding it once and checking the decoded envelope. Structured callers use validate_jsonrpc_value directly.

    validate_tool_header_schema

    fn validate_tool_header_schema(input_schema :
    Json
    ) -> HeaderSchemaValidation

    Validate a tool's inputSchema for x-mcp-header mirror annotations. Returns the list of (property_path, header_name) entries when valid, or an error message describing the first violation. Per the 2026-07-28 streamable HTTP spec:

    • header names must be non-empty HTTP tchars (RFC 9110 §5.1);
    • names are case-insensitively unique within the tool;
    • only integer, string, and boolean typed properties may carry the annotation (not number);
    • the annotation may only appear on properties statically reachable through properties chains; any occurrence under items/oneOf/anyOf/allOf/ if/then/else/$ref invalidates the whole tool.

    validate_tool_parameter_headers

    fn validate_tool_parameter_headers(input_schema :
    Json
    , arguments :
    Json
    , headers : Array[(String, String)]) -> Result[Unit, String]

    Validate recognized x-mcp-header values against their exact argument paths. Unrecognized Mcp-Param headers are ignored, not treated as body parameters.