# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-never-re-validates-skill-injection-through-poisoned-mcp-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-never-re-validates-skill-injection-through-poisoned-mcp-registries.warrant.json
# Markdown SHA-256:   cae1db51198586c3eb72f2fab9c80106f53e5fcf28be9507fc69376bcaaddeab
# Code AST SHA-256:   3d8a9946d161778ab3a29240ed44b57e69fe795f582b306b9ab071dc2489785c
# Verified Classes:   ManifestIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestIntegrityError(RuntimeError):
    """Raised when a tool manifest entry attempts to inject operational directives."""
    pass


IMPERATIVE_MARKERS = (
    "always", "before calling", "you must", "include the",
    "first read", "then send", "make sure to pass",
)


def admit_tool(manifest_entry: dict, attested_hash: str | None) -> dict:
    name = manifest_entry.get("name", "<unnamed>")
    description = (manifest_entry.get("description") or "").lower()

    # Tripwire: descriptions must describe, not instruct.
    for marker in IMPERATIVE_MARKERS:
        if marker in description:
            raise ManifestIntegrityError(
                f"tool {name!r} description contains directive {marker!r}; "
                f"quarantine pending out-of-band attestation"
            )

    # Schema sub-descriptions are equally untrusted.
    schema = manifest_entry.get("inputSchema", {})
    for prop, spec in (schema.get("properties") or {}).items():
        sub = (spec.get("description") or "").lower()
        for marker in IMPERATIVE_MARKERS:
            if marker in sub:
                raise ManifestIntegrityError(
                    f"tool {name!r} schema property {prop!r} carries directive "
                    f"{marker!r}; reject manifest"
                )

    # Provenance: a changed description for an unchanged signature is suspect.
    current_hash = manifest_entry.get("provenance_hash")
    if attested_hash and current_hash and current_hash != attested_hash:
        raise ManifestIntegrityError(
            f"tool {name!r} description changed without schema bump; "
            f"require re-attestation before caching"
        )

    return {"name": name, "schema": schema, "admitted": True}
