# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-an-mcp-streamable-batch-upgrade-mid-tool-call-the-sse-to-stream-promotion-race-and-its-per-tool-capability-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-an-mcp-streamable-batch-upgrade-mid-tool-call-the-sse-to-stream-promotion-race-and-its-per-tool-capability-invariant.warrant.json
# Markdown SHA-256:   8197d20e7fae61502e380ecc4bfc485fe298f0b40517e9a82b4b11af787775ab
# Code AST SHA-256:   a474885b9d0a52ad20e28b624c83afe66614b10d8e1c2c34b0d57995686a25ec
# Verified Classes:   StreamNegotiationError, ToolCapability, BatchResponse
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Any


class StreamNegotiationError(RuntimeError):
    """Raised when a batch response's encoding or per-tool stream framing
    violates the MCP HTTP-native transport invariant."""
    pass


@dataclass
class ToolCapability:
    name: str
    streaming: bool


@dataclass
class BatchResponse:
    content_type: str
    events: list[dict[str, Any]] = field(default_factory=list)
    body: Any = None


def validate_batch_response(
    response: BatchResponse,
    requested_tools: list[ToolCapability],
    client_accepts_sse: bool,
) -> dict[str, Any]:
    """
    Enforce the SSE-to-stream promotion invariant for a batch response.

    Rules:
      1. Encoding is frozen by Content-Type; the reader must bind to it,
         not to the request's Accept header.
      2. A batch containing any non-streaming tool must NOT be promoted to
         SSE unless the server emitted explicit per-tool framing.
      3. Repeated JSON-RPC ids in an SSE stream are only valid for tools
         declared streaming AND opted into accumulation.
      4. A streaming tool must receive an explicit terminal event before
         its accumulated content is treated as final.
    """
    streaming_tools = {t.name for t in requested_tools if t.streaming}
    non_streaming_tools = {t.name for t in requested_tools if not t.streaming}

    if response.content_type == "application/json":
        if client_accepts_sse and not isinstance(response.body, list):
            raise StreamNegotiationError(
                "Client bound an SSE reader but server returned JSON body; "
                "reader framing must follow Content-Type, not Accept."
            )
        # Buffered streaming tool is acceptable ONLY if marked buffered.
        for item in response.body or []:
            if item.get("id") in streaming_tools:
                result = item.get("result", {})
                if result.get("streaming") is True and not result.get("buffered"):
                    raise StreamNegotiationError(
                        f"Streaming tool id={item.get('id')} returned in JSON "
                        f"batch without buffered marker; partial result may be "
                        f"indistinguishable from complete."
                    )
        return {"encoding": "json", "results": response.body}

    if response.content_type == "text/event-stream":
        if not client_accepts_sse:
            raise StreamNegotiationError(
                "Server promoted to SSE but client did not accept event-stream."
            )
        if non_streaming_tools and streaming_tools:
            # Mixed batch promoted to SSE: require explicit per-tool framing.
            seen: dict[Any, int] = {}
            terminal: set[Any] = set()
            for ev in response.events:
                payload = ev.get("data", {})
                rid = payload.get("id")
                seen[rid] = seen.get(rid, 0) + 1
                if payload.get("result", {}).get("terminal") is True:
                    terminal.add(rid)
            for rid, count in seen.items():
                if count > 1 and rid not in streaming_tools:
                    raise StreamNegotiationError(
                        f"Mixed batch promoted to SSE: non-streaming id={rid} "
                        f"appeared {count} times; accumulation semantics undefined."
                    )
                if rid in streaming_tools and rid not in terminal:
                    raise StreamNegotiationError(
                        f"Streaming tool id={rid} received no terminal event; "
                        f"accumulated content must not be treated as final."
                    )
        return {"encoding": "sse", "events": response.events}

    raise StreamNegotiationError(
        f"Unrecognized Content-Type for MCP batch: {response.content_type!r}"
    )


def handle_batch(response: BatchResponse, tools: list[ToolCapability], accept_sse: bool):
    try:
        return validate_batch_response(response, tools, accept_sse)
    except StreamNegotiationError as e:
        # Refuse the batch; caller must re-issue tools individually.
        raise StreamNegotiationError(
            f"Batch refused, re-issue tools separately: {e}"
        ) from e
