"""Standalone Streamable HTTP MCP Events (SEP-3415) playground server. Provides a SEP-3415 MCP server with poll and push delivery and isolated per-room endpoints at ``/r//mcp`` (plus a ``/mcp`` public fallback) alongside a browser control plane for triggering events, testing truncated gaps, subscription revocations, ``maxAgeMs``, ``maxEvents``, and ``--resume``. Run locally: uv run examples/mcp/events/playground/app.py --port 8765 Deploy to Hugging Face Spaces (Docker Space, port 7860): Upload the contents of this directory to a Docker Space repository. """ from __future__ import annotations import argparse import asyncio import contextlib import contextvars import json import os import re import secrets import time from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from pathlib import Path from typing import TYPE_CHECKING, Any, Literal import uvicorn from mcp.server.extension import Extension, MethodBinding from mcp.server.mcpserver import MCPServer from mcp.server.transport_security import TransportSecuritySettings from mcp.shared.exceptions import MCPError from mcp.shared.subscriptions import SUBSCRIPTION_ID_META_KEY from mcp_types import ( INVALID_PARAMS, ErrorData, Notification, PaginatedRequestParams, PaginatedResult, RequestParams, Result, ) from pydantic import BaseModel, ConfigDict, Field from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import ( FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse, ) from starlette.routing import Route if TYPE_CHECKING: from collections.abc import AsyncIterator from mcp.server.context import ServerRequestContext from starlette.types import ASGIApp, Receive, Scope, Send # --------------------------------------------------------------------------- # SEP-3415 wire models (inlined so this server has zero fast-agent dependency) # --------------------------------------------------------------------------- EVENTS_EXTENSION = "io.modelcontextprotocol/events" EVENTS_NOT_FOUND = -32023 EVENTS_FORBIDDEN = -32024 EVENTS_UNSUPPORTED = -32026 class EventDescriptor(BaseModel): model_config = ConfigDict(populate_by_name=True) name: str description: str | None = None delivery: list[str] input_schema: dict[str, Any] | None = Field(default=None, alias="inputSchema") payload_schema: dict[str, Any] | None = Field(default=None, alias="payloadSchema") meta: dict[str, Any] | None = Field(default=None, alias="_meta") class EventOccurrence(BaseModel): model_config = ConfigDict(populate_by_name=True) event_id: str = Field(alias="eventId") name: str timestamp: str data: dict[str, Any] cursor: str | None = None meta: dict[str, Any] | None = Field(default=None, alias="_meta") class ListEventsResult(PaginatedResult): events: list[EventDescriptor] result_type: Literal["complete"] = Field(default="complete", alias="resultType") class PollEventsRequestParams(RequestParams): name: str arguments: dict[str, Any] = Field(default_factory=dict) cursor: str | None = None max_age_ms: int | None = Field(default=None, alias="maxAgeMs") max_events: int | None = Field(default=None, alias="maxEvents") class PollEventsResult(Result): events: list[EventOccurrence] = Field(default_factory=list) cursor: str | None = None truncated: bool = False has_more: bool = Field(default=False, alias="hasMore") next_poll_ms: int | None = Field(default=None, alias="nextPollMs") result_type: Literal["complete"] = Field(default="complete", alias="resultType") class StreamEventsRequestParams(RequestParams): name: str arguments: dict[str, Any] = Field(default_factory=dict) cursor: str | None = None max_age_ms: int | None = Field(default=None, alias="maxAgeMs") heartbeat_ms: int | None = Field(default=None, alias="heartbeatMs") class StreamEventsResult(Result): result_type: Literal["complete"] = Field(default="complete", alias="resultType") class EventStreamActive(BaseModel): model_config = ConfigDict(populate_by_name=True) cursor: str | None = None truncated: bool = False heartbeat_ms: int = Field(alias="heartbeatMs") class EventStreamHeartbeat(BaseModel): cursor: str | None = None class EventStreamTerminated(BaseModel): error: ErrorData # --------------------------------------------------------------------------- # Per-room in-memory playground state # --------------------------------------------------------------------------- MAX_STREAM_HISTORY = 500 MAX_POLL_LOG = 200 MAX_RECENT_EVENTS = 100 ROOM_ACTIVITY_LIMIT = 10 DEFAULT_HEARTBEAT_MS = 5_000 MAX_HEARTBEAT_MS = 30_000 ROOM_TTL_SECONDS = 4 * 3600 MAX_ROOMS = 500 PUBLIC_ROOM_ID = "public" ROOM_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{2,31}$") ROOM_MCP_PATH_RE = re.compile(r"^/r/([^/]+)/mcp/?$") _ROOM_ADJECTIVES = ( "amber", "cobalt", "crisp", "delta", "echo", "glass", "linen", "lunar", "matte", "prism", "quartz", "signal", "silver", "slate", "solar", "vector", ) _ROOM_NOUNS = ( "beacon", "bridge", "bus", "clock", "dial", "gate", "latch", "meter", "node", "pulse", "relay", "scope", "switch", "trace", "valve", "wave", ) @dataclass(frozen=True) class StoredEvent: event_id: str stream_seq: int name: str filter_key: str timestamp: datetime data: dict[str, Any] def to_occurrence(self, *, include_cursor: bool = False) -> EventOccurrence: return EventOccurrence( event_id=self.event_id, name=self.name, timestamp=self.timestamp.isoformat(), data=self.data, cursor=str(self.stream_seq) if include_cursor else None, ) def to_dict(self) -> dict[str, Any]: return { "event_id": self.event_id, "name": self.name, "filter_key": self.filter_key, "timestamp": self.timestamp.isoformat(), "data": self.data, } @dataclass class PlaygroundState: room_id: str = PUBLIC_ROOM_ID push_enabled: bool = True poll_enabled: bool = True poll_interval_ms: int = field( default_factory=lambda: max(250, int(os.environ.get("POLL_INTERVAL_MS", "2000"))) ) heartbeat_ms: int = field( default_factory=lambda: max( 1_000, min(int(os.environ.get("HEARTBEAT_MS", str(DEFAULT_HEARTBEAT_MS))), MAX_HEARTBEAT_MS), ) ) streams: dict[tuple[str, str], list[StoredEvent]] = field(default_factory=dict) stream_totals: dict[tuple[str, str], int] = field(default_factory=dict) pending_gaps: set[tuple[str, str]] = field(default_factory=set) forbidden_keys: set[tuple[str, str]] = field(default_factory=set) poll_log: list[dict[str, Any]] = field(default_factory=list) delivery_log: list[dict[str, Any]] = field(default_factory=list) recent_events: list[dict[str, Any]] = field(default_factory=list) last_polled: dict[tuple[str, str], float] = field(default_factory=dict) active_pollers: dict[tuple[str, str, str], dict[str, Any]] = field(default_factory=dict) open_streams: dict[int, dict[str, Any]] = field(default_factory=dict) push_stream_count: int = 0 push_delivered_count: int = 0 poll_count: int = 0 poll_delivered_count: int = 0 emitted_count: int = 0 delivery_seq: int = 0 event_seq: int = 0 last_touched: float = field(default_factory=time.monotonic) subscribers: set[asyncio.Queue[dict[str, Any]]] = field(default_factory=set) # Set and replaced on every state change, so waiting push streams in this room wake up. changed: asyncio.Event = field(default_factory=asyncio.Event) def touch(self) -> None: self.last_touched = time.monotonic() def notify_browser(self, payload: dict[str, Any]) -> None: for queue in list(self.subscribers): if queue.full(): with contextlib.suppress(asyncio.QueueEmpty): queue.get_nowait() with contextlib.suppress(asyncio.QueueFull): queue.put_nowait(payload) def wake_streams(self) -> None: self.changed.set() self.changed = asyncio.Event() def notify(self, payload: dict[str, Any]) -> None: self.notify_browser(payload) self.wake_streams() def arm_gap(self, key: tuple[str, str]) -> None: self.touch() # Arm both the next-poll one-shot marker and every matching currently open push stream. self.pending_gaps.add(key) target = f"{key[0]}:{key[1]}" for info in self.open_streams.values(): if info.get("key") == target: info["pending_gap"] = True self.notify({"kind": "fault", "channel": "control", "reason": "gap_armed", "name": key[0]}) def _poll_active_cutoff(self) -> float: window = max((self.poll_interval_ms * 4) / 1000.0, 20.0) return time.monotonic() - window def active_streams(self) -> list[str]: cutoff = self._poll_active_cutoff() active: list[str] = [] seen: set[str] = set() for info in self.open_streams.values(): key_str = str(info.get("key", "")) if key_str and key_str not in seen: seen.add(key_str) active.append(key_str) for k, ts in sorted(self.last_polled.items(), key=lambda item: item[1], reverse=True): if ts >= cutoff: key_str = f"{k[0]}:{k[1]}" if key_str not in seen: seen.add(key_str) active.append(key_str) return active def active_polls(self) -> list[dict[str, Any]]: cutoff = self._poll_active_cutoff() now_mono = time.monotonic() stale_keys = [ poller_key for poller_key, info in self.active_pollers.items() if float(info.get("last_polled_mono", 0.0)) < cutoff ] for poller_key in stale_keys: self.active_pollers.pop(poller_key, None) ordered = sorted( self.active_pollers.values(), key=lambda item: float(item.get("last_polled_mono", 0.0)), reverse=True, ) return [ { **{k: v for k, v in info.items() if k != "last_polled_mono"}, "idle_seconds": round( max(0.0, now_mono - float(info.get("last_polled_mono", 0.0))), 1 ), } for info in ordered ] def emit(self, event_name: str, filter_key: str, data: dict[str, Any]) -> StoredEvent: self.touch() key = (event_name, filter_key) self.event_seq += 1 self.emitted_count += 1 stream_seq = self.stream_totals.get(key, 0) + 1 self.stream_totals[key] = stream_seq record = StoredEvent( event_id=f"ev-{self.event_seq}", stream_seq=stream_seq, name=event_name, filter_key=filter_key, timestamp=datetime.now(UTC), data=data, ) bucket = self.streams.setdefault(key, []) bucket.append(record) if len(bucket) > MAX_STREAM_HISTORY: del bucket[:-MAX_STREAM_HISTORY] self.recent_events.append(record.to_dict()) if len(self.recent_events) > MAX_RECENT_EVENTS: del self.recent_events[:-MAX_RECENT_EVENTS] self.notify( { "kind": "emit", "event_id": record.event_id, "name": event_name, "filter_key": filter_key, } ) return record def record_delivery(self, entry: dict[str, Any]) -> None: self.delivery_seq += 1 is_idle_poll = ( entry.get("mode") == "poll" and entry.get("returned", 0) == 0 and not entry.get("truncated") and not entry.get("has_more") and not entry.get("error") ) if is_idle_poll and self.delivery_log: last = self.delivery_log[-1] if ( last.get("mode") == "poll" and last.get("returned", 0) == 0 and not last.get("truncated") and not last.get("has_more") and not last.get("error") and last.get("client") == entry.get("client") and last.get("name") == entry.get("name") and last.get("arguments") == entry.get("arguments") and last.get("cursor_out") == entry.get("cursor_out") ): last["at"] = entry.get("at") last["cursor_in"] = entry.get("cursor_in") last["polls"] = int(last.get("polls", 1)) + 1 return self.delivery_log.append(entry) if len(self.delivery_log) > MAX_POLL_LOG: del self.delivery_log[:-MAX_POLL_LOG] def reset(self) -> None: # Keep stream_totals and event_seq monotonic so connected clients see # truncated=True and fresh event IDs instead of silently skipping events. self.touch() self.streams.clear() self.pending_gaps.clear() self.forbidden_keys.clear() self.poll_log.clear() self.delivery_log.clear() self.active_pollers.clear() self.push_delivered_count = 0 self.poll_count = 0 self.poll_delivered_count = 0 self.emitted_count = 0 self.delivery_seq = 0 self.recent_events.clear() self.last_polled.clear() self.notify({"kind": "state"}) class RoomRegistry: def __init__(self) -> None: self._rooms: dict[str, PlaygroundState] = { PUBLIC_ROOM_ID: PlaygroundState(room_id=PUBLIC_ROOM_ID) } def new_room_id(self) -> str: for _ in range(16): candidate = ( f"{secrets.choice(_ROOM_ADJECTIVES)}-" f"{secrets.choice(_ROOM_NOUNS)}-" f"{secrets.randbelow(90) + 10}" ) if candidate not in self._rooms: return candidate return f"room-{secrets.token_hex(4)}" def validate_room_id(self, room_id: str) -> str | None: cleaned = room_id.strip().lower() if ROOM_ID_RE.match(cleaned): return cleaned return None def get_or_create(self, room_id: str) -> PlaygroundState: self._prune() room = self._rooms.get(room_id) if room is None: room = PlaygroundState(room_id=room_id) self._rooms[room_id] = room else: room.touch() return room def _prune(self) -> None: now = time.monotonic() expired = [ rid for rid, room in self._rooms.items() if rid != PUBLIC_ROOM_ID and (now - room.last_touched) > ROOM_TTL_SECONDS ] for rid in expired: self._rooms.pop(rid, None) if len(self._rooms) > MAX_ROOMS: evictable = sorted( ( (bool(room.open_streams or room.subscribers), room.last_touched, rid) for rid, room in self._rooms.items() if rid != PUBLIC_ROOM_ID ), key=lambda item: (item[0], item[1]), ) overflow = len(self._rooms) - MAX_ROOMS for _, _, rid in evictable[:overflow]: self._rooms.pop(rid, None) registry = RoomRegistry() current_room_var: contextvars.ContextVar[PlaygroundState | None] = contextvars.ContextVar( "current_room", default=None ) def get_state() -> PlaygroundState: room = current_room_var.get() if room is not None: return room return registry.get_or_create(PUBLIC_ROOM_ID) def _resolve_stream_key( name: str, arguments: dict[str, Any], delivery: Literal["poll", "push"] ) -> tuple[str, str]: if name == "job.status_changed": job_id = arguments.get("job_id") if not isinstance(job_id, str) or not job_id.strip(): raise MCPError(INVALID_PARAMS, "job_id is required") return ("job.status_changed", job_id.strip()) if name == "system.pulse": return ("system.pulse", "*") if name == "webhook.only_alert": raise MCPError( EVENTS_UNSUPPORTED, f"Event {name!r} does not support {delivery} delivery", {"feature": "deliveryMode", "value": delivery}, ) raise MCPError(EVENTS_NOT_FOUND, "NotFound", {"kind": "event"}) # --------------------------------------------------------------------------- # SEP-3415 extension handlers # --------------------------------------------------------------------------- def _extract_client_identity(ctx: ServerRequestContext[Any, Any]) -> dict[str, str | None]: client_params = ctx.session.client_params client_info = client_params.client_info if client_params is not None else None client_name = client_info.name.strip() if client_info and client_info.name else None client_version = client_info.version.strip() if client_info and client_info.version else None http_req = ctx.request if isinstance(ctx.request, Request) else None user_agent = http_req.headers.get("user-agent") if http_req is not None else None if client_name: client_display = ( f"{client_name} {client_version}".strip() if client_version else client_name ) elif user_agent: client_display = user_agent.split()[0][:40] else: client_display = "mcp-client" return { "client": client_display, "client_name": client_name, "client_version": client_version, } async def list_events( ctx: ServerRequestContext[Any, Any], params: PaginatedRequestParams ) -> ListEventsResult: del ctx, params state = get_state() state.touch() modes: list[str] = [] if state.poll_enabled: modes.append("poll") if state.push_enabled: modes.append("push") return ListEventsResult( events=[ EventDescriptor( name="job.status_changed", description=( "Fires when a job transitions between stages (queued, running, done, failed)." ), delivery=modes, input_schema={ "type": "object", "properties": { "job_id": {"type": "string", "description": "Target job identifier"} }, "required": ["job_id"], }, payload_schema={ "type": "object", "properties": { "job_id": {"type": "string"}, "stage": {"type": "string"}, "detail": {"type": "string"}, }, }, ), EventDescriptor( name="system.pulse", description="Server pulse event with no required arguments.", delivery=modes, input_schema={"type": "object", "properties": {}}, payload_schema={ "type": "object", "properties": { "seq": {"type": "integer"}, "note": {"type": "string"}, }, }, ), EventDescriptor( name="webhook.only_alert", description="Webhook-only alert (not pollable; useful for testing client UI).", delivery=["webhook"], input_schema={"type": "object", "properties": {}}, ), ] ) async def poll_events( ctx: ServerRequestContext[Any, Any], params: PollEventsRequestParams ) -> PollEventsResult: state = get_state() state.touch() key = _resolve_stream_key(params.name, params.arguments, "poll") identity = _extract_client_identity(ctx) client_display = identity["client"] or "mcp-client" if not state.poll_enabled: poller_key = (client_display, params.name, key[1]) state.active_pollers.pop(poller_key, None) state.record_delivery( { "mode": "poll", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "client_name": identity["client_name"], "client_version": identity["client_version"], "cursor_in": params.cursor, "cursor_out": params.cursor, "returned": 0, "truncated": False, "has_more": False, "error": "-32026 Poll delivery disabled", } ) state.notify_browser( { "kind": "fault", "channel": "poll", "reason": "poll_disabled", "name": params.name, "client": client_display, } ) raise MCPError( EVENTS_UNSUPPORTED, "Poll delivery is disabled in this room", {"feature": "deliveryMode", "value": "poll"}, ) if key in state.forbidden_keys: poller_key = (client_display, params.name, key[1]) state.active_pollers.pop(poller_key, None) state.record_delivery( { "mode": "poll", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "client_name": identity["client_name"], "client_version": identity["client_version"], "cursor_in": params.cursor, "cursor_out": params.cursor, "returned": 0, "truncated": False, "has_more": False, "error": "-32024 Forbidden (subscription revoked)", } ) state.notify_browser( { "kind": "fault", "channel": "poll", "reason": "forbidden", "name": params.name, "client": client_display, } ) raise MCPError(EVENTS_FORBIDDEN, "Subscription revoked by server") now_mono = time.monotonic() state.last_polled[key] = now_mono history = state.streams.get(key, []) total = state.stream_totals.get(key, 0) # Sequence number of the last evicted event (0 when nothing has been trimmed). evicted_through = total - len(history) truncated = False if params.cursor is None: start = len(history) else: try: cursor_seq = int(params.cursor) except ValueError as exc: raise MCPError(INVALID_PARAMS, f"Invalid cursor: {params.cursor!r}") from exc if cursor_seq < 0: raise MCPError(INVALID_PARAMS, f"Invalid cursor: {params.cursor!r}") if cursor_seq < evicted_through or cursor_seq > total: truncated = True start = 0 else: start = cursor_seq - evicted_through if key in state.pending_gaps and params.cursor is not None: state.pending_gaps.discard(key) truncated = True sliced = history[start:] if params.max_age_ms is not None and params.max_age_ms >= 0: cutoff = datetime.now(UTC) - timedelta(milliseconds=params.max_age_ms) filtered = [ev for ev in sliced if ev.timestamp >= cutoff] if len(filtered) < len(sliced): truncated = True sliced = filtered has_more = False next_cursor_seq = total if params.max_events is not None and params.max_events > 0 and len(sliced) > params.max_events: sliced = sliced[: params.max_events] has_more = True next_cursor_seq = sliced[-1].stream_seq result = PollEventsResult( events=[ev.to_occurrence() for ev in sliced], cursor=str(next_cursor_seq), truncated=truncated, has_more=has_more, next_poll_ms=state.poll_interval_ms, ) now_iso = datetime.now(UTC).isoformat() returned_count = len(result.events) state.poll_count += 1 state.poll_delivered_count += returned_count poller_key = (client_display, params.name, key[1]) poller_info = state.active_pollers.get(poller_key) if poller_info is None: poller_info = { "client": client_display, "client_name": identity["client_name"], "client_version": identity["client_version"], "key": f"{key[0]}:{key[1]}", "name": params.name, "filter_key": key[1], "arguments": dict(params.arguments), "cursor": result.cursor, "polls": 1, "delivered": returned_count, "last_polled_at": now_iso, "last_polled_mono": now_mono, } state.active_pollers[poller_key] = poller_info else: poller_info["cursor"] = result.cursor poller_info["polls"] = int(poller_info.get("polls", 0)) + 1 poller_info["delivered"] = int(poller_info.get("delivered", 0)) + returned_count poller_info["last_polled_at"] = now_iso poller_info["last_polled_mono"] = now_mono poll_entry = { "at": now_iso, "name": params.name, "arguments": dict(params.arguments), "client": client_display, "client_name": identity["client_name"], "client_version": identity["client_version"], "cursor_in": params.cursor, "cursor_out": result.cursor, "returned": returned_count, "truncated": truncated, "has_more": has_more, } state.poll_log.append(poll_entry) if len(state.poll_log) > MAX_POLL_LOG: del state.poll_log[:-MAX_POLL_LOG] state.record_delivery({"mode": "poll", **poll_entry}) state.notify_browser( { "kind": "fault" if truncated else "poll", "channel": "poll", "client": client_display, "name": params.name, "filter_key": key[1], "returned": returned_count, "truncated": truncated, "cursor": result.cursor, } ) return result def _events_after( state: PlaygroundState, key: tuple[str, str], position: int ) -> tuple[list[StoredEvent], int, bool]: """Return the events after ``position``, the position they follow, and whether any were lost.""" history = state.streams.get(key, []) total = state.stream_totals.get(key, 0) evicted_through = total - len(history) if position < evicted_through or position > total: return list(history), evicted_through, True return [ev for ev in history if ev.stream_seq > position], position, False async def stream_events( ctx: ServerRequestContext[Any, Any], params: StreamEventsRequestParams ) -> StreamEventsResult: state = get_state() state.touch() key = _resolve_stream_key(params.name, params.arguments, "push") identity = _extract_client_identity(ctx) client_display = identity["client"] or "mcp-client" if not state.push_enabled: state.record_delivery( { "mode": "stream", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "cursor_in": params.cursor, "cursor_out": params.cursor, "returned": 0, "truncated": False, "has_more": False, "error": "-32026 Push delivery disabled", } ) state.notify_browser( { "kind": "fault", "channel": "push", "reason": "push_disabled", "name": params.name, "client": client_display, } ) raise MCPError( EVENTS_UNSUPPORTED, "Push delivery is disabled in this room", {"feature": "deliveryMode", "value": "push"}, ) if key in state.forbidden_keys: state.record_delivery( { "mode": "stream", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "cursor_in": params.cursor, "cursor_out": params.cursor, "returned": 0, "truncated": False, "has_more": False, "error": "-32024 Forbidden (subscription revoked)", } ) state.notify_browser( { "kind": "fault", "channel": "push", "reason": "forbidden", "name": params.name, "client": client_display, } ) raise MCPError(EVENTS_FORBIDDEN, "Subscription revoked by server") client_heartbeat_ms = ( max(1_000, min(params.heartbeat_ms, MAX_HEARTBEAT_MS)) if params.heartbeat_ms is not None else None ) heartbeat_ms = client_heartbeat_ms if client_heartbeat_ms is not None else state.heartbeat_ms heartbeat_s = heartbeat_ms / 1000.0 meta = {SUBSCRIPTION_ID_META_KEY: ctx.request_id} loop = asyncio.get_running_loop() last_sent = loop.time() async def send(kind: str, frame: BaseModel) -> None: nonlocal last_sent notification = Notification[dict[str, Any], str]( method=f"notifications/events/{kind}", params=frame.model_dump(by_alias=True, exclude_none=True) | {"_meta": meta}, ) await ctx.session.send_notification(notification, related_request_id=ctx.request_id) last_sent = loop.time() # Take the wake-up event before reading, so an emit or gap during send is not missed. changed = state.changed if params.cursor is None: events, position, truncated = [], state.stream_totals.get(key, 0), False else: try: cursor_seq = int(params.cursor) except ValueError as exc: raise MCPError(INVALID_PARAMS, f"Invalid cursor: {params.cursor!r}") from exc if cursor_seq < 0: raise MCPError(INVALID_PARAMS, f"Invalid cursor: {params.cursor!r}") events, position, truncated = _events_after(state, key, cursor_seq) if params.max_age_ms is not None and params.max_age_ms >= 0: cutoff = datetime.now(UTC) - timedelta(milliseconds=params.max_age_ms) recent = [ev for ev in events if ev.timestamp >= cutoff] if len(recent) < len(events): truncated = True position = recent[0].stream_seq - 1 if recent else events[-1].stream_seq events = recent opened_at = datetime.now(UTC).isoformat() state.push_stream_count += 1 stream_id = state.push_stream_count info: dict[str, Any] = { "stream": stream_id, "client": client_display, "client_name": identity["client_name"], "client_version": identity["client_version"], "key": f"{key[0]}:{key[1]}", "name": params.name, "arguments": dict(params.arguments), "opened_at": opened_at, "cursor": str(position), "heartbeat_ms": heartbeat_ms, "delivered": 0, "pending_gap": False, "close_reason": None, } state.open_streams[stream_id] = info state.record_delivery( { "mode": "stream", "at": opened_at, "name": params.name, "arguments": dict(params.arguments), "client": client_display, "cursor_in": params.cursor, "cursor_out": str(position), "returned": 0, "truncated": truncated, "has_more": False, "note": "opened events/stream", } ) state.notify_browser( { "kind": "stream_open", "channel": "push", "stream": stream_id, "client": client_display, "name": params.name, "filter_key": key[1], "cursor": str(position), } ) close_note = "closed events/stream" try: await send( "active", EventStreamActive(cursor=str(position), truncated=truncated, heartbeat_ms=heartbeat_ms), ) # The stream runs until the client closes it, push is disabled/dropped, or revoked. while True: if info["close_reason"] is not None or not state.push_enabled: close_note = info["close_reason"] or "closed events/stream (push disabled)" return StreamEventsResult.model_validate({"_meta": meta}) cursor_before = str(position) delivered_now = 0 for ev in events: await send("event", ev.to_occurrence(include_cursor=True)) position = ev.stream_seq info["delivered"] += 1 delivered_now += 1 info["cursor"] = str(position) if delivered_now: state.touch() state.push_delivered_count += delivered_now state.record_delivery( { "mode": "push", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "cursor_in": cursor_before, "cursor_out": str(position), "returned": delivered_now, "truncated": truncated, "has_more": False, } ) state.notify_browser( { "kind": "push", "stream": stream_id, "client": client_display, "name": params.name, "filter_key": key[1], "returned": delivered_now, "truncated": truncated, "cursor": str(position), } ) remaining = max(0.0, (last_sent + heartbeat_s) - loop.time()) try: async with asyncio.timeout(remaining): await changed.wait() except TimeoutError: state.touch() await send("heartbeat", EventStreamHeartbeat(cursor=str(position))) state.notify_browser( { "kind": "heartbeat", "stream": stream_id, "client": client_display, "name": params.name, "cursor": str(position), } ) if info["close_reason"] is not None or not state.push_enabled: close_note = info["close_reason"] or "closed events/stream (push disabled)" return StreamEventsResult.model_validate({"_meta": meta}) if key in state.forbidden_keys: close_note = "terminated events/stream (forbidden)" state.notify_browser( { "kind": "fault", "channel": "push", "reason": "forbidden", "name": params.name, } ) error = ErrorData(code=EVENTS_FORBIDDEN, message="Subscription revoked by server") await send("terminated", EventStreamTerminated(error=error)) return StreamEventsResult.model_validate({"_meta": meta}) heartbeat_changed = False if client_heartbeat_ms is None and state.heartbeat_ms != heartbeat_ms: heartbeat_ms = state.heartbeat_ms heartbeat_s = heartbeat_ms / 1000.0 info["heartbeat_ms"] = heartbeat_ms heartbeat_changed = True changed = state.changed events, position, truncated = _events_after(state, key, position) if info["pending_gap"]: info["pending_gap"] = False truncated = True if truncated: state.notify_browser( { "kind": "fault", "channel": "push", "name": params.name, "filter_key": key[1], "truncated": True, } ) active = EventStreamActive( cursor=str(position), truncated=True, heartbeat_ms=heartbeat_ms ) await send("active", active) elif heartbeat_changed: active = EventStreamActive( cursor=str(position), truncated=False, heartbeat_ms=heartbeat_ms ) await send("active", active) state.notify_browser({"kind": "state"}) finally: state.open_streams.pop(stream_id, None) state.record_delivery( { "mode": "stream", "at": datetime.now(UTC).isoformat(), "name": params.name, "arguments": dict(params.arguments), "client": client_display, "cursor_in": str(position), "cursor_out": str(position), "returned": 0, "truncated": False, "has_more": False, "note": close_note, } ) state.notify_browser({"kind": "state"}) class PlaygroundEventsExtension(Extension): identifier = EVENTS_EXTENSION def methods(self) -> list[MethodBinding]: return [ MethodBinding("events/list", PaginatedRequestParams, list_events), MethodBinding("events/poll", PollEventsRequestParams, poll_events), MethodBinding("events/stream", StreamEventsRequestParams, stream_events), ] mcp = MCPServer("events-playground", extensions=[PlaygroundEventsExtension()]) @mcp.tool() def start_job(job_id: str, description: str = "training run") -> str: """Start a new background job and emit its initial queued event.""" state = get_state() state.emit( "job.status_changed", job_id, {"job_id": job_id, "stage": "queued", "detail": description}, ) return ( f"Started job {job_id} ({description}). " f"Subscribe to job.status_changed with job_id={job_id} to follow updates." ) @mcp.tool() def get_job_details(job_id: str) -> dict[str, Any]: """Fetch recorded history and latest stage for a job.""" state = get_state() state.touch() history = state.streams.get(("job.status_changed", job_id), []) return { "job_id": job_id, "stages": [ {"event_id": ev.event_id, "timestamp": ev.timestamp.isoformat(), **ev.data} for ev in history ], "latest_stage": history[-1].data.get("stage", "unknown") if history else "unknown", } @mcp.tool() def advance_job(job_id: str, stage: str, detail: str = "") -> str: """Advance a job to a new stage, firing job.status_changed.""" state = get_state() state.emit( "job.status_changed", job_id, {"job_id": job_id, "stage": stage, "detail": detail}, ) return f"Job {job_id} -> {stage}" # --------------------------------------------------------------------------- # HTTP control plane & browser UI # --------------------------------------------------------------------------- def _room_from_request(request: Request) -> PlaygroundState | None: raw_room = request.path_params.get("room_id") if raw_room is None: return registry.get_or_create(PUBLIC_ROOM_ID) valid = registry.validate_room_id(str(raw_room)) if valid is None: return None return registry.get_or_create(valid) def _invalid_room_response() -> JSONResponse: return JSONResponse( {"error": "room_id must be 3-32 lowercase letters, digits, or hyphens"}, status_code=400, ) STATIC_DIR = Path(__file__).resolve().parent / "static" async def http_health(request: Request) -> JSONResponse: del request return JSONResponse({"status": "ok"}) async def http_static_hf_logo(request: Request) -> Response: del request asset = STATIC_DIR / "hf-logo.svg" if not asset.is_file(): return JSONResponse({"error": "asset not found"}, status_code=404) return FileResponse( asset, media_type="image/svg+xml", headers={"Cache-Control": "public, max-age=86400"}, ) async def http_emit(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() body = await request.json() event_name = str(body.get("event_name") or "job.status_changed") filter_key = str(body.get("filter_key") or body.get("job_id") or "*") data = body.get("data") if not isinstance(data, dict): data = { "job_id": filter_key, "stage": str(body.get("stage") or "running"), "detail": str(body.get("detail") or ""), } record = state.emit(event_name, filter_key, data) return JSONResponse(record.to_dict()) async def http_gap(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() body = await request.json() key = ( str(body.get("event_name") or "job.status_changed"), str(body.get("filter_key") or body.get("job_id") or "*"), ) state.arm_gap(key) return JSONResponse({"gap_armed": list(key)}) async def http_terminate(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() body = await request.json() key = ( str(body.get("event_name") or "job.status_changed"), str(body.get("filter_key") or body.get("job_id") or "*"), ) state.forbidden_keys.add(key) state.notify({"kind": "fault", "channel": "control", "reason": "revoked", "name": key[0]}) return JSONResponse({"forbidden": list(key)}) async def http_unterminate(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() body = await request.json() key = ( str(body.get("event_name") or "job.status_changed"), str(body.get("filter_key") or body.get("job_id") or "*"), ) state.forbidden_keys.discard(key) state.notify({"kind": "state"}) return JSONResponse({"restored": list(key)}) async def http_config(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() body = await request.json() if not isinstance(body, dict): return JSONResponse({"error": "JSON object body required"}, status_code=400) updated = False if "poll_interval_ms" in body: raw_poll = body["poll_interval_ms"] if isinstance(raw_poll, bool): return JSONResponse({"error": "poll_interval_ms must be an integer"}, status_code=400) try: state.poll_interval_ms = max(250, min(int(raw_poll), 300_000)) except (TypeError, ValueError): return JSONResponse({"error": "poll_interval_ms must be an integer"}, status_code=400) updated = True if "heartbeat_ms" in body: raw_hb = body["heartbeat_ms"] if isinstance(raw_hb, bool): return JSONResponse({"error": "heartbeat_ms must be an integer"}, status_code=400) try: state.heartbeat_ms = max(1_000, min(int(raw_hb), MAX_HEARTBEAT_MS)) except (TypeError, ValueError): return JSONResponse({"error": "heartbeat_ms must be an integer"}, status_code=400) updated = True if "push_enabled" in body: raw_push = body["push_enabled"] if not isinstance(raw_push, bool): return JSONResponse({"error": "push_enabled must be a boolean"}, status_code=400) state.push_enabled = raw_push if not raw_push: for info in state.open_streams.values(): if info["close_reason"] is None: info["close_reason"] = "closed events/stream (push disabled)" updated = True if "poll_enabled" in body: raw_poll_enabled = body["poll_enabled"] if not isinstance(raw_poll_enabled, bool): return JSONResponse({"error": "poll_enabled must be a boolean"}, status_code=400) state.poll_enabled = raw_poll_enabled if not raw_poll_enabled: state.active_pollers.clear() state.last_polled.clear() updated = True if updated: state.touch() state.notify({"kind": "state"}) return JSONResponse( { "poll_interval_ms": state.poll_interval_ms, "heartbeat_ms": state.heartbeat_ms, "push_enabled": state.push_enabled, "poll_enabled": state.poll_enabled, } ) async def http_drop_streams(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() raw = await request.body() body: dict[str, Any] = {} if raw: try: parsed = json.loads(raw) except json.JSONDecodeError: return JSONResponse({"error": "invalid JSON body"}, status_code=400) if not isinstance(parsed, dict): return JSONResponse({"error": "JSON object body required"}, status_code=400) body = parsed target_stream = body.get("stream") count = 0 if target_stream is not None: if isinstance(target_stream, bool): return JSONResponse({"error": "stream must be an integer"}, status_code=400) try: target_id = int(target_stream) except (TypeError, ValueError): return JSONResponse({"error": "stream must be an integer"}, status_code=400) info = state.open_streams.get(target_id) if info is not None: info["close_reason"] = "dropped events/stream" count = 1 else: for info in state.open_streams.values(): info["close_reason"] = "dropped events/stream" count += 1 state.touch() state.wake_streams() state.notify_browser({"kind": "stream_drop", "dropped": count}) return JSONResponse({"dropped": count}) async def http_reset(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() state.reset() return JSONResponse({"reset": True, "room_id": state.room_id}) async def http_stats(request: Request) -> JSONResponse: state = _room_from_request(request) if state is None: return _invalid_room_response() return JSONResponse( { "room_id": state.room_id, "activity_limit": ROOM_ACTIVITY_LIMIT, "push_enabled": state.push_enabled, "poll_enabled": state.poll_enabled, "poll_interval_ms": state.poll_interval_ms, "heartbeat_ms": state.heartbeat_ms, "push_delivered_count": state.push_delivered_count, "poll_delivered_count": state.poll_delivered_count, "delivery_count": state.delivery_seq, "streams": {f"{k[0]}:{k[1]}": len(v) for k, v in state.streams.items()}, "active_streams": state.active_streams(), "active_polls": state.active_polls(), "pending_gaps": [f"{k[0]}:{k[1]}" for k in sorted(state.pending_gaps)], "forbidden": [f"{k[0]}:{k[1]}" for k in sorted(state.forbidden_keys)], "open_streams": [ {k: v for k, v in info.items() if k not in ("pending_gap", "close_reason")} for info in state.open_streams.values() ], "event_count": state.emitted_count, "poll_count": state.poll_count, "recent_events": state.recent_events[-ROOM_ACTIVITY_LIMIT:], "recent_polls": state.poll_log[-ROOM_ACTIVITY_LIMIT:], "recent_deliveries": state.delivery_log[-ROOM_ACTIVITY_LIMIT:], } ) async def http_stream(request: Request) -> Response: """Server-Sent Events stream pushing real-time emit/poll pulses to the UI.""" state = _room_from_request(request) if state is None: return _invalid_room_response() queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=32) state.subscribers.add(queue) async def event_generator() -> AsyncIterator[str]: try: yield f"data: {json.dumps({'kind': 'connected'})}\n\n" while True: if await request.is_disconnected(): break try: item = await asyncio.wait_for(queue.get(), timeout=15.0) yield f"data: {json.dumps(item)}\n\n" except TimeoutError: yield ": keepalive\n\n" finally: state.subscribers.discard(queue) return StreamingResponse( event_generator(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) DASHBOARD_HTML = """ MCP Events Test Lab
MCP Events Test Lab

