# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-capability-negotiation-is-silently-degrading-to-a-lower-protocol-version-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-capability-negotiation-is-silently-degrading-to-a-lower-protocol-version-mid-session.warrant.json
# Markdown SHA-256:   85aa4e6465a00d6d9178332f1758cd7d1abab6ad53e246e7250c7e032120dacf
# Code AST SHA-256:   7eb4f90ab7c8088c442f34e7feb09f0821dd9371bf8c647a50fccda2d7ead86d
# Verified Classes:   CapabilityDowngradeError, Session
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDowngradeError(RuntimeError):
    """Raised when a session's negotiated version/capabilities do not
    support a feature the caller is about to use."""
    pass


SUPPORTED_VERSIONS = ["2024-11-05", "2025-03-26", "2025-06-18"]

# Features each version guarantees, independent of what the server advertises.
VERSION_FEATURES = {
    "2024-11-05": {"tools", "resources", "prompts"},
    "2025-03-26": {"tools", "resources", "prompts", "resources.subscribe"},
    "2025-06-18": {"tools", "resources", "prompts", "resources.subscribe",
                   "tools.structured_content", "sampling", "roots"},
}


class Session:
    def __init__(self, client_native_version, requested_caps):
        self.client_native_version = client_native_version
        self.requested_caps = set(requested_caps)
        self.protocol_version = None
        self.effective_caps = set()

    def negotiate(self, server_reply):
        """server_reply: {'protocolVersion': str, 'capabilities': {...}}"""
        offered = server_reply["protocolVersion"]
        if offered not in SUPPORTED_VERSIONS:
            raise CapabilityDowngradeError(
                f"server offered unsupported version {offered!r}"
            )
        # Accept only if we can re-gate. Compute the intersection NOW.
        self.protocol_version = offered
        version_caps = VERSION_FEATURES[offered]
        server_caps = set(server_reply.get("capabilities", {}).keys())
        self.effective_caps = (
            self.requested_caps & version_caps & server_caps
        )
        # If we were downgraded, native-only features must be dropped.
        dropped = self.requested_caps - self.effective_caps
        if offered != self.client_native_version and dropped:
            # Record the reduction; do NOT keep native gates alive.
            self._downgrade_dropped = dropped

    def require(self, feature):
        """Every request-shaping site MUST call this before shaping."""
        if self.protocol_version is None:
            raise CapabilityDowngradeError("require() before negotiation")
        if feature not in self.effective_caps:
            raise CapabilityDowngradeError(
                f"feature {feature!r} unavailable: negotiated "
                f"{self.protocol_version}, effective caps "
                f"{sorted(self.effective_caps)}"
            )


# Usage: a tool-call path that would have gated on a module constant.
def shape_tool_call(session, name, args):
    # WRONG in the failing client: gated on client_native_version.
    # RIGHT: gate on the per-session effective set.
    if "tools.structured_content" in session.requested_caps:
        session.require("tools.structured_content")  # raises on downgrade
    return {"name": name, "arguments": args}


if __name__ == "__main__":
    s = Session("2025-06-18", {"tools", "sampling", "tools.structured_content"})
    # Server downgrades and omits sampling + structured content.
    s.negotiate({"protocolVersion": "2024-11-05",
                 "capabilities": {"tools": {}, "resources": {}}})
    # This will raise instead of silently emitting a mis-shaped request:
    shape_tool_call(s, "search", {"q": "x"})
