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
Snapshot document and outputs in MCP execute_code (#9654)
Trevor Manz907609593329
diff --git a/marimo/_mcp/code_server/main.py b/marimo/_mcp/code_server/main.pyindex f2e0ed7b69..56d170e975 100644--- a/marimo/_mcp/code_server/main.py+++ b/marimo/_mcp/code_server/main.py@@ -23,6 +23,7 @@ from marimo._server.scratchpad import (EXECUTION_TIMEOUT,ScratchCellListener,extract_result,+ snapshot_for_scratchpad,)from marimo._types.ids import SessionId@@ -131,8 +132,14 @@ def setup_code_mcp_server(listener = ScratchCellListener(run_id=run_id)with session.scoped(listener):async with session.scratchpad_lock:+ notebook_cells, cell_outputs = snapshot_for_scratchpad(session)session.put_control_request(- ExecuteScratchpadCommand(code=code, run_id=run_id),+ ExecuteScratchpadCommand(+ code=code,+ notebook_cells=notebook_cells,+ cell_outputs=cell_outputs,+ run_id=run_id,+ ),from_consumer_id=None,)await listener.wait(timeout=EXECUTION_TIMEOUT)diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 7117ca968a..ac25c3e7fa 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -9,7 +9,6 @@ from starlette.authentication import requiresfrom starlette.responses import JSONResponse, StreamingResponsefrom marimo import _loggers-from marimo._messaging.notebook.outputs import CellOutputsfrom marimo._messaging.notification import AlertNotificationfrom marimo._runtime.commands import HTTPRequest, UpdateUIElementCommandfrom marimo._server.api.deps import AppState@@ -274,6 +273,7 @@ async def execute_code(from marimo._server.scratchpad import (ScratchCellListener,build_done_event,+ snapshot_for_scratchpad,)app_state = AppState(request)@@ -326,20 +326,14 @@ async def execute_code(http_req.meta["screenshot_server_url"] = (f"{scheme}://{app_state.host}:{app_state.port}{base_url}")- cell_ids = session.document.cell_ids- cell_outputs = CellOutputs(- output=session.session_view.get_cell_outputs(cell_ids),- console_outputs=(- session.session_view.get_cell_console_outputs(- cell_ids- )- ),+ notebook_cells, cell_outputs = snapshot_for_scratchpad(+ session)session.put_control_request(ExecuteScratchpadCommand(code=body.code,request=http_req,- notebook_cells=tuple(session.document.cells),+ notebook_cells=notebook_cells,cell_outputs=cell_outputs,run_id=run_id,),diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.pyindex 4c9ecf1cc1..5d0bedd569 100644--- a/marimo/_server/scratchpad.py+++ b/marimo/_server/scratchpad.py@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, TypedDictfrom marimo._ai._tools.types import CodeExecutionResultfrom marimo._messaging.cell_output import CellChannel+from marimo._messaging.notebook.outputs import CellOutputsfrom marimo._messaging.notification import (CellNotification,CompletedRunNotification,@@ -20,6 +21,7 @@ from marimo._session.extensions.types import EventAwareExtensionif TYPE_CHECKING:from collections.abc import AsyncGenerator+ from marimo._messaging.notebook.document import NotebookCellfrom marimo._messaging.types import KernelMessagefrom marimo._session.session import Session@@ -186,6 +188,26 @@ class ScratchCellListener(EventAwareExtension):# -- Helpers ------------------------------------------------------------------+def snapshot_for_scratchpad(+ session: Session,+) -> tuple[tuple[NotebookCell, ...], CellOutputs]:+ """Snapshot the notebook document and per-cell outputs for code_mode.++ Returned by both `/api/execute` and the MCP `execute_code` tool+ and passed on `ExecuteScratchpadCommand` so `cm.get_context()`+ can expose cells and their last outputs.+ """+ cell_ids = session.document.cell_ids+ notebook_cells = tuple(session.document.cells)+ cell_outputs = CellOutputs(+ output=session.session_view.get_cell_outputs(cell_ids),+ console_outputs=session.session_view.get_cell_console_outputs(+ cell_ids+ ),+ )+ return notebook_cells, cell_outputs++def _format_console(msg: CellNotification) -> list[str]:"""Extract SSE-formatted stdout/stderr events from a CellNotification."""if msg.console is None:diff --git a/tests/_server/test_scratchpad.py b/tests/_server/test_scratchpad.pyindex 4e1647b319..2231143b03 100644--- a/tests/_server/test_scratchpad.py+++ b/tests/_server/test_scratchpad.py@@ -21,6 +21,7 @@ from marimo._server.scratchpad import (_format_sse,build_done_event,extract_result,+ snapshot_for_scratchpad,)_TEST_RUN_ID = "test-run-id"@@ -52,6 +53,41 @@ def _parse_sse(sse: str) -> tuple[str, dict[str, object]]:return event, json.loads(data)+class TestSnapshotForScratchpad:+ """Snapshot helper shared by `/api/execute` and MCP `execute_code`."""++ def test_packages_document_and_outputs(self) -> None:+ from marimo._ast.cell import CellConfig+ from marimo._messaging.notebook.document import (+ NotebookCell as DocCell,+ )+ from marimo._types.ids import CellId_t++ cell = DocCell(+ id=CellId_t("a"),+ code="print('hi'); x = 1",+ name="",+ config=CellConfig(),+ )+ output = CellOutput(+ channel=CellChannel.OUTPUT, mimetype="text/plain", data="1"+ )+ console = [CellOutput.stdout("hi\n")]++ session = MagicMock()+ session.document.cells = (cell,)+ session.document.cell_ids = (cell.id,)+ session.session_view.get_cell_outputs.return_value = {cell.id: output}+ session.session_view.get_cell_console_outputs.return_value = {+ cell.id: console+ }++ notebook_cells, cell_outputs = snapshot_for_scratchpad(session)+ assert notebook_cells == (cell,)+ assert cell_outputs.output == snapshot({"a": output})+ assert cell_outputs.console_outputs == snapshot({"a": console})++class TestExtractResult:def test_no_notification(self) -> None:result = extract_result(_make_session())