# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-tool-server-silently-retain-filesystem-authority-after-its-declared-capability-scope-is-revoked-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-mcp-tool-server-silently-retain-filesystem-authority-after-its-declared-capability-scope-is-revoked-mid-session.warrant.json
# Markdown SHA-256:   c60329cbcea139bde915cbef349d5ccb2e6e1bb218f235cda35d405c538498ff
# Code AST SHA-256:   7806a06492300c1094ad401adf33103a3203cacc6541093e97c3dd1336c5996f
# Verified Classes:   ScopeDivergenceError, Scope, ScopedHandle, ScopedToolServer
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import threading
from dataclasses import dataclass, field
from typing import Optional


class ScopeDivergenceError(RuntimeError):
    """Raised when an in-flight handle outlives the scope that authorized it."""
    pass


@dataclass(frozen=True)
class Scope:
    tools: frozenset
    roots: tuple
    epoch: int  # monotonic counter, bumped on every revocation


@dataclass
class ScopedHandle:
    path: str
    authorizing_epoch: int
    fd: int
    _open: bool = field(default=True)


class ScopedToolServer:
    def __init__(self, scope: Scope):
        self._scope = scope
        self._lock = threading.Lock()
        self._handles: dict[str, ScopedHandle] = {}

    def _live_scope(self) -> Scope:
        with self._lock:
            return self._scope

    def revoke(self, new_scope: Scope) -> None:
        with self._lock:
            # bump epoch so every pre-existing handle is provably stale
            self._scope = Scope(
                tools=new_scope.tools,
                roots=new_scope.roots,
                epoch=self._scope.epoch + 1,
            )

    def open_for_read(self, path: str) -> ScopedHandle:
        scope = self._live_scope()
        if "read_file" not in scope.tools:
            raise ScopeDivergenceError(f"read_file not in scope epoch {scope.epoch}")
        if not any(path.startswith(r) for r in scope.roots):
            raise ScopeDivergenceError(f"{path} outside roots {scope.roots}")
        h = ScopedHandle(path=path, authorizing_epoch=scope.epoch, fd=hash(path))
        self._handles[path] = h
        return h

    def read(self, h: ScopedHandle, n: int) -> bytes:
        # The critical invariant: re-validate at use, not just at open.
        scope = self._live_scope()
        if not h._open:
            raise ScopeDivergenceError("handle closed")
        if h.authorizing_epoch != scope.epoch:
            raise ScopeDivergenceError(
                f"handle authorized under epoch {h.authorizing_epoch}, "
                f"live scope is epoch {scope.epoch}; aborting read of {h.path}"
            )
        if "read_file" not in scope.tools:
            raise ScopeDivergenceError(f"read_file revoked at epoch {scope.epoch}")
        if not any(h.path.startswith(r) for r in scope.roots):
            raise ScopeDivergenceError(
                f"{h.path} no longer under live roots {scope.roots}"
            )
        return b"x" * n


def demonstrate_divergence() -> None:
    server = ScopedToolServer(
        Scope(tools=frozenset({"read_file", "write_file"}),
              roots=("/work/project",), epoch=0)
    )
    h = server.open_for_read("/work/project/a.txt")  # warm phase, epoch 0
    server.revoke(
        Scope(tools=frozenset({"read_file"}),
              roots=("/work/project/readonly",), epoch=0)
    )
    # Naive server would return data here. Correct server must raise.
    server.read(h, 16)  # -> ScopeDivergenceError, epoch 0 != 1


if __name__ == "__main__":
    try:
        demonstrate_divergence()
    except ScopeDivergenceError as e:
        print(f"boundary enforced: {e}")