MCP Events Test Lab

Trigger server events in your isolated room and watch fast-agent wake from idle, catch up after gaps, and handle revoked streams.

Monitor live HTTP/SSE channel activity in fast-agent with /mcp, and inspect or switch subscriptions with /events.

Signal Monitor IDLE · awaiting room traffic
Emit Push Poll
CH1 EMIT CH2 PUSH CH3 POLL
Emitted 0
Push streams 0 live
Poll requests 0
Cadence heartbeat 5000ms · poll 2000ms
Waiting for an MCP client to subscribe via push or poll
Server delivery controls events/list: poll + push
Controls which delivery modes this room advertises in events/list and enforces on requests.
events/stream
events/poll
Active subscribers 0 active
Identified automatically via MCP clientInfo — run /mcp in fast-agent to watch client-side channel activity.

No active subscribers yet. Connect fast-agent and subscribe to system.pulse or job.status_changed.

Prompts to try in fast-agent

Trigger buttons activate automatically as soon as fast-agent subscribes via push or poll.

Wake on pulse

Waiting for a system.pulse subscription, or click Send pulse anytime. Edit the prompt to ask for one trigger (subscribe once) if you want it to stop after the first event.

Follow a job to completion

Waiting for a job.status_changed subscription, then emit running and done.

Test gaps and revocation

