# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-session-capability-envelope-when-an-http-native-mcp-server-multiplexes-tool-lists-across-keep-alive-connections.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-session-capability-envelope-when-an-http-native-mcp-server-multiplexes-tool-lists-across-keep-alive-connections.warrant.json
# Markdown SHA-256:   e478f8ffddaa3f82e94b1ed09eedfcfd4b1b14850b350b0ee8a69cf0bbd812d2
# Code AST SHA-256:   d6162d354d492c1abd090a9817ffe3d44bc0df29b7100ea3fcfc6ff63f64211a
# Verified Classes:   StaleCapabilityEnvelope, EnvelopeCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleCapabilityEnvelope(RuntimeError):
    """Raised when a tool invocation targets an envelope the client can no longer prove is current."""
    pass


class EnvelopeCache:
    def __init__(self, envelope_id: str, tools: dict[str, str]):
        self.envelope_id = envelope_id
        self.tools = tools  # name -> schema_version
        self.validated_at: float | None = None

    def invalidate(self) -> None:
        self.tools = {}
        self.envelope_id = ""
        self.validated_at = None


def invoke_tool(cache: EnvelopeCache, name: str, args: dict, now: float,
                staleness_bound_s: float = 60.0) -> dict:
    if not cache.envelope_id or cache.validated_at is None:
        raise StaleCapabilityEnvelope(
            f"no validated envelope; refusing tools/call {name!r}"
        )
    if now - cache.validated_at > staleness_bound_s:
        raise StaleCapabilityEnvelope(
            f"envelope {cache.envelope_id!r} stale by {now - cache.validated_at:.1f}s; "
            f"must revalidate tools/list before invoking {name!r}"
        )
    if name not in cache.tools:
        raise StaleCapabilityEnvelope(
            f"tool {name!r} absent from current envelope {cache.envelope_id!r}; "
            f"do not retry, renegotiate"
        )
    # server must echo envelope_id; a mismatch means the session was rebuilt
    response = _rpc(cache, "tools/call", {"name": name, "arguments": args})
    if response.get("envelope_id") != cache.envelope_id:
        cache.invalidate()
        raise StaleCapabilityEnvelope(
            f"server executed {name!r} under envelope {response.get('envelope_id')!r}, "
            f"client held {cache.envelope_id!r}; cache invalidated, re-list required"
        )
    return response


def _rpc(cache: EnvelopeCache, method: str, params: dict) -> dict:
    # transport stub; real implementation issues the HTTP request
    return {"result": {}, "envelope_id": cache.envelope_id}
