Get Started

MCP Transports: stdio and Stateless Streamable HTTP

Transport carries MCP messages. It does not supply missing protocol state. In 2026-07-28local stdio and remote Streamable HTTP both carry self-describing requests.

65 minutesLearnPythonFree lesson

Learning Objectives

  • Choose stdio for local child processes and Streamable HTTP for network services.
  • Implement the modern single-endpoint, POST-only Streamable HTTP contract.
  • Mirror and validate MCP version, method, and name headers against the JSON-RPC body.
  • Deliver request-scoped SSE and long-lived subscriptions/listen streams correctly.
  • Migrate session-based and legacy HTTP+SSE deployments without presenting legacy behavior as modern.

The Problem

Earlier Streamable HTTP revisions combined protocol negotiation with connection and session behavior. A server could mint Mcp-Session-Idexpose a standalone GET stream, accept DELETE for session termination, and resume SSE with Last-Event-ID.

MCP 2026-07-28 removes those mechanisms from the modern wire. Every request can land on any healthy worker because its protocol version and client capabilities travel in the request body. HTTP headers mirror selected fields for routing and policy, but the server validates those headers against the body before execution.

The result is easier to scale and easier to reason about. It also means that a server teaching the 2025 transport as current is teaching the wrong failure and security model.

The Concept

stdio

The stdio binding is for a client-launched subprocess:

  • Client writes one UTF-8 JSON-RPC message per line to stdin.
  • Server writes one UTF-8 JSON-RPC message per line to stdout.
  • Server writes diagnostics to stderr.
  • Server exits promptly on stdin EOF.
  • Every modern request carries version and client capabilities in params._meta.

The process may live for many calls, but it is not a modern protocol session. If it exits unexpectedly, in-flight requests are lost. Restart the process, rediscover, relist, reopen subscriptions, and retry safe operations with new request ids.

Streamable HTTP in 2026-07-28

A modern server exposes one MCP endpoint, such as /mcpthat accepts POST.

Every JSON-RPC request or notification is a new HTTP POST. The body contains one JSON-RPC message. Clients do not send JSON-RPC responses to the server.

For a request, the server returns either:

  • Content-Type: application/json with one JSON-RPC response; or
  • Content-Type: text/event-stream with notifications related to that request, followed by the final JSON-RPC response.

For an accepted notification, the server returns 202 Accepted with no body.

Clients advertise both response types:

HTTP
Accept: application/json, text/event-stream

POST-only means POST-only

Modern Streamable HTTP has no standalone GET stream and no DELETE session endpoint.

  • GET /mcp returns 405 Method Not Allowed.
  • DELETE /mcp returns 405 Method Not Allowed.
  • Mcp-Session-Id is ignored and never minted or echoed.
  • Last-Event-ID is ignored because modern streams are not resumable.

If a request-scoped stream breaks before its final response, the client has lost that in-flight request. It may issue a new request with a new JSON-RPC id when retry is safe. It must not attempt stream resumption.

Origin validation

Servers validate Origin on incoming connections to prevent DNS rebinding. If the header is present and not explicitly allowed, return 403 Forbidden. A non-browser client may omit Originwhich the official transport rules permit.

Local servers should bind to 127.0.0.1not every interface. Network services still need authentication and authorization on every request. Origin validation is not authentication.

Use exact origin matching after canonical configuration. Prefix checks such as origin.startswith("https://trusted.example") are unsafe because they can accept attacker-controlled suffixes.

Required HTTP metadata headers

Every modern POST request includes:

HTTP
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: notes_search

Header rules:

  • MCP-Protocol-Version is required and must equal params._meta.io.modelcontextprotocol/protocolVersion.
  • Mcp-Method is required and must equal the JSON-RPC method.
  • Mcp-Name is required for tools/callresources/readand prompts/get.
  • Mcp-Name equals params.nameor params.uri for resources/read.
  • Header values are case-sensitive even though header names are case-insensitive.

Unsafe or non-ASCII Mcp-Name values use the exact UTF-8 Base64 sentinel:

Text
=?base64?{Base64EncodedValue}?=

The server decodes that value before comparing it with the body.

