# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-egress-policy-bypass-when-a-sandboxed-tool-re-enters-through-a-nested-mcp-client.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-egress-policy-bypass-when-a-sandboxed-tool-re-enters-through-a-nested-mcp-client.warrant.json
# Markdown SHA-256:   dfed9fbc5e8e7f4211813f9a1a2595a15dd8ec6ecc13b08c936e35677d230953
# Code AST SHA-256:   035ea64a23432ce663d06756d3921717a41aa5bccadc731c5e8021398dca28cd
# Verified Classes:   EgressPolicyBypass
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EgressPolicyBypass(RuntimeError):
    """Raised when an egress flow's kernel owner does not match an enrolled MCP principal."""


ENROLLED_PRINCIPALS = {"analytics-mcp"}  # serverInfo.name values the host authorized


def authorize_egress(flow: dict, enrolled: set[str] = ENROLLED_PRINCIPALS) -> None:
    """
    flow keys:
      - socket_owner_pid: int  (from SO_PEERCRED / /proc/<pid>)
      - cgroup_egress_grant: str | None  (kernel-anchored grant, authoritative)
      - mcp_client_info_name: str  (advisory only; never trust alone)
      - destination: str
      - opened_after_call_result: bool
    """
    if flow["cgroup_egress_grant"] is None:
        raise EgressPolicyBypass(
            f"egress to {flow['destination']} from pid {flow['socket_owner_pid']} "
            f"has no kernel-anchored grant; MCP identity "
            f"{flow['mcp_client_info_name']!r} is advisory and cannot authorize"
        )
    if flow["mcp_client_info_name"] not in enrolled:
        # nested client re-declared an identity the host never enrolled
        raise EgressPolicyBypass(
            f"un-enrolled MCP principal {flow['mcp_client_info_name']!r} "
            f"opened egress to {flow['destination']}"
        )
    if flow["opened_after_call_result"]:
        raise EgressPolicyBypass(
            f"post-result egress to {flow['destination']} from "
            f"{flow['mcp_client_info_name']!r}: tool returned before network use, "
            f"indicating undeclared network capability"
        )


def handle_nested_initialize(client_info: dict, outer_initialized: bool) -> None:
    if outer_initialized:
        raise EgressPolicyBypass(
            f"second initialize on logical server with clientInfo "
            f"{client_info.get('name')!r}: nested client construction is forbidden "
            f"unless the sub-server is enrolled in the manifest"
        )
