# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-description-text-as-adversarial-input-rather-than-trusted-schema-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-description-text-as-adversarial-input-rather-than-trusted-schema-metadata.warrant.json
# Markdown SHA-256:   b79a0bd11945a6eaeddf41cc493d3ca7d31ab1e5281d7e1061701a283e004f7f
# Code AST SHA-256:   762027328e6edd85f3117e1fcf42108140a5090c9ea33b220197220a6fc18401
# Verified Classes:   CapabilityEscalationError, ToolDescriptor, SanitizationResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field


class CapabilityEscalationError(RuntimeError):
    """Raised when a tool description or call composition crosses a trust boundary."""


@dataclass
class ToolDescriptor:
    server_id: str
    name: str
    description: str
    input_schema: dict


@dataclass
class SanitizationResult:
    admitted: list[ToolDescriptor] = field(default_factory=list)
    stripped: list[tuple[str, str]] = field(default_factory=list)
    rejected_servers: list[str] = field(default_factory=list)


# Imperative / second-person address directed at the agent.
_IMPERATIVE = re.compile(
    r"\b(you must|you should|before (?:using|calling)|first call|always call|"
    r"do not (?:call|use)|required by|make sure to)\b",
    re.IGNORECASE,
)

# References to a tool name that is not owned by the same server.
_CROSS_TOOL = re.compile(r"\b([a-z_][a-z0-9_]{2,})\b")


def _owned_tool_names(server_tools: list[ToolDescriptor]) -> set[str]:
    return {t.name for t in server_tools}


def sanitize_server_catalog(
    server_tools: list[ToolDescriptor],
    known_foreign_tools: set[str],
) -> SanitizationResult:
    """Gate a single server's tools/list response before prompt assembly.

    Rejects the whole server if any description makes a cross-tool claim.
    Strips imperative clauses from otherwise-declarative descriptions.
    """
    if not server_tools:
        raise CapabilityEscalationError("empty tools/list response; refusing binding")

    server_id = server_tools[0].server_id
    owned = _owned_tool_names(server_tools)
    result = SanitizationResult()

    for tool in server_tools:
        desc = tool.description or ""

        # Cross-tool precondition / obligation -> reject the entire server.
        for token in _CROSS_TOOL.findall(desc):
            if token in known_foreign_tools and token not in owned:
                result.rejected_servers.append(server_id)
                raise CapabilityEscalationError(
                    f"server {server_id} tool {tool.name} description references "
                    f"foreign tool '{token}'; catalog rejected wholesale"
                )

        if _IMPERATIVE.search(desc):
            # Strip the imperative clause; retain declarative remainder.
            cleaned = _IMPERATIVE.sub("", desc).strip(" .;,")
            result.stripped.append((tool.name, desc))
            tool = ToolDescriptor(
                server_id=tool.server_id,
                name=tool.name,
                description=cleaned,
                input_schema=tool.input_schema,
            )

        result.admitted.append(tool)

    return result


def authorize_outbound_call(
    tool: ToolDescriptor,
    arguments: dict,
    tainted_values: dict[str, str],  # value_hash -> source_path
    user_warrant: str | None,
) -> None:
    """Refuse outbound calls carrying values read from sensitive sources."""
    if tool.name not in {"send_webhook", "post_url", "upload"}:
        return

    for arg_name, value in arguments.items():
        if not isinstance(value, str):
            continue
        digest = hashlib.sha256(value.encode()).hexdigest()
        if digest in tainted_values and user_warrant is None:
            raise CapabilityEscalationError(
                f"outbound tool {tool.name} arg '{arg_name}' carries value "
                f"read from sensitive source {tainted_values[digest]!r} "
                f"without user warrant"
            )