Missing, malformed, or mismatched mirrored headers return HTTP 400 with JSON-RPC code -32020. If header and body agree on a version the server does not support, return HTTP 400 with -32022 and exact error data such as {"supported":["2026-07-28"],"requested":"2027-01-01"}.

An unknown modern method returns HTTP 404 with JSON-RPC -32601. The JSON-RPC body is important because a dual-era client uses it to distinguish a modern error from a legacy endpoint miss.

Request-scoped SSE

A server may choose SSE for one long-running request:

Text
POST tools/call id=41
  <- notifications/progress related to id=41
  <- notifications/progress related to id=41
  <- JSON-RPC response id=41
stream closes

The server must not send independent JSON-RPC requests on this stream. Sampling, elicitation, and roots interactions use Multi Round-Trip Request results. Closing the response stream cancels that request.

Do not add SSE event ids for replay. Last-Event-ID resumption is not part of the modern revision.

Long-lived changes use subscriptions/listen

Change notifications use a client-opened request, not standalone GET:

JSON
{
  "jsonrpc": "2.0",
  "id": "listen-1",
  "method": "subscriptions/listen",
  "params": {
    "notifications": {
      "toolsListChanged": true,
      "resourceSubscriptions": ["notes://note-1"]
    },
    "_meta": {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {},
      "io.modelcontextprotocol/clientInfo": {
        "name": "course-client",
        "version": "1.0.0"
      }
    }
  }
}

The POST response is a long-lived SSE stream. Its first protocol message is notifications/subscriptions/acknowledged. The acknowledgement, every change notification, and the final result carry io.modelcontextprotocol/subscriptionId in _metaequal to the listen request id. The server may emit SSE comments as keepalives. When the stream drops, the client reissues subscriptions/listen with a new request id and refetches affected data.

resources/subscribe and resources/unsubscribe belong to the legacy era. Do not use them on a modern connection.

Explicit application state

Removing protocol sessions does not forbid workflows with state. The server may mint an opaque state handle and return it as a normal tool result. The client passes that handle as an explicit argument on later calls.

Bind handles to the authenticated principal, make them unguessable, expire them, and authorize every use. This makes state visible at the application layer instead of hiding it in transport affinity.

The failure caused by hidden replica state is mechanical:

  1. Request A reaches replica 1 and creates a draft in that process's memory.
  2. The response does not return a draft handle because the implementation assumes the connection identifies the draft.
  3. Request B is a fresh POST and reaches replica 2.
  4. Replica 2 has valid protocol metadata but no way to name or load the draft, so the workflow fails or reads the wrong local object.
  5. Sticky routing appears to fix the symptom until a restart, rollout, reschedule, or failover moves the next request.

The correct boundary has two parts. Protocol context stays in each request. Durable application state lives in a shared store under a server-minted handle returned to the client. The next call supplies that handle, any replica loads the same record, and authorization binds the record to the authenticated principal and tenant. Replica memory may cache a record, but it cannot be the only copy required for correctness.

Choose the state mechanism by lifetime. Request-local variables can serve one call. A short MRTR continuation can use integrity-protected requestState. A draft or durable task needs an explicit handle plus shared persistence, expiry, concurrency control, and idempotency. None of those objects is an MCP protocol session.

HTTP dual-era compatibility

A client that supports modern and legacy servers attempts a modern POST first. If it receives HTTP 400404or 405it inspects the body:

  • A recognized modern JSON-RPC error proves the server is modern. Correct the request or retry an advertised version. Do not downgrade.
  • An empty body or an unrecognized response may indicate a legacy HTTP+SSE server. Only then try the old GET endpoint and expect its legacy endpoint event.

A server can support both eras during migration by routing modern metadata to the modern POST-only implementation and retaining separate legacy endpoints for old clients. Never describe the legacy GET, DELETE, session id, or replay behavior as part of 2026-07-28.

Use It

code/main.py implements a finite, modern Streamable HTTP server with the Python standard library. It validates Origin and mirrored headers, ignores removed session headers, returns JSON for normal calls, and demonstrates a finite subscriptions/listen SSE stream.

Terminal
cd code
python3 main.py --probe
python3 -m unittest discover tests -v

