# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-capability-descriptions-as-executable-attack-surface-rather-than-inert-documentation-in-mcp-manifest-ingestion.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-capability-descriptions-as-executable-attack-surface-rather-than-inert-documentation-in-mcp-manifest-ingestion.warrant.json
# Markdown SHA-256:   6922695c98113d1ea2a3871773d33de17200e584e7eee0757b1e5b777af1d86f
# Code AST SHA-256:   b34935cc41d03c957a9b737e78ede9f7ed46218d113279f129fc1899c5fc2961
# Verified Classes:   DescriptionTaintViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DescriptionTaintViolation(RuntimeError):
    """Raised when a tool-call parameter is populated from working-memory
    state while the tool's description carries unverified imperative text."""
    pass


IMPERATIVE_MARKERS = (
    "always", "before calling", "first send", "include the",
    "forward the", "must pass", "prepend", "append the",
)


def is_description_tainted(description: str) -> bool:
    lowered = description.lower()
    return any(marker in lowered for marker in IMPERATIVE_MARKERS)


def synthesize_call(tool, args, working_memory):
    """Build a tool call, enforcing parameter provenance.

    args: {param_name: ("literal" | "memory", value_or_key)}
    """
    tainted = is_description_tainted(tool.description)
    resolved = {}
    for param, (source, ref) in args.items():
        if source == "memory":
            if tainted:
                raise DescriptionTaintViolation(
                    f"tool '{tool.name}' has imperative-laden description; "
                    f"parameter '{param}' may not be populated from working "
                    f"memory (ref={ref!r}). Attest the description or pass a "
                    f"literal value."
                )
            resolved[param] = working_memory[ref]
        else:
            resolved[param] = ref

    # Free-form parameters are exfil channels: forbid memory-sourced values
    # even when the description looks clean, unless explicitly attested.
    for param, value in resolved.items():
        spec = tool.parameters.get(param, {})
        if spec.get("type") in ("string", "object") and not spec.get("enum"):
            if args[param][0] == "memory" and not tool.attested_freeform.get(param):
                raise DescriptionTaintViolation(
                    f"free-form parameter '{param}' on '{tool.name}' received "
                    f"memory-sourced value without attestation; refusing call."
                )
    return {"tool": tool.name, "arguments": resolved}
