# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-authorization-envelope-bleed-when-an-http-native-mcp-server-multiplexes-concurrent-tool-calls-under-per-tool-rate-limits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-authorization-envelope-bleed-when-an-http-native-mcp-server-multiplexes-concurrent-tool-calls-under-per-tool-rate-limits.warrant.json
# Markdown SHA-256:   e184acd048841edfd9c0ff65784ceba6209c57cdeec7d4329db576e1b496eb25
# Code AST SHA-256:   92a6f909b1a93fa164500c9b10092ae64eb74d9ca6a7fe862878ec2b4678fb60
# Verified Classes:   EnvelopeBleedError, CallEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EnvelopeBleedError(RuntimeError):
    """Raised when a multiplexed MCP response reports a tool/envelope identity
    that does not match the request that produced it. This indicates the server
    resolved authorization or rate-limit state from a shared transport context
    rather than the request payload; retrying will reproduce the corruption."""


@dataclass(frozen=True)
class CallEnvelope:
    request_id: str
    tool_name: str
    token_id: str

    def envelope_id(self) -> str:
        raw = f"{self.token_id}:{self.tool_name}:{self.request_id}".encode()
        return hashlib.sha256(raw).hexdigest()[:16]


def verify_response_envelope(
    request: CallEnvelope,
    response_tool_name: str,
    response_envelope_id: str,
    response_status: int,
) -> None:
    # The server must echo the tool it actually charged. If it echoes a
    # different tool, the multiplexer leaked a shared RequestContext value.
    if response_tool_name != request.tool_name:
        raise EnvelopeBleedError(
            f"envelope bleed: request for tool={request.tool_name!r} "
            f"(req={request.request_id}) was charged to tool="
            f"{response_tool_name!r}; server resolved envelope from shared "
            f"transport context, not request payload"
        )
    if response_envelope_id != request.envelope_id():
        raise EnvelopeBleedError(
            f"envelope id mismatch: expected {request.envelope_id()!r} "
            f"for {request.tool_name!r}, got {response_envelope_id!r}; "
            f"per-tool rate bucket may be keyed on connection, not request"
        )
    # A 429 is only trustworthy if it is attributed to the tool we called.
    if response_status == 429 and response_tool_name != request.tool_name:
        raise EnvelopeBleedError(
            f"429 misattribution for {request.tool_name!r}: backpressure "
            f"signal belongs to {response_tool_name!r}; do not adapt "
            f"concurrency model from this response"
        )
