from __future__ import annotations import enum import asyncio from contextlib import AsyncExitStack, asynccontextmanager from typing import TYPE_CHECKING, Any import pydantic from mcp import ClientSession from mcp.client.websocket import websocket_client from ....box.workspace import BoxWorkspaceSession if TYPE_CHECKING: from .mcp import RuntimeMCPSession class MCPSessionErrorPhase(enum.Enum): """Which phase of the MCP lifecycle failed.""" CONFIG_ERROR = 'config_error' SESSION_CREATE = 'session_create' DEP_INSTALL = 'dep_install' PROCESS_START = 'process_start' RELAY_CONNECT = 'relay_connect' MCP_INIT = 'mcp_init' RUNTIME = 'runtime' TOOL_CALL = 'tool_call' OAUTH_REQUIRED = 'oauth_required' # Stdio MCP refused because Box is disabled in config or currently # unavailable. Not transient — retries would be pointless. The frontend # uses this phase to render a localized actionable message instead of # the raw RuntimeError text. BOX_UNAVAILABLE = 'box_unavailable' def _get_default_memory_mb(ap) -> int: """Read box.default_memory_mb from instance config (env: BOX__DEFAULT_MEMORY_MB). Falls back to 1536 MB — a safe floor for Node.js V8 + WASM under nsjail. Operators running memory-constrained hosts can lower this; those with large machines can raise it. Individual MCP servers can still override via their own box.memory_mb setting. """ try: data = getattr(getattr(ap, 'instance_config', None), 'data', None) if isinstance(data, dict): return int(data.get('box', {}).get('default_memory_mb', 1536)) except (TypeError, ValueError): pass return 1536 class MCPServerBoxConfig(pydantic.BaseModel): """Structured configuration for running an MCP server inside a Box container.""" image: str | None = None network: str = 'on' # MCP servers need network for dependency installation # Retained solely to detect legacy host_path configs and fail explicitly. host_path: str | None = None env: dict[str, str] = pydantic.Field(default_factory=dict) startup_timeout_sec: int = 300 # First Docker bootstrap may need to build a venv and install MCP deps. cpus: float | None = None memory_mb: int | None = None pids_limit: int | None = None read_only_rootfs: bool | None = None model_config = pydantic.ConfigDict(extra='ignore') _HANDSHAKE_ATTEMPT_TIMEOUT_SEC = 10.0 @asynccontextmanager async def authenticated_websocket_client(url: str, headers: dict[str, str]): """MCP WebSocket transport with host-only Box relay headers. The upstream MCP helper does not expose WebSocket handshake headers. This mirrors that transport while keeping the Box control token out of the URL, JSON-RPC payloads, and logs. """ import json import anyio import mcp.types as mcp_types from mcp.shared.message import SessionMessage from pydantic import ValidationError from websockets.asyncio.client import connect as ws_connect from websockets.typing import Subprotocol read_stream_writer, read_stream = anyio.create_memory_object_stream(0) write_stream, write_stream_reader = anyio.create_memory_object_stream(0) async with ws_connect( url, subprotocols=[Subprotocol('mcp')], additional_headers=dict(headers), proxy=None, ) as websocket: async def ws_reader(): async with read_stream_writer: async for raw_text in websocket: try: message = mcp_types.JSONRPCMessage.model_validate_json(raw_text) await read_stream_writer.send(SessionMessage(message)) except ValidationError as exc: # pragma: no cover - upstream parity await read_stream_writer.send(exc) async def ws_writer(): async with write_stream_reader: async for session_message in write_stream_reader: payload = session_message.message.model_dump( by_alias=True, mode='json', exclude_none=True, ) await websocket.send(json.dumps(payload)) async with anyio.create_task_group() as task_group: task_group.start_soon(ws_reader) task_group.start_soon(ws_writer) yield read_stream, write_stream task_group.cancel_scope.cancel() class _TransferredStack: """Adapts an already-populated AsyncExitStack into an async context manager so ownership of its resources can be transferred into another exit stack. Entering is a no-op; exiting closes the wrapped stack (and thus the live WS transport + ClientSession) when the owning session shuts down.""" def __init__(self, stack: AsyncExitStack): self._stack = stack async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self._stack.aclose() return False class _ColdStartRetry(Exception): """Signal: the managed process is alive but not yet answering the MCP handshake because it is still cold-starting (e.g. `npx -y ` is still installing). The outer lifecycle retry treats this like a transient reconnect: it reuses the live process and does not count toward the fatal retry budget, so a slow cold start is waited out rather than failing. """ class BoxStdioSessionRuntime: """Encapsulate Box-backed stdio MCP session orchestration.""" def __init__(self, owner: RuntimeMCPSession): self.owner = owner self.config = MCPServerBoxConfig.model_validate(owner.server_config.get('box', {})) @property def ap(self): return self.owner.ap @property def server_name(self) -> str: return self.owner.server_name @property def server_config(self) -> dict: return self.owner.server_config def _build_workspace( self, *, workdir: str = '/workspace', ) -> BoxWorkspaceSession: session_id = self.owner._build_box_session_id() return BoxWorkspaceSession( self.ap.box_service, self.owner.execution_context, session_id, selected_backend=self.owner.sandbox_backend, selected_e2b_config=self.owner.sandbox_e2b_config, selected_limits=getattr(self.owner, 'sandbox_limits', None), workdir=workdir, env=self.config.env, network=self.config.network, read_only_rootfs=self.config.read_only_rootfs if self.config.read_only_rootfs is not None else False, image=self.config.image, cpus=self.config.cpus, # Node.js runtimes (npx/bunx) reserve large virtual address space and # load WebAssembly modules (llhttp) on startup; the default 512 MB # cgroup_mem_max is too small and causes OOM kills (return_code=137). # Per-server override wins; global default comes from # config.yaml box.default_memory_mb (env: BOX__DEFAULT_MEMORY_MB). memory_mb=(self.config.memory_mb or _get_default_memory_mb(self.ap)), pids_limit=self.config.pids_limit, persistent=True, ) @property def process_id(self) -> str: """Each MCP server gets a unique process_id within the shared session.""" task_id = self.owner.server_config.get('_sandbox_task_id') return f'{self.owner.server_uuid}-{task_id}' if task_id else self.owner.server_uuid def uses_box_stdio(self) -> bool: if self.server_config.get('mode') != 'stdio': return False box_service = getattr(self.ap, 'box_service', None) if box_service is None: return False # Transport selection follows operator intent, not momentary health. # An enabled Box may be reconnecting; initialize() waits for it instead # of falling through to unsandboxed host stdio or exhausting retries. return bool(getattr(box_service, 'enabled', True)) async def initialize(self) -> None: if str(self.config.host_path or '').strip(): self.owner.error_phase = MCPSessionErrorPhase.CONFIG_ERROR raise ValueError( f"MCP server '{self.server_name}' configures box.host_path, which is no longer " 'supported in network-only Box mode. Remove box.host_path and use a package-based ' 'stdio command (for example npx or uvx) or a remote HTTP/SSE MCP server.' ) await self._wait_for_box_runtime() if ( self.owner.sandbox_backend is None or self.owner.sandbox_limits is None or self.owner.sandbox_e2b_config is None ): selection = await self.ap.box_service.resolve_workspace_selection(self.owner.execution_context) self.owner.sandbox_backend = self.owner.sandbox_backend or selection['backend'] if getattr(self.owner, 'sandbox_limits', None) is None: self.owner.sandbox_limits = selection.get('limits', {}) if self.owner.sandbox_e2b_config is None: self.owner.sandbox_e2b_config = selection['e2b'] workspace = self._build_workspace() process_cwd = '/workspace' try: await workspace.create_session() except Exception: self.owner.error_phase = MCPSessionErrorPhase.SESSION_CREATE raise # Reuse an already-running managed process instead of rebuilding it. # The Box runtime keeps the managed process alive across a transient # WebSocket transport drop, so on a reconnect we only need to re-attach # the WS below. if not await self._managed_process_is_running(): try: payload = workspace.build_process_payload( self.server_config['command'], self.server_config.get('args', []), env=self.server_config.get('env', {}), cwd=process_cwd, ) payload['process_id'] = self.process_id await workspace.box_service.start_managed_process( workspace.execution_context, workspace.session_id, payload, ) except Exception: self.owner.error_phase = MCPSessionErrorPhase.PROCESS_START raise else: self.ap.logger.info( f'MCP server {self.server_name}: reusing live managed process ' f'process_id={self.process_id} (transport reconnect)' ) ( websocket_url, websocket_headers, ) = await workspace.get_managed_process_websocket_connection(self.process_id) # Attach the WS transport + MCP session ONCE, on the owner's exit stack, # in the same task as the serve loop that follows. websocket_client and # ClientSession use anyio task groups whose cancel scope is bound to the # frame/stack that entered them, so they must live on the owner exit # stack (not a deferred/transferred one) or the streams close the moment # initialize() returns and the next request fails with "Connection # closed". # # A slow (`npx -y `) cold start makes this single attempt fail # while the process is still alive — the package is still installing and # cannot answer the handshake. We surface that to the outer retry loop # as a _ColdStartRetry: it must NOT stop the process (it is healthy and # will be reused) and must NOT consume the fatal retry budget. The next # attempt re-attaches to the same live process; once it has finished # cold start the handshake succeeds and stays healthy. try: transport_context = ( authenticated_websocket_client(websocket_url, websocket_headers) if websocket_headers else websocket_client(websocket_url) ) transport = await self.owner.exit_stack.enter_async_context(transport_context) read_stream, write_stream = transport self.owner.session = await self.owner.exit_stack.enter_async_context( ClientSession(read_stream, write_stream) ) except Exception: self.owner.error_phase = MCPSessionErrorPhase.RELAY_CONNECT if not await self._managed_process_has_exited(): # Process is alive but not yet serving (cold start) — reconnect. raise _ColdStartRetry(f'{self.server_name}: transport not ready during cold start') raise try: await asyncio.wait_for(self.owner.session.initialize(), timeout=_HANDSHAKE_ATTEMPT_TIMEOUT_SEC) except Exception as exc: self.owner.error_phase = MCPSessionErrorPhase.MCP_INIT if not await self._managed_process_has_exited(): raise _ColdStartRetry( f'{self.server_name}: handshake not ready during cold start ({type(exc).__name__})' ) raise async def monitor_process_health(self) -> None: from langbot_plugin.box.models import BoxManagedProcessStatus workspace = self._build_workspace() consecutive_errors = 0 while not self.owner._shutdown_event.is_set(): try: info = await workspace.get_managed_process(self.process_id) if isinstance(info, dict): status = info.get('status', '') else: status = getattr(info, 'status', '') if status == BoxManagedProcessStatus.EXITED.value or status == BoxManagedProcessStatus.EXITED: return consecutive_errors = 0 except Exception as exc: consecutive_errors += 1 self.ap.logger.warning( f'MCP monitor for {self.server_name}: get_managed_process failed ' f'({consecutive_errors}/{self.owner._MONITOR_MAX_CONSECUTIVE_ERRORS}): ' f'{type(exc).__name__}: {exc}' ) if consecutive_errors >= self.owner._MONITOR_MAX_CONSECUTIVE_ERRORS: return # Capture stderr logs from the managed process if isinstance(info, dict): stderr_text = info.get('stderr', '') or info.get('stderr_preview', '') else: stderr_text = getattr(info, 'stderr', '') or getattr(info, 'stderr_preview', '') if stderr_text and stderr_text != self.owner._last_stderr_text: # Find new lines not in the previous snapshot old_lines = set(self.owner._last_stderr_text.splitlines()) if self.owner._last_stderr_text else set() new_lines = [l for l in stderr_text.splitlines() if l and l not in old_lines] self.owner._last_stderr_text = stderr_text import time as _time for line in new_lines: level = ( 'error' if any(k in line.upper() for k in ('ERROR', 'CRITICAL')) else 'warning' if 'WARNING' in line.upper() else 'debug' if 'DEBUG' in line.upper() else 'info' ) self.owner._log_buffer.append({'ts': _time.time(), 'level': level, 'text': line}) await asyncio.sleep(self.owner._MONITOR_POLL_INTERVAL) async def _managed_process_is_running(self) -> bool: """Return True if this server's managed process exists and is running. Used to decide whether initialize() must (re)start the process or can simply re-attach the WebSocket transport to a process the Box runtime kept alive across a transient transport drop. """ from langbot_plugin.box.models import BoxManagedProcessStatus workspace = self._build_workspace() try: info = await workspace.get_managed_process(self.process_id) except Exception: return False status = info.get('status', '') if isinstance(info, dict) else getattr(info, 'status', '') return status in (BoxManagedProcessStatus.RUNNING.value, BoxManagedProcessStatus.RUNNING) async def _managed_process_has_exited(self) -> bool: """Return True only if the process is DEFINITIVELY gone (reports EXITED). Distinct from ``not _managed_process_is_running()``: a process that has just been spawned may not yet report RUNNING, and a transient query error is not proof of exit. During the cold-start handshake retry we must NOT treat 'not yet running' or 'query failed' as a terminal failure, or we bail out to the outer rebuild path and churn the process (relay then rejects the early re-attach with HTTP 400). Only a successful query that reports EXITED stops the retry loop. """ from langbot_plugin.box.models import BoxManagedProcessStatus workspace = self._build_workspace() try: info = await workspace.get_managed_process(self.process_id) except Exception: # Unknown — treat as 'still coming up', not exited. return False status = info.get('status', '') if isinstance(info, dict) else getattr(info, 'status', '') return status in (BoxManagedProcessStatus.EXITED.value, BoxManagedProcessStatus.EXITED) async def _wait_for_box_runtime(self) -> None: timeout_sec = max(float(self.config.startup_timeout_sec or 120), 1.0) deadline = asyncio.get_running_loop().time() + timeout_sec warned = False while not getattr(self.ap.box_service, 'available', False): if not warned: self.ap.logger.warning( f'MCP server {self.server_name}: waiting for Box runtime before starting stdio process' ) warned = True if asyncio.get_running_loop().time() >= deadline: self.owner.error_phase = MCPSessionErrorPhase.BOX_UNAVAILABLE raise Exception(f'Box runtime is not available after {int(timeout_sec)} seconds') await asyncio.sleep(1) async def cleanup_session(self) -> None: if not self.uses_box_stdio(): return workspace = self._build_workspace() # Transient config-page tests share the same 'mcp-shared' Box session as # live servers; stop only this process_id so live servers stay running. if getattr(self.owner, 'is_transient', False): try: await workspace.stop_managed_process(self.process_id) except Exception as exc: self.ap.logger.warning( f'MCP server {self.server_name}: failed to stop transient test process ' f'process_id={self.process_id}: {type(exc).__name__}: {exc}' ) return # In the shared-session model, we do not delete the session itself. # Stop only this MCP server's managed process; deleting the session # would kill other MCP servers sharing the same container. try: await workspace.stop_managed_process(self.process_id) except Exception as exc: self.ap.logger.warning( f'MCP server {self.server_name}: failed to stop managed process ' f'process_id={self.process_id}: {type(exc).__name__}: {exc}' ) return self.ap.logger.info( f'MCP server {self.server_name}: stopped process_id={self.process_id} ' f'(shared session {self.owner._build_box_session_id()} kept alive)' ) def build_box_session_payload(self, session_id: str) -> dict[str, Any]: workspace = self._build_workspace() workspace.session_id = session_id return workspace.build_session_payload() def build_box_process_payload(self) -> dict[str, Any]: workspace = self._build_workspace() return workspace.build_process_payload( self.server_config['command'], self.server_config.get('args', []), env=self.server_config.get('env', {}), )