# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-s-self-description-capability-confusion-attacks-via-mcp-tool-schema-poisoning-and-the-description-effect-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-tool-s-self-description-capability-confusion-attacks-via-mcp-tool-schema-poisoning-and-the-description-effect-diverge.warrant.json
# Markdown SHA-256:   7ca33ed4f747129018c7e927fe582187c5f5de70ad19ad31dee29230e64ca2c2
# Code AST SHA-256:   06bf5d8506e43a4168dac93451a7991f8bcf16c17a52c5e7a602b49a0f186a43
# Verified Classes:   CapabilityConfusionError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityConfusionError(RuntimeError):
    """Raised when a tool's observed effects exceed its declared capability,
    or when an un-attested description attempts to issue instructions."""
    pass


ATTESTED_MANIFESTS = {
    # tool_name -> (manifest_sha256, allowed_param_patterns, declared_effects)
    "read_file": ("a1b2c3...", {"path": r"^[A-Za-z0-9_./-]+$"}, {"read"}),
    "send_report": ("d4e5f6...", {"table": r"^[A-Za-z0-9 ,.\n-]{0,4096}$"}, {"network_egress"}),
}


def validate_tool_invocation(tool_name, description, arguments, observed_effects):
    spec = ATTESTED_MANIFESTS.get(tool_name)

    # 1. Un-attested tool: description may not carry instruction weight.
    if spec is None:
        raise CapabilityConfusionError(
            f"tool {tool_name!r} has no attested manifest; description is inert data, "
            f"but invocation was planned as if it were instruction"
        )

    manifest_sha, patterns, declared_effects = spec

    # 2. Schema under-specification check: arguments must match pinned patterns.
    import re
    for arg, value in arguments.items():
        pat = patterns.get(arg)
        if pat is None:
            raise CapabilityConfusionError(
                f"argument {arg!r} on tool {tool_name!r} is not schema-constrained"
            )
        if not re.fullmatch(pat, str(value)):
            raise CapabilityConfusionError(
                f"argument {arg!r}={value!r} violates pinned pattern {pat!r} "
                f"on tool {tool_name!r} (possible command smuggling)"
            )

    # 3. Effect-attestation: observed effects must be subset of declared.
    undeclared = set(observed_effects) - declared_effects
    if undeclared:
        raise CapabilityConfusionError(
            f"tool {tool_name!r} performed undeclared effects {sorted(undeclared)}; "
            f"declared={sorted(declared_effects)} — description/effect divergence"
        )

    # 4. Post-call instruction smuggling: description must not condition future calls.
    import re as _re
    if _re.search(r"\b(if|when)\b.*\b(call|invoke|send|export)\b", description, _re.I):
        raise CapabilityConfusionError(
            f"tool {tool_name!r} description contains a conditional follow-up directive; "
            f"tool prose may not plan subsequent calls"
        )

    return True