The probe checks:

  • invalid Origin is rejected;
  • discovery succeeds without a session id;
  • Mcp-Session-Id and Last-Event-ID are ignored;
  • header mismatch returns -32020;
  • unsupported version returns -32022 with exact supported and requested data;
  • an accepted id-less notification returns HTTP 202 with no body;
  • GET and DELETE return 405;
  • subscriptions/listen is a POST response stream whose acknowledgement, notifications, and final result carry its subscription id.

Ship It

This lesson ships outputs/skill-mcp-transport-migrator.md. It removes modern protocol sessions, adds header-body validation, replaces standalone GET with subscriptions/listenand keeps any legacy bridge visibly separate.

Exercises

  1. Remove Mcp-Method from a POST. Confirm HTTP 400 and error -32020.
  2. Send matching header and body version 2027-01-01. Confirm HTTP 400error -32022and exact data {"supported":["2026-07-28"],"requested":"2027-01-01"}.
  3. Send a Base64 sentinel Mcp-Name for a non-ASCII resource URI. Confirm the decoded value is compared with params.uri.
  4. Break the finite listen stream before its final response. Reissue it with a new JSON-RPC id and refetch tools.
  5. Add an explicit workflow handle to the ping tool. Bind it to an authorization subject without using connection affinity.

Key Terms

TermMeaning
stdioNewline-delimited JSON-RPC over a client-launched subprocess
Streamable HTTPSingle endpoint where each modern message is a new POST
Request-scoped SSEPOST response stream containing related notifications and final response
subscriptions/listenLong-lived POST request for opted-in change notifications
Header mismatchHTTP 400 and JSON-RPC -32020 when mirrored headers disagree with body
Origin validationDNS-rebinding defense for incoming connections, not authentication
Explicit state handleApplication token passed as an ordinary argument instead of hidden session state
Legacy bridgeSeparate earlier-era behavior kept only for compatibility

Further Reading

Check what you learned

6 questions. Answer each one to see why.

Question 1 of 60 correct

Which HTTP method carries every modern Streamable HTTP message?

The full code

Every file for this lesson. Copy it, run it, then change it.

main.py
"""Phase 13 Lesson 09: stateless MCP Streamable HTTP.
Lesson: phases/13-tools-and-protocols/09-mcp-transports/docs/en.md
Specification: https://modelcontextprotocol.io/specification/2026-07-28/
Implements POST-only transport, header validation, JSON, and finite SSE.
Run: python3 main.py
"""

from __future__ import annotations

import base64
import json
import sys
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Mapping


PROTOCOL_VERSION = "2026-07-28"
SUPPORTED_VERSIONS = [PROTOCOL_VERSION]
VERSION_KEY = "io.modelcontextprotocol/protocolVersion"
CAPABILITIES_KEY = "io.modelcontextprotocol/clientCapabilities"
CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo"
SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo"
SUBSCRIPTION_ID_KEY = "io.modelcontextprotocol/subscriptionId"

CLIENT_INFO = {"name": "lesson-09-client", "version": "2.0.0"}
SERVER_INFO = {"name": "lesson-09-http", "version": "2.0.0"}
SERVER_CAPABILITIES = {"tools": {"listChanged": True}}
ORIGIN_ALLOWLIST = {
    "http://localhost",
    "http://127.0.0.1",
    "https://client.example",
}
MAX_REQUEST_BYTES = 1_048_576
READ_TIMEOUT_SECONDS = 5.0
ROUTING_HEADERS = ("MCP-Protocol-Version", "Mcp-Method", "Mcp-Name")

TOOLS = [
    {
        "name": "ping",
        "description": "Return pong for a transport health check.",
        "inputSchema": {"type": "object", "properties": {}, "required": []},
        "annotations": {"readOnlyHint": True, "idempotentHint": True},
    }
]


class RpcFault(Exception):
    def __init__(self, code: int, message: str, data: Any | None = None) -> None:
        super().__init__(message)
        self.code = code
        self.data = data


def request_meta(version: str = PROTOCOL_VERSION) -> dict[str, Any]:
    return {
        VERSION_KEY: version,
        CAPABILITIES_KEY: {},
        CLIENT_INFO_KEY: CLIENT_INFO.copy(),
    }


