# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-egress-policy-on-mcp-tool-results-before-they-re-enter-the-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-egress-policy-on-mcp-tool-results-before-they-re-enter-the-reasoning-loop.warrant.json
# Markdown SHA-256:   91510b172bd194fd19cbd67e024ae6967fa05ebfe91994c2a44dc053dfecaa2d
# Code AST SHA-256:   713185c64e788ce1b237f570d71e30b4aa52e5e9ac9ccd8759d0a3a5f94357d7
# Verified Classes:   EgressPolicyViolation, ContentBlock, ToolResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class EgressPolicyViolation(RuntimeError):
    """Raised when an MCP tool result fails admission-time egress policy."""


@dataclass(frozen=True)
class ContentBlock:
    type: str
    mime_type: str | None
    payload: bytes


@dataclass(frozen=True)
class ToolResult:
    server_id: str
    trusted: bool
    blocks: list[ContentBlock]


ALLOWED_UNTRUSTED_MIME = frozenset({"text/plain", "application/json"})
MAX_BLOCK_BYTES = 256 * 1024


def admit_result(result: ToolResult) -> list[dict]:
    """Decide whether an MCP CallToolResult may enter the model context.

    Runs before any block is appended to the transcript. Rejects the whole
    result on any violation; partial admission is a boundary hole.
    """
    if result.trusted:
        return [
            {"role": "tool", "content": b.payload.decode("utf-8", "replace")}
            for b in result.blocks
        ]

    admitted: list[dict] = []
    for idx, block in enumerate(result.blocks):
        if block.type not in {"text", "resource"}:
            raise EgressPolicyViolation(
                f"server={result.server_id} block={idx} type={block.type!r} "
                f"not admissible from untrusted server"
            )
        if block.mime_type not in ALLOWED_UNTRUSTED_MIME:
            raise EgressPolicyViolation(
                f"server={result.server_id} block={idx} "
                f"mime={block.mime_type!r} outside allowlist"
            )
        if len(block.payload) > MAX_BLOCK_BYTES:
            raise EgressPolicyViolation(
                f"server={result.server_id} block={idx} "
                f"size={len(block.payload)} exceeds {MAX_BLOCK_BYTES}"
            )
        digest = hashlib.sha256(block.payload).hexdigest()[:16]
        admitted.append(
            {
                "role": "tool",
                "content": (
                    f"[UNTRUSTED_DATA server={result.server_id} "
                    f"block={idx} sha256={digest}]\n"
                    f"{block.payload.decode('utf-8', 'replace')}\n"
                    f"[/UNTRUSTED_DATA]"
                ),
            }
        )
    return admitted


def admit_or_typed_error(result: ToolResult) -> list[dict]:
    """Admission wrapper that converts violations into a legible tool error.

    Silent drops cause the model to retry with mutated arguments, which is
    its own divergence mode; the rejection must be visible.
    """
    try:
        return admit_result(result)
    except EgressPolicyViolation as exc:
        return [
            {
                "role": "tool",
                "content": f"[EGRESS_REJECTED server={result.server_id}] {exc}",
            }
        ]
