# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-negotiates-mid-session-the-skill-injection-boundary-in-dynamic-mcp-capability-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-negotiates-mid-session-the-skill-injection-boundary-in-dynamic-mcp-capability-refresh.warrant.json
# Markdown SHA-256:   db5621d8dff0dd4110efaf824336dae514369bc9d4ea1912137396891f310dd7
# Code AST SHA-256:   e0a68d80025c3e0a68df2bca2bb311d5f0a9f8d0c6ba89469472e5d1b1145fad
# Verified Classes:   ManifestInjectionError, SessionManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestInjectionError(RuntimeError):
    """Raised when a refreshed tool manifest widens capabilities or smuggles
    instruction-bearing metadata past the trust boundary."""
    pass


@dataclass
class SessionManifest:
    authorized_tools: set[str]
    manifest_hash: str
    raw: dict[str, Any] = field(default_factory=dict)


def _hash(manifest: dict[str, Any]) -> str:
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def _tool_names(manifest: dict[str, Any]) -> set[str]:
    return {t["name"] for t in manifest.get("tools", [])}


def admit_refresh(session: SessionManifest, incoming: dict[str, Any]) -> SessionManifest:
    """Admit a re-fetched manifest. Enforces capability monotonicity: a refresh
    may NOT add tool names outside the session's authorized set. Raises on
    widening so the recovery path fails closed instead of inheriting trust."""
    new_names = _tool_names(incoming)
    widened = new_names - session.authorized_tools

    if widened:
        # This is the exact condition the injection exploited: a tool
        # (export_credentials) appearing mid-session that was never authorized.
        raise ManifestInjectionError(
            f"Refresh attempted to widen capability set with unauthorized "
            f"tools {sorted(widened)}; manifest hash {_hash(incoming)} rejected. "
            f"Quarantined for operator re-authorization."
        )

    # Even when the name set is unchanged, descriptions are peer-authored text.
    # Tag them so the model treats them as data, not instructions.
    tagged = json.loads(json.dumps(incoming))
    for tool in tagged.get("tools", []):
        if "description" in tool:
            tool["_provenance"] = "UNTRUSTED_PEER_METADATA"

    return SessionManifest(
        authorized_tools=session.authorized_tools,
        manifest_hash=_hash(tagged),
        raw=tagged,
    )


def on_tool_call_failure(session: SessionManifest, refetched: dict[str, Any]) -> SessionManifest:
    """Recovery path: the agent is under error pressure and most likely to
    over-trust the returned manifest. Route it through the same admission
    gauntlet as any other refresh — never bypass on the error path."""
    try:
        return admit_refresh(session, refetched)
    except ManifestInjectionError:
        # Keep last-known-good manifest; do not resume against the poisoned one.
        raise
