"""Standalone MCP Tasks Playground (SEP-2663 / 2026-07-28 + MCP 2026-06-18). Runs on Hugging Face Spaces (Docker) or locally via uvicorn: uvicorn app:app --host 0.0.0.0 --port 7860 """ from __future__ import annotations import asyncio import contextlib import contextvars import html import json import os import secrets import sys from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from pathlib import Path from typing import TYPE_CHECKING, Any, Literal 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.inbound import MCP_NAME_HEADER, decode_header_value from mcp_types import CallToolRequestParams, InputResponses, RequestParams, TextContent from pydantic import 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 Mount, Route _HERE = Path(__file__).resolve().parent if str(_HERE) not in sys.path: sys.path.insert(0, str(_HERE)) from rooms import ( # noqa: E402 HEADER_MISMATCH, INTERNAL_ERROR, INVALID_PARAMS, MISSING_REQUIRED_CLIENT_CAPABILITY, PUBLIC_ROOM_ID, TERMINAL_STATUSES, InvalidInputResponseError, RoomCapacityError, RoomRegistry, RoomState, TaskLookupError, TaskRecord, ) if TYPE_CHECKING: from mcp.server.context import ServerRequestContext from mcp.server.lowlevel.server import CallNext, HandlerResult from starlette.types import ASGIApp, Receive, Scope, Send STATIC_DIR = _HERE / "static" SERVER_VERSION = "2026.07.28" TASKS_EXTENSION = "io.modelcontextprotocol/tasks" _VALID_RUN_MODES = frozenset({"auto", "sync", "task"}) _VALID_FAIL_MODES = frozenset({"none", "tool_error", "rpc_error"}) _VALID_ENVIRONMENTS = frozenset({"staging", "prod"}) _VALID_APPROVAL_MODES = frozenset({"form", "url", "sampling", "multi"}) _MANUAL_ONLY_ACTIONS = frozenset( {"progress", "input_form", "input_url", "complete", "tool_error", "fail"} ) registry = RoomRegistry() current_room_id: contextvars.ContextVar[str] = contextvars.ContextVar( "playground_room_id", default=PUBLIC_ROOM_ID ) current_request_origin: contextvars.ContextVar[str] = contextvars.ContextVar( "playground_request_origin", default="http://127.0.0.1:7860" ) class GetTaskRequestParams(RequestParams): task_id: str = Field(alias="taskId") class UpdateTaskRequestParams(RequestParams): task_id: str = Field(alias="taskId") input_responses: InputResponses = Field(alias="inputResponses") class CancelTaskRequestParams(RequestParams): task_id: str = Field(alias="taskId") def _trusted_base_url(fallback_origin: str | None = None) -> str: """Derive a trusted public origin for approval URLs (never trusting X-Forwarded-Host).""" configured = os.environ.get("PUBLIC_BASE_URL", "").strip() if configured: return configured.rstrip("/") space_host = os.environ.get("SPACE_HOST", "").strip() if space_host: if space_host.startswith(("http://", "https://")): return space_host.rstrip("/") return f"https://{space_host.rstrip('/')}" if fallback_origin: return fallback_origin.rstrip("/") return current_request_origin.get().rstrip("/") def _local_origin_from_scope(scope: Scope) -> str: """Compute a safe local fallback origin from the ASGI scope (ignoring X-Forwarded-Host).""" scheme = str(scope.get("scheme") or "http") server = scope.get("server") if isinstance(server, tuple) and len(server) == 2: host, port = server[0], server[1] if (scheme == "http" and port == 80) or (scheme == "https" and port == 443): return f"{scheme}://{host}" return f"{scheme}://{host}:{port}" return "http://127.0.0.1:7860" def _local_origin_from_request(request: Request) -> str: return _trusted_base_url(_local_origin_from_scope(request.scope)) def _get_room() -> RoomState: return registry.get_or_create(current_room_id.get()) 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 if client_info is not None else None client_version = client_info.version if client_info is not None else None http_req = ctx.request if isinstance(ctx.request, Request) else None raw_label = http_req.query_params.get("client") if http_req is not None else None label = raw_label.strip()[:48] if raw_label and raw_label.strip() else None user_agent = http_req.headers.get("user-agent") if http_req is not None else None name_ver = f"{client_name} {client_version or ''}".strip() if client_name else "" if label and name_ver: client_display = f"{label} ({name_ver})" elif label: client_display = label elif name_ver: client_display = name_ver 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, "client_label": label, } def _client_has_tasks_extension(ctx: ServerRequestContext[Any, Any]) -> bool: caps = ctx.session.client_capabilities if caps is None or caps.extensions is None: return False return TASKS_EXTENSION in caps.extensions def _require_client_tasks_extension(ctx: ServerRequestContext[Any, Any]) -> None: if not _client_has_tasks_extension(ctx): raise MCPError( MISSING_REQUIRED_CLIENT_CAPABILITY, f"Client must advertise extension {TASKS_EXTENSION!r} to use MCP tasks", data={"requiredCapabilities": {"extensions": {TASKS_EXTENSION: {}}}}, ) def _require_deploy_client_capabilities( ctx: ServerRequestContext[Any, Any], approval_mode: str ) -> None: """Enforce per-request client MRTR capabilities before creating inputRequests.""" caps = ctx.session.client_capabilities missing: dict[str, Any] = {} needs_form = approval_mode in ("form", "multi") needs_url = approval_mode == "url" needs_sampling = approval_mode in ("sampling", "multi") if needs_form: elic = caps.elicitation if caps is not None else None has_form = elic is not None and (elic.form is not None or elic.url is None) if not has_form: missing.setdefault("elicitation", {})["form"] = {} if needs_url: elic = caps.elicitation if caps is not None else None has_url = elic is not None and elic.url is not None if not has_url: missing.setdefault("elicitation", {})["url"] = {} if needs_sampling: has_sampling = caps is not None and caps.sampling is not None if not has_sampling: missing["sampling"] = {} if missing: raise MCPError( MISSING_REQUIRED_CLIENT_CAPABILITY, f"Client lacks required capabilities for approval_mode={approval_mode!r}", data={"requiredCapabilities": missing}, ) def _require_outstanding_input_capabilities( ctx: ServerRequestContext[Any, Any], input_requests: Mapping[str, Mapping[str, Any]] ) -> None: """Enforce per-request client MRTR capabilities before returning input_required on tasks/get.""" needs_form = False needs_url = False needs_sampling = False for req in input_requests.values(): method = req.get("method") params = req.get("params") if method == "elicitation/create": mode = params.get("mode") if isinstance(params, Mapping) else None if mode == "url": needs_url = True else: needs_form = True elif method == "sampling/createMessage": needs_sampling = True caps = ctx.session.client_capabilities missing: dict[str, Any] = {} if needs_form: elic = caps.elicitation if caps is not None else None has_form = elic is not None and (elic.form is not None or elic.url is None) if not has_form: missing.setdefault("elicitation", {})["form"] = {} if needs_url: elic = caps.elicitation if caps is not None else None has_url = elic is not None and elic.url is not None if not has_url: missing.setdefault("elicitation", {})["url"] = {} if needs_sampling: has_sampling = caps is not None and caps.sampling is not None if not has_sampling: missing["sampling"] = {} if missing: raise MCPError( MISSING_REQUIRED_CLIENT_CAPABILITY, "Client lacks required capabilities for outstanding task inputRequests", data={"requiredCapabilities": missing}, ) def _require_mcp_name_header(ctx: ServerRequestContext[Any, Any], expected_task_id: str) -> None: """Validate Mcp-Name routing header at the handler boundary for Streamable HTTP requests.""" http_req = ctx.request if http_req is None: return raw_values = http_req.headers.getlist(MCP_NAME_HEADER) if len(raw_values) != 1: raise MCPError( HEADER_MISMATCH, f"Header {MCP_NAME_HEADER!r} must appear exactly once and match params.taskId", ) decoded = decode_header_value(raw_values[0]) if decoded != expected_task_id: raise MCPError( HEADER_MISMATCH, f"Header {MCP_NAME_HEADER!r} ({decoded!r}) does not match params.taskId ({expected_task_id!r})", ) def _require_non_blank_str(args: Mapping[str, Any], key: str, default: str | None = None) -> str: raw = args.get(key, default) if not isinstance(raw, str) or not raw.strip(): raise MCPError(INVALID_PARAMS, f"Argument {key!r} must be a non-empty string") return raw.strip() def _require_positive_int( args: Mapping[str, Any], key: str, *, default: int, minimum: int = 1, maximum: int = 3_600_000, ) -> int: raw = args.get(key, default) if isinstance(raw, bool) or not isinstance(raw, int): raise MCPError(INVALID_PARAMS, f"Argument {key!r} must be an integer") if raw < minimum or raw > maximum: raise MCPError( INVALID_PARAMS, f"Argument {key!r} must be between {minimum} and {maximum}", ) return raw def _require_optional_ttl_ms(args: Mapping[str, Any], key: str = "ttl_ms") -> int | None: raw = args.get(key) if raw is None: return None if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0: raise MCPError(INVALID_PARAMS, f"Argument {key!r} must be a positive integer or null") return raw async def _subscriptions_tasks_guard( ctx: ServerRequestContext[Any, Any], call_next: Callable[[ServerRequestContext[Any, Any]], Awaitable[Any]], ) -> Any: """Reject subscriptions/listen with taskIds when client did not negotiate tasks extension.""" if ctx.method == "subscriptions/listen" and isinstance(ctx.params, Mapping): notifs = ctx.params.get("notifications") if isinstance(notifs, Mapping) and "taskIds" in notifs: _require_client_tasks_extension(ctx) return await call_next(ctx) async def _drive_run_job( room: RoomState, record: TaskRecord, *, name: str, steps: int, step_ms: int, fail_mode: str, ) -> None: try: for idx in range(1, steps + 1): if record.cancel_requested or record.status in TERMINAL_STATUSES: return room.set_progress(record, f"Step {idx}/{steps}: processing {name}...") await asyncio.sleep(step_ms / 1000.0) if record.cancel_requested or record.status in TERMINAL_STATUSES: return if fail_mode == "tool_error": room.complete_task( record, { "content": [ { "type": "text", "text": f"Job '{name}' finished with tool-level error (isError=true).", } ], "isError": True, "resultType": "complete", }, status_message="Completed with tool-level error", ) elif fail_mode == "rpc_error": room.fail_task( record, code=INTERNAL_ERROR, message=f"Simulated JSON-RPC failure during '{name}'", data={"job": name, "reason": "simulated_rpc_error"}, ) else: room.complete_task( record, { "content": [ { "type": "text", "text": f"Job '{name}' completed successfully across {steps} step(s).", } ], "isError": False, "resultType": "complete", }, status_message=f"Completed {steps}/{steps} steps", ) except asyncio.CancelledError: room.cancel_task(record, reason="Cancelled while running") raise async def _wait_for_input_keys(record: TaskRecord, keys: list[str]) -> bool: """Wait until all requested input keys are answered or the task becomes terminal.""" while True: if record.cancel_requested or record.status in TERMINAL_STATUSES: return False if all(k in record.answered_responses for k in keys): return True waiter = record.updated_event await waiter.wait() async def _wait_for_url_decision( record: TaskRecord, req_key: str ) -> Literal["approve", "decline"] | None: """Wait until a real one-shot browser POST records approve/decline for req_key.""" while True: if record.cancel_requested or record.status in TERMINAL_STATUSES: return None decision = record.url_decisions.get(req_key) if decision is not None: return decision waiter = record.updated_event await waiter.wait() async def _drive_deploy_release( room: RoomState, record: TaskRecord, *, service: str, environment: str, approval_mode: str, base_url: str, ) -> None: try: room.set_progress(record, f"Preparing deployment plan for {service} -> {environment}...") await asyncio.sleep(0.15) if record.cancel_requested or record.status in TERMINAL_STATUSES: return requests: dict[str, dict[str, Any]] = {} form_key: str | None = None url_key: str | None = None sampling_key: str | None = None if approval_mode in ("form", "multi"): form_key = record.next_input_key() requests[form_key] = { "method": "elicitation/create", "params": { "mode": "form", "message": f"Approve deployment of {service} to {environment}?", "requestedSchema": { "type": "object", "properties": { "confirm": { "type": "boolean", "title": "Confirm deployment", "default": False, }, "reason": { "type": "string", "title": "Change ticket / reason", }, }, "required": ["confirm"], }, }, } if approval_mode == "url": url_key = record.next_input_key() elicitation_id = f"elicit_{secrets.token_urlsafe(12)}" approve_url = f"{base_url}/r/{room.room_id}/approve/{elicitation_id}" room.url_approvals[elicitation_id] = { "taskId": record.task_id, "reqKey": url_key, "service": service, "environment": environment, "resolved": False, } requests[url_key] = { "method": "elicitation/create", "params": { "mode": "url", "elicitationId": elicitation_id, "url": approve_url, "message": f"Open the approval page to authorize {service} -> {environment}.", }, } if approval_mode in ("sampling", "multi"): sampling_key = record.next_input_key() requests[sampling_key] = { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": ( f"Write a one-sentence release note for deploying " f"{service} to {environment}." ), }, } ], "maxTokens": 120, }, } keys = list(requests.keys()) room.set_input_required( record, requests, status_message=f"Waiting for {approval_mode} input ({', '.join(keys)})", ) ready = await _wait_for_input_keys(record, keys) if not ready: return # Validate form approval: require action == "accept" AND confirm is True. if form_key is not None: form_resp = record.answered_responses.get(form_key, {}) content = form_resp.get("content") confirmed = isinstance(content, Mapping) and content.get("confirm") is True if form_resp.get("action") != "accept" or not confirmed: room.cancel_task( record, reason=( f"Deployment rejected during form approval " f"(action={form_resp.get('action')}, confirm={confirmed})" ), ) return # Validate URL approval: client accept only consents to open URL; wait for browser POST! if url_key is not None: url_resp = record.answered_responses.get(url_key, {}) if url_resp.get("action") != "accept": room.cancel_task( record, reason=( f"Deployment cancelled: client returned {url_resp.get('action')!r} " "for URL elicitation" ), ) return room.set_progress( record, f"Client accepted URL for {service} -> {environment}; waiting for browser approval...", ) browser_decision = await _wait_for_url_decision(record, url_key) if browser_decision is None: return if browser_decision != "approve": room.cancel_task( record, reason="Deployment declined on out-of-band approval page", ) return summary_parts = [f"Deployed {service} to {environment} (mode={approval_mode})."] if form_key is not None: content = record.answered_responses[form_key].get("content", {}) if isinstance(content, Mapping) and content.get("reason"): summary_parts.append(f"Reason: {content['reason']}.") if sampling_key is not None: sample = record.answered_responses[sampling_key] sample_content = sample.get("content", {}) if isinstance(sample_content, Mapping) and "text" in sample_content: summary_parts.append(f"Release note: {sample_content['text']}") room.complete_task( record, { "content": [{"type": "text", "text": " ".join(summary_parts)}], "isError": False, "resultType": "complete", }, status_message=f"Deployed {service} to {environment}", ) except asyncio.CancelledError: room.cancel_task(record, reason="Deployment cancelled") raise async def handle_tasks_get( ctx: ServerRequestContext[Any, Any], params: GetTaskRequestParams ) -> dict[str, Any]: room = _get_room() client_info = _extract_client_identity(ctx) try: _require_mcp_name_header(ctx, params.task_id) _require_client_tasks_extension(ctx) try: record = room.get_task(params.task_id) except TaskLookupError as exc: raise MCPError(INVALID_PARAMS, str(exc)) from exc if record.status == "input_required": _require_outstanding_input_capabilities(ctx, record.input_requests) except MCPError as exc: room.record_poll(params.task_id, status="error", fault=True) room.log_rpc( "tasks/get", { "taskId": params.task_id, "error": exc.error.message, "client": client_info["client"], }, ) raise room.record_poll(record.task_id, status=record.status, fault=False) room.log_rpc( "tasks/get", { "taskId": record.task_id, "status": record.status, "client": client_info["client"], }, ) return record.to_get_wire() async def handle_tasks_update( ctx: ServerRequestContext[Any, Any], params: UpdateTaskRequestParams ) -> dict[str, Any]: _require_mcp_name_header(ctx, params.task_id) _require_client_tasks_extension(ctx) room = _get_room() client_info = _extract_client_identity(ctx) dumped_responses: dict[str, dict[str, Any]] = {} for key, resp in params.input_responses.items(): dumped_responses[key] = resp.model_dump(by_alias=True, exclude_none=True) try: record = room.apply_input_responses(params.task_id, dumped_responses) except (TaskLookupError, InvalidInputResponseError) as exc: room.log_rpc( "tasks/update", {"taskId": params.task_id, "error": str(exc), "client": client_info["client"]}, ) raise MCPError(INVALID_PARAMS, str(exc)) from exc room.log_rpc( "tasks/update", { "taskId": record.task_id, "keys": sorted(dumped_responses.keys()), "remaining": sorted(record.input_requests.keys()), "status": record.status, "client": client_info["client"], }, ) return {"resultType": "complete"} async def handle_tasks_cancel( ctx: ServerRequestContext[Any, Any], params: CancelTaskRequestParams ) -> dict[str, Any]: _require_mcp_name_header(ctx, params.task_id) _require_client_tasks_extension(ctx) room = _get_room() client_info = _extract_client_identity(ctx) try: record = room.request_cancel(params.task_id) except TaskLookupError as exc: room.log_rpc( "tasks/cancel", {"taskId": params.task_id, "error": str(exc), "client": client_info["client"]}, ) raise MCPError(INVALID_PARAMS, str(exc)) from exc room.log_rpc( "tasks/cancel", { "taskId": record.task_id, "status": record.status, "client": client_info["client"], }, ) return {"resultType": "complete"} class TasksPlaygroundExtension(Extension): identifier = TASKS_EXTENSION def methods(self) -> list[MethodBinding]: return [ MethodBinding("tasks/get", GetTaskRequestParams, handle_tasks_get), MethodBinding("tasks/update", UpdateTaskRequestParams, handle_tasks_update), MethodBinding("tasks/cancel", CancelTaskRequestParams, handle_tasks_cancel), ] async def intercept_tool_call( self, params: CallToolRequestParams, ctx: ServerRequestContext[Any, Any], call_next: CallNext, ) -> HandlerResult: room = _get_room() args = dict(params.arguments or {}) tool_name = params.name client_info = _extract_client_identity(ctx) if tool_name == "run_job": name = _require_non_blank_str(args, "name", default="nightly-build") mode = args.get("mode", "auto") if mode not in _VALID_RUN_MODES: raise MCPError( INVALID_PARAMS, f"Invalid mode {mode!r}; expected one of {sorted(_VALID_RUN_MODES)}", ) fail_mode = args.get("fail_mode", "none") if fail_mode not in _VALID_FAIL_MODES: raise MCPError( INVALID_PARAMS, f"Invalid fail_mode {fail_mode!r}; expected one of {sorted(_VALID_FAIL_MODES)}", ) steps = _require_positive_int(args, "steps", default=5, minimum=1, maximum=100) step_ms = _require_positive_int(args, "step_ms", default=600, minimum=1, maximum=60_000) ttl_ms = _require_optional_ttl_ms(args, "ttl_ms") poll_interval_ms = _require_positive_int( args, "poll_interval_ms", default=room.effective_poll_interval_ms(600), minimum=1, maximum=60_000, ) if mode == "task": _require_client_tasks_extension(ctx) if not room.async_tasks_enabled: msg = "Async task creation is disabled in this room" room.log_rpc( "tools/call", {"tool": tool_name, "error": msg, "client": client_info["client"]}, ) raise MCPError(INTERNAL_ERROR, msg) use_task = mode == "task" or ( mode == "auto" and room.async_tasks_enabled and _client_has_tasks_extension(ctx) ) if not use_task: if fail_mode == "rpc_error": msg = f"Simulated JSON-RPC failure during '{name}'" room.log_rpc( "tools/call", { "tool": tool_name, "error": msg, "client": client_info["client"], }, ) raise MCPError(INTERNAL_ERROR, msg) room.log_rpc( "tools/call", { "tool": tool_name, "resultType": "complete", "isError": fail_mode == "tool_error", "client": client_info["client"], }, ) if fail_mode == "tool_error": return { "content": [ { "type": "text", "text": f"Sync job '{name}' failed with tool error (isError=true).", } ], "isError": True, "resultType": "complete", } return { "content": [ { "type": "text", "text": f"Sync job '{name}' completed immediately without creating a task.", } ], "isError": False, "resultType": "complete", } _require_client_tasks_extension(ctx) try: record = room.create_task( tool_name=tool_name, title=f"Job: {name}", arguments=args, manual=False, status_message=f"Queued job '{name}' ({steps} steps)...", ttl_ms=ttl_ms, poll_interval_ms=poll_interval_ms, client=client_info["client"], client_name=client_info["client_name"], client_version=client_info["client_version"], client_label=client_info["client_label"], ) except RoomCapacityError as exc: raise MCPError(INTERNAL_ERROR, str(exc)) from exc record.bg_task = asyncio.create_task( _drive_run_job( room, record, name=name, steps=steps, step_ms=step_ms, fail_mode=fail_mode, ) ) room.log_rpc( "tools/call", { "tool": tool_name, "resultType": "task", "taskId": record.task_id, "client": client_info["client"], }, ) return record.to_create_wire() if tool_name == "deploy_release": service = _require_non_blank_str(args, "service", default="checkout-api") environment = args.get("environment", "prod") if environment not in _VALID_ENVIRONMENTS: raise MCPError( INVALID_PARAMS, f"Invalid environment {environment!r}; expected one of {sorted(_VALID_ENVIRONMENTS)}", ) approval_mode = args.get("approval_mode", "form") if approval_mode not in _VALID_APPROVAL_MODES: raise MCPError( INVALID_PARAMS, f"Invalid approval_mode {approval_mode!r}; expected one of {sorted(_VALID_APPROVAL_MODES)}", ) poll_interval_ms = _require_positive_int( args, "poll_interval_ms", default=room.effective_poll_interval_ms(600), minimum=1, maximum=60_000, ) _require_client_tasks_extension(ctx) _require_deploy_client_capabilities(ctx, approval_mode) if not room.async_tasks_enabled: msg = "Async task creation is disabled in this room" room.log_rpc( "tools/call", {"tool": tool_name, "error": msg, "client": client_info["client"]}, ) raise MCPError(INTERNAL_ERROR, msg) try: record = room.create_task( tool_name=tool_name, title=f"Deploy {service} ({environment})", arguments=args, manual=False, status_message=f"Starting {approval_mode} deployment workflow...", ttl_ms=None, poll_interval_ms=poll_interval_ms, client=client_info["client"], client_name=client_info["client_name"], client_version=client_info["client_version"], client_label=client_info["client_label"], ) except RoomCapacityError as exc: raise MCPError(INTERNAL_ERROR, str(exc)) from exc record.bg_task = asyncio.create_task( _drive_deploy_release( room, record, service=service, environment=environment, approval_mode=approval_mode, base_url=_trusted_base_url(), ) ) room.log_rpc( "tools/call", { "tool": tool_name, "resultType": "task", "taskId": record.task_id, "client": client_info["client"], }, ) return record.to_create_wire() if tool_name == "open_manual_task": title = _require_non_blank_str(args, "title", default="Interactive Demo Task") ttl_ms = _require_optional_ttl_ms(args, "ttl_ms") poll_interval_ms = _require_positive_int( args, "poll_interval_ms", default=room.effective_poll_interval_ms(1000), minimum=1, maximum=60_000, ) _require_client_tasks_extension(ctx) if not room.async_tasks_enabled: msg = "Async task creation is disabled in this room" room.log_rpc( "tools/call", {"tool": tool_name, "error": msg, "client": client_info["client"]}, ) raise MCPError(INTERNAL_ERROR, msg) try: record = room.create_task( tool_name=tool_name, title=title, arguments=args, manual=True, status_message="Waiting for dashboard operator actions...", ttl_ms=ttl_ms, poll_interval_ms=poll_interval_ms, client=client_info["client"], client_name=client_info["client_name"], client_version=client_info["client_version"], client_label=client_info["client_label"], ) except RoomCapacityError as exc: raise MCPError(INTERNAL_ERROR, str(exc)) from exc room.log_rpc( "tools/call", { "tool": tool_name, "resultType": "task", "taskId": record.task_id, "client": client_info["client"], }, ) return record.to_create_wire() return await call_next(ctx) mcp_server = MCPServer( name="mcp-tasks-playground", version=SERVER_VERSION, instructions=( "Interactive SEP-2663 MCP Tasks Playground. " "Use run_job, deploy_release, or open_manual_task to exercise async task handles, " "MRTR input_required (elicitation + sampling), cancellation, TTL expiry, and errors." ), extensions=[TasksPlaygroundExtension()], middleware=[_subscriptions_tasks_guard], ) @mcp_server.tool() async def run_job( name: str = "nightly-build", steps: int = 5, step_ms: int = 600, mode: Literal["auto", "sync", "task"] = "auto", fail_mode: Literal["none", "tool_error", "rpc_error"] = "none", ttl_ms: int | None = None, poll_interval_ms: int = 600, ) -> list[TextContent]: """Run a multi-step job that executes synchronously or as a SEP-2663 async task.""" return [ TextContent( type="text", text=f"Sync completion for {name} (mode={mode}, steps={steps}, fail_mode={fail_mode})", ) ] @mcp_server.tool() async def deploy_release( service: str = "checkout-api", environment: Literal["staging", "prod"] = "prod", approval_mode: Literal["form", "url", "sampling", "multi"] = "form", poll_interval_ms: int = 600, ) -> list[TextContent]: """Deploy a release with human-in-the-loop MRTR approval (form, url, sampling, or multi).""" return [ TextContent( type="text", text=f"Deployment tool invoked for {service} ({environment}, {approval_mode})", ) ] @mcp_server.tool() async def open_manual_task( title: str = "Interactive Demo Task", ttl_ms: int | None = None, poll_interval_ms: int = 1000, ) -> list[TextContent]: """Create a live task driven manually from the browser dashboard.""" return [TextContent(type="text", text=f"Manual task opened: {title}")] _mcp_asgi = mcp_server.streamable_http_app( stateless_http=True, json_response=True, transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False), ) class RoomScopeMiddleware: """ASGI wrapper that ONLY binds room/origin contextvars and rewrites /r//mcp -> /mcp. Never reads or buffers request bodies, preserving MCP SDK body limits and disconnect semantics. """ 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", "") room_id: str | None = None rewritten_scope = scope if path == "/mcp" or path == "/mcp/": room_id = PUBLIC_ROOM_ID elif path.startswith("/r/") and (path.endswith("/mcp") or path.endswith("/mcp/")): parts = path.strip("/").split("/") if len(parts) == 3 and parts[0] == "r" and parts[2] == "mcp": validated = registry.validate_room_id(parts[1]) if validated is None: resp = JSONResponse({"error": "Invalid room ID"}, status_code=400) await resp(scope, receive, send) return room_id = validated rewritten_scope = dict(scope) rewritten_scope["path"] = "/mcp" rewritten_scope["raw_path"] = b"/mcp" if room_id is None: await self._inner(scope, receive, send) return room_token = current_room_id.set(room_id) origin_token = current_request_origin.set(_local_origin_from_scope(scope)) try: await self._inner(rewritten_scope, receive, send) finally: current_room_id.reset(room_token) current_request_origin.reset(origin_token) # --------------------------------------------------------------------------- # Web Dashboard & Room API Routes # --------------------------------------------------------------------------- def _resolve_room_or_400(request: Request) -> RoomState | JSONResponse: raw = request.path_params.get("room_id", PUBLIC_ROOM_ID) validated = registry.validate_room_id(str(raw)) if validated is None: return JSONResponse({"error": "Invalid room ID"}, status_code=400) return registry.get_or_create(validated) async def root_redirect(request: Request) -> Response: return RedirectResponse( url=f"/r/{registry.new_room_id()}", status_code=302, headers={"Cache-Control": "no-store"}, ) async def room_dashboard(request: Request) -> Response: resolved = _resolve_room_or_400(request) if isinstance(resolved, JSONResponse): return resolved return FileResponse(STATIC_DIR / "index.html") async def hf_logo(request: Request) -> Response: return FileResponse(STATIC_DIR / "hf-logo.svg", media_type="image/svg+xml") async def health(request: Request) -> JSONResponse: return JSONResponse( { "status": "ok", "server": "mcp-tasks-playground", "version": SERVER_VERSION, "extension": TASKS_EXTENSION, } ) async def api_state(request: Request) -> JSONResponse: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room room.prune_expired() base_url = _local_origin_from_request(request) return JSONResponse( { "roomId": room.room_id, "mcpEndpoint": f"{base_url}/r/{room.room_id}/mcp", "publicMcpEndpoint": f"{base_url}/mcp", "tasks": [rec.to_ui_dict() for rec in reversed(list(room.tasks.values()))], "rpcLog": list(reversed(room.rpc_log[-60:])), "urlApprovals": { eid: {**info, "url": f"{base_url}/r/{room.room_id}/approve/{eid}"} for eid, info in room.url_approvals.items() }, "asyncTasksEnabled": room.async_tasks_enabled, "pollIntervalMs": room.effective_poll_interval_ms(1000), "pollCount": room.poll_count, } ) async def api_config(request: Request) -> JSONResponse: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room try: raw_body = await request.body() body: Any = json.loads(raw_body) if raw_body else {} except ValueError: return JSONResponse({"error": "Invalid JSON body"}, status_code=400) if not isinstance(body, dict): return JSONResponse({"error": "JSON body must be an object"}, status_code=400) next_async_enabled: bool | None = None if "asyncTasksEnabled" in body or "async_tasks_enabled" in body: raw_enabled = ( body["asyncTasksEnabled"] if "asyncTasksEnabled" in body else body["async_tasks_enabled"] ) if not isinstance(raw_enabled, bool): return JSONResponse({"error": "asyncTasksEnabled must be a boolean"}, status_code=400) next_async_enabled = raw_enabled has_poll_update = "pollIntervalMs" in body or "poll_interval_ms" in body next_poll_override: int | None = None if has_poll_update: raw_poll = body["pollIntervalMs"] if "pollIntervalMs" in body else body["poll_interval_ms"] if raw_poll is None: next_poll_override = None elif ( isinstance(raw_poll, bool) or not isinstance(raw_poll, int) or not (250 <= raw_poll <= 60_000) ): return JSONResponse( {"error": "pollIntervalMs must be an integer between 250 and 60000, or null"}, status_code=400, ) else: next_poll_override = raw_poll if next_async_enabled is not None: room.async_tasks_enabled = next_async_enabled if has_poll_update: room.poll_interval_override_ms = next_poll_override if next_poll_override is not None: room.update_live_poll_intervals(next_poll_override) room.touch() room.notify({"kind": "state"}) return JSONResponse( { "asyncTasksEnabled": room.async_tasks_enabled, "pollIntervalMs": room.effective_poll_interval_ms(1000), } ) async def api_events(request: Request) -> Response: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=32) room.subscribers.add(queue) async def event_stream() -> AsyncIterator[str]: try: yield f"data: {json.dumps({'kind': 'connected', 'roomId': room.room_id})}\n\n" while True: if await request.is_disconnected(): break try: event = await asyncio.wait_for(queue.get(), timeout=20.0) yield f"data: {json.dumps(event)}\n\n" except TimeoutError: yield ": keepalive\n\n" finally: room.subscribers.discard(queue) return StreamingResponse( event_stream(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, ) async def api_spawn_manual(request: Request) -> JSONResponse: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room if not room.async_tasks_enabled: return JSONResponse( {"error": "Async task creation is disabled in this room"}, status_code=409 ) body = await request.json() if await request.body() else {} title = str(body.get("title") or "Manual Playground Task").strip() if not title: return JSONResponse({"error": "title must be non-empty"}, status_code=400) ttl_raw = body.get("ttlMs") if ttl_raw is not None and ( isinstance(ttl_raw, bool) or not isinstance(ttl_raw, int) or ttl_raw <= 0 ): return JSONResponse({"error": "ttlMs must be a positive integer or null"}, status_code=400) try: record = room.create_task( tool_name="open_manual_task", title=title, arguments={"title": title, "ttl_ms": ttl_raw}, manual=True, status_message="Created from dashboard; ready for manual transitions", ttl_ms=ttl_raw, poll_interval_ms=room.effective_poll_interval_ms(1000), client="dashboard", ) except RoomCapacityError as exc: return JSONResponse({"error": str(exc)}, status_code=503) return JSONResponse(record.to_ui_dict(), status_code=201) async def api_task_action(request: Request) -> JSONResponse: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room task_id = str(request.path_params["task_id"]) body = await request.json() if await request.body() else {} action = str(body.get("action") or "") if action == "purge": return JSONResponse({"purged": room.purge_task(task_id)}) try: record = room.get_task(task_id) except TaskLookupError as exc: return JSONResponse({"error": str(exc)}, status_code=404) if action == "cancel": room.request_cancel(task_id) return JSONResponse(record.to_ui_dict()) if action in _MANUAL_ONLY_ACTIONS and not record.manual: return JSONResponse( { "error": ( f"Action {action!r} is only allowed on manual tasks (open_manual_task). " "Automated tasks only support 'cancel' and 'purge'." ) }, status_code=400, ) if action in _MANUAL_ONLY_ACTIONS and record.status in ("completed", "failed", "cancelled"): return JSONResponse( {"error": f"Task {task_id} is already {record.status}"}, status_code=409, ) if action == "progress": msg = str(body.get("message") or "Working on next step...") room.set_progress(record, msg) elif action == "input_form": req_key = record.next_input_key() prompt = str(body.get("message") or "Please confirm to continue this task") room.set_input_required( record, { req_key: { "method": "elicitation/create", "params": { "mode": "form", "message": prompt, "requestedSchema": { "type": "object", "properties": { "confirm": {"type": "boolean", "title": "Confirm", "default": True}, "note": {"type": "string", "title": "Operator note"}, }, "required": ["confirm"], }, }, } }, status_message=f"Waiting for form input ({req_key})", ) elif action == "input_url": req_key = record.next_input_key() elicitation_id = f"elicit_{secrets.token_urlsafe(12)}" base_url = _local_origin_from_request(request) approve_url = f"{base_url}/r/{room.room_id}/approve/{elicitation_id}" room.url_approvals[elicitation_id] = { "taskId": record.task_id, "reqKey": req_key, "service": record.title, "environment": "manual", "resolved": False, } room.set_input_required( record, { req_key: { "method": "elicitation/create", "params": { "mode": "url", "elicitationId": elicitation_id, "url": approve_url, "message": f"Open approval link for {record.title}", }, } }, status_message=f"Waiting for URL approval ({req_key})", ) elif action == "complete": text = str(body.get("text") or f"Task '{record.title}' completed manually.") room.complete_task( record, { "content": [{"type": "text", "text": text}], "isError": False, "resultType": "complete", }, status_message="Completed from dashboard", ) elif action == "tool_error": text = str(body.get("text") or f"Tool error reported for '{record.title}'.") room.complete_task( record, { "content": [{"type": "text", "text": text}], "isError": True, "resultType": "complete", }, status_message="Completed with tool-level error", ) elif action == "fail": msg = str(body.get("message") or f"Protocol error for '{record.title}'") room.fail_task(record, code=INTERNAL_ERROR, message=msg) else: return JSONResponse({"error": f"Unknown action: {action!r}"}, status_code=400) return JSONResponse(record.to_ui_dict()) async def api_reset(request: Request) -> JSONResponse: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room cancelled = room.reset() if cancelled: await asyncio.gather(*cancelled, return_exceptions=True) return JSONResponse({"reset": True, "roomId": room.room_id}) async def approve_url_page(request: Request) -> Response: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room eid = str(request.path_params["elicitation_id"]) entry = room.url_approvals.get(eid) if entry is None: return HTMLResponse("

Approval link not found or expired

", status_code=404) if entry.get("resolved"): return HTMLResponse( "

Approval link already used

This one-shot approval link has already been submitted.

", status_code=409, ) task_id = str(entry["taskId"]) try: record = room.get_task(task_id) except TaskLookupError: room.url_approvals.pop(eid, None) return HTMLResponse("

Task expired or not found

", status_code=410) if record.status in TERMINAL_STATUSES: room.url_approvals.pop(eid, None) return HTMLResponse( f"

Task is already {html.escape(record.status)}

", status_code=410 ) service = html.escape(str(entry.get("service", "task"))) env = html.escape(str(entry.get("environment", "prod"))) safe_task_id = html.escape(task_id) safe_room = html.escape(room.room_id) body = f""" Approve {service} · MCP Tasks Test Lab

MCP Tasks Test Lab · Out-of-band URL Elicitation

Approve task action

Authorize {service} in {env}?

Task ID: {safe_task_id} · Room: {safe_room}

Synthetic demo notice: unauthenticated test control for SEP-2663 interoperability testing. Never submit real credentials or secrets.

""" return HTMLResponse(body) async def approve_url_post(request: Request) -> Response: room = _resolve_room_or_400(request) if isinstance(room, JSONResponse): return room eid = str(request.path_params["elicitation_id"]) form = await request.form() raw_decision = str(form.get("decision") or "").strip().lower() if raw_decision not in ("approve", "decline"): return HTMLResponse( "

Invalid decision

Explicit decision ('approve' or 'decline') is required.

", status_code=400, ) decision: Literal["approve", "decline"] = "approve" if raw_decision == "approve" else "decline" applied, message, record = room.record_url_decision(eid, decision) if not applied: status_code = 409 if "already" in message.lower() else 410 return HTMLResponse( f"

Approval not applied

{html.escape(message)}

", status_code=status_code, ) safe_room = html.escape(room.room_id) safe_task_id = html.escape(record.task_id if record is not None else "") badge_color = "#16794b" if decision == "approve" else "#c84323" return HTMLResponse( f""" Decision Recorded · MCP Tasks Test Lab

Decision recorded: {html.escape(decision)}

Decision recorded. Task {safe_task_id} has been notified.

← Return to room dashboard

""" ) @contextlib.asynccontextmanager async def lifespan(_app: Starlette) -> AsyncIterator[None]: async with mcp_server.session_manager.run(): try: yield finally: await registry.shutdown_all() routes = [ Route("/", root_redirect, methods=["GET"]), Route("/new", root_redirect, methods=["GET"]), Route("/health", health, methods=["GET"]), Route("/static/hf-logo.svg", hf_logo, methods=["GET"]), Route("/r/{room_id}", room_dashboard, methods=["GET"]), Route("/r/{room_id}/api/state", api_state, methods=["GET"]), Route("/r/{room_id}/api/events", api_events, methods=["GET"]), Route("/r/{room_id}/api/config", api_config, methods=["POST"]), Route("/r/{room_id}/api/tasks", api_spawn_manual, methods=["POST"]), Route("/r/{room_id}/api/tasks/{task_id}/action", api_task_action, methods=["POST"]), Route("/r/{room_id}/api/reset", api_reset, methods=["POST"]), Route("/r/{room_id}/approve/{elicitation_id}", approve_url_page, methods=["GET"]), Route("/r/{room_id}/approve/{elicitation_id}", approve_url_post, methods=["POST"]), Mount("/", app=_mcp_asgi), ] app: ASGIApp = RoomScopeMiddleware(Starlette(routes=routes, lifespan=lifespan))