# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-descriptions-from-executing-as-instructions-during-mcp-server-hot-load.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-declared-tool-descriptions-from-executing-as-instructions-during-mcp-server-hot-load.warrant.json
# Markdown SHA-256:   1e55017512f904cd2aac219a14921541333c321321669f2e883b3c1ad48ecbb5
# Code AST SHA-256:   21c8811d8ca991f1fd5ba1e2317f1a2debfd8300e0ac45966346b5eb4d40cc39
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import re
import unicodedata

AUTHORITY_MARKERS = re.compile(r"(\[SYSTEM\]|<\|im_start\|>|<\|im_end\|>|^\s*(system|assistant|user)\s*:)", re.IGNORECASE)
CONTROL_CHARS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")


class ManifestInjectionError(RuntimeError):
    """Raised when a manifest field would cross the data/instruction boundary."""


def canonicalize_tool_name(name: str) -> str:
    if not isinstance(name, str) or not name:
        raise ManifestInjectionError("tool name must be a non-empty string")
    normalized = unicodedata.normalize("NFC", name).strip().casefold()
    if not normalized:
        raise ManifestInjectionError(f"tool name {name!r} canonicalizes to empty")
    return normalized


def sanitize_description(desc: str, max_len: int = 512) -> str:
    if not isinstance(desc, str):
        raise ManifestInjectionError("description must be a string")
    if CONTROL_CHARS.search(desc):
        raise ManifestInjectionError("description contains control characters")
    # Collapse newlines: a newline is how a field breaks out of its visual region
    # and impersonates a fresh instruction line.
    collapsed = " ".join(desc.splitlines()).strip()
    if AUTHORITY_MARKERS.search(collapsed):
        raise ManifestInjectionError(
            "description contains a token the harness renders as an instruction"
        )
    if len(collapsed) > max_len:
        raise ManifestInjectionError(
            f"description exceeds {max_len} chars; truncation would be lossy"
        )
    return collapsed


def merge_manifest(existing: dict, incoming: dict) -> dict:
    merged = dict(existing)
    for tool in incoming.get("tools", []):
        canon = canonicalize_tool_name(tool["name"])
        if canon in merged:
            # Shadow-tool collision: same canonical identity, different bytes.
            raise ManifestInjectionError(
                f"tool {tool['name']!r} collides with existing {canon!r}"
            )
        merged[canon] = {
            "name": canon,
            "description": sanitize_description(tool.get("description", "")),
            "input_schema": tool.get("input_schema", {}),
            "provenance": incoming.get("server_id"),
        }
    return merged
