# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-tool-result-whose-transport-attestation-was-minted-against-a-different-capability-snapshot-than-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-mcp-tool-result-whose-transport-attestation-was-minted-against-a-different-capability-snapshot-than-t.warrant.json
# Markdown SHA-256:   b15ef01f2fbe698d7c1e7c18e81541dc62fe4e7ee5d26354cc31fee2138cf901
# Code AST SHA-256:   17cecc119cb682be6bd8511ac578c6eaf52ffe338603df3106404ddac052ace2
# Verified Classes:   CapabilitySnapshotSkew, AttestationIntegrityError, NegotiatedSession
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass


class CapabilitySnapshotSkew(RuntimeError):
    """Raised when an MCP result's attestation is bound to a capability
    snapshot the client did not negotiate for the active session."""


class AttestationIntegrityError(RuntimeError):
    """Raised when a result envelope fails digest or signature verification."""


@dataclass(frozen=True)
class NegotiatedSession:
    session_id: str
    capability_snapshot: str  # S_negotiated, byte-exact hash of manifest
    server_key: bytes


def _canonical_digest(result_bytes: bytes) -> str:
    return hashlib.sha256(result_bytes).hexdigest()


def verify_and_bind(
    session: NegotiatedSession,
    envelope: dict,
    result_bytes: bytes,
) -> None:
    """Verify content integrity AND capability binding.

    Fails closed on any skew. Never mutates session.capability_snapshot.
    """
    # 1. Content integrity: recompute digest over canonical result bytes.
    recomputed = _canonical_digest(result_bytes)
    if not hmac.compare_digest(recomputed, envelope["attestation"]["result_digest"]):
        raise AttestationIntegrityError(
            f"result digest mismatch: envelope={envelope['attestation']['result_digest']} "
            f"recomputed={recomputed}"
        )

    # 2. Replay binding: envelope must answer the outstanding session request.
    if envelope.get("session_id") != session.session_id:
        raise AttestationIntegrityError(
            f"session mismatch: envelope={envelope.get('session_id')} "
            f"negotiated={session.session_id}"
        )

    # 3. Signature over the binding tuple, not just the result.
    signing_input = "|".join(
        [
            envelope["attestation"]["result_digest"],
            envelope["attestation"]["capability_snapshot"],
            envelope.get("nonce", ""),
            session.session_id,
        ]
    ).encode()
    expected_sig = hmac.new(session.server_key, signing_input, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected_sig, envelope["attestation"]["sig"]):
        raise AttestationIntegrityError("attestation signature invalid")

    # 4. Capability binding: the decisive check that naive verifiers omit.
    envelope_snapshot = envelope["attestation"]["capability_snapshot"]
    if envelope_snapshot != session.capability_snapshot:
        raise CapabilitySnapshotSkew(
            "result bound to capability snapshot "
            f"{envelope_snapshot!r} but session negotiated "
            f"{session.capability_snapshot!r}; plan state is stale, "
            "renegotiate tools/list and re-plan from checkpoint before consuming"
        )


def consume_tool_result(session: NegotiatedSession, envelope: dict, result_bytes: bytes) -> dict:
    """Entry point the agent calls for every tool result. Fails closed on skew."""
    verify_and_bind(session, envelope, result_bytes)
    return envelope["result"]
