# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-elicitation-and-sampling-requests-as-adversarial-control-flow-not-user-intent.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-elicitation-and-sampling-requests-as-adversarial-control-flow-not-user-intent.warrant.json
# Markdown SHA-256:   15c4d701070fc37014e2d3580c9b85ccdcb75bc10c12535db21eb4fd9911eecb
# Code AST SHA-256:   f9809d37cfe406995614a82d10b487e316176b1ccbe963456a48936caf6c1a51
# Verified Classes:   ElicitationHijackError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ElicitationHijackError(RuntimeError):
    """Raised when a server-initiated MCP turn attempts to cross an authority
    or channel boundary the runtime is required to enforce."""


SENSITIVE_PATTERNS = ("passphrase", "password", "token", "secret", "key", "credential", "pin")


def _is_sensitive(schema: dict) -> bool:
    for field in schema.get("properties", {}).values():
        blob = " ".join(str(field.get(k, "")) for k in ("title", "description", "format")).lower()
        if any(p in blob for p in SENSITIVE_PATTERNS):
            return True
    return False


def handle_elicitation(req: dict, origin_trust: str, calls_in_flight: int, prior_elicitations: int) -> dict:
    server = req.get("server_id", "<unknown>")
    schema = req.get("params", {}).get("requestedSchema", {})

    # No channel chaining: elicitation may not be nested inside sampling.
    if req.get("nested_in") == "sampling":
        raise ElicitationHijackError(f"server {server}: elicitation nested in sampling refused")

    # Sensitive-class fields are refused before the human is shown anything.
    if _is_sensitive(schema):
        raise ElicitationHijackError(f"server {server}: sensitive schema field refused at runtime")

    # Budget: one elicitation per in-flight tool call for untrusted origins.
    if origin_trust != "first_party" and prior_elicitations >= 1:
        raise ElicitationHijackError(f"server {server}: elicitation budget exceeded for call")

    return {"action": "surface", "provenance": server, "trust": origin_trust}


def handle_sampling(req: dict, origin_trust: str) -> dict:
    server = req.get("server_id", "<unknown>")
    # The sampling system prompt is runtime-owned; a server may not override it.
    if req.get("params", {}).get("systemPrompt") is not None:
        raise ElicitationHijackError(f"server {server}: sampling system-prompt override refused")
    # Sampling output is ephemeral; never persisted as a replayable tool result.
    return {"action": "sample", "ephemeral": True, "provenance": server}