Arm truncated gap sends truncated: true on the active push stream or next poll; Revoke job sends -32024 Forbidden so fast-agent ends the subscription.

Buffer events without waking

Send a few pulses to see them queue in the toolbar (and under /mcp) without waking the agent. Your next turn automatically includes all queued events.

fast-agent commands

Click any command to copy — use /mcp to watch the live activity stream.

Event control deck

Custom event payloads and fault injection for this room.

System pulse system.pulse

Job lifecycle job.status_changed

Delivery toggles (above): disabling push or poll removes that mode from events/list and rejects events/stream or events/poll with -32026; active subscriptions on that mode terminate after refreshing events/list, while new subscriptions automatically pick the remaining mode.

Drop push streams: closes open events/stream responses cleanly with their final result (without revoking) so fast-agent reconnects from its saved cursor and catches up retained events.

Arm truncated gap: marks the next delivery with truncated: true, simulating aged-out events so the agent knows to re-fetch state via get_job_details.

Revoke job: returns -32024 Forbidden (or terminates the push stream) so fast-agent ends the subscription cleanly.

Room activity Last 10

Recent events

0 emitted

No events emitted in this room yet.

Delivery & poll log

0 deliveries

Waiting for push deliveries or events/poll calls.

Try with HF Jobs on the Hugging Face MCP Server

