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 prompts and ActiveNotebooks prompt to marimo mcp server (#6760)
Joaquin Corominad8ab0197d15f
diff --git a/marimo/_ai/_tools/base.py b/marimo/_ai/_tools/base.pyindex 0fa688e0b1..55068e9115 100644--- a/marimo/_ai/_tools/base.py+++ b/marimo/_ai/_tools/base.py@@ -2,7 +2,6 @@from __future__ import annotationsimport inspect-import refrom abc import ABC, abstractmethodfrom dataclasses import asdict, dataclass, is_dataclassfrom typing import (@@ -28,6 +27,7 @@ from marimo._server.ai.tools.types import (from marimo._server.api.deps import AppStateBasefrom marimo._server.sessions import Session, SessionManagerfrom marimo._types.ids import SessionId+from marimo._utils.case import to_snake_casefrom marimo._utils.dataclass_to_openapi import PythonTypeToOpenAPIfrom marimo._utils.parse_dataclass import parse_raw@@ -123,7 +123,7 @@ class ToolBase(Generic[ArgsT, OutT], ABC):# get name from class nameif self.name == "":- self.name = self._to_snake_case(self.__class__.__name__)+ self.name = to_snake_case(self.__class__.__name__)# get description from class docstringif self.description == "":@@ -241,17 +241,6 @@ class ToolBase(Generic[ArgsT, OutT], ABC):return args # type: ignore[return-value]return parse_raw(args, self.Args)- def _to_snake_case(self, name: str) -> str:- """Convert a PascalCase/CamelCase class name to snake_case function name.-- Examples:- GetCellMap -> get_cell_map- """- # Handle acronyms and normal Camel/Pascal case transitions- s1 = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)- s2 = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1)- return s2.replace("-", "_").lower()-# error defaults/hooksdef _default_error_code(self) -> str:return "UNEXPECTED_ERROR"diff --git a/marimo/_mcp/server/_prompts/base.py b/marimo/_mcp/server/_prompts/base.pynew file mode 100644index 0000000000..61e09dfb8b--- /dev/null+++ b/marimo/_mcp/server/_prompts/base.py@@ -0,0 +1,73 @@+# Copyright 2024 Marimo. All rights reserved.+"""Base class for MCP prompts."""++from __future__ import annotations++from abc import ABC, abstractmethod+from typing import TYPE_CHECKING, Callable++from marimo._utils.case import to_snake_case++if TYPE_CHECKING:+ from mcp.types import PromptMessage++ from marimo._ai._tools.base import ToolContext+++class PromptBase(ABC):+ """Base class for MCP prompts.++ Subclasses should:+ - Set description via class docstring (or override description attribute)+ - Implement get_messages() to return list[PromptMessage]+ """++ name: str = ""+ description: str = ""+ context: ToolContext++ def __init__(self, context: ToolContext) -> None:+ self.context = context++ # Infer name from class name (e.g., ActiveNotebooksPrompt -> active_notebooks_prompt)+ if self.name == "":+ self.name = to_snake_case(self.__class__.__name__)++ # Get description from class docstring+ if self.description == "":+ self.description = (self.__class__.__doc__ or "").strip()++ @abstractmethod+ def handle(self) -> list[PromptMessage]:+ """Generate prompt messages."""+ ...++ def as_mcp_prompt_fn(self) -> Callable[[], list[PromptMessage]]:+ """Return a callable suitable for mcp.prompt() registration."""+ from mcp.types import PromptMessage, TextContent++ def handler() -> list[PromptMessage]:+ try:+ return self.handle()+ except Exception as e:+ # Return error as a prompt message instead of raising+ error_message = (+ f"Error generating prompt '{self.name}': {str(e)}\n\n"+ f"Please try again or contact support if the issue persists."+ )+ return [+ PromptMessage(+ role="user",+ content=TextContent(+ type="text",+ text=error_message,+ ),+ )+ ]++ # Set metadata for MCP registration+ handler.__name__ = self.name+ handler.__doc__ = self.description+ handler.__annotations__ = {"return": list[PromptMessage]}++ return handlerdiff --git a/marimo/_mcp/server/_prompts/prompts/notebooks.py b/marimo/_mcp/server/_prompts/prompts/notebooks.pynew file mode 100644index 0000000000..67deb97512--- /dev/null+++ b/marimo/_mcp/server/_prompts/prompts/notebooks.py@@ -0,0 +1,71 @@+# Copyright 2024 Marimo. All rights reserved.+"""MCP Prompts for notebook information."""++from __future__ import annotations++from typing import TYPE_CHECKING++from marimo._mcp.server._prompts.base import PromptBase++if TYPE_CHECKING:+ from mcp.types import PromptMessage+++class ActiveNotebooks(PromptBase):+ """Get current active notebooks and their session IDs and file paths."""++ def handle(self) -> list[PromptMessage]:+ """Generate prompt messages for all active notebook sessions.++ Returns:+ List of PromptMessage objects, one per active session.+ """+ from mcp.types import PromptMessage, TextContent++ session_manager = self.context.session_manager++ # Get all active sessions+ sessions = session_manager.sessions++ if not sessions:+ return [+ PromptMessage(+ role="user",+ content=TextContent(+ type="text",+ text="No active marimo notebook sessions found.",+ ),+ )+ ]++ # Create a message for each session+ messages: list[PromptMessage] = []+ for session_id, session in sessions.items():+ # Get file path if available+ maybe_file_path = session.app_file_manager.filename++ # Create actionable message for this session+ if maybe_file_path:+ message = (+ f"Notebook session ID: {session_id}\n"+ f"Notebook file path: {maybe_file_path}\n\n"+ f"Use this session_id when calling MCP tools that require it. "+ f"You can also edit the notebook directly by modifying the file at the path above."+ )+ else:+ message = (+ f"Notebook session ID: {session_id}\n\n"+ f"Use this session_id when calling MCP tools that require it."+ )++ messages.append(+ PromptMessage(+ role="user",+ content=TextContent(+ type="text",+ text=message,+ ),+ )+ )++ return messagesdiff --git a/marimo/_mcp/server/_prompts/registry.py b/marimo/_mcp/server/_prompts/registry.pynew file mode 100644index 0000000000..d60e881470--- /dev/null+++ b/marimo/_mcp/server/_prompts/registry.py@@ -0,0 +1,9 @@+# Copyright 2024 Marimo. All rights reserved.+"""Registry of all supported MCP prompts."""++from marimo._mcp.server._prompts.base import PromptBase+from marimo._mcp.server._prompts.prompts.notebooks import ActiveNotebooks++SUPPORTED_MCP_PROMPTS: list[type[PromptBase]] = [+ ActiveNotebooks,+]diff --git a/marimo/_mcp/server/main.py b/marimo/_mcp/server/main.pyindex bdbff1f3da..656fbbb1e6 100644--- a/marimo/_mcp/server/main.py+++ b/marimo/_mcp/server/main.py@@ -38,6 +38,10 @@ def setup_mcp_server(app: Starlette) -> None:from starlette.responses import JSONResponsefrom starlette.routing import Mount+ from marimo._mcp.server._prompts.registry import (+ SUPPORTED_MCP_PROMPTS,+ )+mcp = FastMCP("marimo-mcp-server",stateless_http=True,@@ -46,12 +50,19 @@ def setup_mcp_server(app: Starlette) -> None:streamable_http_path="/server",)- # Register all tools+ # Create context for tools and promptscontext = ToolContext(app=app)++ # Register all toolsfor tool in SUPPORTED_BACKEND_AND_MCP_TOOLS:tool_with_context = tool(context)mcp.tool()(tool_with_context.as_mcp_tool_fn())+ # Register all prompts+ for prompt in SUPPORTED_MCP_PROMPTS:+ prompt_with_context = prompt(context)+ mcp.prompt()(prompt_with_context.as_mcp_prompt_fn())+# Initialize streamable HTTP appmcp_app = mcp.streamable_http_app()diff --git a/marimo/_utils/case.py b/marimo/_utils/case.pyindex 663c299beb..995111a301 100644--- a/marimo/_utils/case.py+++ b/marimo/_utils/case.py@@ -2,6 +2,7 @@from __future__ import annotations+import refrom typing import Any@@ -16,6 +17,15 @@ def to_camel_case(snake_str: str) -> str:return snake_str[0].lower() + pascal_case[1:]+def to_snake_case(string: str) -> str:+ if string == "":+ return ""++ s1 = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", string)+ s2 = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1)+ return s2.replace("-", "_").lower()++def deep_to_camel_case(snake_dict: Any) -> dict[str, Any]:if isinstance(snake_dict, list):return [deep_to_camel_case(item) for item in snake_dict] # type: ignore # noqa: E501diff --git a/tests/_mcp/server/prompts/test_notebooks_prompts.py b/tests/_mcp/server/prompts/test_notebooks_prompts.pynew file mode 100644index 0000000000..bc20625616--- /dev/null+++ b/tests/_mcp/server/prompts/test_notebooks_prompts.py@@ -0,0 +1,78 @@+import pytest++pytest.importorskip("mcp", reason="MCP requires Python 3.10+")++from unittest.mock import Mock++from marimo._mcp.server._prompts.prompts.notebooks import ActiveNotebooks+from marimo._server.sessions import Session+++def test_active_notebooks_metadata():+ """Test that name and description are properly set."""+ prompt = ActiveNotebooks(context=Mock())+ assert prompt.name == "active_notebooks"+ assert (+ prompt.description+ == "Get current active notebooks and their session IDs and file paths."+ )+++def test_active_notebooks_no_sessions():+ """Test output when no sessions are active."""+ context = Mock()+ context.session_manager.sessions = {}++ prompt = ActiveNotebooks(context=context)+ messages = prompt.handle()++ assert len(messages) == 1+ assert messages[0].role == "user"+ assert messages[0].content.type == "text"+ assert (+ "No active marimo notebook sessions found" in messages[0].content.text+ )+++def test_active_notebooks_with_sessions():+ """Test output with active sessions."""+ context = Mock()++ # Mock session with file path+ session1 = Mock(spec=Session)+ session1.app_file_manager = Mock()+ session1.app_file_manager.filename = "/path/to/notebook.py"++ # Mock session without file path+ session2 = Mock(spec=Session)+ session2.app_file_manager = Mock()+ session2.app_file_manager.filename = None++ context.session_manager.sessions = {+ "session_1": session1,+ "session_2": session2,+ }++ prompt = ActiveNotebooks(context=context)+ messages = prompt.handle()++ assert len(messages) == 2++ # Check first message (with file path)+ assert messages[0].role == "user"+ assert messages[0].content.type == "text"+ assert "session_1" in messages[0].content.text+ assert "/path/to/notebook.py" in messages[0].content.text+ assert (+ "Use this session_id when calling MCP tools"+ in messages[0].content.text+ )++ # Check second message (without file path)+ assert messages[1].role == "user"+ assert messages[1].content.type == "text"+ assert "session_2" in messages[1].content.text+ assert (+ "Use this session_id when calling MCP tools"+ in messages[1].content.text+ )