A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add experimental code-mode MCP server (#8477)
Trevor Manz9ed50d6e40ec
diff --git a/marimo/_ai/_tools/types.py b/marimo/_ai/_tools/types.pyindex b1fe4ecda1..082522eed1 100644--- a/marimo/_ai/_tools/types.py+++ b/marimo/_ai/_tools/types.py@@ -61,3 +61,18 @@ class MarimoErrorDetail:class MarimoCellConsoleOutputs:stdout: list[str] = field(default_factory=list)stderr: list[str] = field(default_factory=list)+++@dataclass+class ListSessionsResult:+ sessions: list[MarimoNotebookInfo] = field(default_factory=list)+++@dataclass+class CodeExecutionResult:+ success: bool+ output: Optional[str] = None+ stdout: list[str] = field(default_factory=list)+ stderr: list[str] = field(default_factory=list)+ errors: list[str] = field(default_factory=list)+ error: Optional[str] = Nonediff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 61afb73a96..4c02585b19 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -42,6 +42,7 @@ from marimo._cli.utils import ()from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._lint import run_check+from marimo._mcp.setup import McpTypefrom marimo._server.file_router import (AppFileRouter,LazyListOfFilesAppFileRouter,@@ -257,6 +258,24 @@ edit_help_msg = "\n".join()+class _OptionalValueOption(click.Option):+ """A click Option that supports an optional value.++ Works around a regression in click 8.3.x where the documented+ ``is_flag=False, flag_value=...`` pattern is broken.+ See: https://github.com/pallets/click/issues/3084+ """++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ opt_flag_value = kwargs.pop("flag_value", None)+ kwargs.setdefault("default", None)+ kwargs["is_flag"] = False+ super().__init__(*args, **kwargs)+ self._flag_needs_value = True+ if opt_flag_value is not None:+ self.flag_value = opt_flag_value++@main.command(help=edit_help_msg)@click.option("-p",@@ -368,11 +387,12 @@ edit_help_msg = "\n".join()@click.option("--mcp",- is_flag=True,- default=False,- type=bool,+ cls=_OptionalValueOption,+ flag_value="tools",+ default=None,+ type=click.Choice(["tools", "code-mode"]),hidden=True,- help="Enable MCP server endpoint at /mcp/server for LLM integration.",+ help="Enable MCP server endpoint.",)@click.option("--mcp-allow-remote",@@ -433,7 +453,7 @@ def edit(skew_protection: bool,remote_url: Optional[str],convert: bool,- mcp: bool,+ mcp: Optional[McpType],mcp_allow_remote: bool,server_startup_command: Optional[str],asset_url: Optional[str],diff --git a/marimo/_mcp/code_server/__init__.py b/marimo/_mcp/code_server/__init__.pynew file mode 100644index 0000000000..fe2d2e388e--- /dev/null+++ b/marimo/_mcp/code_server/__init__.py@@ -0,0 +1 @@+# Copyright 2026 Marimo. All rights reserved.diff --git a/marimo/_mcp/code_server/lifespan.py b/marimo/_mcp/code_server/lifespan.pynew file mode 100644index 0000000000..a439fe68eb--- /dev/null+++ b/marimo/_mcp/code_server/lifespan.py@@ -0,0 +1,39 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import contextlib+from typing import TYPE_CHECKING++from marimo._loggers import marimo_logger++LOGGER = marimo_logger()++if TYPE_CHECKING:+ from collections.abc import AsyncIterator++ from starlette.applications import Starlette+++async def code_mcp_server_lifespan(app: Starlette) -> AsyncIterator[None]:+ """Lifespan for Code Mode MCP server functionality."""++ try:+ code_mcp_app = getattr(app.state, "code_mcp", None)+ if code_mcp_app is None:+ LOGGER.warning("Code MCP server not found in app state")+ yield+ return++ async with code_mcp_app.session_manager.run():+ LOGGER.info("Code MCP server session manager started")+ yield++ except ImportError as e:+ LOGGER.warning(f"Code MCP server dependencies not available: {e}")+ yield+ return+ except Exception as e:+ LOGGER.error(f"Failed to start Code MCP server: {e}")+ yield+ returndiff --git a/marimo/_mcp/code_server/main.py b/marimo/_mcp/code_server/main.pynew file mode 100644index 0000000000..3ad63e4f64--- /dev/null+++ b/marimo/_mcp/code_server/main.py@@ -0,0 +1,272 @@+# Copyright 2026 Marimo. All rights reserved.+"""+Code Mode MCP Server for Marimo++A minimal MCP server that lets external AI agents execute Python code+in a running marimo kernel via the scratchpad.+"""++from __future__ import annotations++import asyncio+import os+from typing import TYPE_CHECKING, Any++from marimo._ai._tools.types import (+ CodeExecutionResult,+ ListSessionsResult,+ MarimoNotebookInfo,+)+from marimo._dependencies.dependencies import DependencyManager+from marimo._loggers import marimo_logger+from marimo._messaging.cell_output import CellChannel+from marimo._messaging.notification import CellNotification+from marimo._messaging.serde import deserialize_kernel_message+from marimo._runtime.scratch import SCRATCH_CELL_ID+from marimo._session.events import SessionEventBus, SessionEventListener+from marimo._types.ids import SessionId++LOGGER = marimo_logger()++if TYPE_CHECKING:+ from starlette.applications import Starlette+ from starlette.types import Receive, Scope, Send++ from marimo._messaging.types import KernelMessage+ from marimo._session.session import Session++_EXECUTION_TIMEOUT = 30.0 # seconds+++class _ScratchCellListener(SessionEventListener):+ """Listens for scratch cell idle notifications and signals waiters.++ Implements SessionExtension so it can be dynamically attached to a+ session via session.attach_extension / session.detach_extension.+ """++ def __init__(self) -> None:+ self._waiters: dict[str, asyncio.Event] = {}++ def wait_for(self, session_id: str) -> asyncio.Event:+ event = asyncio.Event()+ self._waiters[session_id] = event+ return event++ # SessionExtension protocol+ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:+ del session+ event_bus.subscribe(self)++ def on_detach(self) -> None:+ pass++ def on_notification_sent(+ self, session: Session, notification: KernelMessage+ ) -> None:+ del session+ msg = deserialize_kernel_message(notification)+ if not isinstance(msg, CellNotification):+ return+ if msg.cell_id != SCRATCH_CELL_ID:+ return+ if msg.status != "idle":+ return+ # Signal any waiter for this session+ for sid, event in list(self._waiters.items()):+ if not event.is_set():+ event.set()+ del self._waiters[sid]+++def setup_code_mcp_server(+ app: Starlette, *, allow_remote: bool = False+) -> None:+ """Create and configure the Code Mode MCP server.++ Mounts at /mcp with a single /server streamable HTTP endpoint.+ Exposes two tools: `list_sessions` and `execute_code`.++ Args:+ app: Starlette application instance for accessing marimo state+ allow_remote: If True, disable DNS rebinding protection to allow remote access behind proxies.+ """+ if not DependencyManager.mcp.has():+ from click import ClickException++ msg = "MCP dependencies not available. Install with `pip install marimo[mcp]` or `uv add marimo[mcp]`"+ raise ClickException(msg)++ from mcp.server.fastmcp import FastMCP+ from starlette.middleware.base import BaseHTTPMiddleware+ from starlette.responses import JSONResponse+ from starlette.routing import Mount++ from marimo._runtime.commands import ExecuteScratchpadCommand+ from marimo._server.api.deps import AppStateBase+ from marimo._session.model import ConnectionState++ transport_security = None+ if allow_remote:+ from mcp.server.transport_security import TransportSecuritySettings++ transport_security = TransportSecuritySettings(+ enable_dns_rebinding_protection=False,+ )++ mcp = FastMCP(+ "marimo-code-mcp",+ stateless_http=True,+ log_level="WARNING",+ streamable_http_path="/server",+ transport_security=transport_security,+ )++ # Per-session locks to prevent overlapping scratchpad executions+ session_locks: dict[str, asyncio.Lock] = {}+ listener = _ScratchCellListener()++ @mcp.tool()+ async def list_sessions() -> ListSessionsResult:+ """List active marimo sessions.++ Returns a list of active sessions, each with 'name', 'path',+ and 'session_id' fields.+ Use the session_id with execute_code to run code in that session.+ """+ state = AppStateBase.from_app(app)+ session_manager = state.session_manager++ sessions: list[MarimoNotebookInfo] = []+ for session_id, session in session_manager.sessions.items():+ conn_state = session.connection_state()+ if conn_state in (ConnectionState.OPEN, ConnectionState.ORPHANED):+ full_path = session.app_file_manager.path+ filename = session.app_file_manager.filename+ basename = os.path.basename(filename) if filename else None+ sessions.append(+ MarimoNotebookInfo(+ name=basename or "new notebook",+ path=full_path or "(unsaved notebook)",+ session_id=SessionId(session_id),+ )+ )++ return ListSessionsResult(sessions=sessions[::-1])++ @mcp.tool()+ async def execute_code(session_id: str, code: str) -> CodeExecutionResult:+ """Execute Python code in a notebook's kernel scratchpad.++ The code runs in the scratchpad — a temporary execution environment+ that has access to all variables defined in the notebook but does not+ affect the notebook's cells or dependency graph.++ Args:+ session_id: The session ID of the notebook (from list_sessions).+ code: Python code to execute.+ """+ state = AppStateBase.from_app(app)+ session = state.session_manager.get_session(SessionId(session_id))++ if session is None:+ return CodeExecutionResult(+ success=False,+ error=f"Session '{session_id}' not found. "+ "Use list_sessions to find valid session IDs.",+ )++ # Attach listener as a session extension+ session.attach_extension(listener)++ lock = session_locks.setdefault(session_id, asyncio.Lock())+ async with lock:+ try:+ # Set up event before sending command+ done = listener.wait_for(session_id)++ # Send the scratchpad execution command+ session.put_control_request(+ ExecuteScratchpadCommand(code=code),+ from_consumer_id=None,+ )++ # Wait for the scratch cell to become idle+ await asyncio.wait_for(done.wait(), timeout=_EXECUTION_TIMEOUT)+ except asyncio.TimeoutError:+ return CodeExecutionResult(+ success=False,+ error=f"Execution timed out after {_EXECUTION_TIMEOUT}s",+ )+ finally:+ session.detach_extension(listener)++ return _extract_result(session)++ # Build the streamable HTTP app+ mcp_app = mcp.streamable_http_app()++ class RequiresEditMiddleware(BaseHTTPMiddleware):+ async def __call__(+ self, scope: Scope, receive: Receive, send: Send+ ) -> None:+ auth = scope.get("auth")+ if auth is None or "edit" not in auth.scopes:+ response = JSONResponse(+ {"detail": "Forbidden"}, status_code=403+ )+ return await response(scope, receive, send)+ return await self.app(scope, receive, send)++ mcp_app.add_middleware(RequiresEditMiddleware)++ app.routes.insert(0, Mount("/mcp", mcp_app))+ app.state.code_mcp = mcp+++def _extract_result(session: Any) -> CodeExecutionResult:+ """Read the scratch cell's final state from the session view."""+ cell_notif = session.session_view.cell_notifications.get(SCRATCH_CELL_ID)+ if cell_notif is None:+ return CodeExecutionResult(success=True)++ # Output+ output_data = None+ if cell_notif.output is not None:+ data = cell_notif.output.data+ if isinstance(data, str):+ output_data = data+ elif isinstance(data, dict):+ output_data = data.get(+ "text/plain", data.get("text/html", str(data))+ )+ # list → errors, handled below++ # Console+ stdout: list[str] = []+ stderr: list[str] = []+ for out in (+ cell_notif.console if isinstance(cell_notif.console, list) else []+ ):+ if out is None:+ continue+ if out.channel == CellChannel.STDOUT:+ stdout.append(str(out.data))+ elif out.channel == CellChannel.STDERR:+ stderr.append(str(out.data))++ # Errors+ errors: list[str] = []+ if cell_notif.output is not None and isinstance(+ cell_notif.output.data, list+ ):+ for err in cell_notif.output.data:+ errors.append(str(getattr(err, "msg", None) or err))++ return CodeExecutionResult(+ success=len(errors) == 0,+ output=output_data,+ stdout=stdout,+ stderr=stderr,+ errors=errors,+ )diff --git a/marimo/_mcp/setup.py b/marimo/_mcp/setup.pynew file mode 100644index 0000000000..23d19bf7c9--- /dev/null+++ b/marimo/_mcp/setup.py@@ -0,0 +1,36 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Literal++from marimo._types.lifespan import Lifespan++McpType = Literal["tools", "code-mode"]++if TYPE_CHECKING:+ from starlette.applications import Starlette+++def setup_mcp_server(+ app: Starlette, mode: McpType, *, allow_remote: bool = False+) -> Lifespan[Starlette]:+ """Set up the MCP server for the given mode.++ Returns the corresponding lifespan context manager that must be+ included in the application's lifespan chain.+ """+ if mode == "tools":+ from marimo._mcp.server.lifespan import mcp_server_lifespan+ from marimo._mcp.server.main import setup_mcp_server as _setup_tools++ _setup_tools(app, allow_remote=allow_remote)+ return mcp_server_lifespan+ elif mode == "code-mode":+ from marimo._mcp.code_server.lifespan import code_mcp_server_lifespan+ from marimo._mcp.code_server.main import (+ setup_code_mcp_server as _setup_code,+ )++ _setup_code(app, allow_remote=allow_remote)+ return code_mcp_server_lifespan+ raise ValueError(f"Unknown MCP mode: {mode}")diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex c30329331b..935cbec0e5 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -9,14 +9,14 @@ from typing import Optionalimport uvicorn-import marimo._server.api.lifespans as lifespansfrom marimo._cli.print import echofrom marimo._cli.sandbox import SandboxModefrom marimo._config.manager import get_default_config_managerfrom marimo._config.settings import GLOBAL_SETTINGS-from marimo._mcp.server.main import setup_mcp_server+from marimo._mcp.setup import McpType, setup_mcp_serverfrom marimo._messaging.notification import StartupLogsNotificationfrom marimo._runtime.commands import SerializedCLIArgs+from marimo._server.api import lifespansfrom marimo._server.config import (StarletteServerStateInit,)@@ -177,7 +177,7 @@ def start(redirect_console_to_browser: bool,skew_protection: bool,remote_url: Optional[str] = None,- mcp: bool = False,+ mcp: McpType | None = None,mcp_allow_remote: bool = False,server_startup_command: Optional[str] = None,asset_url: Optional[str] = None,@@ -277,12 +277,7 @@ def start(*LIFESPAN_REGISTRY.get_all(),]- mcp_enabled = mcp and mode == SessionMode.EDIT-- if mcp_enabled:- from marimo._mcp.server.lifespan import mcp_server_lifespan-- lifespans_list.append(mcp_server_lifespan)+ mcp_enabled = mcp is not None and mode == SessionMode.EDIT(external_port, external_host) = _resolve_proxy(port, host, proxy)enable_auth = not AuthToken.is_empty(session_manager.auth_token)@@ -299,8 +294,13 @@ def start(timeout=timeout,)- if mcp_enabled:- setup_mcp_server(app, allow_remote=mcp_allow_remote)+ if mcp_enabled and mcp is not None:+ # setup_mcp_server returns the lifespan for the chosen mode;+ # appending it to lifespans_list works because Lifespans stores+ # a reference to the list and iterates it at startup time.+ lifespans_list.append(+ setup_mcp_server(app, mcp, allow_remote=mcp_allow_remote)+ )init_state = StarletteServerStateInit(port=external_port,@@ -312,7 +312,7 @@ def start(session_manager=session_manager,config_manager=config_reader,remote_url=remote_url,- mcp_server_enabled=mcp,+ mcp_server_enabled=mcp_enabled,skew_protection=skew_protection,enable_auth=enable_auth,)diff --git a/marimo/_session/session.py b/marimo/_session/session.pyindex 4ba3c60e2f..a733b0af95 100644--- a/marimo/_session/session.py+++ b/marimo/_session/session.py@@ -228,6 +228,17 @@ class SessionImpl(Session):)continue+ def attach_extension(self, extension: SessionExtension) -> None:+ """Dynamically attach an extension to the session."""+ self.extensions.append(extension)+ extension.on_attach(self, self._event_bus)++ def detach_extension(self, extension: SessionExtension) -> None:+ """Dynamically detach an extension from the session."""+ extension.on_detach()+ if extension in self.extensions:+ self.extensions.remove(extension)+@propertydef consumers(self) -> Mapping[SessionConsumer, ConsumerId]:"""Get the consumers in the session."""diff --git a/marimo/_session/types.py b/marimo/_session/types.pyindex d224d14a32..26ad5c0f2e 100644--- a/marimo/_session/types.py+++ b/marimo/_session/types.py@@ -20,6 +20,7 @@ if TYPE_CHECKING:from marimo._messaging.types import KernelMessagefrom marimo._runtime import commandsfrom marimo._session.consumer import SessionConsumer+ from marimo._session.extensions.types import SessionExtensionfrom marimo._session.model import (ConnectionState,SessionMode,@@ -181,6 +182,14 @@ class Session(Protocol):"""Instantiate the app."""...+ def attach_extension(self, extension: SessionExtension) -> None:+ """Dynamically attach an extension to the session."""+ ...++ def detach_extension(self, extension: SessionExtension) -> None:+ """Dynamically detach an extension from the session."""+ ...+def close(self) -> None:"""Close the session."""...diff --git a/tests/_mcp/code_server/test_code_server.py b/tests/_mcp/code_server/test_code_server.pynew file mode 100644index 0000000000..025c469e04--- /dev/null+++ b/tests/_mcp/code_server/test_code_server.py@@ -0,0 +1,281 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from unittest.mock import MagicMock++import pytest++from marimo._mcp.code_server.lifespan import code_mcp_server_lifespan++pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++from typing import TYPE_CHECKING++from starlette.applications import Starlette+from starlette.authentication import AuthCredentials, SimpleUser+from starlette.middleware import Middleware+from starlette.middleware.authentication import AuthenticationMiddleware+from starlette.testclient import TestClient++from marimo._mcp.code_server.main import setup_code_mcp_server+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.notification import CellNotification+from marimo._runtime.scratch import SCRATCH_CELL_ID+from marimo._server.api.middleware import AuthBackend+from marimo._session.model import ConnectionState+from tests._server.mocks import get_mock_session_manager++if TYPE_CHECKING:+ from starlette.requests import HTTPConnection+++def create_test_app() -> Starlette:+ """Create a test Starlette app with Code MCP server."""+ app = Starlette(+ middleware=[+ Middleware(+ AuthenticationMiddleware,+ backend=AuthBackend(should_authenticate=False),+ ),+ ],+ )+ app.state.session_manager = get_mock_session_manager()+ setup_code_mcp_server(app)+ return app+++def test_code_mcp_server_starts_up():+ """Test that Code MCP server can be set up and routes are registered."""+ app = create_test_app()++ assert hasattr(app.state, "code_mcp")+ assert any("/mcp" in str(route.path) for route in app.routes)+++async def test_code_mcp_server_requires_edit_scope():+ """Test that Code MCP server validates 'edit' scope is present."""++ class MockAuthBackendNoEdit:+ async def authenticate(self, conn: HTTPConnection):+ del conn+ return AuthCredentials(scopes=["read"]), SimpleUser("test_user")++ app_no_edit = Starlette(+ middleware=[+ Middleware(+ AuthenticationMiddleware,+ backend=MockAuthBackendNoEdit(),+ ),+ ],+ )+ app_no_edit.state.session_manager = get_mock_session_manager()+ setup_code_mcp_server(app_no_edit)++ client = TestClient(app_no_edit, raise_server_exceptions=False)+ response = client.get("/mcp/server")+ assert response.status_code == 403++ class MockAuthBackendWithEdit:+ async def authenticate(self, conn: HTTPConnection):+ del conn+ return AuthCredentials(scopes=["edit"]), SimpleUser("test_user")++ app_with_edit = Starlette(+ middleware=[+ Middleware(+ AuthenticationMiddleware,+ backend=MockAuthBackendWithEdit(),+ ),+ ],+ )+ setup_code_mcp_server(app_with_edit)+ async with code_mcp_server_lifespan(app_with_edit):+ app_with_edit.state.session_manager = get_mock_session_manager()+ client_with_edit = TestClient(app_with_edit)+ response = client_with_edit.get("/mcp/server")+ assert response.status_code != 403+++def _make_mock_session(+ *,+ filename: str = "/path/to/notebook.py",+ connection_state: ConnectionState = ConnectionState.OPEN,+) -> MagicMock:+ """Create a mock session for testing."""+ session = MagicMock()+ session.app_file_manager.path = filename+ session.app_file_manager.filename = filename+ session.connection_state.return_value = connection_state+ session.session_view = MagicMock()+ session.session_view.cell_notifications = {}+ return session+++def _make_idle_scratch_notification(+ *,+ output_data: str | None = None,+ stdout: list[str] | None = None,+ stderr: list[str] | None = None,+ errors: list[object] | None = None,+) -> CellNotification:+ """Create a CellNotification for the scratch cell in idle state."""+ output = None+ if output_data is not None:+ output = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data=output_data,+ )+ elif errors is not None:+ output = CellOutput(+ channel=CellChannel.MARIMO_ERROR,+ mimetype="application/vnd.marimo+error",+ data=errors,+ )++ console: list[CellOutput] = []+ for msg in stdout or []:+ console.append(+ CellOutput(+ channel=CellChannel.STDOUT, mimetype="text/plain", data=msg+ )+ )+ for msg in stderr or []:+ console.append(+ CellOutput(+ channel=CellChannel.STDERR, mimetype="text/plain", data=msg+ )+ )++ return CellNotification(+ cell_id=SCRATCH_CELL_ID,+ output=output,+ console=console if console else None,+ status="idle",+ )+++class TestGetActiveNotebooks:+ def test_no_sessions_returns_empty(self):+ """get_active_notebooks returns empty list with no sessions."""+ app = create_test_app()+ assert app.state.session_manager.sessions == {}++ def test_session_lookup(self):+ """Sessions injected into the repository can be looked up."""+ app = create_test_app()+ sm = app.state.session_manager++ mock_session = _make_mock_session(filename="/path/to/nb.py")+ sm._repository._sessions["s1"] = mock_session+ assert sm.get_session("s1") is mock_session+++class TestExecuteCode:+ async def test_session_not_found(self):+ """Session lookup returns None for missing sessions."""+ app = create_test_app()+ from marimo._server.api.deps import AppStateBase++ state = AppStateBase.from_app(app)+ assert state.session_manager.get_session("nonexistent") is None++ def test_scratchpad_command_dispatch(self):+ """put_control_request is called with ExecuteScratchpadCommand."""+ app = create_test_app()+ sm = app.state.session_manager++ mock_session = _make_mock_session()+ sm._repository._sessions["s1"] = mock_session++ from marimo._runtime.commands import ExecuteScratchpadCommand++ command = ExecuteScratchpadCommand(code="2 + 2")+ mock_session.put_control_request(command, from_consumer_id=None)+ mock_session.put_control_request.assert_called_once_with(+ command, from_consumer_id=None+ )++ def test_idle_notification_output_extraction(self):+ """Output data is extracted correctly from idle scratch notification."""+ notif = _make_idle_scratch_notification(output_data="4")+ assert notif.status == "idle"+ assert notif.output is not None+ assert notif.output.data == "4"++ def test_stdout_extraction(self):+ """Stdout messages are extracted from console outputs."""+ notif = _make_idle_scratch_notification(stdout=["hello\n"])+ assert notif.console is not None+ console_list = (+ notif.console+ if isinstance(notif.console, list)+ else [notif.console]+ )+ stdout_msgs = [+ str(o.data)+ for o in console_list+ if o.channel == CellChannel.STDOUT+ ]+ assert stdout_msgs == ["hello\n"]++ def test_stderr_extraction(self):+ """Stderr messages are extracted from console outputs."""+ notif = _make_idle_scratch_notification(+ output_data="ok", stderr=["warning: something\n"]+ )+ assert notif.console is not None+ console_list = (+ notif.console+ if isinstance(notif.console, list)+ else [notif.console]+ )+ stderr_msgs = [+ str(o.data)+ for o in console_list+ if o.channel == CellChannel.STDERR+ ]+ assert stderr_msgs == ["warning: something\n"]++ def test_error_extraction(self):+ """Errors are extracted from output data list."""+ mock_error = MagicMock()+ mock_error.msg = "NameError: name 'x' is not defined"+ notif = _make_idle_scratch_notification(errors=[mock_error])+ assert notif.output is not None+ assert isinstance(notif.output.data, list)+ assert len(notif.output.data) == 1++ def test_notification_set_after_command(self):+ """Simulates the full flow: command -> notification -> output."""+ app = create_test_app()+ sm = app.state.session_manager++ mock_session = _make_mock_session()+ sm._repository._sessions["s1"] = mock_session++ notif = _make_idle_scratch_notification(+ output_data="4", stdout=["debug\n"]+ )++ def set_notification(*args: object, **kwargs: object):+ del args+ del kwargs+ mock_session.session_view.cell_notifications = {+ SCRATCH_CELL_ID: notif+ }++ mock_session.put_control_request.side_effect = set_notification++ from marimo._runtime.commands import ExecuteScratchpadCommand++ command = ExecuteScratchpadCommand(code="2 + 2")+ mock_session.put_control_request(command, from_consumer_id=None)++ cell_notif = mock_session.session_view.cell_notifications.get(+ SCRATCH_CELL_ID+ )+ assert cell_notif is not None+ assert cell_notif.status == "idle"+ assert cell_notif.output is not None+ assert cell_notif.output.data == "4"