# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-list-mutation-as-a-capability-scope-revocation-event.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-list-mutation-as-a-capability-scope-revocation-event.warrant.json
# Markdown SHA-256:   4a180b5ecffdc3b43b0ca94a2b6f69f8577bad7aeb1655910cf140b38071a685
# Code AST SHA-256:   35837b0e2aa8998e341401e0bc74dab46e8213e0764936717218b99b9271f466
# Verified Classes:   ToolSurfaceMutationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ToolSurfaceMutationError(RuntimeError):
    """Raised when the advertised tool surface diverges from the grant-time snapshot
    in a way that changes the authorized tool set for a session."""
    pass


def enforce_surface_invariant(session, current_tools, grant_snapshot):
    """
    session: object with .scope_grants (set of scope strings) and .surface_digest
    current_tools: list of dicts with 'name' and 'scope' keys from tools/list
    grant_snapshot: dict mapping tool name -> scope at grant time
    """
    live = {t["name"]: t["scope"] for t in current_tools}

    added = set(live) - set(grant_snapshot)
    removed = set(grant_snapshot) - set(live)
    renamed_or_rescoped = {
        name for name in set(live) & set(grant_snapshot)
        if live[name] != grant_snapshot[name]
    }

    # A wildcard scope in the grant expands against the grant-time snapshot only.
    def authorized_under_grant(name, scope):
        return any(
            g == scope or (g.endswith(":*") and scope.startswith(g[:-1]))
            for g in session.scope_grants
        )

    # Any added tool that would be reachable under existing grants is a widening.
    widening = {n for n in added if authorized_under_grant(n, live[n])}

    if widening:
        raise ToolSurfaceMutationError(
            f"scope widening: tools {sorted(widening)} became reachable under "
            f"existing grants {sorted(session.scope_grants)} without re-authorization"
        )

    if removed or renamed_or_rescoped:
        raise ToolSurfaceMutationError(
            f"surface contract broken: removed={sorted(removed)} "
            f"rescoped={sorted(renamed_or_rescoped)}; session must re-authorize "
            f"against grant snapshot before further dispatch"
        )

    return True
