# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-registry-skill-injection-as-a-capability-widening-event-rather-than-a-benign-plugin-load.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-registry-skill-injection-as-a-capability-widening-event-rather-than-a-benign-plugin-load.warrant.json
# Markdown SHA-256:   244e1db5ec458b9197c05241e03679d95baa0efb75144b8cbf8eb636b8d11a74
# Code AST SHA-256:   d6ebc629e8c05eed41c33f07cbd9ec6d355213a29e0fc0aca473b7851f7cb5dc
# Verified Classes:   UndeclaredCapabilityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UndeclaredCapabilityError(RuntimeError):
    """Raised when a manifest's prose asserts a parameter or routing rule
    that the tool's signed schema does not declare."""
    pass


def admit_tool(manifest: dict, signed_schema: dict) -> dict:
    """
    Gate a dynamically discovered tool before it enters the selection context.
    Rejects any manifest whose prose names a parameter or enum value absent
    from the signed schema, because such prose can steer tool selection
    without schema validation.
    """
    declared_params = set(signed_schema.get("parameters", {}).keys())
    declared_enums = {
        v for spec in signed_schema.get("parameters", {}).values()
        for v in (spec.get("enum") or [])
    }
    prose = " ".join([
        manifest.get("description", ""),
        " ".join(manifest.get("examples", [])),
        " ".join(manifest.get("param_docs", {}).values()),
    ])

    # Extract candidate identifiers and quoted literals from prose.
    import re
    candidates = set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", prose))
    candidates |= set(re.findall(r'"([^"]+)"', prose))

    # Parameters named in prose but absent from schema = authority widening.
    undeclared = {
        c for c in candidates
        if c not in declared_params
        and c not in declared_enums
        and c not in {"the", "a", "an", "to", "for", "of", "and", "or",
                      "when", "with", "this", "that", "is", "be", "by"}
        and ("=" in prose or c.lower() in {"source", "mode", "scope", "role",
                                           "target", "action", "level"})
    }
    if undeclared:
        raise UndeclaredCapabilityError(
            f"manifest for {manifest.get('name')!r} asserts undeclared "
            f"capability tokens {sorted(undeclared)}; schema declares only "
            f"{sorted(declared_params)}. Refusing admission."
        )

    return {
        "name": manifest["name"],
        "schema": signed_schema,
        # Prose deliberately omitted from selection context.
    }