Connect to https://hf.co/mcp to subscribe to live HF Jobs events in fast-agent.

Open hf.co/mcp
Isolated room expires after 4 hours of inactivity. fast-agent TUI commands: /mcp · /events · /events select
""" def _render_dashboard(room_id: str) -> HTMLResponse: return HTMLResponse(DASHBOARD_HTML.replace("__ROOM_ID__", room_id)) async def http_root(request: Request) -> RedirectResponse: del request room_id = registry.new_room_id() registry.get_or_create(room_id) return RedirectResponse( url=f"/r/{room_id}", status_code=302, headers={"Cache-Control": "no-store"}, ) async def http_room_index(request: Request) -> Response: raw_room = str(request.path_params["room_id"]) valid = registry.validate_room_id(raw_room) if valid is None: return RedirectResponse( url=f"/r/{registry.new_room_id()}", status_code=302, headers={"Cache-Control": "no-store"}, ) registry.get_or_create(valid) return _render_dashboard(valid) # Disable localhost-only Host header checks so the server works behind reverse # proxies such as Hugging Face Spaces (*.hf.space). mcp_app = mcp.streamable_http_app( streamable_http_path="/mcp", stateless_http=True, host="0.0.0.0", transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False), ) @contextlib.asynccontextmanager async def lifespan(starlette_app: Starlette): del starlette_app async with mcp.session_manager.run(): yield starlette_app = Starlette( lifespan=lifespan, routes=[ Route("/", http_root, methods=["GET"]), Route("/new", http_root, methods=["GET"]), Route("/r/{room_id}", http_room_index, methods=["GET"]), Route("/health", http_health, methods=["GET"]), Route("/static/hf-logo.svg", http_static_hf_logo, methods=["GET"]), # Room-scoped control plane Route("/r/{room_id}/emit", http_emit, methods=["POST"]), Route("/r/{room_id}/emit-gap", http_gap, methods=["POST"]), Route("/r/{room_id}/terminate", http_terminate, methods=["POST"]), Route("/r/{room_id}/unterminate", http_unterminate, methods=["POST"]), Route("/r/{room_id}/config", http_config, methods=["POST"]), Route("/r/{room_id}/drop-streams", http_drop_streams, methods=["POST"]), Route("/r/{room_id}/reset", http_reset, methods=["POST"]), Route("/r/{room_id}/stats", http_stats, methods=["GET"]), Route("/r/{room_id}/stream", http_stream, methods=["GET"]), # Public fallback control plane (backwards compatible) Route("/emit", http_emit, methods=["POST"]), Route("/emit-gap", http_gap, methods=["POST"]), Route("/terminate", http_terminate, methods=["POST"]), Route("/unterminate", http_unterminate, methods=["POST"]), Route("/config", http_config, methods=["POST"]), Route("/drop-streams", http_drop_streams, methods=["POST"]), Route("/reset", http_reset, methods=["POST"]), Route("/stats", http_stats, methods=["GET"]), Route("/stream", http_stream, methods=["GET"]), *mcp_app.routes, ], ) class RoomScopeMiddleware: """Bind per-room PlaygroundState via ContextVar for /r//mcp.""" def __init__(self, inner: ASGIApp) -> None: self._inner = inner async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self._inner(scope, receive, send) return path: str = scope.get("path", "") match = ROOM_MCP_PATH_RE.match(path) if match is not None: valid = registry.validate_room_id(match.group(1)) if valid is None: response = _invalid_room_response() await response(scope, receive, send) return room_state = registry.get_or_create(valid) token = current_room_var.set(room_state) rewritten = dict(scope) rewritten["path"] = "/mcp" if "raw_path" in rewritten: rewritten["raw_path"] = b"/mcp" try: await self._inner(rewritten, receive, send) finally: current_room_var.reset(token) return if path in ("/mcp", "/mcp/"): token = current_room_var.set(registry.get_or_create(PUBLIC_ROOM_ID)) try: await self._inner(scope, receive, send) finally: current_room_var.reset(token) return await self._inner(scope, receive, send) app: ASGIApp = RoomScopeMiddleware(starlette_app) def main() -> None: parser = argparse.ArgumentParser(description="MCP Events (SEP-3415) Playground Server") parser.add_argument("--host", default=os.environ.get("HOST", "0.0.0.0")) parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "7860"))) args = parser.parse_args() uvicorn.run(app, host=args.host, port=args.port, log_level="info") if __name__ == "__main__": main()