Skip to content

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.

Bulk notebook state visibility for MCP tools (#8269)

Florian Verdonck9db72bd80165
diff --git a/docs/guides/editor_features/tools.md b/docs/guides/editor_features/tools.md
index 8bd4089255..c64cafe181 100644
--- a/docs/guides/editor_features/tools.md
+++ b/docs/guides/editor_features/tools.md
@@ -16,9 +16,9 @@ These tools are available when using the [chat panel in ask mode](ai_completion.
| Tool | Description |
|------|-------------|
| **get_active_notebooks** | List all currently active marimo notebooks. Returns summary statistics and notebook details including names, paths, and session IDs. Start here to discover which notebooks are available. |
-| **get_lightweight_cell_map** | Get an overview of notebook structure showing a preview of each cell. Takes a `session_id` and optional `preview_lines` parameter. Returns cell IDs, preview text, line counts, and cell types (code, markdown, SQL). |
-| **get_cell_runtime_data** | Get detailed runtime information for a specific cell. Takes `session_id` and `cell_id` parameters. Returns full cell code, error details, runtime metadata (execution time, runtime state), and variables defined by the cell. |
-| **get_cell_outputs** | Get execution output from a specific cell. Takes `session_id` and `cell_id` parameters. Returns visual output (HTML, charts, tables, etc.) with mimetype, stdout messages, and stderr messages. |
+| **get_lightweight_cell_map** | Get an overview of notebook structure showing a preview of each cell. Takes a `session_id` and optional `preview_lines` parameter. Returns cell IDs, preview text, line counts, cell types (code, markdown, SQL), runtime state (`idle`, `running`, `queued`, etc.), and `has_output`/`has_console_output` flags. |
+| **get_cell_runtime_data** | Get detailed runtime information for one or more cells. Takes `session_id` and `cell_ids` (list) parameters. Returns full cell code, error details, runtime metadata (execution time, runtime state), and variables defined by each cell. |
+| **get_cell_outputs** | Get execution output from one or more cells. Takes `session_id` and `cell_ids` (list) parameters. Returns visual output (HTML, charts, tables, etc.) with mimetype, stdout messages, and stderr messages for each cell. |
### Data
diff --git a/marimo/_ai/_tools/tools/cells.py b/marimo/_ai/_tools/tools/cells.py
index d765a583dd..e6f6be6b81 100644
--- a/marimo/_ai/_tools/tools/cells.py
+++ b/marimo/_ai/_tools/tools/cells.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any, Optional
@@ -14,6 +15,7 @@ from marimo._ai._tools.types import (
)
from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._ast.models import CellData
+from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import Error
from marimo._messaging.notification import (
CellNotification,
@@ -44,6 +46,10 @@ class LightweightCellInfo:
preview: str
line_count: int
cell_type: SupportedCellType
+ runtime_state: Optional[str] = None
+ has_output: bool = False
+ has_console_output: bool = False
+ has_errors: bool = False
@dataclass
@@ -61,6 +67,8 @@ class CellRuntimeMetadata:
# keep as str for py39/Pydantic compatibility and to avoid Literal/Enum
# validation issues in models.
runtime_state: Optional[str] = None
+ # Duration of the last execution in milliseconds.
+ # Only populated when runtime_state is "idle"; null otherwise.
execution_time: Optional[float] = None
@@ -77,21 +85,15 @@ class GetCellRuntimeDataData:
variables: Optional[CellVariables] = None
-def _default_cell_runtime_data() -> GetCellRuntimeDataData:
- return GetCellRuntimeDataData(session_id="", cell_id="")
-
-
@dataclass
class GetCellRuntimeDataArgs:
session_id: SessionId
- cell_id: CellId_t
+ cell_ids: list[CellId_t] = field(default_factory=list)
@dataclass
class GetCellRuntimeDataOutput(SuccessResult):
- data: GetCellRuntimeDataData = field(
- default_factory=_default_cell_runtime_data
- )
+ data: list[GetCellRuntimeDataData] = field(default_factory=list)
@dataclass
@@ -102,18 +104,24 @@ class CellVisualOutput:
visual_mimetype: Optional[str] = None
+@dataclass
+class CellOutputData:
+ cell_id: str
+ visual_output: CellVisualOutput = field(default_factory=CellVisualOutput)
+ console_outputs: MarimoCellConsoleOutputs = field(
+ default_factory=MarimoCellConsoleOutputs
+ )
+
+
@dataclass
class GetCellOutputArgs:
session_id: SessionId
- cell_id: CellId_t
+ cell_ids: list[CellId_t] = field(default_factory=list)
@dataclass
class GetCellOutputOutput(SuccessResult):
- visual_output: CellVisualOutput = field(default_factory=CellVisualOutput)
- console_outputs: MarimoCellConsoleOutputs = field(
- default_factory=MarimoCellConsoleOutputs
- )
+ cells: list[CellOutputData] = field(default_factory=list)
class GetLightweightCellMap(
@@ -124,6 +132,13 @@ class GetLightweightCellMap(
This tool provides an overview of notebook structure for initial navigation,
showing a preview of each cell's content without full code or outputs.
+ Each cell includes a runtime_state field with one of the following values:
+ - "idle": cell has executed and is quiescent (includes cells with errors)
+ - "running": cell is actively executing
+ - "queued": cell is waiting on a running dependency
+ - "disabled-transitively": cell is disabled because a parent cell is disabled
+ - null: cell has never been executed
+
Args:
session_id: The session ID of the notebook from get_active_notebooks
preview_lines: Number of lines to show per cell (default: 3)
@@ -149,6 +164,7 @@ class GetLightweightCellMap(
context = self.context
session = context.get_session(session_id)
cell_manager = session.app_file_manager.app.cell_manager
+ session_view = session.session_view
notebook_filename = (
session.app_file_manager.filename or "untitled_notebook.py"
)
@@ -164,6 +180,26 @@ class GetLightweightCellMap(
# Determine cell type using compiled cell info when available
cell_type = self._get_cell_type(cell_data)
+ # Get runtime info from cell notifications
+ runtime_state: Optional[str] = None
+ has_output = False
+ has_console_output = False
+ has_errors = False
+ cell_notif = session_view.cell_notifications.get(cell_data.cell_id)
+ if cell_notif is not None:
+ if cell_notif.status is not None:
+ runtime_state = cell_notif.status
+ has_errors = (
+ cell_notif.output is not None
+ and cell_notif.output.channel == CellChannel.MARIMO_ERROR
+ )
+ has_output = (
+ not has_errors
+ and cell_notif.output is not None
+ and cell_notif.output.data is not None
+ )
+ has_console_output = bool(cell_notif.console)
+
# Add cell to cell map
cells.append(
LightweightCellInfo(
@@ -171,6 +207,10 @@ class GetLightweightCellMap(
preview=preview,
line_count=len(code_lines),
cell_type=cell_type,
+ runtime_state=runtime_state,
+ has_output=has_output,
+ has_console_output=has_console_output,
+ has_errors=has_errors,
)
)
@@ -223,61 +263,75 @@ class GetLightweightCellMap(
class GetCellRuntimeData(
ToolBase[GetCellRuntimeDataArgs, GetCellRuntimeDataOutput]
):
- """Get runtime data for a specific cell including code, errors, and variables.
+ """Get runtime data for one or more cells including code, errors, and variables.
- This tool provides detailed runtime information for a specific cell,
- including its source code, any execution errors, and the variables
- defined or modified in that cell.
+ This tool provides detailed runtime information for the given cells,
+ including source code, any execution errors, and the variables
+ defined or modified in each cell.
+
+ Each cell's metadata includes a runtime_state field with one of the following values:
+ - "idle": cell has executed and is quiescent (includes cells with errors)
+ - "running": cell is actively executing
+ - "queued": cell is waiting on a running dependency
+ - "disabled-transitively": cell is disabled because a parent cell is disabled
+ - null: cell has never been executed
+
+ The execution_time field contains the duration of the last execution in
+ milliseconds. It is only populated when runtime_state is "idle"; it is
+ null while the cell is running, queued, or has not been executed.
Args:
session_id: The session ID of the notebook from get_active_notebooks
- cell_id: The specific cell ID to get runtime data for from get_lightweight_cell_map
+ cell_ids: A list of cell IDs to get runtime data for from get_lightweight_cell_map.
+ If an empty list is provided, it will return data for all cells.
Returns:
- A success result containing cell runtime data including code, errors, and variables.
+ A success result containing cell runtime data including code, errors, and variables for each cell.
"""
guidelines = ToolGuidelines(
when_to_use=[
- "When inspecting a specific cell's code, errors, or variables",
- "After identifying a cell of interest from the cell map",
+ "When inspecting one or more cells' code, errors, or variables",
+ "After identifying cells of interest from the cell map",
],
prerequisites=[
"You must have a valid session id from an active notebook",
- "You must have a valid cell id from an active notebook",
+ "You must have valid cell ids from an active notebook",
],
)
def handle(self, args: GetCellRuntimeDataArgs) -> GetCellRuntimeDataOutput:
session_id = args.session_id
- cell_id = args.cell_id
context = self.context
session = context.get_session(session_id)
- # Get cell data using CellManager's existing method
- cell_data = self._get_cell_data(session, session_id, cell_id)
-
- # Get cell code/source
- cell_code = cell_data.code
-
- # Get cell errors from session view with actual error details
- cell_errors = context.get_cell_errors(session_id, cell_id)
-
- # Get cell runtime metadata
- cell_metadata = self._get_cell_metadata(session, cell_id)
-
- # Get variable names and values defined by the cell
- cell_variables = self._get_cell_variables(session, cell_data)
+ # Empty cell_ids means "return all cells"
+ cell_ids = args.cell_ids
+ if not cell_ids:
+ cell_manager = session.app_file_manager.app.cell_manager
+ cell_ids = [cd.cell_id for cd in cell_manager.cell_data()]
+
+ results: list[GetCellRuntimeDataData] = []
+ for cell_id in cell_ids:
+ cell_data = self._get_cell_data(session, session_id, cell_id)
+ cell_code = cell_data.code
+ cell_errors = context.get_cell_errors(session_id, cell_id)
+ cell_metadata = self._get_cell_metadata(session, cell_id)
+ cell_variables = self._get_cell_variables(session, cell_data)
+
+ results.append(
+ GetCellRuntimeDataData(
+ session_id=session_id,
+ cell_id=cell_id,
+ code=cell_code,
+ errors=cell_errors,
+ metadata=cell_metadata,
+ variables=cell_variables,
+ )
+ )
return GetCellRuntimeDataOutput(
- data=GetCellRuntimeDataData(
- session_id=session_id,
- cell_id=cell_id,
- code=cell_code,
- errors=cell_errors,
- metadata=cell_metadata,
- variables=cell_variables,
- ),
+ data=results,
next_steps=[
"Review cell code for understanding the implementation",
"Check errors to identify any execution issues",
@@ -313,8 +367,13 @@ class GetCellRuntimeData(
if cell_notif and cell_notif.status is not None:
runtime_state = cell_notif.status
- # Get execution time if available
- execution_time = session_view.last_execution_time.get(cell_id)
+ # Only return execution time when the cell is idle — that's when
+ # the value is a duration in milliseconds. While the cell is
+ # running the stored value is the start timestamp (epoch), which
+ # would be confusing for consumers.
+ execution_time: Optional[float] = None
+ if runtime_state == "idle":
+ execution_time = session_view.last_execution_time.get(cell_id)
return CellRuntimeMetadata(
runtime_state=runtime_state, execution_time=execution_time
@@ -345,24 +404,25 @@ class GetCellRuntimeData(
class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
- """Get cell execution output including visual display and console streams.
+ """Get cell execution outputs including visual display and console streams.
Args:
session_id: The session ID of the notebook from get_active_notebooks
- cell_id: The specific cell ID from get_lightweight_cell_map
+ cell_ids: A list of cell IDs from get_lightweight_cell_map.
+ If an empty list is provided, it will return outputs for all cells.
Returns:
- Visual output (HTML, charts, tables, etc.) with mimetype and console streams (stdout/stderr).
+ Visual output (HTML, charts, tables, etc.) with mimetype and console streams (stdout/stderr) for each cell.
"""
guidelines = ToolGuidelines(
when_to_use=[
- "When you need to see what a cell displayed or printed to the user",
- "To review charts, visualizations, markdown, HTML, or console output from a cell",
+ "When you need to see what one or more cells displayed or printed",
+ "To review charts, visualizations, markdown, HTML, or console output from cells",
],
prerequisites=[
"You must have a valid session id from an active notebook",
- "You must have a valid cell id from an active notebook",
+ "You must have valid cell ids from an active notebook",
],
)
@@ -370,26 +430,43 @@ class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
context = self.context
session = context.get_session(args.session_id)
session_view = session.session_view
- cell_id = args.cell_id
- cell_notif = session_view.cell_notifications.get(cell_id)
- if cell_notif is None:
- raise ToolExecutionError(
- f"Cell {cell_id} not found in session {args.session_id}",
- code="CELL_NOT_FOUND",
- is_retryable=False,
- suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",
- )
+ # Empty cell_ids means "return all cells"
+ cell_ids = args.cell_ids
+ if not cell_ids:
+ cell_manager = session.app_file_manager.app.cell_manager
+ cell_ids = [cd.cell_id for cd in cell_manager.cell_data()]
+
+ results: list[CellOutputData] = []
+ for cell_id in cell_ids:
+ cell_notif = session_view.cell_notifications.get(cell_id)
+
+ if cell_notif is None:
+ raise ToolExecutionError(
+ f"Cell {cell_id} not found in session {args.session_id}",
+ code="CELL_NOT_FOUND",
+ is_retryable=False,
+ suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",
+ )
- visual_output, visual_mimetype = self._get_visual_output(cell_notif)
- console_outputs = context.get_cell_console_outputs(cell_notif)
+ visual_output, visual_mimetype = self._get_visual_output(
+ cell_notif
+ )
+ console_outputs = context.get_cell_console_outputs(cell_notif)
+
+ results.append(
+ CellOutputData(
+ cell_id=cell_id,
+ visual_output=CellVisualOutput(
+ visual_output=visual_output,
+ visual_mimetype=visual_mimetype,
+ ),
+ console_outputs=console_outputs,
+ )
+ )
return GetCellOutputOutput(
- visual_output=CellVisualOutput(
- visual_output=visual_output,
- visual_mimetype=visual_mimetype,
- ),
- console_outputs=console_outputs,
+ cells=results,
next_steps=[
"Review visual_output to see what was displayed to the user",
"Check stdout/stderr for print statements and warnings",
@@ -402,11 +479,40 @@ class GetCellOutputs(ToolBase[GetCellOutputArgs, GetCellOutputOutput]):
visual_output = None
visual_mimetype = None
if cell_notif.output:
- data = cell_notif.output.data
- visual_output = self._get_str_output_data(data)
- visual_mimetype = cell_notif.output.mimetype
+ if cell_notif.output.channel == CellChannel.MARIMO_ERROR:
+ visual_output = self._get_error_output_data(
+ cell_notif.output.data
+ )
+ visual_mimetype = "application/json"
+ else:
+ data = cell_notif.output.data
+ visual_output = self._get_str_output_data(data)
+ visual_mimetype = cell_notif.output.mimetype
return visual_output, visual_mimetype
+ def _get_error_output_data(
+ self, data: str | list[Error] | dict[str, Any]
+ ) -> str:
+ """Convert error output data to structured JSON."""
+ if not isinstance(data, list):
+ return str(data)
+
+ errors: list[dict[str, Any]] = []
+ for err in data:
+ if isinstance(err, dict):
+ errors.append(
+ {
+ "type": err.get("type", "UnknownError"),
+ "message": err.get("msg", str(err)),
+ }
+ )
+ else:
+ err_type: str = getattr(err, "type", type(err).__name__)
+ describe_fn = getattr(err, "describe", None)
+ message = describe_fn() if callable(describe_fn) else str(err)
+ errors.append({"type": err_type, "message": str(message)})
+ return json.dumps(errors)
+
def _get_str_output_data(
self, data: str | list[Error] | dict[str, Any]
) -> str:
diff --git a/tests/_ai/tools/tools/test_cells.py b/tests/_ai/tools/tools/test_cells.py
index 0d9fd5d6f8..3c868c6738 100644
--- a/tests/_ai/tools/tools/test_cells.py
+++ b/tests/_ai/tools/tools/test_cells.py
@@ -9,10 +9,15 @@ from marimo._ai._tools.base import ToolContext
from marimo._ai._tools.tools.cells import (
CellRuntimeMetadata,
CellVariables,
+ GetCellOutputArgs,
GetCellOutputs,
GetCellRuntimeData,
+ GetCellRuntimeDataArgs,
GetLightweightCellMap,
+ GetLightweightCellMapArgs,
)
+from marimo._ai._tools.types import MarimoCellConsoleOutputs
+from marimo._ai._tools.utils.exceptions import ToolExecutionError
from marimo._messaging.notification import VariableValue
from marimo._types.ids import CellId_t, SessionId
from tests._ai.tools.test_utils import MockSession, MockSessionView
@@ -143,11 +148,8 @@ def test_get_cell_runtime_data_invalid_cell():
context.get_session.return_value = mock_session
tool.context = context
- from marimo._ai._tools.tools.cells import GetCellRuntimeDataArgs
- from marimo._ai._tools.utils.exceptions import ToolExecutionError
-
args = GetCellRuntimeDataArgs(
- session_id=SessionId("test"), cell_id=CellId_t("invalid")
+ session_id=SessionId("test"), cell_ids=[CellId_t("invalid")]
)
with pytest.raises(ToolExecutionError) as exc_info:
@@ -155,6 +157,81 @@ def test_get_cell_runtime_data_invalid_cell():
assert exc_info.value.code == "CELL_NOT_FOUND"
+def test_get_cell_runtime_data_empty_cell_ids():
+ """Test GetCellRuntimeData with empty cell_ids returns all cells."""
+ tool = GetCellRuntimeData(ToolContext())
+
+ cell_data_1 = Mock()
+ cell_data_1.cell_id = CellId_t("c1")
+ cell_data_1.code = "x = 1"
+ cell_data_1.cell = None
+
+ cell_data_2 = Mock()
+ cell_data_2.cell_id = CellId_t("c2")
+ cell_data_2.code = "y = 2"
+ cell_data_2.cell = None
+
+ mock_cell_manager = Mock()
+ mock_cell_manager.cell_data.return_value = [cell_data_1, cell_data_2]
+ mock_cell_manager.get_cell_data.side_effect = lambda cid: (
+ cell_data_1 if cid == "c1" else cell_data_2
+ )
+
+ mock_session = Mock()
+ mock_session.app_file_manager.app.cell_manager = mock_cell_manager
+ mock_session.session_view = MockSessionView()
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ context.get_cell_errors.return_value = []
+ tool.context = context
+
+ args = GetCellRuntimeDataArgs(session_id=SessionId("test"), cell_ids=[])
+ result = tool.handle(args)
+ assert len(result.data) == 2
+ assert result.data[0].cell_id == "c1"
+ assert result.data[1].cell_id == "c2"
+
+
+def test_get_cell_outputs_empty_cell_ids():
+ """Test GetCellOutputs with empty cell_ids returns all cells."""
+ tool = GetCellOutputs(ToolContext())
+
+ cell_data_1 = Mock()
+ cell_data_1.cell_id = CellId_t("c1")
+
+ cell_data_2 = Mock()
+ cell_data_2.cell_id = CellId_t("c2")
+
+ mock_cell_manager = Mock()
+ mock_cell_manager.cell_data.return_value = [cell_data_1, cell_data_2]
+
+ notif_c1 = MockCellNotification(
+ output=MockOutput(data="42", mimetype="text/plain"),
+ console=None,
+ )
+ notif_c2 = MockCellNotification(output=None, console=None)
+
+ mock_session = Mock()
+ mock_session.app_file_manager.app.cell_manager = mock_cell_manager
+ mock_session.session_view = MockSessionView(
+ cell_notifications={"c1": notif_c1, "c2": notif_c2}
+ )
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ context.get_cell_console_outputs.return_value = MarimoCellConsoleOutputs()
+ tool.context = context
+
+ args = GetCellOutputArgs(session_id=SessionId("test"), cell_ids=[])
+ result = tool.handle(args)
+ assert len(result.cells) == 2
+ assert result.cells[0].cell_id == "c1"
+ assert result.cells[0].visual_output.visual_output == "42"
+ assert result.cells[1].cell_id == "c2"
+ assert result.cells[1].visual_output.visual_output is None
+
+
def test_get_visual_output_with_html():
tool = GetCellOutputs(ToolContext())
output = MockOutput(data="<div>test</div>", mimetype="text/html")
@@ -172,3 +249,241 @@ def test_get_visual_output_no_output():
visual_output, mimetype = tool._get_visual_output(cell_notification) # type: ignore[arg-type]
assert visual_output is None
assert mimetype is None
+
+
+def test_get_visual_output_with_error():
+ """Test that error output is returned as structured JSON."""
+ import json
+
+ tool = GetCellOutputs(ToolContext())
+ error = MockError(type="NameError", _message="name 'x' is not defined")
+ output = MockOutput(
+ channel="marimo-error",
+ data=[error],
+ mimetype="application/vnd.marimo+error",
+ )
+ cell_notification = MockCellNotification(output=output)
+
+ visual_output, mimetype = tool._get_visual_output(cell_notification) # type: ignore[arg-type]
+ assert mimetype == "application/json"
+ parsed = json.loads(visual_output)
+ assert len(parsed) == 1
+ assert parsed[0]["type"] == "NameError"
+ assert parsed[0]["message"] == "name 'x' is not defined"
+
+
+def test_lightweight_cell_map_includes_runtime_info():
+ """Test that LightweightCellInfo includes runtime_state, has_output,
+ has_console_output, and has_errors from cell notifications."""
+ tool = GetLightweightCellMap(ToolContext())
+
+ # Mock cell data
+ cell_data_1 = Mock()
+ cell_data_1.cell_id = "c1"
+ cell_data_1.code = "x = 1"
+ cell_data_1.cell = None # no compiled cell
+
+ cell_data_2 = Mock()
+ cell_data_2.cell_id = "c2"
+ cell_data_2.code = "print('hello')"
+ cell_data_2.cell = None
+
+ cell_data_3 = Mock()
+ cell_data_3.cell_id = "c3"
+ cell_data_3.code = "y = 2"
+ cell_data_3.cell = None
+
+ cell_data_4 = Mock()
+ cell_data_4.cell_id = "c4"
+ cell_data_4.code = "z = bad_var"
+ cell_data_4.cell = None
+
+ # Mock cell manager
+ mock_cell_manager = Mock()
+ mock_cell_manager.cell_data.return_value = [
+ cell_data_1,
+ cell_data_2,
+ cell_data_3,
+ cell_data_4,
+ ]
+
+ # Cell notifications:
+ # c1 is idle with output
+ # c2 is running with console output
+ # c3 has no notification
+ # c4 is idle with an error
+ notif_c1 = MockCellNotification(
+ status="idle",
+ output=MockOutput(data="42", mimetype="text/plain"),
+ console=None,
+ )
+ notif_c2 = MockCellNotification(
+ status="running",
+ output=None,
+ console=[MockConsoleOutput(channel="stdout", data="hello")],
+ )
+ notif_c4 = MockCellNotification(
+ status="idle",
+ output=MockOutput(
+ channel="marimo-error",
+ data=[
+ MockError(
+ type="NameError", _message="name 'bad_var' is not defined"
+ )
+ ],
+ mimetype="application/vnd.marimo+error",
+ ),
+ console=None,
+ )
+
+ mock_session = Mock()
+ mock_session.app_file_manager.app.cell_manager = mock_cell_manager
+ mock_session.app_file_manager.filename = "test.py"
+ mock_session.session_view = MockSessionView(
+ cell_notifications={"c1": notif_c1, "c2": notif_c2, "c4": notif_c4}
+ )
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ tool.context = context
+
+ args = GetLightweightCellMapArgs(
+ session_id=SessionId("test"), preview_lines=3
+ )
+ result = tool.handle(args)
+
+ assert len(result.cells) == 4
+
+ # c1: idle, has output, no console output, no errors
+ assert result.cells[0].cell_id == "c1"
+ assert result.cells[0].runtime_state == "idle"
+ assert result.cells[0].has_output is True
+ assert result.cells[0].has_console_output is False
+ assert result.cells[0].has_errors is False
+
+ # c2: running, no output, has console output, no errors
+ assert result.cells[1].cell_id == "c2"
+ assert result.cells[1].runtime_state == "running"
+ assert result.cells[1].has_output is False
+ assert result.cells[1].has_console_output is True
+ assert result.cells[1].has_errors is False
+
+ # c3: no notification at all
+ assert result.cells[2].cell_id == "c3"
+ assert result.cells[2].runtime_state is None
+ assert result.cells[2].has_output is False
+ assert result.cells[2].has_console_output is False
+ assert result.cells[2].has_errors is False
+
+ # c4: idle, has errors, no regular output
+ assert result.cells[3].cell_id == "c4"
+ assert result.cells[3].runtime_state == "idle"
+ assert result.cells[3].has_output is False
+ assert result.cells[3].has_console_output is False
+ assert result.cells[3].has_errors is True
+
+
+def test_get_cell_runtime_data_batched():
+ """Test GetCellRuntimeData with multiple cell IDs."""
+ tool = GetCellRuntimeData(ToolContext())
+
+ # Mock two cells
+ cell_data_1 = Mock()
+ cell_data_1.code = "x = 1"
+ cell_data_1.cell = None
+
+ cell_data_2 = Mock()
+ cell_data_2.code = "y = 2"
+ cell_data_2.cell = None
+
+ mock_cell_manager = Mock()
+ mock_cell_manager.get_cell_data.side_effect = lambda cid: (
+ cell_data_1 if cid == "c1" else cell_data_2
+ )
+
+ notif_c1 = MockCellNotification(status="idle")
+ notif_c2 = MockCellNotification(status="running")
+
+ mock_session = Mock()
+ mock_session.app_file_manager.app.cell_manager = mock_cell_manager
+ mock_session.session_view = MockSessionView(
+ cell_notifications={"c1": notif_c1, "c2": notif_c2},
+ last_execution_time={"c1": 10.0, "c2": 20.0},
+ )
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ context.get_cell_errors.return_value = []
+ tool.context = context
+
+ args = GetCellRuntimeDataArgs(
+ session_id=SessionId("test"),
+ cell_ids=[CellId_t("c1"), CellId_t("c2")],
+ )
+ result = tool.handle(args)
+
+ assert len(result.data) == 2
+ assert result.data[0].cell_id == "c1"
+ assert result.data[0].code == "x = 1"
+ assert result.data[0].metadata.runtime_state == "idle" # type: ignore[union-attr]
+ assert result.data[0].metadata.execution_time == 10.0 # type: ignore[union-attr]
+ assert result.data[1].cell_id == "c2"
+ assert result.data[1].code == "y = 2"
+ assert result.data[1].metadata.runtime_state == "running" # type: ignore[union-attr]
+ # execution_time is only populated when idle
+ assert result.data[1].metadata.execution_time is None # type: ignore[union-attr]
+
+
+def test_get_cell_outputs_batched():
+ """Test GetCellOutputs with multiple cell IDs."""
+ tool = GetCellOutputs(ToolContext())
+
+ notif_c1 = MockCellNotification(
+ output=MockOutput(data="<b>hi</b>", mimetype="text/html"),
+ console=None,
+ )
+ notif_c2 = MockCellNotification(output=None, console=None)
+
+ mock_session = Mock()
+ mock_session.session_view = MockSessionView(
+ cell_notifications={"c1": notif_c1, "c2": notif_c2}
+ )
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ context.get_cell_console_outputs.return_value = MarimoCellConsoleOutputs()
+ tool.context = context
+
+ args = GetCellOutputArgs(
+ session_id=SessionId("test"),
+ cell_ids=[CellId_t("c1"), CellId_t("c2")],
+ )
+ result = tool.handle(args)
+
+ assert len(result.cells) == 2
+ assert result.cells[0].cell_id == "c1"
+ assert result.cells[0].visual_output.visual_output == "<b>hi</b>"
+ assert result.cells[0].visual_output.visual_mimetype == "text/html"
+ assert result.cells[1].cell_id == "c2"
+ assert result.cells[1].visual_output.visual_output is None
+
+
+def test_get_cell_outputs_invalid_cell():
+ """Test GetCellOutputs raises for unknown cell ID."""
+ tool = GetCellOutputs(ToolContext())
+
+ mock_session = Mock()
+ mock_session.session_view = MockSessionView(cell_notifications={})
+
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = mock_session
+ tool.context = context
+
+ args = GetCellOutputArgs(
+ session_id=SessionId("test"),
+ cell_ids=[CellId_t("missing")],
+ )
+
+ with pytest.raises(ToolExecutionError) as exc_info:
+ tool.handle(args)
+ assert exc_info.value.code == "CELL_NOT_FOUND"
diff --git a/tests/_server/ai/tools/test_tool_manager.py b/tests/_server/ai/tools/test_tool_manager.py
index 2ec246a580..150e4e7b87 100644
--- a/tests/_server/ai/tools/test_tool_manager.py
+++ b/tests/_server/ai/tools/test_tool_manager.py
@@ -71,18 +71,19 @@ def test_validate_backend_tool_arguments(manager: ToolManager):
# Test valid arguments
is_valid, error = manager._validate_backend_tool_arguments(
- "get_cell_runtime_data", {"session_id": "test", "cell_id": "cell1"}
+ "get_cell_runtime_data",
+ {"session_id": "test", "cell_ids": ["cell1"]},
)
assert is_valid is True
assert error == ""
- # Test missing required argument
+ # Test invalid argument (unknown key)
is_valid, error = manager._validate_backend_tool_arguments(
"get_cell_runtime_data",
- {"session_id": "test"}, # missing cell_id
+ {"session_id": "test", "bad_key": "value"},
)
assert is_valid is False
- assert "missing 1 required positional argument: 'cell_id'" in error
+ assert "Invalid arguments" in error
def test_get_tool(manager: ToolManager):