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
feat: add MCP server integration with notebook inspection tools (#6222)
Joaquin Coromina8b162e17f1a6
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex ca8a221582..a447181b0f 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -445,6 +445,15 @@ https://github.com/marimo-team/marimo/issues/5219.""",hidden=True,help="When opening a .py file, enable fallback conversion from pypercent, script, or text.",)+ "--mcp",+ is_flag=True,+ default=False,+ show_default=True,+ type=bool,+ hidden=True,+ help="Enable MCP server endpoint at /mcp/server for LLM integration.",+)@click.option("--asset-url",default=None,@@ -483,6 +492,7 @@ def edit(skew_protection: bool,remote_url: Optional[str],convert: bool,+ mcp: bool,asset_url: Optional[str],timeout: Optional[float],name: Optional[str],@@ -612,6 +622,7 @@ def edit(redirect_console_to_browser=True,ttl_seconds=None,remote_url=remote_url,+ mcp=mcp,asset_url=asset_url,timeout=timeout,)diff --git a/marimo/_mcp/server/exceptions.py b/marimo/_mcp/server/exceptions.pynew file mode 100644index 0000000000..a9baa02992--- /dev/null+++ b/marimo/_mcp/server/exceptions.py@@ -0,0 +1,95 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Optional+++@dataclass+class ToolErrorDetails:+ """Structured representation of tool execution error details."""++ message: str+ code: str = "TOOL_ERROR"+ status: int = 400+ is_retryable: bool = False+ suggested_fix: Optional[str] = None+ meta: Optional[dict[str, Any]] = None++ def to_dict(self) -> dict[str, Any]:+ """Return a dictionary representation of the error details."""+ return {+ "message": self.message,+ "code": self.code,+ "status": self.status,+ "is_retryable": self.is_retryable,+ "suggested_fix": self.suggested_fix,+ "meta": self.meta or {},+ }+++class ToolExecutionError(Exception):+ """Raise this from a tool to signal a descriptive, structured failure."""++ def __init__(+ self,+ message: str,+ *,+ code: str = "TOOL_ERROR",+ status: int = 400,+ is_retryable: bool = False,+ suggested_fix: Optional[str] = None,+ meta: Optional[dict[str, Any]] = None,+ ):+ # Create the structured error details using the dataclass+ self.details = ToolErrorDetails(+ message=message,+ code=code,+ status=status,+ is_retryable=is_retryable,+ suggested_fix=suggested_fix,+ meta=meta,+ )++ # Create a structured message that includes all error details+ structured_message = self._create_structured_message()+ super().__init__(structured_message)++ @property+ def original_message(self) -> str:+ """Access the original message through the details dataclass."""+ return self.details.message++ @property+ def code(self) -> str:+ """Access the error code through the details dataclass."""+ return self.details.code++ @property+ def status(self) -> int:+ """Access the status through the details dataclass."""+ return self.details.status++ @property+ def is_retryable(self) -> bool:+ """Access the retryable flag through the details dataclass."""+ return self.details.is_retryable++ @property+ def suggested_fix(self) -> Optional[str]:+ """Access the suggested fix through the details dataclass."""+ return self.details.suggested_fix++ @property+ def meta(self) -> dict[str, Any]:+ """Access the meta data through the details dataclass."""+ return self.details.meta or {}++ def _create_structured_message(self) -> str:+ """Create a message that includes all structured error information."""+ import json++ return json.dumps(self.details.to_dict(), separators=(",", ":"))++ def to_dict(self) -> dict[str, Any]:+ """Return a dictionary representation of the error details for testing."""+ return self.details.to_dict()diff --git a/marimo/_mcp/server/lifespan.py b/marimo/_mcp/server/lifespan.pynew file mode 100644index 0000000000..0746befc6f--- /dev/null+++ b/marimo/_mcp/server/lifespan.py@@ -0,0 +1,32 @@+import contextlib+from collections.abc import AsyncIterator++from starlette.applications import Starlette++from marimo._loggers import marimo_logger++LOGGER = marimo_logger()+++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():+ LOGGER.info("MCP server session manager started")+ # Session manager owns request lifecycle during app run+ yield++ except ImportError as e:+ LOGGER.warning(f"MCP server dependencies not available: {e}")+ yield+ return+ except Exception as e:+ LOGGER.error(f"Failed to start MCP server: {e}")+ raisediff --git a/marimo/_mcp/server/main.py b/marimo/_mcp/server/main.pynew file mode 100644index 0000000000..bf912fd127--- /dev/null+++ b/marimo/_mcp/server/main.py@@ -0,0 +1,60 @@+# Copyright 2024 Marimo. All rights reserved.+"""+MCP (Model Context Protocol) Server Implementation for Marimo++This module implements an MCP server that provides LLMs with access to marimo+notebook context and functionality.+"""++from typing import TYPE_CHECKING++from starlette.routing import Mount++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+++def setup_mcp_server(app: "Starlette") -> "StreamableHTTPSessionManager":+ """Create and configure MCP server for marimo integration.++ Args:+ app: Starlette application instance for accessing marimo state+ server_name: Name for the MCP server instance+ stateless_http: Whether to use stateless HTTP mode++ Returns:+ 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,+ log_level="WARNING",+ )++ # Change base path from /mcp to /server+ mcp.settings.streamable_http_path = "/server"++ # Register all tools+ register_notebooks_tools(mcp, app)+ register_cells_tools(mcp, app)++ # Initialize streamable HTTP app+ mcp_app = mcp.streamable_http_app()++ # Add to the top of the routes to avoid conflicts with other routes+ app.routes.insert(0, Mount("/mcp", mcp_app))++ return mcp.session_managerdiff --git a/marimo/_mcp/server/responses.py b/marimo/_mcp/server/responses.pynew file mode 100644index 0000000000..999f289e27--- /dev/null+++ b/marimo/_mcp/server/responses.py@@ -0,0 +1,14 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal, Optional+++@dataclass(kw_only=True)+class SuccessResult:+ status: Literal["success", "error", "warning"] = "success"+ auth_required: bool = False+ next_steps: Optional[list[str]] = None+ action_url: Optional[str] = None+ message: Optional[str] = None+ meta: Optional[dict[str, Any]] = Nonediff --git a/marimo/_mcp/server/tools/cells.py b/marimo/_mcp/server/tools/cells.pynew file mode 100644index 0000000000..305c6a5294--- /dev/null+++ b/marimo/_mcp/server/tools/cells.py@@ -0,0 +1,412 @@+from dataclasses import dataclass+from enum import Enum+from typing import TYPE_CHECKING, Optional++from mcp.server.fastmcp import FastMCP+from starlette.applications import Starlette++from marimo._ast.cell import RuntimeStateType+from marimo._ast.models import CellData+from marimo._mcp.server.exceptions import ToolExecutionError+from marimo._mcp.server.responses import (+ SuccessResult,+)+from marimo._messaging.ops import VariableValue+from marimo._server.api.deps import AppStateBase+from marimo._types.ids import CellId_t, SessionId++if TYPE_CHECKING:+ from marimo._ast.cell import Cell+ from marimo._server.sessions import Session+++class SupportedCellType(Enum):+ """Enum for core marimo cell types."""++ CODE = "code"+ MARKDOWN = "markdown"+ SQL = "sql"+++@dataclass(kw_only=True)+class LightweightCellInfo:+ cell_id: str+ preview: str # First X lines of code+ line_count: int+ cell_type: SupportedCellType+++@dataclass(kw_only=True)+class GetLightweightCellMapData:+ session_id: str+ notebook_name: str+ cells: list[LightweightCellInfo]+ total_cells: int+ preview_lines: int # How many lines were shown per cell+++@dataclass(kw_only=True)+class GetLightweightCellMapResponse(SuccessResult):+ data: GetLightweightCellMapData+++@dataclass(kw_only=True)+class ErrorDetail:+ type: str+ message: str+ traceback: list[str]+++@dataclass(kw_only=True)+class CellErrors:+ has_errors: bool+ error_details: Optional[list[ErrorDetail]]+++@dataclass(kw_only=True)+class CellRuntimeMetadata:+ runtime_state: Optional[RuntimeStateType]+ execution_time: Optional[float]+++CellVariables = dict[str, VariableValue]+++@dataclass(kw_only=True)+class GetCellRuntimeDataData:+ session_id: str+ cell_id: str+ code: Optional[str]+ errors: Optional[CellErrors]+ metadata: Optional[CellRuntimeMetadata]+ variables: Optional[CellVariables]+++@dataclass(kw_only=True)+class GetCellRuntimeDataResponse(SuccessResult):+ data: GetCellRuntimeDataData+++def register_cells_tools(mcp: FastMCP, app: Starlette) -> None:+ """Register cell-level management tools"""++ @mcp.tool()+ def get_lightweight_cell_map(+ session_id: str, preview_lines: int = 3+ ) -> GetLightweightCellMapResponse:+ """Get a lightweight map of cells showing the first few lines of each cell.++ This tool provides an overview of notebook structure for initial navigation,+ showing a preview of each cell's content without full code or outputs.++ Args:+ session_id: The session ID of the notebook from get_active_notebooks+ preview_lines: Number of lines to show per cell (default: 3)++ Returns:+ A success result containing lightweight cell previews and navigation info.+ """+ try:+ app_state = AppStateBase.from_app(app)++ # Access session manager and get the specific session+ session_manager = app_state.session_manager+ session_id_typed = SessionId(session_id)+ if session_id_typed not in session_manager.sessions:+ raise ToolExecutionError(+ f"Session {session_id} not found",+ code="SESSION_NOT_FOUND",+ is_retryable=False,+ suggested_fix="Use get_active_notebooks to find valid session IDs",+ )++ session = session_manager.sessions[session_id_typed]++ # Get cell manager from the session's app file manager+ cell_manager = session.app_file_manager.app.cell_manager+ notebook_filename = (+ session.app_file_manager.filename or "untitled_notebook.py"+ )++ # Build actual cell map from cell manager data+ cells: list[LightweightCellInfo] = []+ for cell_data in cell_manager.cell_data():+ code_lines = cell_data.code.split("\n")+ preview = "\n".join(code_lines[:preview_lines])++ # Determine cell type using actual marimo cell data when available+ cell_type = _determine_cell_type(+ cell_data.code, cell_data.cell+ )++ cells.append(+ LightweightCellInfo(+ cell_id=cell_data.cell_id,+ preview=preview,+ line_count=len(code_lines),+ cell_type=cell_type,+ )+ )++ # Return a success result with lightweight cell map+ return GetLightweightCellMapResponse(+ data=GetLightweightCellMapData(+ session_id=session_id,+ notebook_name=notebook_filename,+ cells=cells,+ total_cells=len(cells),+ preview_lines=preview_lines,+ ),+ next_steps=[+ "Use cell_id to get full cell content or execute specific cells",+ "Identify key sections based on cell types and previews",+ "Focus on import cells first to understand dependencies",+ ],+ message="Refer to cells ordinally in the following format: @[cell:1]. Do _not_ use cell_id when discussing the with users.",+ )++ except Exception as e:+ # Return a structured error result+ raise ToolExecutionError(+ f"Failed to retrieve cell map for session {session_id}",+ code="CELL_MAP_ERROR",+ is_retryable=True,+ suggested_fix="Verify the session_id exists and the notebook is active. You can use the get_active_notebooks tool.",+ meta={+ "session_id": session_id,+ "preview_lines": preview_lines,+ },+ ) from e++ @mcp.tool()+ def get_cell_runtime_data(+ session_id: str, cell_id: str+ ) -> GetCellRuntimeDataResponse:+ """Get runtime data for a specific cell 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.++ 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++ Returns:+ A success result containing cell runtime data including code, errors, and variables.+ """+ try:+ app_state = AppStateBase.from_app(app)++ # Access session manager and get the specific session+ session_manager = app_state.session_manager+ session_id_typed = SessionId(session_id)+ if session_id_typed not in session_manager.sessions:+ raise ToolExecutionError(+ f"Session {session_id} not found",+ code="SESSION_NOT_FOUND",+ is_retryable=False,+ suggested_fix="Use get_active_notebooks to find valid session IDs",+ )++ session = session_manager.sessions[session_id_typed]+ cell_manager = session.app_file_manager.app.cell_manager++ # Get cell data using CellManager's existing method+ cell_id_typed = CellId_t(cell_id)+ cell_data = cell_manager.get_cell_data(cell_id_typed)+ if cell_data is None:+ raise ToolExecutionError(+ f"Cell {cell_id} not found in session {session_id}",+ code="CELL_NOT_FOUND",+ is_retryable=False,+ suggested_fix="Use get_lightweight_cell_map to find valid cell IDs",+ )++ # Get cell code/source+ cell_code = cell_data.code++ # Get cell errors from session view with actual error details+ cell_errors = _get_cell_errors(session, cell_id_typed)++ # Get cell runtime metadata+ cell_metadata = _get_cell_metadata(session, cell_id_typed)++ # Get variable names and values defined by the cell+ cell_variables = _get_cell_variables(session, cell_data)++ return GetCellRuntimeDataResponse(+ data=GetCellRuntimeDataData(+ session_id=session_id,+ cell_id=cell_id,+ code=cell_code,+ errors=cell_errors,+ metadata=cell_metadata,+ variables=cell_variables,+ ),+ next_steps=[+ "Review cell code for understanding the implementation",+ "Check errors to identify any execution issues",+ "Examine variables to understand cell outputs and state",+ ],+ )++ except ToolExecutionError:+ # Re-raise our specific tool errors (like CELL_NOT_FOUND, SESSION_NOT_FOUND)+ raise+ except Exception as e:+ # Only catch unexpected exceptions+ raise ToolExecutionError(+ f"Failed to retrieve runtime data for cell {cell_id} in session {session_id}",+ code="CELL_RUNTIME_ERROR",+ is_retryable=True,+ suggested_fix="Verify the session_id using get_active_notebooks and the cell_id using get_lightweight_cell_map.",+ meta={"session_id": session_id, "cell_id": cell_id},+ ) from e+++# Utility functions+def is_markdown_cell(code: str) -> bool:+ """Check if a cell is a markdown cell."""+ if code.lstrip().startswith("mo.md("):+ return True+ return False+++def _determine_cell_type(+ code: str, cell: Optional["Cell"] = None+) -> SupportedCellType:+ """Determine the type of cell based on marimo's compiled cell data.++ Uses the actual Language field from CellData.cell.language when available,+ falling back to code analysis for edge cases.+ Only returns types from Literal["code", "markdown", "sql"].+ """++ # If we have the compiled cell data, use marimo's official language detection+ if cell is not None:+ language = cell._cell.language+ if language == "sql":+ return SupportedCellType.SQL+ elif language == "python":+ # For Python cells, check if it's actually a markdown cell+ # by using marimo's official markdown detection+ if is_markdown_cell(code):+ return SupportedCellType.MARKDOWN+ return SupportedCellType.CODE++ # Default to code for all other cases+ return SupportedCellType.CODE+++def _get_cell_errors(session: "Session", cell_id: CellId_t) -> CellErrors:+ """Get cell errors from session view with actual error details."""+ from marimo._messaging.cell_output import CellChannel++ # Get cell operation from session view+ session_view = session.session_view+ cell_op = session_view.cell_operations.get(cell_id)++ if cell_op is None:+ # No operations recorded for this cell+ return CellErrors(has_errors=False, error_details=None)++ # Check for actual error details in the output+ has_errors = False+ error_details = []+ if cell_op.output and cell_op.output.channel == CellChannel.MARIMO_ERROR:+ has_errors = True+ # Extract actual error objects+ errors = cell_op.output.data+ if isinstance(errors, list):+ for error in errors:+ if hasattr(error, "type") and hasattr(error, "describe"):+ # Rich Error object+ error_detail = ErrorDetail(+ type=error.type,+ message=error.describe(),+ traceback=getattr(error, "traceback", []),+ )+ error_details.append(error_detail)+ elif isinstance(error, dict):+ # Dict-based error+ dict_error_detail = ErrorDetail(+ type=error.get("type", "UnknownError"),+ message=error.get("msg", str(error)),+ traceback=error.get("traceback", []),+ )+ error_details.append(dict_error_detail)+ else:+ # Fallback for other error types+ fallback_error_detail = ErrorDetail(+ type=type(error).__name__,+ message=str(error),+ traceback=[],+ )+ error_details.append(fallback_error_detail)++ # Check console outputs for STDERR (includes print statements to stderr, warnings, etc.)+ if cell_op.console:+ console_outputs = (+ cell_op.console+ if isinstance(cell_op.console, list)+ else [cell_op.console]+ )+ for console_output in console_outputs:+ if console_output.channel == CellChannel.STDERR:+ has_errors = True+ stderr_error_detail = ErrorDetail(+ type="STDERR",+ message=str(console_output.data),+ traceback=[],+ )+ error_details.append(stderr_error_detail)++ return CellErrors(+ has_errors=has_errors,+ error_details=error_details if error_details else None,+ )+++def _get_cell_metadata(+ session: "Session", cell_id: CellId_t+) -> CellRuntimeMetadata:+ """Get cell runtime metadata including status and execution info."""+ # Get basic runtime state from session view+ session_view = session.session_view+ cell_op = session_view.cell_operations.get(cell_id)++ runtime_state = None+ if cell_op and cell_op.status is not None:+ runtime_state = cell_op.status++ # Get execution time if available+ execution_time = session_view.last_execution_time.get(cell_id)++ return CellRuntimeMetadata(+ runtime_state=runtime_state, execution_time=execution_time+ )+++def _get_cell_variables(+ session: "Session", cell_data: Optional[CellData]+) -> CellVariables:+ """Get variables defined by a specific cell and their values."""+ if not cell_data or not cell_data.cell:+ return {}++ # Get all current variables from session view+ session_view = session.session_view+ all_variables = session_view.variable_values++ # Get variables defined by this cell+ cell_defs = cell_data.cell._cell.defs++ # Filter to only variables defined by this cell+ cell_variables: CellVariables = {}+ for var_name in cell_defs:+ if var_name in all_variables:+ var_value = all_variables[var_name]+ cell_variables[var_name] = var_value++ return cell_variablesdiff --git a/marimo/_mcp/server/tools/notebooks.py b/marimo/_mcp/server/tools/notebooks.pynew file mode 100644index 0000000000..af398671d1--- /dev/null+++ b/marimo/_mcp/server/tools/notebooks.py@@ -0,0 +1,125 @@+from dataclasses import dataclass+from typing import Optional++from mcp.server.fastmcp import FastMCP+from starlette.applications import Starlette++from marimo._mcp.server.exceptions import ToolExecutionError+from marimo._mcp.server.responses import (+ SuccessResult,+)+from marimo._server.api.deps import AppStateBase+from marimo._server.model import ConnectionState+from marimo._server.models.home import MarimoFile+from marimo._types.ids import SessionId+from marimo._utils.paths import pretty_path+++@dataclass(kw_only=True)+class NotebookInfo:+ name: str+ path: str+ session_id: Optional[SessionId]+ initialization_id: Optional[str]+++@dataclass(kw_only=True)+class SummaryInfo:+ total_notebooks: int+ total_sessions: int+ active_connections: int+++@dataclass(kw_only=True)+class GetActiveNotebooksData:+ summary: SummaryInfo+ notebooks: list[NotebookInfo]+++@dataclass(kw_only=True)+class GetActiveNotebooksResponse(SuccessResult):+ data: GetActiveNotebooksData+++def register_notebooks_tools(mcp: FastMCP, app: Starlette) -> None:+ """Register notebook-level management tools"""++ @mcp.tool()+ def get_active_notebooks() -> GetActiveNotebooksResponse:+ """List currently active marimo notebooks and a summary block.++ Returns:+ A success result containing summary statistics and notebook details.+ """+ try:+ app_state = AppStateBase.from_app(app)+ active_files = _get_active_sessions_internal(app_state)++ # Build notebooks list+ notebooks: list[NotebookInfo] = []+ for file_info in active_files:+ notebooks.append(+ NotebookInfo(+ name=file_info.name,+ path=file_info.path,+ session_id=file_info.session_id,+ initialization_id=file_info.initialization_id,+ )+ )++ # Build summary statistics+ session_manager = app_state.session_manager+ summary: SummaryInfo = SummaryInfo(+ total_notebooks=len(active_files),+ total_sessions=len(session_manager.sessions),+ active_connections=session_manager.get_active_connection_count(),+ )++ # Build data object+ data = GetActiveNotebooksData(summary=summary, notebooks=notebooks)++ # Return a success result with summary statistics and notebook details+ return GetActiveNotebooksResponse(+ data=data,+ next_steps=[+ "Use the `get_lightweight_cell_map` tool to get the content of a notebook"+ ],+ )++ except Exception as e:+ # Return a structured error result+ raise ToolExecutionError(+ "Failed to retrieve active notebooks",+ code="NOTEBOOK_FETCH_ERROR",+ is_retryable=True,+ suggested_fix="Tell the user to check if marimo server is running and accessible. Suggest restarting the server if they haven't already tried that.",+ ) from e+++# Utility functions+++def _get_active_sessions_internal(app_state: AppStateBase) -> list[MarimoFile]:+ """+ Get active sessions from the app state.++ This replicates the logic from marimo/_server/api/endpoints/home.py+ """+ import os++ files: list[MarimoFile] = []+ for session_id, session in app_state.session_manager.sessions.items():+ state = session.connection_state()+ if state == ConnectionState.OPEN or state == ConnectionState.ORPHANED:+ filename = session.app_file_manager.filename+ basename = os.path.basename(filename) if filename else None+ files.append(+ MarimoFile(+ name=(basename or "new notebook"),+ path=(pretty_path(filename) if filename else session_id),+ session_id=session_id,+ initialization_id=session.initialization_id,+ )+ )+ # Return most recent notebooks first (reverse chronological order)+ return files[::-1]diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex c0c5e46b2f..cfee77faa5 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -14,6 +14,7 @@ if TYPE_CHECKING:from starlette.applications import Starlettefrom starlette.datastructures import Statefrom starlette.requests import Request+ from starlette.types import ASGIAppfrom starlette.websockets import WebSocketfrom uvicorn import Server@@ -93,6 +94,11 @@ class AppStateBase:headless: bool = self.state.headlessreturn headless+ @property+ def skew_protection(self) -> bool:+ skew_protection: bool = self.state.skew_protection+ return skew_protection+@propertydef skew_protection_token(self) -> SkewProtectionToken:return self.session_manager.skew_protection_token@@ -101,6 +107,15 @@ class AppStateBase:def remote_url(self) -> Optional[str]:return getattr(self.state, "remote_url", None)+ @property+ def mcp_server_enabled(self) -> bool:+ mcp_server_enabled: bool = self.state.mcp_server_enabled+ return mcp_server_enabled++ @property+ def mcp_handler(self) -> Optional[ASGIApp]:+ return getattr(self.state, "mcp_handler", None)+@propertydef asset_url(self) -> Optional[str]:return getattr(self.state, "asset_url", None)diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex 62d642465f..2d72493341 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -15,6 +15,7 @@ from marimo._server.lsp import any_lsp_server_runningfrom marimo._server.model import SessionModefrom marimo._server.print import (print_experimental_features,+ print_mcp,print_shutdown,print_startup,)@@ -138,6 +139,8 @@ async def logging(app: Starlette) -> AsyncIterator[None]:state = AppState.from_app(app)manager: SessionManager = state.session_managerfile_router = manager.file_router+ mcp_server_enabled = state.mcp_server_enabled+ skew_protection_enabled = state.skew_protection# Startup messageif not manager.quiet:@@ -152,6 +155,13 @@ async def logging(app: Starlette) -> AsyncIterator[None]:print_experimental_features(state.config_manager.get_config())+ if mcp_server_enabled:+ mcp_url = _mcp_startup_url(state)+ server_token = None+ if skew_protection_enabled:+ server_token = str(state.session_manager.skew_protection_token)+ print_mcp(mcp_url, server_token)+yield# Shutdown message@@ -211,3 +221,34 @@ def _startup_url(state: AppStateBase) -> str:if AuthToken.is_empty(state.session_manager.auth_token):return urlreturn f"{url}?access_token={str(state.session_manager.auth_token)}"+++def _mcp_startup_url(state: AppStateBase) -> str:+ host = state.host+ port = state.port+ base_url = state.base_url++ # Handle localhost pretty printing (same logic as _startup_url)+ try:+ if (+ socket.getnameinfo((host, port), socket.NI_NOFQDN)[0]+ == "localhost"+ ):+ host = "localhost"+ except Exception:+ ...++ # Construct MCP endpoint URL+ mcp_prefix = "/mcp"+ mcp_name = "server"+ full_mcp_path = f"{mcp_prefix}/{mcp_name}"+ url = f"http://{host}:{port}{base_url}{full_mcp_path}"+ if port == 80:+ url = f"http://{host}{base_url}{full_mcp_path}"+ elif port == 443:+ url = f"https://{host}{base_url}{full_mcp_path}"++ # Add access token if not empty+ if AuthToken.is_empty(state.session_manager.auth_token):+ return url+ return f"{url}?access_token={str(state.session_manager.auth_token)}"diff --git a/marimo/_server/print.py b/marimo/_server/print.pyindex 663efc91dc..944a304506 100644--- a/marimo/_server/print.py+++ b/marimo/_server/print.py@@ -155,3 +155,19 @@ def print_experimental_features(config: MarimoConfig) -> None:print_tabbed(f"{_utf8('🧪')} {green('Experimental features (use with caution)')}: {', '.join(keys)}")+++def print_mcp(mcp_url: str, server_token: str | None) -> None:+ """Print MCP server configuration when MCP is enabled."""+ print_()+ print_tabbed(+ f"{_utf8('🔗')} {green('Experimental MCP Server Configuration', bold=True)}"+ )+ print_tabbed(+ f"{_utf8('➜')} {green('MCP Server URL')}: {_colorized_url(mcp_url)}"+ )+ if server_token is not None:+ print_tabbed(+ f"{_utf8('➜')} {green('Add Header')}: Marimo-Server-Token: {muted(server_token)}"+ )+ print_()diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex b4c487d2b9..d3b071c8aa 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -90,6 +90,7 @@ def start(redirect_console_to_browser: bool,skew_protection: bool,remote_url: Optional[str] = None,+ mcp: bool = False,asset_url: Optional[str] = None,timeout: Optional[float] = None,) -> None:@@ -163,21 +164,26 @@ def start(log_level = "info" if development_mode else "error"+ lifespans_list = [+ lifespans.lsp,+ lifespans.mcp,+ lifespans.etc,+ lifespans.signal_handler,+ lifespans.logging,+ lifespans.open_browser,+ *LIFESPAN_REGISTRY.get_all(),+ ]++ if mcp and mode == SessionMode.EDIT:+ from marimo._mcp.server.lifespan import mcp_server_lifespan++ lifespans_list.append(mcp_server_lifespan)+(external_port, external_host) = _resolve_proxy(port, host, proxy)app = create_starlette_app(base_url=base_url,host=external_host,- lifespan=Lifespans(- [- lifespans.lsp,- lifespans.mcp,- lifespans.etc,- lifespans.signal_handler,- lifespans.logging,- lifespans.open_browser,- *LIFESPAN_REGISTRY.get_all(),- ]- ),+ lifespan=Lifespans(lifespans_list),allow_origins=allow_origins,enable_auth=not AuthToken.is_empty(session_manager.auth_token),lsp_servers=list(lsp_composite_server.servers.values())@@ -197,6 +203,8 @@ def start(app.state.asset_url = asset_urlapp.state.config_manager = config_readerapp.state.remote_url = remote_url+ app.state.mcp_server_enabled = mcp+ app.state.skew_protection = skew_protection# Resource initialization# Increase the limit on open file descriptors to prevent resourcediff --git a/pyproject.toml b/pyproject.tomlindex d44ab1b383..58d4638ede 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -119,6 +119,11 @@ lsp = ["python-lsp-ruff>=2.0.0",]+mcp = [+ "mcp>=1.0.0; python_version >= '3.10'",+]++docs = ["mkdocs>=1.6.1","mkdocs-material>=9.5.49",diff --git a/tests/_mcp/server/test_exceptions.py b/tests/_mcp/server/test_exceptions.pynew file mode 100644index 0000000000..284363f08d--- /dev/null+++ b/tests/_mcp/server/test_exceptions.py@@ -0,0 +1,111 @@+"""Tests for marimo._mcp.server.exceptions module."""++import json++import pytest++# Skip all MCP tests if Python < 3.10 or MCP not available+pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++from marimo._mcp.server.exceptions import ToolExecutionError+++def test_tool_execution_error_basic():+ """Test basic ToolExecutionError creation."""+ error = ToolExecutionError("Something went wrong")++ assert error.original_message == "Something went wrong"+ assert error.code == "TOOL_ERROR"+ assert error.status == 400+ assert error.is_retryable is False+ assert error.suggested_fix is None+ assert error.meta == {}+++def test_tool_execution_error_with_all_params():+ """Test ToolExecutionError with all parameters."""+ meta_data = {"session_id": "test123", "cell_id": "abc"}++ error = ToolExecutionError(+ "Custom error message",+ code="CUSTOM_ERROR",+ status=500,+ is_retryable=True,+ suggested_fix="Try restarting the server",+ meta=meta_data,+ )++ assert error.original_message == "Custom error message"+ assert error.code == "CUSTOM_ERROR"+ assert error.status == 500+ assert error.is_retryable is True+ assert error.suggested_fix == "Try restarting the server"+ assert error.meta == meta_data+++def test_tool_execution_error_structured_message():+ """Test that the structured message contains all error details."""+ error = ToolExecutionError(+ "Test error",+ code="TEST_CODE",+ status=422,+ is_retryable=True,+ suggested_fix="Fix the test",+ meta={"key": "value"},+ )++ # The structured message should be valid JSON+ structured_msg = str(error)+ parsed = json.loads(structured_msg)++ assert parsed["message"] == "Test error"+ assert parsed["code"] == "TEST_CODE"+ assert parsed["status"] == 422+ assert parsed["is_retryable"] is True+ assert parsed["suggested_fix"] == "Fix the test"+ assert parsed["meta"] == {"key": "value"}+++def test_tool_execution_error_to_dict():+ """Test the to_dict method."""+ error = ToolExecutionError(+ "Dict test",+ code="DICT_ERROR",+ status=404,+ is_retryable=False,+ suggested_fix="Check the ID",+ meta={"test": True},+ )++ error_dict = error.to_dict()++ expected = {+ "code": "DICT_ERROR",+ "message": "Dict test",+ "status": 404,+ "is_retryable": False,+ "suggested_fix": "Check the ID",+ "meta": {"test": True},+ }++ assert error_dict == expected+++def test_tool_execution_error_inheritance():+ """Test that ToolExecutionError properly inherits from Exception."""+ error = ToolExecutionError("Test inheritance")++ assert isinstance(error, Exception)++ # Should be raisable and catchable+ with pytest.raises(ToolExecutionError) as exc_info:+ raise error++ assert exc_info.value.original_message == "Test inheritance"+++def test_tool_execution_error_none_meta():+ """Test that None meta gets converted to empty dict."""+ error = ToolExecutionError("Test", meta=None)++ assert error.meta == {}diff --git a/tests/_mcp/server/test_main.py b/tests/_mcp/server/test_main.pynew file mode 100644index 0000000000..31a95c9791--- /dev/null+++ b/tests/_mcp/server/test_main.py@@ -0,0 +1,11 @@+# Copyright 2024 Marimo. All rights reserved.+import pytest++pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++# TODO: Currently researching best practices for how to test MCP Servers in memory+# Need to investigate:+# - How to create an in-memory MCP server instance for testing+# - Best practices for mocking MCP client-server communication+# - Testing MCP protocol compliance and tool execution+# - Integration testing patterns for MCP serversdiff --git a/tests/_mcp/server/test_responses.py b/tests/_mcp/server/test_responses.pynew file mode 100644index 0000000000..545de98d6e--- /dev/null+++ b/tests/_mcp/server/test_responses.py@@ -0,0 +1,72 @@+"""Tests for marimo._mcp.server.responses module."""++from typing import TypedDict++import pytest++# Skip all MCP tests if Python < 3.10 or MCP not available+pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++from marimo._mcp.server.responses import (+ SuccessResult,+)+++class SampleData(TypedDict):+ message: str+ count: int+++def test_success_result_basic():+ """Test basic success result creation."""+ result = SuccessResult()++ assert result.status == "success"+ assert result.auth_required is False+ assert result.next_steps is None+ assert result.action_url is None+ assert result.message is None+ assert result.meta is None+++def test_success_result_with_all_params():+ """Test success result with all optional parameters."""+ next_steps = ["Step 1", "Step 2"]++ result = SuccessResult(+ status="warning",+ auth_required=True,+ next_steps=next_steps,+ action_url="https://example.com",+ message="Custom message",+ meta={"key": "value"},+ )++ assert result.status == "warning"+ assert result.auth_required is True+ assert result.next_steps == next_steps+ assert result.action_url == "https://example.com"+ assert result.message == "Custom message"+ assert result.meta == {"key": "value"}+++def test_success_result_with_meta():+ """Test success result with meta data."""+ meta_data = {"key": "value", "count": 100}++ result = SuccessResult(meta=meta_data)++ assert result.meta == meta_data+++def test_success_result_type_structure():+ """Test that SuccessResult has the expected structure."""+ result = SuccessResult()++ # Verify all required fields exist+ assert hasattr(result, "status")+ assert hasattr(result, "auth_required")+ assert hasattr(result, "next_steps")+ assert hasattr(result, "action_url")+ assert hasattr(result, "message")+ assert hasattr(result, "meta")diff --git a/tests/_mcp/server/tools/test_cells.py b/tests/_mcp/server/tools/test_cells.pynew file mode 100644index 0000000000..ffe61daffc--- /dev/null+++ b/tests/_mcp/server/tools/test_cells.py@@ -0,0 +1,266 @@+"""Tests for marimo._mcp.server.tools.cells module."""++from unittest.mock import Mock++import pytest++# Skip all MCP tests if Python < 3.10 or MCP not available+pytest.importorskip("mcp", reason="MCP requires Python 3.10+")+++from marimo._mcp.server.tools.cells import (+ CellErrors,+ CellRuntimeMetadata,+ CellVariables,+ SupportedCellType,+ _determine_cell_type,+ _get_cell_errors,+ _get_cell_metadata,+ _get_cell_variables,+)+from marimo._messaging.cell_output import CellChannel+from marimo._messaging.ops import VariableValue+++class MockCellOp:+ """Mock CellOp for testing."""++ def __init__(self, output=None, console=None, status=None):+ self.output = output+ self.console = console+ self.status = status+++class MockOutput:+ """Mock output for testing."""++ def __init__(self, channel, data):+ self.channel = channel+ self.data = data+++class MockConsoleOutput:+ """Mock console output for testing."""++ def __init__(self, channel, data):+ self.channel = channel+ self.data = data+++class MockError:+ """Mock error object for testing."""++ def __init__(self, error_type, message, traceback=None):+ self.type = error_type+ self._message = message+ self.traceback = traceback or []++ def describe(self):+ return self._message+++class MockSessionView:+ """Mock session view for testing."""++ def __init__(+ self,+ cell_operations=None,+ last_execution_time=None,+ variable_values=None,+ ):+ self.cell_operations = cell_operations or {}+ self.last_execution_time = last_execution_time or {}+ self.variable_values = variable_values or {}+++class MockSession:+ """Mock session for testing."""++ def __init__(self, session_view):+ self.session_view = session_view+++class MockCell:+ """Mock cell for testing."""++ def __init__(self, language="python", defs=None):+ self._cell = Mock()+ self._cell.language = language+ self._cell.defs = defs or set()+++def test_determine_cell_type_default():+ """Test _determine_cell_type defaults to CODE."""+ result = _determine_cell_type("print('hello')")+ assert result == SupportedCellType.CODE+++def test_determine_cell_type_with_sql_cell():+ """Test _determine_cell_type with SQL cell."""+ cell = MockCell(language="sql")++ result = _determine_cell_type("SELECT * FROM table", cell)+ assert result == SupportedCellType.SQL+++def test_determine_cell_type_with_python_cell():+ """Test _determine_cell_type with Python cell."""+ cell = MockCell(language="python")++ result = _determine_cell_type("x = 1", cell)+ assert result == SupportedCellType.CODE+++def test_get_cell_errors_no_cell_op():+ """Test _get_cell_errors when no cell operation exists."""+ session_view = MockSessionView()+ session = MockSession(session_view)++ result = _get_cell_errors(session, "nonexistent_cell")++ expected = CellErrors(has_errors=False, error_details=None)+ assert result == expected+++def test_get_cell_errors_with_marimo_error():+ """Test _get_cell_errors with marimo error."""+ error = MockError(+ "NameError", "name 'x' is not defined", ["line 1", "line 2"]+ )+ output = MockOutput(CellChannel.MARIMO_ERROR, [error])+ cell_op = MockCellOp(output=output)++ session_view = MockSessionView(cell_operations={"cell1": cell_op})+ session = MockSession(session_view)++ result = _get_cell_errors(session, "cell1")++ assert result.has_errors is True+ assert len(result.error_details) == 1+ assert result.error_details[0].type == "NameError"+ assert result.error_details[0].message == "name 'x' is not defined"+ assert result.error_details[0].traceback == ["line 1", "line 2"]+++def test_get_cell_errors_with_stderr():+ """Test _get_cell_errors with STDERR output."""+ console_output = MockConsoleOutput(+ CellChannel.STDERR, "Warning: deprecated function"+ )+ cell_op = MockCellOp(console=[console_output])++ session_view = MockSessionView(cell_operations={"cell1": cell_op})+ session = MockSession(session_view)++ result = _get_cell_errors(session, "cell1")++ assert result.has_errors is True+ assert len(result.error_details) == 1+ assert result.error_details[0].type == "STDERR"+ assert result.error_details[0].message == "Warning: deprecated function"+ assert result.error_details[0].traceback == []+++def test_get_cell_errors_dict_error():+ """Test _get_cell_errors with dict-based error."""+ dict_error = {+ "type": "ValueError",+ "msg": "invalid value",+ "traceback": ["tb1"],+ }+ output = MockOutput(CellChannel.MARIMO_ERROR, [dict_error])+ cell_op = MockCellOp(output=output)++ session_view = MockSessionView(cell_operations={"cell1": cell_op})+ session = MockSession(session_view)++ result = _get_cell_errors(session, "cell1")++ assert result.has_errors is True+ assert result.error_details[0].type == "ValueError"+ assert result.error_details[0].message == "invalid value"+ assert result.error_details[0].traceback == ["tb1"]+++def test_get_cell_metadata_basic():+ """Test _get_cell_metadata basic functionality."""+ cell_op = MockCellOp(status="idle")+ session_view = MockSessionView(+ cell_operations={"cell1": cell_op}, last_execution_time={"cell1": 42.5}+ )+ session = MockSession(session_view)++ result = _get_cell_metadata(session, "cell1")++ expected = CellRuntimeMetadata(+ runtime_state="idle",+ execution_time=42.5,+ )+ assert result == expected+++def test_get_cell_metadata_no_cell_op():+ """Test _get_cell_metadata when no cell operation exists."""+ session_view = MockSessionView()+ session = MockSession(session_view)++ result = _get_cell_metadata(session, "nonexistent")++ expected = CellRuntimeMetadata(+ runtime_state=None,+ execution_time=None,+ )+ assert result == expected+++def test_get_cell_variables_no_cell_data():+ """Test _get_cell_variables with no cell data."""+ session = MockSession(MockSessionView())++ result = _get_cell_variables(session, None)++ assert result == {}+++def test_get_cell_variables_with_variables():+ """Test _get_cell_variables with actual variables."""+ # Mock cell with defined variables+ cell = MockCell(defs={"x", "y"})+ cell_data = Mock()+ cell_data.cell = cell++ # Mock variable values+ var_x = VariableValue("x", 42, "int")+ var_y = VariableValue("y", "hello", "str")+ var_z = VariableValue("z", [1, 2, 3], "list") # Not defined by this cell++ session_view = MockSessionView(+ variable_values={"x": var_x, "y": var_y, "z": var_z}+ )+ session = MockSession(session_view)++ result = _get_cell_variables(session, cell_data)++ expected: CellVariables = {"x": var_x, "y": var_y}+ assert result == expected+ assert (+ "z" not in result+ ) # Should not include variables not defined by this cell+++def test_get_cell_variables_missing_variables():+ """Test _get_cell_variables when some defined variables are missing from session."""+ cell = MockCell(defs={"x", "y", "z"})+ cell_data = Mock()+ cell_data.cell = cell++ # Only some variables are available in session+ var_x = VariableValue("x", 1, "int")+ session_view = MockSessionView(variable_values={"x": var_x})+ session = MockSession(session_view)++ result = _get_cell_variables(session, cell_data)++ # Should only include variables that exist in session+ expected: CellVariables = {"x": var_x}+ assert result == expecteddiff --git a/tests/_mcp/server/tools/test_notebooks.py b/tests/_mcp/server/tools/test_notebooks.pynew file mode 100644index 0000000000..738b6a8f16--- /dev/null+++ b/tests/_mcp/server/tools/test_notebooks.py@@ -0,0 +1,185 @@+"""Tests for marimo._mcp.server.tools.notebooks module."""++import os+from unittest.mock import Mock, patch++import pytest++# Skip all MCP tests if Python < 3.10 or MCP not available+pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++from marimo._mcp.server.tools.notebooks import _get_active_sessions_internal+from marimo._server.model import ConnectionState+++class MockSession:+ """Mock session for testing."""++ def __init__(+ self, connection_state, filename=None, session_id="test_session"+ ):+ self._connection_state = connection_state+ self.app_file_manager = Mock()+ self.app_file_manager.filename = filename+ self.initialization_id = f"init_{session_id}"++ def connection_state(self):+ return self._connection_state+++class MockSessionManager:+ """Mock session manager for testing."""++ def __init__(self, sessions=None):+ self.sessions = sessions or {}+++class MockAppState:+ """Mock app state for testing."""++ def __init__(self, sessions=None):+ self.session_manager = MockSessionManager(sessions)+++def test_get_active_sessions_internal_empty():+ """Test _get_active_sessions_internal with no sessions."""+ app_state = MockAppState()++ result = _get_active_sessions_internal(app_state)++ assert result == []+++def test_get_active_sessions_internal_open_session():+ """Test _get_active_sessions_internal with an open session."""+ session = MockSession(+ connection_state=ConnectionState.OPEN,+ filename="/path/to/notebook.py",+ session_id="session1",+ )++ app_state = MockAppState({"session1": session})++ with patch(+ "marimo._mcp.server.tools.notebooks.pretty_path"+ ) as mock_pretty_path:+ mock_pretty_path.return_value = "notebook.py"++ result = _get_active_sessions_internal(app_state)++ assert len(result) == 1+ assert result[0].name == "notebook.py"+ assert result[0].path == "notebook.py"+ assert result[0].session_id == "session1"+ assert result[0].initialization_id == "init_session1"+++def test_get_active_sessions_internal_orphaned_session():+ """Test _get_active_sessions_internal with an orphaned session."""+ session = MockSession(+ connection_state=ConnectionState.ORPHANED,+ filename="/path/to/test.py",+ session_id="session2",+ )++ app_state = MockAppState({"session2": session})++ with patch(+ "marimo._mcp.server.tools.notebooks.pretty_path"+ ) as mock_pretty_path:+ mock_pretty_path.return_value = "test.py"++ result = _get_active_sessions_internal(app_state)++ assert len(result) == 1+ assert result[0].name == "test.py"+++def test_get_active_sessions_internal_closed_session():+ """Test _get_active_sessions_internal ignores closed sessions."""+ session = MockSession(+ connection_state=ConnectionState.CLOSED,+ filename="/path/to/closed.py",+ session_id="session3",+ )++ app_state = MockAppState({"session3": session})++ result = _get_active_sessions_internal(app_state)++ assert result == []+++def test_get_active_sessions_internal_no_filename():+ """Test _get_active_sessions_internal with session that has no filename."""+ session = MockSession(+ connection_state=ConnectionState.OPEN,+ filename=None,+ session_id="session4",+ )++ app_state = MockAppState({"session4": session})++ result = _get_active_sessions_internal(app_state)++ assert len(result) == 1+ assert result[0].name == "new notebook"+ assert result[0].path == "session4" # Uses session_id as path+ assert result[0].session_id == "session4"+++def test_get_active_sessions_internal_multiple_sessions():+ """Test _get_active_sessions_internal with multiple sessions."""+ sessions = {+ "session1": MockSession(+ ConnectionState.OPEN, "/path/first.py", "session1"+ ),+ "session2": MockSession(+ ConnectionState.CLOSED, "/path/closed.py", "session2"+ ),+ "session3": MockSession(+ ConnectionState.ORPHANED, "/path/third.py", "session3"+ ),+ }++ app_state = MockAppState(sessions)++ with patch(+ "marimo._mcp.server.tools.notebooks.pretty_path"+ ) as mock_pretty_path:+ mock_pretty_path.side_effect = lambda x: os.path.basename(x)++ result = _get_active_sessions_internal(app_state)++ # Should only include OPEN and ORPHANED sessions (not CLOSED)+ assert len(result) == 2++ # Results should be in reverse order (most recent first)+ session_ids = [f.session_id for f in result]+ assert "session3" in session_ids # ORPHANED session included+ assert "session1" in session_ids # OPEN session included+ assert "session2" not in session_ids # CLOSED session excluded+++def test_get_active_sessions_internal_reverse_order():+ """Test that results are returned in reverse order."""+ sessions = {+ "first": MockSession(ConnectionState.OPEN, "/path/a.py", "first"),+ "second": MockSession(ConnectionState.OPEN, "/path/b.py", "second"),+ "third": MockSession(ConnectionState.OPEN, "/path/c.py", "third"),+ }++ app_state = MockAppState(sessions)++ with patch(+ "marimo._mcp.server.tools.notebooks.pretty_path"+ ) as mock_pretty_path:+ mock_pretty_path.side_effect = lambda x: os.path.basename(x)++ result = _get_active_sessions_internal(app_state)++ # The exact order depends on dict iteration, but should be reversed+ # We can at least verify that we get all 3 sessions+ assert len(result) == 3+ session_ids = [f.session_id for f in result]+ assert set(session_ids) == {"first", "second", "third"}