# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-did-verified-a2a-peer-as-unauthenticated-at-the-mcp-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-did-verified-a2a-peer-as-unauthenticated-at-the-mcp-tool-boundary.warrant.json
# Markdown SHA-256:   a9878078fc9e1ad8ac9ab1ca7cef5b939cf94f162b8a460b32da23eea5388a00
# Code AST SHA-256:   e771ec09175cab2b88b798309c25b97cbb81e047d2317198e7dfc495817eff87
# Verified Classes:   SubjectSubstitutionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SubjectSubstitutionError(RuntimeError):
    """Raised when an MCP tool call presents a credential whose subject
    is not the executing subject, i.e. DID trust was inherited across
    the A2A->MCP translation instead of re-bound to the leaf executor."""


def authorize_mcp_call(
    a2a_caller_did: str,
    executor_did: str | None,
    presented_vc: dict,
    tool: str,
    resource: str,
) -> bool:
    subject = presented_vc.get("credentialSubject", {}).get("id")
    proof_scope = presented_vc.get("proof", {}).get("scope", {})
    actor_claim = presented_vc.get("act", {}).get("sub")

    # Invariant: the credential must name the executor, not an ancestor.
    if executor_did is None:
        raise SubjectSubstitutionError(
            f"executor has no DID; presented credential subject is {subject!r} "
            f"(A2A caller {a2a_caller_did!r}) — cannot bind tool {tool!r}"
        )

    if subject != executor_did:
        raise SubjectSubstitutionError(
            f"credential subject {subject!r} != executor {executor_did!r} "
            f"for tool {tool!r}; DID verification at A2A ingress does not "
            f"authorize leaf execution"
        )

    if actor_claim != executor_did:
        raise SubjectSubstitutionError(
            f"act.sub {actor_claim!r} does not match executor {executor_did!r}; "
            f"delegation chain terminus is not the acting subject"
        )

    if proof_scope.get("tool") != tool or proof_scope.get("resource") != resource:
        raise SubjectSubstitutionError(
            f"proof scope {proof_scope!r} does not cover tool={tool!r} "
            f"resource={resource!r}; credential is unscoped ambient authority"
        )

    return True
