Skip to content

Commit e25bf9a

Browse files
committed
Snapshot document and outputs in MCP execute_code
Mirrors what `/api/execute` already does. `cm.get_context()` previously raised "NotebookDocument not available" when invoked from code run via the MCP tool, because `execute_code` didn't populate `notebook_cells` or `cell_outputs` on `ExecuteScratchpadCommand`.
1 parent 2ea7dcf commit e25bf9a

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

marimo/_mcp/code_server/main.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ def setup_code_mcp_server(
5656
from starlette.responses import JSONResponse
5757
from starlette.routing import Mount
5858

59+
from marimo._messaging.notebook.outputs import CellOutputs
5960
from marimo._runtime.commands import ExecuteScratchpadCommand
6061
from marimo._server.api.deps import AppStateBase
6162
from marimo._session.model import ConnectionState
@@ -131,8 +132,22 @@ async def execute_code(session_id: str, code: str) -> CodeExecutionResult:
131132
listener = ScratchCellListener(run_id=run_id)
132133
with session.scoped(listener):
133134
async with session.scratchpad_lock:
135+
# Snapshot document + outputs so code_mode (cm.get_context)
136+
# can read cells and their last outputs. Mirrors /api/execute.
137+
cell_ids = session.document.cell_ids
138+
cell_outputs = CellOutputs(
139+
output=session.session_view.get_cell_outputs(cell_ids),
140+
console_outputs=(
141+
session.session_view.get_cell_console_outputs(cell_ids)
142+
),
143+
)
134144
session.put_control_request(
135-
ExecuteScratchpadCommand(code=code, run_id=run_id),
145+
ExecuteScratchpadCommand(
146+
code=code,
147+
notebook_cells=tuple(session.document.cells),
148+
cell_outputs=cell_outputs,
149+
run_id=run_id,
150+
),
136151
from_consumer_id=None,
137152
)
138153
await listener.wait(timeout=EXECUTION_TIMEOUT)

0 commit comments

Comments
 (0)