# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-an-mcp-tool-s-declared-output-schema-and-its-actual-returned-bytes-and-why-does-post-hoc-valida.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-an-mcp-tool-s-declared-output-schema-and-its-actual-returned-bytes-and-why-does-post-hoc-valida.warrant.json
# Markdown SHA-256:   e27911cce4118bbe0bf020cce36ff4807484d6ca32e1bb949a6535a4e58ba438
# Code AST SHA-256:   f571ef7effd7bc987414a9d676ac567a7669e49e577c6a4f69f449659f5ddabd
# Verified Classes:   ToolOutputAdmissionError
# Defensive Guards:   11 fail-closed invariants (zero external deps)

class ToolOutputAdmissionError(RuntimeError):
    """Raised when an MCP tool result fails client-held admission at the byte boundary."""
    pass


# Client-held, closed allowlist. Derived from operator config, NOT from tools/list.
# Each entry bounds type, length, and character class. No 'additionalProperties: true'.
ADMISSIBLE_SHAPES = {
    "search_docs": {
        "results": {"type": "array", "max_items": 50,
                    "item_pattern": r"^[A-Za-z0-9 ,.\-]{0,200}$"},
    },
}


def admit_tool_output(tool_name: str, raw_bytes: bytes) -> dict:
    import json, re, unicodedata

    if tool_name not in ADMISSIBLE_SHAPES:
        raise ToolOutputAdmissionError(
            f"tool {tool_name!r} not on client allowlist; refusing admission"
        )

    # Condition 2: validate the exact bytes, canonicalized, before parsing.
    try:
        text = raw_bytes.decode("utf-8", errors="strict")
    except UnicodeDecodeError as e:
        raise ToolOutputAdmissionError(f"non-UTF-8 bytes from {tool_name}: {e}")
    if text.startswith("\ufeff"):
        raise ToolOutputAdmissionError("BOM present; refusing non-canonical encoding")
    text = unicodedata.normalize("NFC", text)

    # Condition 2b: reject duplicate keys, which parse ambiguously across runtimes.
    def _no_dup(pairs):
        seen = set()
        for k, _ in pairs:
            if k in seen:
                raise ToolOutputAdmissionError(f"duplicate key {k!r} in {tool_name}")
            seen.add(k)
        return dict(pairs)

    try:
        payload = json.loads(text, object_pairs_hook=_no_dup)
    except json.JSONDecodeError as e:
        raise ToolOutputAdmissionError(f"malformed JSON from {tool_name}: {e}")

    shape = ADMISSIBLE_SHAPES[tool_name]
    if not isinstance(payload, dict):
        raise ToolOutputAdmissionError(f"{tool_name} returned non-object")
    # Closed shape: no keys beyond those declared. This is what refuses _note,
    # search_docs_v2 suggestions, and any server-injected extras.
    extra = set(payload) - set(shape)
    if extra:
        raise ToolOutputAdmissionError(f"{tool_name} returned undeclared keys: {extra}")

    for field, spec in shape.items():
        if field not in payload:
            raise ToolOutputAdmissionError(f"{tool_name} missing required field {field!r}")
        val = payload[field]
        if spec["type"] == "array":
            if not isinstance(val, list):
                raise ToolOutputAdmissionError(f"{tool_name}.{field} not an array")
            if len(val) > spec["max_items"]:
                raise ToolOutputAdmissionError(
                    f"{tool_name}.{field} exceeds max_items={spec['max_items']}"
                )
            pat = re.compile(spec["item_pattern"])
            for i, item in enumerate(val):
                if not isinstance(item, str) or not pat.match(item):
                    # The injection string fails here: it contains '=' and "'"
                    # outside the admitted character class.
                    raise ToolOutputAdmissionError(
                        f"{tool_name}.{field}[{i}] violates admitted character class"
                    )
    return payload
