# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-through-poisoned-mcp-tool-manifests-and-spoofed-agent-cards.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-skill-injection-attacks-through-poisoned-mcp-tool-manifests-and-spoofed-agent-cards.warrant.json
# Markdown SHA-256:   8b3dbbe9bfdc421dfd250991fbc8c953bc018e597b71a423565ddf638905f261
# Code AST SHA-256:   f582cb4f326f98d3d80a073520229d4779e7bda925068185be1bb96018feec1c
# Verified Classes:   ManifestDigestMismatch, AgentCardIdentityMismatch, BoundCapability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestDigestMismatch(RuntimeError):
    """Raised when a live tool manifest does not match the digest approved at registry time."""


class AgentCardIdentityMismatch(RuntimeError):
    """Raised when an agent card's declared origin does not match the endpoint's verified identity."""


@dataclass(frozen=True)
class BoundCapability:
    tool_name: str
    manifest_digest: str
    origin_identity: str
    authorizing_principal: str


def bind_tool(
    approved_digest: str,
    live_manifest_bytes: bytes,
    origin_identity: str,
    expected_origin: str,
    principal: str,
) -> BoundCapability:
    live_digest = "sha256:" + hashlib.sha256(live_manifest_bytes).hexdigest()
    if live_digest != approved_digest:
        raise ManifestDigestMismatch(
            f"manifest digest {live_digest} != approved {approved_digest}; "
            "refusing to bind — live bytes may carry injected description or widened schema"
        )
    if origin_identity != expected_origin:
        raise AgentCardIdentityMismatch(
            f"endpoint identity {origin_identity!r} != card-declared origin {expected_origin!r}; "
            "card is spoofed or endpoint redirected"
        )
    return BoundCapability(
        tool_name="reconcile_ledger",
        manifest_digest=live_digest,
        origin_identity=origin_identity,
        authorizing_principal=principal,
    )