def make_request(
    request_id: int | str,
    method: str,
    params: dict[str, Any] | None = None,
    *,
    version: str = PROTOCOL_VERSION,
) -> dict[str, Any]:
    body_params = dict(params or {})
    body_params["_meta"] = request_meta(version)
    return {"jsonrpc": "2.0", "id": request_id, "method": method, "params": body_params}


def rpc_error(
    request_id: int | str | None,
    code: int,
    message: str,
    data: Any | None = None,
) -> dict[str, Any]:
    error: dict[str, Any] = {"code": code, "message": message}
    if data is not None:
        error["data"] = data
    return {"jsonrpc": "2.0", "id": request_id, "error": error}


def complete(
    payload: dict[str, Any],
    *,
    ttl_ms: int | None = None,
    cache_scope: str = "private",
    result_meta: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    metadata = {SERVER_INFO_KEY: SERVER_INFO.copy()}
    if result_meta:
        metadata.update(result_meta)
    result = {
        "resultType": "complete",
        **payload,
        "_meta": metadata,
    }
    if ttl_ms is not None:
        result["ttlMs"] = ttl_ms
        result["cacheScope"] = cache_scope
    return result


def origin_allowed(origin: str | None) -> bool:
    return origin is None or origin in ORIGIN_ALLOWLIST


def encode_header_value(value: str) -> str:
    safe = all(0x20 <= ord(character) <= 0x7E for character in value)
    sentinel = value.startswith("=?base64?") and value.endswith("?=")
    if safe and value == value.strip() and not sentinel:
        return value
    encoded = base64.b64encode(value.encode("utf-8")).decode("ascii")
    return f"=?base64?{encoded}?="


def decode_header_value(value: str) -> str:
    if value.startswith("=?base64?") and value.endswith("?="):
        encoded = value[len("=?base64?") : -2]
        try:
            return base64.b64decode(encoded, validate=True).decode("utf-8")
        except (ValueError, UnicodeDecodeError) as exc:
            raise RpcFault(-32020, "Malformed Base64 MCP header value") from exc
    if any(ord(character) < 0x20 or ord(character) > 0x7E for character in value):
        raise RpcFault(-32020, "Malformed MCP header value")
    return value


def body_name(message: dict[str, Any]) -> str | None:
    params = message.get("params", {})
    if message.get("method") == "resources/read":
        value = params.get("uri")
    elif message.get("method") in {"tools/call", "prompts/get"}:
        value = params.get("name")
    else:
        return None
    return value if isinstance(value, str) else None


def http_headers_for(
    message: dict[str, Any],
    *,
    origin: str = "http://localhost",
    extra: Mapping[str, str] | None = None,
) -> dict[str, str]:
    meta = message["params"]["_meta"]
    headers = {
        "Accept": "application/json, text/event-stream",
        "Content-Type": "application/json",
        "Origin": origin,
        "MCP-Protocol-Version": str(meta[VERSION_KEY]),
        "Mcp-Method": str(message["method"]),
    }
    name = body_name(message)
    if name is not None:
        headers["Mcp-Name"] = encode_header_value(name)
    if extra:
        headers.update(extra)
    return headers


def validate_request_structure(message: dict[str, Any]) -> str:
    if message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
        raise RpcFault(-32600, "Invalid Request")
    params = message.get("params")
    if not isinstance(params, dict):
        raise RpcFault(-32602, "params must be an object")
    meta = params.get("_meta")
    if not isinstance(meta, dict):
        raise RpcFault(-32602, "params._meta is required")
    version = meta.get(VERSION_KEY)
    if not isinstance(version, str):
        raise RpcFault(-32602, f"{VERSION_KEY} is required")
    if not isinstance(meta.get(CAPABILITIES_KEY), dict):
        raise RpcFault(-32602, f"{CAPABILITIES_KEY} is required")
    client_info = meta.get(CLIENT_INFO_KEY)
    if client_info is not None and (
        not isinstance(client_info, dict)
        or not isinstance(client_info.get("name"), str)
        or not isinstance(client_info.get("version"), str)
    ):
        raise RpcFault(-32602, f"{CLIENT_INFO_KEY} is malformed")
    return version


def validate_supported_version(version: str) -> None:
    if version not in SUPPORTED_VERSIONS:
        raise RpcFault(
            -32022,
            "Unsupported protocol version",
            {"supported": SUPPORTED_VERSIONS.copy(), "requested": version},
        )


def validate_http_headers(
    headers: Mapping[str, str],
    message: dict[str, Any],
    body_version: str,
) -> None:
    header_version = headers.get("MCP-Protocol-Version")
    if header_version is None or header_version != body_version:
        raise RpcFault(-32020, "Header mismatch: MCP-Protocol-Version")
    header_method = headers.get("Mcp-Method")
    if header_method is None or header_method != message["method"]:
        raise RpcFault(-32020, "Header mismatch: Mcp-Method")
    expected_name = body_name(message)
    if message["method"] in {"tools/call", "resources/read", "prompts/get"}:
        header_name = headers.get("Mcp-Name")
        if header_name is None or expected_name is None:
            raise RpcFault(-32020, "Header mismatch: Mcp-Name")
        if decode_header_value(header_name) != expected_name:
            raise RpcFault(-32020, "Header mismatch: Mcp-Name")


def reject_duplicate_routing_headers(headers: Any) -> None:
    get_all = getattr(headers, "get_all", None)
    if not callable(get_all):
        return
    for name in ROUTING_HEADERS:
        if len(get_all(name, [])) > 1:
            raise RpcFault(-32020, f"Duplicate routing header: {name}")


def reject_duplicate_origin(headers: Any) -> None:
    get_all = getattr(headers, "get_all", None)
    if callable(get_all) and len(get_all("Origin", [])) > 1:
        raise RpcFault(-32020, "Duplicate Origin header")


def reject_ambiguous_body_framing(headers: Any) -> None:
    get_all = getattr(headers, "get_all", None)
    if not callable(get_all):
        return
    if len(get_all("Content-Length", [])) > 1:
        raise ValueError("duplicate Content-Length headers are not allowed")
    if get_all("Transfer-Encoding", []):
        raise ValueError("Transfer-Encoding is not supported")


def dispatch(message: dict[str, Any]) -> dict[str, Any] | None:
    if "id" not in message:
        return None
    request_id = message["id"]
    try:
        version = validate_request_structure(message)
        validate_supported_version(version)
        method = message["method"]
        params = message["params"]
        if method == "server/discover":
            result = complete(
                {
                    "supportedVersions": SUPPORTED_VERSIONS.copy(),
                    "capabilities": SERVER_CAPABILITIES.copy(),
                    "instructions": "Call ping for a transport health check.",
                },
                ttl_ms=3_600_000,
                cache_scope="public",
            )
        elif method == "tools/list":
            result = complete(
                {"tools": sorted(TOOLS, key=lambda tool: tool["name"])},
                ttl_ms=30_000,
                cache_scope="public",
            )
        elif method == "tools/call":
            if params.get("name") != "ping" or not isinstance(params.get("arguments", {}), dict):
                result = complete(
                    {
                        "content": [{"type": "text", "text": "Unknown or invalid tool"}],
                        "isError": True,
                    }
                )
            else:
                result = complete(
                    {"content": [{"type": "text", "text": "pong"}], "isError": False}
                )
        elif method == "subscriptions/listen":
            notifications = params.get("notifications")
            if not isinstance(notifications, dict):
                raise RpcFault(-32602, "subscriptions/listen requires notifications")
            result = complete({})
        else:
            raise RpcFault(-32601, f"Method not found: {method}")
        return {"jsonrpc": "2.0", "id": request_id, "result": result}
    except RpcFault as exc:
        return rpc_error(request_id, exc.code, str(exc), exc.data)


def accepted_filter(requested: dict[str, Any]) -> dict[str, Any]:
    accepted: dict[str, Any] = {}
    for key in ("toolsListChanged", "promptsListChanged", "resourcesListChanged"):
        if requested.get(key) is True:
            accepted[key] = True
    resources = requested.get("resourceSubscriptions")
    if isinstance(resources, list) and all(isinstance(uri, str) for uri in resources):
        accepted["resourceSubscriptions"] = resources.copy()
    return accepted


def subscription_messages(message: dict[str, Any]) -> list[dict[str, Any]]:
    request_id = message["id"]
    requested = message["params"]["notifications"]
    accepted = accepted_filter(requested)
    subscription_meta = {SUBSCRIPTION_ID_KEY: request_id}
    messages: list[dict[str, Any]] = [
        {
            "jsonrpc": "2.0",
            "method": "notifications/subscriptions/acknowledged",
            "params": {"notifications": accepted, "_meta": subscription_meta.copy()},
        }
    ]
    if accepted.get("toolsListChanged"):
        messages.append(
            {
                "jsonrpc": "2.0",
                "method": "notifications/tools/list_changed",
                "params": {"_meta": subscription_meta.copy()},
            }
        )
    resources = accepted.get("resourceSubscriptions", [])
    if resources:
        messages.append(
            {
                "jsonrpc": "2.0",
                "method": "notifications/resources/updated",
                "params": {"uri": resources[0], "_meta": subscription_meta.copy()},
            }
        )
    messages.append(
        {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": complete({}, result_meta=subscription_meta),
        }
    )
    return messages


class Handler(BaseHTTPRequestHandler):
    def log_message(self, format_string: str, *args: Any) -> None:
        sys.stderr.write("[mcp-http] " + (format_string % args) + "\n")

    def _write_json(self, status: int, payload: dict[str, Any]) -> None:
        body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _write_fault(self, status: int, request_id: Any, fault: RpcFault) -> None:
        self._write_json(status, rpc_error(request_id, fault.code, str(fault), fault.data))

    def _valid_path_and_origin(self) -> bool:
        if self.path != "/mcp":
            self._write_json(404, {"error": "Not found"})
            return False
        try:
            reject_duplicate_origin(self.headers)
        except RpcFault as fault:
            self._write_fault(400, None, fault)
            return False
        origin = self.headers.get("Origin")
        if not origin_allowed(origin):
            self._write_json(403, {"error": "Origin not allowed"})
            return False
        return True

    def _method_not_allowed(self) -> None:
        body = json.dumps({"error": "Method not allowed"}).encode("utf-8")
        self.send_response(405)
        self.send_header("Allow", "POST")
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _write_subscription_stream(self, message: dict[str, Any]) -> None:
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.send_header("Cache-Control", "no-cache")
        self.send_header("X-Accel-Buffering", "no")
        self.end_headers()
        for payload in subscription_messages(message):
            self.wfile.write(
                f"data: {json.dumps(payload, separators=(',', ':'))}\n\n".encode("utf-8")
            )
            self.wfile.flush()

    def do_POST(self) -> None:
        if not self._valid_path_and_origin():
            return
        content_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
        if content_type != "application/json":
            self._write_json(415, {"error": "Content-Type must be application/json"})
            return
        accept = self.headers.get("Accept", "")
        if "application/json" not in accept or "text/event-stream" not in accept:
            self._write_json(406, {"error": "Accept must include JSON and SSE"})
            return
        try:
            reject_ambiguous_body_framing(self.headers)
            raw_length = self.headers.get("Content-Length")
            if raw_length is None:
                raise ValueError("Content-Length is required")
            if not raw_length.isascii() or not raw_length.isdigit():
                raise ValueError("Content-Length must contain ASCII decimal digits")
            length = int(raw_length)
            if not 1 <= length <= MAX_REQUEST_BYTES:
                raise ValueError(
                    f"Content-Length must be from 1 through {MAX_REQUEST_BYTES}"
                )
            self.connection.settimeout(READ_TIMEOUT_SECONDS)
            body = self.rfile.read(length)
            if len(body) != length:
                raise ValueError("request body ended before Content-Length bytes arrived")
            message = json.loads(body)
            if not isinstance(message, dict):
                raise ValueError("message must be an object")
        except (ValueError, json.JSONDecodeError, TimeoutError) as exc:
            self._write_json(400, rpc_error(None, -32700, "Parse error", {"detail": str(exc)}))
            return

        request_id = message.get("id")
        try:
            body_version = validate_request_structure(message)
            reject_duplicate_routing_headers(self.headers)
            validate_http_headers(self.headers, message, body_version)
            validate_supported_version(body_version)
        except RpcFault as fault:
            self._write_fault(400, request_id, fault)
            return

        if "id" not in message:
            self.send_response(202)
            self.end_headers()
            return

        if message["method"] == "subscriptions/listen":
            notifications = message["params"].get("notifications")
            if not isinstance(notifications, dict):
                self._write_fault(
                    400,
                    request_id,
                    RpcFault(-32602, "subscriptions/listen requires notifications"),
                )
                return
            self._write_subscription_stream(message)
            return

        response = dispatch(message)
        status = 404 if response and response.get("error", {}).get("code") == -32601 else 200
        if response is not None:
            self._write_json(status, response)

    def do_GET(self) -> None:
        if self._valid_path_and_origin():
            self._method_not_allowed()

    def do_DELETE(self) -> None:
        if self._valid_path_and_origin():
            self._method_not_allowed()


def serve(host: str = "127.0.0.1", port: int = 0) -> ThreadingHTTPServer:
    server = ThreadingHTTPServer((host, port), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


def post(url: str, message: dict[str, Any], headers: Mapping[str, str]) -> tuple[int, Any, Any]:
    request = urllib.request.Request(
        url,
        data=json.dumps(message).encode("utf-8"),
        headers=dict(headers),
        method="POST",
    )
    try:
        response = urllib.request.urlopen(request, timeout=3)
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8")
        status = exc.code
        response_headers = exc.headers
        exc.close()
        return status, response_headers, json.loads(body) if body else None
    with response:
        body = response.read().decode("utf-8")
        if response.headers.get_content_type() == "application/json":
            payload: Any = json.loads(body)
        else:
            payload = body
        return response.status, response.headers, payload


def probe() -> None:
    server = serve()
    url = f"http://127.0.0.1:{server.server_port}/mcp"
    print("MCP 2026-07-28 Streamable HTTP probe")

    discover = make_request(1, "server/discover")
    status, _, _ = post(url, discover, http_headers_for(discover, origin="http://evil.example"))
    print(f"  invalid Origin: HTTP {status}")

    status, headers, payload = post(url, discover, http_headers_for(discover))
    print(
        f"  discovery: HTTP {status}, version={payload['result']['supportedVersions'][0]}, "
        f"session-header={headers.get('Mcp-Session-Id')}"
    )

    listing = make_request(2, "tools/list")
    removed = {"Mcp-Session-Id": "ignored", "Last-Event-ID": "ignored"}
    status, headers, payload = post(url, listing, http_headers_for(listing, extra=removed))
    print(
        f"  removed headers ignored: HTTP {status}, tool={payload['result']['tools'][0]['name']}, "
        f"echo={headers.get('Mcp-Session-Id')}"
    )

    mismatched = http_headers_for(listing)
    mismatched["Mcp-Method"] = "tools/call"
    status, _, payload = post(url, listing, mismatched)
    print(f"  header mismatch: HTTP {status}, code={payload['error']['code']}")

    future = make_request(3, "tools/list", version="2027-01-01")
    status, _, payload = post(url, future, http_headers_for(future))
    print(f"  unsupported version: HTTP {status}, code={payload['error']['code']}")

    notification = make_request(4, "tools/list")
    del notification["id"]
    status, _, payload = post(url, notification, http_headers_for(notification))
    print(f"  accepted notification: HTTP {status}, empty-body={payload == ''}")

    for method in ("GET", "DELETE"):
        request = urllib.request.Request(
            url,
            headers={"Origin": "http://localhost"},
            method=method,
        )
        try:
            urllib.request.urlopen(request, timeout=3)
        except urllib.error.HTTPError as exc:
            status = exc.code
            exc.close()
            print(f"  {method}: HTTP {status}")

    listen = make_request(
        "listen-1",
        "subscriptions/listen",
        {"notifications": {"toolsListChanged": True}},
    )
    status, _, stream = post(url, listen, http_headers_for(listen))
    print(
        f"  subscriptions/listen: HTTP {status}, "
        f"SSE={('notifications/subscriptions/acknowledged' in stream)}, "
        f"tagged={SUBSCRIPTION_ID_KEY in stream}"
    )

    server.shutdown()
    server.server_close()


def main() -> None:
    if "--serve" not in sys.argv:
        probe()
        return
    server = serve("127.0.0.1", 8017)
    print("MCP 2026-07-28 endpoint: http://127.0.0.1:8017/mcp")
    try:
        while True:
            time.sleep(60)
    except KeyboardInterrupt:
        server.shutdown()
        server.server_close()


if __name__ == "__main__":
    main()