# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-per-tool-egress-policy-when-an-mcp-server-advertises-a-capability-it-can-only-partially-honor.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-per-tool-egress-policy-when-an-mcp-server-advertises-a-capability-it-can-only-partially-honor.warrant.json
# Markdown SHA-256:   c03d825f146f54662800fda10f4287bac10bdea0f01be8676d75497cfe43e776
# Code AST SHA-256:   9a15f5385188ba6de429ece915a79438a443319a5f415716de5273d3a73a40ec
# Verified Classes:   EgressPolicyViolation, ToolDescriptor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EgressPolicyViolation(RuntimeError):
    """Raised when a tool invocation produces egress outside its resolved policy."""
    pass


class ToolDescriptor:
    def __init__(self, name: str, declared_egress_hosts: frozenset[str], args_can_coerce_to_url: bool):
        self.name = name
        self.declared_egress_hosts = declared_egress_hosts
        self.args_can_coerce_to_url = args_can_coerce_to_url


def admit_invocation(descriptor: ToolDescriptor, observed_egress_hosts: frozenset[str]) -> None:
    """
    Enforce egress policy at resolution scope, not capability scope.
    observed_egress_hosts must be produced by a socket tap the runtime controls,
    covering every hop including redirects and protocol-relative coercions.
    """
    if descriptor.args_can_coerce_to_url and not descriptor.declared_egress_hosts:
        # A tool whose args can resolve to a URL but which declares no egress surface
        # is undeclared, not offline. Refuse rather than assume.
        raise EgressPolicyViolation(
            f"tool {descriptor.name!r} admits URL-coercible args but declares no egress surface; "
            "cannot capability-scope an open coercion domain"
        )

    undeclared = observed_egress_hosts - descriptor.declared_egress_hosts
    if undeclared:
        raise EgressPolicyViolation(
            f"tool {descriptor.name!r} contacted undeclared hosts {sorted(undeclared)}; "
            f"declared surface was {sorted(descriptor.declared_egress_hosts)}"
        )


def run_tool_call(descriptor: ToolDescriptor, observed_egress_hosts: frozenset[str]) -> None:
    # Called after the MCP server returns, with the tap's observed host set.
    admit_invocation(descriptor, observed_egress_hosts)
