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.

Add tables and variable tool (#6396)

Shahmir Varqha1a1138d392ba
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.py
index 5f880875b3..d6a9ffc2f3 100644
--- a/marimo/_ai/_tools/base.py
+++ b/marimo/_ai/_tools/base.py
@@ -9,6 +9,7 @@ from dataclasses import asdict, dataclass, is_dataclass
from typing import (
TYPE_CHECKING,
Any,
+ Callable,
Generic,
Optional,
TypeVar,
@@ -40,11 +41,9 @@ ArgsP = TypeVar("ArgsP", contravariant=True)
OutC = TypeVar("OutC", covariant=True)
if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable
+ from collections.abc import Awaitable
- from starlette.applications import (
- Starlette,
- )
+ from starlette.applications import Starlette
@dataclass
diff --git a/marimo/_ai/_tools/tools/cells.py b/marimo/_ai/_tools/tools/cells.py
index e94aa0ebf6..c79bc230ff 100644
--- a/marimo/_ai/_tools/tools/cells.py
+++ b/marimo/_ai/_tools/tools/cells.py
@@ -73,7 +73,7 @@ class CellVariableValue:
# Cell variables can be arbitrary Python values (int, str, list, dict, ...),
# so we keep this as Any to reflect actual runtime.
value: Optional[Any] = None
- datatype: Optional[str] = None
+ data_type: Optional[str] = None
CellVariables = dict[str, CellVariableValue]
@@ -384,7 +384,7 @@ class GetCellRuntimeData(
cell_variables[var_name] = CellVariableValue(
name=var_name,
value=var_value.value,
- datatype=var_value.datatype,
+ data_type=var_value.datatype,
)
return cell_variables
diff --git a/marimo/_ai/_tools/tools/tables_and_variables.py b/marimo/_ai/_tools/tools/tables_and_variables.py
new file mode 100644
index 0000000000..fa63ad4bdd
--- /dev/null
+++ b/marimo/_ai/_tools/tools/tables_and_variables.py
@@ -0,0 +1,112 @@
+# Copyright 2025 Marimo. All rights reserved.
+from dataclasses import dataclass, field
+from typing import Optional
+
+from marimo._ai._tools.base import ToolBase
+from marimo._ai._tools.tools.cells import CellVariableValue
+from marimo._ai._tools.types import SuccessResult
+from marimo._data.models import DataTableColumn
+from marimo._server.sessions import Session
+from marimo._types.ids import SessionId
+
+
+@dataclass
+class TablesAndVariablesArgs:
+ session_id: SessionId
+ variable_names: list[str]
+
+
+@dataclass
+class DataTableMetadata:
+ """
+ Metadata about a data table.
+
+ source: str - Can be dialect, or source db name.
+ engine: str - The engine or connection handler of the data table.
+ num_rows: int - The number of rows in the data table.
+ num_columns: int - The number of columns in the data table.
+ columns: list[DataTableColumn] - The columns in the data table.
+ primary_keys: Optional[list[str]] - The primary keys of the data table.
+ indexes: Optional[list[str]] - The indexes of the data table.
+ """
+
+ source: str
+ num_rows: Optional[int]
+ num_columns: Optional[int]
+ columns: list[DataTableColumn]
+ engine: Optional[str]
+ primary_keys: Optional[list[str]]
+ indexes: Optional[list[str]]
+
+
+@dataclass
+class TablesAndVariablesOutput(SuccessResult):
+ tables: dict[str, DataTableMetadata] = field(default_factory=dict)
+ variables: dict[str, CellVariableValue] = field(default_factory=dict)
+
+
+class GetTablesAndVariables(
+ ToolBase[TablesAndVariablesArgs, TablesAndVariablesOutput]
+):
+ """
+ Get tables and variables information in the session.
+
+ When provided with a list of variable names, it will return information about the variables and tables mentioned.
+ If an empty list is provided, it will return information about all tables and variables.
+
+ Returns:
+ A success result containing tables (columns, primary keys, indexes, engine, etc.) and variables (value, data type).
+ """
+
+ def handle(self, args: TablesAndVariablesArgs) -> TablesAndVariablesOutput:
+ session = self.context.get_session(args.session_id)
+ return self._get_tables_and_variables(session, args.variable_names)
+
+ def _get_tables_and_variables(
+ self, session: "Session", variable_names: list[str]
+ ) -> TablesAndVariablesOutput:
+ session_view = session.session_view
+ # convert to set for O(1) lookup
+ variable_names_set = set(variable_names)
+ return_all_vars = variable_names_set == set()
+
+ tables = session_view.datasets.tables
+ variables = session_view.variable_values
+
+ filtered_tables = (
+ tables
+ if return_all_vars
+ else filter(lambda table: table.name in variable_names_set, tables)
+ )
+ filtered_variables = (
+ variables
+ if return_all_vars
+ else filter(
+ lambda variable: variable in variable_names_set, variables
+ )
+ )
+
+ data_tables: dict[str, DataTableMetadata] = {}
+ for table in filtered_tables:
+ data_tables[table.name] = DataTableMetadata(
+ source=table.source,
+ num_rows=table.num_rows,
+ num_columns=table.num_columns,
+ columns=table.columns,
+ primary_keys=table.primary_keys,
+ indexes=table.indexes,
+ engine=table.engine,
+ )
+
+ notebook_variables: dict[str, CellVariableValue] = {}
+ for variable_name in filtered_variables:
+ value = variables[variable_name]
+ notebook_variables[variable_name] = CellVariableValue(
+ name=variable_name,
+ value=value.value,
+ data_type=value.datatype,
+ )
+
+ return TablesAndVariablesOutput(
+ tables=data_tables, variables=notebook_variables
+ )
diff --git a/marimo/_ai/_tools/tools_registry.py b/marimo/_ai/_tools/tools_registry.py
new file mode 100644
index 0000000000..b5eae33c06
--- /dev/null
+++ b/marimo/_ai/_tools/tools_registry.py
@@ -0,0 +1,17 @@
+# Copyright 2025 Marimo. All rights reserved.
+from typing import Any
+
+from marimo._ai._tools.base import ToolBase
+from marimo._ai._tools.tools.cells import (
+ GetCellRuntimeData,
+ GetLightweightCellMap,
+)
+from marimo._ai._tools.tools.notebooks import GetActiveNotebooks
+from marimo._ai._tools.tools.tables_and_variables import GetTablesAndVariables
+
+SUPPORTED_BACKEND_AND_MCP_TOOLS: list[type[ToolBase[Any, Any]]] = [
+ GetActiveNotebooks,
+ GetCellRuntimeData,
+ GetLightweightCellMap,
+ GetTablesAndVariables,
+]
diff --git a/marimo/_mcp/server/lifespan.py b/marimo/_mcp/server/lifespan.py
index 21ad303f91..4c66a15afd 100644
--- a/marimo/_mcp/server/lifespan.py
+++ b/marimo/_mcp/server/lifespan.py
@@ -5,6 +5,7 @@ from collections.abc import AsyncIterator
from starlette.applications import Starlette
from marimo._loggers import marimo_logger
+from marimo._mcp.server.main import setup_mcp_server
LOGGER = marimo_logger()
@@ -14,9 +15,6 @@ async def mcp_server_lifespan(app: Starlette) -> AsyncIterator[None]:
"""Lifespan for MCP server functionality (exposing marimo as MCP server)."""
try:
- # Import here to avoid circular imports and optional dependency issues
- from marimo._mcp.server.main import setup_mcp_server
-
session_manager = setup_mcp_server(app)
async with session_manager.run():
diff --git a/marimo/_mcp/server/main.py b/marimo/_mcp/server/main.py
index bf912fd127..4ff3f55273 100644
--- a/marimo/_mcp/server/main.py
+++ b/marimo/_mcp/server/main.py
@@ -8,12 +8,16 @@ notebook context and functionality.
from typing import TYPE_CHECKING
+from mcp.server.fastmcp import FastMCP
from starlette.routing import Mount
+from marimo._ai._tools.base import ToolContext
+from marimo._ai._tools.tools_registry import SUPPORTED_BACKEND_AND_MCP_TOOLS
from marimo._loggers import marimo_logger
LOGGER = marimo_logger()
+
if TYPE_CHECKING:
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.applications import Starlette
@@ -31,13 +35,6 @@ def setup_mcp_server(app: "Starlette") -> "StreamableHTTPSessionManager":
StreamableHTTPSessionManager: MCP session manager
"""
- # Lazily import here to raise import errors if mcp is not installed
- # The import errors will get caught by the marimo/_mcp/server/lifespan.py
- from mcp.server.fastmcp import FastMCP
-
- from marimo._mcp.server.tools.cells import register_cells_tools
- from marimo._mcp.server.tools.notebooks import register_notebooks_tools
-
mcp = FastMCP(
"marimo-mcp-server",
stateless_http=True,
@@ -48,8 +45,10 @@ def setup_mcp_server(app: "Starlette") -> "StreamableHTTPSessionManager":
mcp.settings.streamable_http_path = "/server"
# Register all tools
- register_notebooks_tools(mcp, app)
- register_cells_tools(mcp, app)
+ context = ToolContext(app=app)
+ for tool in SUPPORTED_BACKEND_AND_MCP_TOOLS:
+ tool_with_context = tool(context)
+ mcp.tool()(tool_with_context.as_mcp_tool_fn())
# Initialize streamable HTTP app
mcp_app = mcp.streamable_http_app()
diff --git a/marimo/_mcp/server/tools/cells.py b/marimo/_mcp/server/tools/cells.py
deleted file mode 100644
index 4a30788d67..0000000000
--- a/marimo/_mcp/server/tools/cells.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright 2025 Marimo. All rights reserved.
-
-from mcp.server.fastmcp import FastMCP
-from starlette.applications import Starlette
-
-from marimo._ai._tools.base import ToolContext
-from marimo._ai._tools.tools.cells import (
- GetCellRuntimeData,
- GetLightweightCellMap,
-)
-
-
-def register_cells_tools(mcp: FastMCP, app: Starlette) -> None:
- """Register cell-level management tools"""
-
- context = ToolContext(app=app)
-
- mcp.tool()(GetLightweightCellMap(context).as_mcp_tool_fn())
- mcp.tool()(GetCellRuntimeData(context).as_mcp_tool_fn())
diff --git a/marimo/_mcp/server/tools/notebooks.py b/marimo/_mcp/server/tools/notebooks.py
deleted file mode 100644
index c0aca850fa..0000000000
--- a/marimo/_mcp/server/tools/notebooks.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright 2025 Marimo. All rights reserved.
-
-from mcp.server.fastmcp import FastMCP
-from starlette.applications import Starlette
-
-from marimo._ai._tools.base import ToolContext
-from marimo._ai._tools.tools.notebooks import GetActiveNotebooks
-
-
-def register_notebooks_tools(mcp: FastMCP, app: Starlette) -> None:
- """Register notebook-level management tools"""
-
- context = ToolContext(app=app)
-
- mcp.tool()(GetActiveNotebooks(context).as_mcp_tool_fn())
diff --git a/marimo/_server/ai/tools/tool_manager.py b/marimo/_server/ai/tools/tool_manager.py
index cfe7d1d51c..d9e0b813e0 100644
--- a/marimo/_server/ai/tools/tool_manager.py
+++ b/marimo/_server/ai/tools/tool_manager.py
@@ -10,12 +10,9 @@ from starlette.applications import (
from marimo import _loggers
from marimo._ai._tools.base import ToolBase, ToolContext
-from marimo._ai._tools.tools.cells import (
- GetCellRuntimeData,
- GetLightweightCellMap,
-)
-from marimo._ai._tools.tools.notebooks import GetActiveNotebooks
+from marimo._ai._tools.tools_registry import SUPPORTED_BACKEND_AND_MCP_TOOLS
from marimo._config.config import CopilotMode
+from marimo._server.ai.mcp import get_mcp_client
from marimo._server.ai.tools.types import (
FunctionArgs,
ToolCallResult,
@@ -54,19 +51,12 @@ class ToolManager:
@once
def _init_backend_tools(self) -> None:
- """Initialize backend tools."""
+ """Initialize backend tools. We lazily register tools here instead of in the constructor for performance"""
context = ToolContext(app=self.app)
- # Add backend tools here
- # Backend tools MUST BE DEFINED in:
- # - marimo._ai._tools.tools.*
- backend_tools: list[ToolBase[Any, Any]] = [
- GetActiveNotebooks(context),
- GetCellRuntimeData(context),
- GetLightweightCellMap(context),
- ]
- for tool in backend_tools:
- self._register_backend_tool(tool)
+ for tool in SUPPORTED_BACKEND_AND_MCP_TOOLS:
+ tool_with_context = tool(context)
+ self._register_backend_tool(tool_with_context)
def _register_backend_tool(self, tool: ToolBase[Any, Any]) -> None:
"""Register a backend tool with its handler function and optional validator."""
@@ -182,8 +172,6 @@ class ToolManager:
return []
try:
- from marimo._server.ai.mcp import get_mcp_client
-
mcp_client = get_mcp_client()
mcp_tools = mcp_client.get_all_tools()
return [self._convert_mcp_tool(tool) for tool in mcp_tools]
@@ -275,8 +263,6 @@ class ToolManager:
call_result = await self._invoke_mcp_tool(tool_name, arguments)
# Check if the result indicates an error using the MCP client
- from marimo._server.ai.mcp import get_mcp_client
-
mcp_client = get_mcp_client()
if mcp_client.is_error_result(call_result):
@@ -345,8 +331,6 @@ class ToolManager:
self, tool_name: str, arguments: FunctionArgs
) -> CallToolResult:
"""Invoke an MCP tool via the MCP client."""
- from marimo._server.ai.mcp import get_mcp_client
-
mcp_client = get_mcp_client()
# Create properly typed parameters for the MCP tool
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 49137a7789..58e1f758e1 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -7,6 +7,7 @@ import socket
from typing import TYPE_CHECKING, Any, Optional
from marimo import _loggers
+from marimo._server.ai.tools.tool_manager import setup_tool_manager
from marimo._server.api.deps import AppState, AppStateBase
from marimo._server.api.interrupt import InterruptHandler
from marimo._server.api.utils import open_url_in_browser
@@ -69,8 +70,6 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
@contextlib.asynccontextmanager
async def tool_manager(app: Starlette) -> AsyncIterator[None]:
try:
- from marimo._server.ai.tools.tool_manager import setup_tool_manager
-
# Initialize and attach to app state
setup_tool_manager(app)
diff --git a/tests/_ai/tools/tools/test_cells.py b/tests/_ai/tools/tools/test_cells.py
index 5ae2a18eb5..66efb2e495 100644
--- a/tests/_ai/tools/tools/test_cells.py
+++ b/tests/_ai/tools/tools/test_cells.py
@@ -165,10 +165,10 @@ def test_get_cell_variables():
result = tool._get_cell_variables(session, cell_data)
expected: CellVariables = {
"x": CellVariableValue(
- name="x", value=var_x.value, datatype=var_x.datatype
+ name="x", value=var_x.value, data_type=var_x.datatype
),
"y": CellVariableValue(
- name="y", value=var_y.value, datatype=var_y.datatype
+ name="y", value=var_y.value, data_type=var_y.datatype
),
}
assert result == expected
diff --git a/tests/_ai/tools/tools/test_tables_variables.py b/tests/_ai/tools/tools/test_tables_variables.py
new file mode 100644
index 0000000000..ab9c0a2eb9
--- /dev/null
+++ b/tests/_ai/tools/tools/test_tables_variables.py
@@ -0,0 +1,319 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+import pytest
+
+from marimo._ai._tools.base import ToolContext
+from marimo._ai._tools.tools.cells import CellVariableValue
+from marimo._ai._tools.tools.tables_and_variables import (
+ DataTableMetadata,
+ GetTablesAndVariables,
+ TablesAndVariablesOutput,
+)
+from marimo._data.models import DataTableColumn
+from marimo._messaging.ops import VariableValue
+
+
+@dataclass
+class MockDataset:
+ name: str
+ source: str
+ num_rows: int
+ num_columns: int
+ columns: list[DataTableColumn]
+ engine: str | None = None
+ primary_keys: list[str] | None = None
+ indexes: list[str] | None = None
+
+
+@dataclass
+class MockDatasets:
+ tables: list[MockDataset] = field(default_factory=list)
+
+
+@dataclass
+class MockSessionView:
+ datasets: MockDatasets
+ variable_values: dict[str, VariableValue] = field(default_factory=dict)
+
+
+@dataclass
+class MockSession:
+ session_view: MockSessionView
+
+
+def tool() -> GetTablesAndVariables:
+ """Create a GetTablesAndVariables tool instance."""
+ return GetTablesAndVariables(ToolContext())
+
+
+def sample_columns() -> list[DataTableColumn]:
+ """Sample column information for testing."""
+ return [
+ DataTableColumn("id", "int", "INTEGER", [1, 2, 3]),
+ DataTableColumn("name", "str", "VARCHAR", ["Alice", "Bob"]),
+ DataTableColumn("email", "str", "VARCHAR", ["[email protected]"]),
+ ]
+
+
+def sample_tables(sample_columns: list[DataTableColumn]) -> list[MockDataset]:
+ """Sample table data for testing."""
+ return [
+ MockDataset(
+ name="users",
+ source="database",
+ num_rows=100,
+ num_columns=3,
+ columns=sample_columns,
+ primary_keys=["id"],
+ indexes=["idx_name"],
+ ),
+ MockDataset(
+ name="orders",
+ source="csv",
+ num_rows=50,
+ num_columns=2,
+ columns=[
+ DataTableColumn("order_id", "int", "INTEGER", [1, 2]),
+ DataTableColumn("user_id", "int", "INTEGER", [1, 2]),
+ ],
+ ),
+ ]
+
+
+def sample_variables() -> dict[str, VariableValue]:
+ """Sample variable data for testing."""
+ return {
+ "x": VariableValue("x", 42, "int"),
+ "y": VariableValue("y", "hello", "str"),
+ "df": VariableValue("df", None, "DataFrame"),
+ "my_list": VariableValue("my_list", [1, 2, 3], "list"),
+ }
+
+
+def sample_session(
+ sample_tables: list[MockDataset],
+ sample_variables: dict[str, VariableValue],
+) -> MockSession:
+ """Sample session with tables and variables."""
+ return MockSession(
+ MockSessionView(
+ datasets=MockDatasets(tables=sample_tables),
+ variable_values=sample_variables,
+ )
+ )
+
+
+def test_get_tables_and_variables_empty_list(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test _get_tables_and_variables with empty variable names list (return all)."""
+ result = tool._get_tables_and_variables(sample_session, [])
+
+ assert isinstance(result, TablesAndVariablesOutput)
+ assert len(result.tables) == 2
+ assert len(result.variables) == 4
+
+ # Check tables
+ assert "users" in result.tables
+ assert "orders" in result.tables
+
+ users_table = result.tables["users"]
+ assert users_table.source == "database"
+ assert users_table.num_rows == 100
+ assert users_table.num_columns == 3
+ assert users_table.primary_keys == ["id"]
+ assert users_table.indexes == ["idx_name"]
+ assert len(users_table.columns) == 3
+
+ # Check variables
+ assert "x" in result.variables
+ assert "y" in result.variables
+ assert "df" in result.variables
+ assert "my_list" in result.variables
+
+ x_var = result.variables["x"]
+ assert x_var.name == "x"
+ assert x_var.value == 42
+ assert x_var.data_type == "int"
+
+
+def test_get_tables_and_variables_specific_variables(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test _get_tables_and_variables with specific variable names."""
+ result = tool._get_tables_and_variables(
+ sample_session, ["users", "x", "y"]
+ )
+
+ assert isinstance(result, TablesAndVariablesOutput)
+ assert len(result.tables) == 1 # Only "users" table
+ assert len(result.variables) == 2 # Only "x" and "y" variables
+
+ # Check that only requested items are returned
+ assert "users" in result.tables
+ assert "orders" not in result.tables
+
+ assert "x" in result.variables
+ assert "y" in result.variables
+ assert "df" not in result.variables
+ assert "my_list" not in result.variables
+
+
+def test_get_tables_and_variables_nonexistent_variables(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test _get_tables_and_variables with non-existent variable names."""
+ result = tool._get_tables_and_variables(
+ sample_session, ["nonexistent_table", "nonexistent_var"]
+ )
+
+ assert isinstance(result, TablesAndVariablesOutput)
+ assert len(result.tables) == 0
+ assert len(result.variables) == 0
+
+
+def test_get_tables_and_variables_mixed_existing_nonexistent(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test _get_tables_and_variables with mix of existing and non-existent variables."""
+ result = tool._get_tables_and_variables(
+ sample_session, ["users", "nonexistent_table", "x", "nonexistent_var"]
+ )
+
+ assert isinstance(result, TablesAndVariablesOutput)
+ assert len(result.tables) == 1 # Only "users" table exists
+ assert len(result.variables) == 1 # Only "x" variable exists
+
+ assert "users" in result.tables
+ assert "x" in result.variables
+
+
+def test_data_table_metadata_structure(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test that DataTableMetadata is properly structured."""
+ result = tool._get_tables_and_variables(sample_session, ["users"])
+
+ users_table = result.tables["users"]
+ assert isinstance(users_table, DataTableMetadata)
+ assert users_table.source == "database"
+ assert users_table.num_rows == 100
+ assert users_table.num_columns == 3
+ assert users_table.primary_keys == ["id"]
+ assert users_table.indexes == ["idx_name"]
+
+ # Check column structure
+ assert len(users_table.columns) == 3
+ id_column = users_table.columns[0]
+ assert isinstance(id_column, DataTableColumn)
+ assert id_column.name == "id"
+ assert id_column.type == "int"
+ assert id_column.external_type == "INTEGER"
+ assert id_column.sample_values == [1, 2, 3]
+
+
+def test_cell_variable_value_structure(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test that CellVariableValue is properly structured."""
+ result = tool._get_tables_and_variables(sample_session, ["x", "my_list"])
+
+ x_var = result.variables["x"]
+ assert isinstance(x_var, CellVariableValue)
+ assert x_var.name == "x"
+ assert x_var.value == 42
+ assert x_var.data_type == "int"
+
+ list_var = result.variables["my_list"]
+ assert isinstance(list_var, CellVariableValue)
+ assert list_var.name == "my_list"
+ assert list_var.value == [1, 2, 3]
+ assert list_var.data_type == "list"
+
+
+def test_empty_session(tool: GetTablesAndVariables):
+ """Test _get_tables_and_variables with empty session (no tables or variables)."""
+ empty_session = MockSession(
+ MockSessionView(datasets=MockDatasets(tables=[]), variable_values={})
+ )
+ result = tool._get_tables_and_variables(empty_session, [])
+
+ assert isinstance(result, TablesAndVariablesOutput)
+ assert len(result.tables) == 0
+ assert len(result.variables) == 0
+
+
+def test_table_with_no_primary_keys_or_indexes(tool: GetTablesAndVariables):
+ """Test table with no primary keys or indexes."""
+ table_without_keys = MockDataset(
+ name="simple_table",
+ source="json",
+ num_rows=10,
+ num_columns=2,
+ columns=[
+ DataTableColumn("col1", "str", "TEXT", ["a", "b"]),
+ DataTableColumn("col2", "int", "INTEGER", [1, 2]),
+ ],
+ primary_keys=None,
+ indexes=None,
+ )
+
+ session = MockSession(
+ MockSessionView(
+ datasets=MockDatasets(tables=[table_without_keys]),
+ variable_values={},
+ )
+ )
+
+ result = tool._get_tables_and_variables(session, ["simple_table"])
+
+ simple_table = result.tables["simple_table"]
+ assert simple_table.primary_keys is None
+ assert simple_table.indexes is None
+
+
+def test_variable_with_none_value(tool: GetTablesAndVariables):
+ """Test variable with None value."""
+ variables_with_none = {
+ "none_var": VariableValue("none_var", None, "NoneType"),
+ }
+
+ session = MockSession(
+ MockSessionView(
+ datasets=MockDatasets(tables=[]),
+ variable_values=variables_with_none,
+ )
+ )
+
+ result = tool._get_tables_and_variables(session, ["none_var"])
+
+ none_var = result.variables["none_var"]
+ assert none_var.name == "none_var"
+ assert none_var.value is None
+ assert none_var.data_type == "NoneType"
+
+
+def test_filtering_logic_separate_tables_and_variables(
+ tool: GetTablesAndVariables, sample_session: MockSession
+):
+ """Test that filtering works correctly for both tables and variables separately."""
+ # Request only table names (no matching variables)
+ result = tool._get_tables_and_variables(
+ sample_session, ["users", "orders"]
+ )
+
+ assert len(result.tables) == 2
+ assert len(result.variables) == 0
+
+ # Request only variable names (no matching tables)
+ result = tool._get_tables_and_variables(sample_session, ["x", "y"])
+
+ assert len(result.tables) == 0
+ assert len(result.variables) == 2
diff --git a/tests/_server/ai/tools/test_tool_manager.py b/tests/_server/ai/tools/test_tool_manager.py
index 97e5be7c6a..9bca5bee14 100644
--- a/tests/_server/ai/tools/test_tool_manager.py
+++ b/tests/_server/ai/tools/test_tool_manager.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import pytest
from starlette.applications import Starlette
+from marimo._ai._tools.tools_registry import SUPPORTED_BACKEND_AND_MCP_TOOLS
from marimo._config.manager import get_default_config_manager
from marimo._server.ai.tools.tool_manager import ToolManager
from marimo._server.ai.tools.types import ToolCallResult
@@ -25,12 +26,8 @@ def test_get_tools_for_mode(manager: ToolManager):
# Mock the config to disable MCP
tools = manager.get_tools_for_mode("ask")
- # Should have backend tools (GetActiveNotebooks, GetCellRuntimeData, GetLightweightCellMap)
- assert len(tools) == 3
- tool_names = {tool.name for tool in tools}
- assert "get_active_notebooks" in tool_names
- assert "get_cell_runtime_data" in tool_names
- assert "get_lightweight_cell_map" in tool_names
+ # Should have backend tools
+ assert len(tools) == len(SUPPORTED_BACKEND_AND_MCP_TOOLS)
# All should be backend tools for ask mode
for tool in tools: