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.

feat: add LintNotebook tool to backend and mcp server (#6853)

Joaquin Corominada81f761b198
diff --git a/marimo/_ai/_tools/tools/lint.py b/marimo/_ai/_tools/tools/lint.py
new file mode 100644
index 0000000000..c523ae49e8
--- /dev/null
+++ b/marimo/_ai/_tools/tools/lint.py
@@ -0,0 +1,124 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from marimo._ai._tools.base import ToolBase
+from marimo._ai._tools.types import SuccessResult, ToolGuidelines
+from marimo._lint.diagnostic import Diagnostic, Severity
+from marimo._lint.rule_engine import RuleEngine
+from marimo._types.ids import SessionId
+
+
+@dataclass
+class DiagnosticSummary:
+ """Summary of diagnostics by severity."""
+
+ total_issues: int = 0
+ breaking_issues: int = 0
+ runtime_issues: int = 0
+ formatting_issues: int = 0
+
+
+@dataclass
+class LintNotebookArgs:
+ """Arguments for linting a notebook."""
+
+ session_id: SessionId
+
+
+@dataclass
+class LintNotebookOutput(SuccessResult):
+ """Output from linting a notebook."""
+
+ summary: DiagnosticSummary = field(default_factory=DiagnosticSummary)
+ diagnostics: list[Diagnostic] = field(default_factory=list)
+
+
+class LintNotebook(ToolBase[LintNotebookArgs, LintNotebookOutput]):
+ """Lint a marimo notebook to check for issues.
+
+ Uses marimo's internal linting engine to check for:
+ - Breaking issues: Problems that prevent the notebook from running
+ - Runtime issues: Problems that may cause unexpected behavior
+ - Formatting issues: Code style and formatting problems
+
+ Args:
+ session_id: The session ID of the notebook to lint.
+
+ Returns:
+ A success result containing all diagnostics found and issue counts.
+ """
+
+ guidelines = ToolGuidelines(
+ when_to_use=[
+ "ALWAYS use this tool after making ANY EDITS, CELLS, OR CHANGES to a marimo notebook to verify you didn't introduce any issues",
+ "ALWAYS use this tool when you want to lint a marimo notebook instead of using your own default linting tool",
+ "When the user asks to check or validate their notebook",
+ ],
+ prerequisites=[
+ "You must have a valid session id from an active notebook",
+ ],
+ avoid_if=[
+ "You just made changes to fix lint issues - explain what you fixed instead of immediately linting again",
+ ],
+ additional_info=(
+ "This tool provides static analysis only and does not execute code. "
+ "Some issues may require running the notebook to fully diagnose."
+ ),
+ )
+
+ async def handle(self, args: LintNotebookArgs) -> LintNotebookOutput: # type: ignore[override]
+ session = self.context.get_session(args.session_id)
+ notebook_ir = session.app_file_manager.app.to_ir()
+
+ rule_engine = RuleEngine.create_default()
+ diagnostics = await rule_engine.check_notebook(notebook_ir)
+
+ summary = self._get_diagnostic_summary(diagnostics)
+
+ next_steps = self._build_next_steps(summary)
+
+ return LintNotebookOutput(
+ diagnostics=diagnostics,
+ summary=summary,
+ next_steps=next_steps,
+ )
+
+ def _get_diagnostic_summary(
+ self, diagnostics: list[Diagnostic]
+ ) -> DiagnosticSummary:
+ """Get summary of diagnostics by severity."""
+ summary = DiagnosticSummary()
+
+ for diagnostic in diagnostics:
+ if diagnostic.severity == Severity.BREAKING:
+ summary.breaking_issues += 1
+ elif diagnostic.severity == Severity.RUNTIME:
+ summary.runtime_issues += 1
+ elif diagnostic.severity == Severity.FORMATTING:
+ summary.formatting_issues += 1
+
+ summary.total_issues += 1
+
+ return summary
+
+ def _build_next_steps(self, summary: DiagnosticSummary) -> list[str]:
+ """Build next steps based on the summary of diagnostics."""
+ next_steps = []
+ if summary.breaking_issues > 0:
+ next_steps.append(
+ f"Fix {summary.breaking_issues} breaking issue(s) that prevent the notebook from running properly"
+ )
+ if summary.runtime_issues > 0:
+ next_steps.append(
+ f"Address {summary.runtime_issues} runtime issue(s) that may cause unexpected behavior"
+ )
+ if summary.formatting_issues > 0:
+ next_steps.append(
+ f"Optionally fix {summary.formatting_issues} formatting issue(s) for better code style"
+ )
+ if summary.total_issues == 0:
+ next_steps.append("No issues found - notebook is healthy!")
+
+ return next_steps
diff --git a/marimo/_ai/_tools/tools_registry.py b/marimo/_ai/_tools/tools_registry.py
index 2025d22b04..e30fd4d5ae 100644
--- a/marimo/_ai/_tools/tools_registry.py
+++ b/marimo/_ai/_tools/tools_registry.py
@@ -10,6 +10,7 @@ from marimo._ai._tools.tools.cells import (
)
from marimo._ai._tools.tools.datasource import GetDatabaseTables
from marimo._ai._tools.tools.errors import GetNotebookErrors
+from marimo._ai._tools.tools.lint import LintNotebook
from marimo._ai._tools.tools.notebooks import GetActiveNotebooks
from marimo._ai._tools.tools.rules import GetMarimoRules
from marimo._ai._tools.tools.tables_and_variables import GetTablesAndVariables
@@ -22,4 +23,5 @@ SUPPORTED_BACKEND_AND_MCP_TOOLS: list[type[ToolBase[Any, Any]]] = [
GetTablesAndVariables,
GetDatabaseTables,
GetNotebookErrors,
+ LintNotebook,
]
diff --git a/tests/_ai/tools/tools/test_lint_tool.py b/tests/_ai/tools/tools/test_lint_tool.py
new file mode 100644
index 0000000000..5f16642fd7
--- /dev/null
+++ b/tests/_ai/tools/tools/test_lint_tool.py
@@ -0,0 +1,154 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from unittest.mock import AsyncMock, Mock
+
+from marimo._ai._tools.base import ToolContext
+from marimo._ai._tools.tools.lint import LintNotebook, LintNotebookArgs
+from marimo._lint.diagnostic import Diagnostic, Severity
+from marimo._schemas.serialization import NotebookSerializationV1
+from marimo._types.ids import SessionId
+
+
+@dataclass
+class MockInternalApp:
+ def to_ir(self) -> NotebookSerializationV1:
+ # Return a minimal notebook IR
+ return Mock(spec=NotebookSerializationV1)
+
+
+@dataclass
+class MockAppFileManager:
+ app: MockInternalApp
+
+
+@dataclass
+class MockSession:
+ app_file_manager: MockAppFileManager
+
+
+async def test_lint_notebook_no_issues() -> None:
+ """Test linting a notebook with no issues."""
+ tool = LintNotebook(ToolContext())
+
+ # Mock session with app
+ session = MockSession(
+ app_file_manager=MockAppFileManager(app=MockInternalApp())
+ )
+
+ # Mock ToolContext.get_session
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = session
+ tool.context = context # type: ignore[assignment]
+
+ # Mock RuleEngine to return no diagnostics
+ from unittest.mock import patch
+
+ with patch(
+ "marimo._ai._tools.tools.lint.RuleEngine.create_default"
+ ) as mock_create:
+ mock_engine = Mock()
+ mock_engine.check_notebook = AsyncMock(return_value=[])
+ mock_create.return_value = mock_engine
+
+ out = await tool.handle(LintNotebookArgs(session_id=SessionId("s1")))
+
+ assert out.summary.total_issues == 0
+ assert out.summary.breaking_issues == 0
+ assert out.summary.runtime_issues == 0
+ assert out.summary.formatting_issues == 0
+ assert len(out.diagnostics) == 0
+ assert out.next_steps is not None
+ assert "No issues found" in out.next_steps[0]
+
+
+async def test_lint_notebook_with_issues() -> None:
+ """Test linting a notebook with various types of issues."""
+ tool = LintNotebook(ToolContext())
+
+ # Mock session with app
+ session = MockSession(
+ app_file_manager=MockAppFileManager(app=MockInternalApp())
+ )
+
+ # Mock ToolContext.get_session
+ context = Mock(spec=ToolContext)
+ context.get_session.return_value = session
+ tool.context = context # type: ignore[assignment]
+
+ # Create mock diagnostics
+ breaking_diagnostic = Diagnostic(
+ message="Breaking error",
+ line=1,
+ column=0,
+ code="MB001",
+ name="breaking_rule",
+ severity=Severity.BREAKING,
+ fixable=False,
+ )
+
+ runtime_diagnostic = Diagnostic(
+ message="Runtime warning",
+ line=2,
+ column=0,
+ code="MR001",
+ name="runtime_rule",
+ severity=Severity.RUNTIME,
+ fixable=True,
+ )
+
+ formatting_diagnostic = Diagnostic(
+ message="Formatting issue",
+ line=3,
+ column=0,
+ code="MF001",
+ name="formatting_rule",
+ severity=Severity.FORMATTING,
+ fixable="unsafe",
+ )
+
+ # Mock RuleEngine to return diagnostics
+ from unittest.mock import patch
+
+ with patch(
+ "marimo._ai._tools.tools.lint.RuleEngine.create_default"
+ ) as mock_create:
+ mock_engine = Mock()
+ mock_engine.check_notebook = AsyncMock(
+ return_value=[
+ breaking_diagnostic,
+ runtime_diagnostic,
+ formatting_diagnostic,
+ ]
+ )
+ mock_create.return_value = mock_engine
+
+ out = await tool.handle(LintNotebookArgs(session_id=SessionId("s1")))
+
+ # Check counts
+ assert out.summary.total_issues == 3
+ assert out.summary.breaking_issues == 1
+ assert out.summary.runtime_issues == 1
+ assert out.summary.formatting_issues == 1
+
+ # Check diagnostics
+ assert len(out.diagnostics) == 3
+ assert out.diagnostics[0].message == "Breaking error"
+ assert out.diagnostics[0].severity == Severity.BREAKING
+ assert out.diagnostics[0].code == "MB001"
+ assert out.diagnostics[0].fixable is False
+
+ assert out.diagnostics[1].message == "Runtime warning"
+ assert out.diagnostics[1].severity == Severity.RUNTIME
+ assert out.diagnostics[1].fixable is True
+
+ assert out.diagnostics[2].message == "Formatting issue"
+ assert out.diagnostics[2].severity == Severity.FORMATTING
+ assert out.diagnostics[2].fixable == "unsafe"
+
+ # Check next steps
+ assert out.next_steps is not None
+ assert len(out.next_steps) == 3
+ assert "breaking" in out.next_steps[0].lower()
+ assert "runtime" in out.next_steps[1].lower()
+ assert "formatting" in out.next_steps[2].lower()