# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-mcp-capability-negotiation-when-a-streamable-http-server-silently-omits-sse-fallback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-mcp-capability-negotiation-when-a-streamable-http-server-silently-omits-sse-fallback.warrant.json
# Markdown SHA-256:   15f6580cb8db48f0cc5946bb143b97e548fa067819b37f7367a29a97af6a06e0
# Code AST SHA-256:   89966fa623915f72e9fea6b2212704c09b2c85a8d54db90a92a8ef08a9675319
# Verified Classes:   McpStreamingNegotiationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class McpStreamingNegotiationError(RuntimeError):
    """Raised when a Streamable HTTP session's streaming capability cannot be confirmed
    and the caller has not opted into non-streaming downgrade."""
    pass


def confirm_streaming_capability(
    session_id: str | None,
    probe_response_headers: dict[str, str],
    probe_response_status: int,
    allow_downgrade: bool = True,
) -> str:
    """
    Called immediately after the post-initialize probe (resources/list).
    Returns one of: 'streaming', 'stateful_non_streaming', 'stateless_non_streaming'.
    Raises McpStreamingNegotiationError if the session is ambiguous and downgrade is disallowed.
    """
    content_type = probe_response_headers.get("content-type", "").split(";")[0].strip().lower()
    echoed_session = probe_response_headers.get("mcp-session-id")

    if probe_response_status >= 400:
        # Probe itself failed; cannot classify. Do not assume streaming.
        if not allow_downgrade:
            raise McpStreamingNegotiationError(
                f"Probe failed with status {probe_response_status}; "
                f"streaming capability unconfirmed for session {session_id!r}"
            )
        return "stateless_non_streaming"

    if content_type == "text/event-stream":
        return "streaming"

    if content_type == "application/json":
        if echoed_session:
            return "stateful_non_streaming"
        if not allow_downgrade:
            raise McpStreamingNegotiationError(
                f"Server returned application/json with no Mcp-Session-Id echo on session "
                f"{session_id!r}; streaming unconfirmed and downgrade disallowed. "
                f"Progress notifications and $/cancelRequest will not be delivered."
            )
        return "stateless_non_streaming"

    # Any other content type on a probe response is a protocol violation.
    raise McpStreamingNegotiationError(
        f"Unexpected probe Content-Type {content_type!r} on session {session_id!r}; "
        f"cannot classify streaming capability."
    )


def apply_capability_model(mode: str) -> dict:
    if mode == "streaming":
        return {"progress_tokens": True, "cancel_request": True, "list_changed_push": True, "idempotency_keys": False}
    if mode == "stateful_non_streaming":
        return {"progress_tokens": False, "cancel_request": True, "list_changed_push": False, "idempotency_keys": False}
    if mode == "stateless_non_streaming":
        return {"progress_tokens": False, "cancel_request": False, "list_changed_push": False, "idempotency_keys": True}
    raise McpStreamingNegotiationError(f"Unknown capability mode {mode!r}")
