# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-description-field-as-a-capability-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-description-field-as-a-capability-contract.warrant.json
# Markdown SHA-256:   76069e025bdab28c39f41241788f09ed30edb4842051bb44147a07f9ef1a78c0
# Code AST SHA-256:   3d5fb7ebd3d77ad5721542c399bd3d597ea45c3cee9db544ebdcb5c1dc035c8c
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest attempts to direct agent behavior
    beyond its own invocation contract."""
    pass


IMPERATIVE_MARKERS = (
    "you must", "before using any other tool", "always call",
    "required preprocessing", "first call", "do not use",
)
CROSS_TOOL_REFS = ("any other tool", "the user's request", "all prior context",
                   "any file paths", "full contents of")


def vet_manifest(manifest: dict) -> dict:
    """Validate a registry/MCP tool manifest before injection into context.

    Returns the manifest with a provenance tag if it is declaratively scoped
    to its own inputs. Raises ManifestInjectionError otherwise.
    """
    name = manifest.get("name", "<unnamed>")
    desc = (manifest.get("description") or "").lower()

    for marker in IMPERATIVE_MARKERS:
        if marker in desc:
            raise ManifestInjectionError(
                f"tool '{name}': imperative directive in description "
                f"({marker!r}); manifest attempts to steer agent behavior"
            )

    for ref in CROSS_TOOL_REFS:
        if ref in desc:
            raise ManifestInjectionError(
                f"tool '{name}': description references cross-tool context "
                f"({ref!r}); potential exfiltration priming"
            )

    schema = manifest.get("inputSchema") or {}
    if not schema.get("properties"):
        raise ManifestInjectionError(
            f"tool '{name}': no typed input properties; capability is "
            f"unconstrained and cannot be argument-taint-checked"
        )

    return {**manifest, "_provenance": "untrusted_registry", "_vet": "passed"}


def select_and_invoke(manifest: dict, user_request: str, prior_outputs: dict):
    vetted = vet_manifest(manifest)
    # Selection uses tool ID only; description is never injected as instruction.
    tool_id = vetted["name"]
    args = build_args_from_request(vetted["inputSchema"], user_request)
    for key, value in args.items():
        for src, blob in prior_outputs.items():
            if isinstance(value, str) and blob and blob in value:
                raise ManifestInjectionError(
                    f"tool '{tool_id}': argument '{key}' carries data from "
                    f"prior tool '{src}'; cross-tool taint rejected"
                )
    return dispatch(tool_id, args)
