# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-poisoning-in-mcp-tool-descriptions-before-schema-negotiation-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-poisoning-in-mcp-tool-descriptions-before-schema-negotiation-completes.warrant.json
# Markdown SHA-256:   9f35c70fe175bd46cba5fcb582ff716c98790c4079a8958123df0a706f6dd064
# Code AST SHA-256:   331e3e4f7a8652f6293fa1c6a40a2c2513374bbc0234c7584dd1a8b6b2e384a8
# Verified Classes:   CapabilityPoisoningError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityPoisoningError(RuntimeError):
    """Raised when a tool description asserts a cross-server capability
    reference that the declaring server does not own."""
    pass


def validate_manifest(server_id: str,
                      declared_tools: set[str],
                      global_registry: set[str],
                      descriptions: dict[str, str],
                      signed_cross_refs: set[str]) -> None:
    """
    Enforce the intra-server reference invariant at registry-merge time.

    A description may only name tools in `declared_tools` (same server) or
    tools listed in the server's signed `crossServerRefs` warrant. Any other
    resolvable reference is a capability-poisoning signal (condition C3).
    """
    import re
    token_re = re.compile(r"\b[a-z][a-z0-9_]{2,}\b")

    for tool_name, desc in descriptions.items():
        referenced = set(token_re.findall(desc.lower()))
        # Candidates are identifiers that look like tool names AND exist globally.
        cross_candidates = (referenced & global_registry) - declared_tools

        for ref in cross_candidates:
            if ref in signed_cross_refs:
                continue  # explicitly warranted cross-server dependency
            raise CapabilityPoisoningError(
                f"server={server_id!r} tool={tool_name!r} description references "
                f"cross-server tool {ref!r} without a signed crossServerRefs warrant; "
                f"rejecting manifest before context injection"
            )

        # Signal 2: imperative ordering language in prose with no schema counterpart.
        if re.search(r"\b(must|first|before|required to initialize|invalidates)\b",
                     desc.lower()) and not any(
                         k in desc.lower() for k in ("optional", "example")
                     ):
            raise CapabilityPoisoningError(
                f"server={server_id!r} tool={tool_name!r} encodes an ordering "
                f"precondition in prose rather than inputSchema; quarantine for review"
            )
