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.

refactor backend tools to use abstract class (#6235)

Shahmir Varqha2c31a186257b
diff --git a/marimo/_ai/_convert.py b/marimo/_ai/_convert.py
index 8ab91e34a8..31e0518663 100644
--- a/marimo/_ai/_convert.py
+++ b/marimo/_ai/_convert.py
@@ -14,7 +14,7 @@ from marimo._ai._types import (
TextPart,
ToolInvocationPart,
)
-from marimo._server.ai.tools import Tool
+from marimo._server.ai.tools.types import Tool
if TYPE_CHECKING:
from anthropic.types.message_param import ( # type: ignore[import-not-found]
diff --git a/marimo/_server/ai/backend_tools/__init__.py b/marimo/_server/ai/backend_tools/__init__.py
deleted file mode 100644
index c630d10b22..0000000000
--- a/marimo/_server/ai/backend_tools/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-"""Backend tools for marimo AI system."""
-# from marimo._server.ai.backend_tools.sample_tool import register_sample_tool # Uncomment to enable sample tool
-
-
-def register_all_backend_tools() -> None:
- """Register all backend tools with the tool manager."""
- # register_sample_tool() # Uncomment to enable sample tool
diff --git a/marimo/_server/ai/backend_tools/sample_tool.py b/marimo/_server/ai/backend_tools/sample_tool.py
deleted file mode 100644
index 9ac12650b4..0000000000
--- a/marimo/_server/ai/backend_tools/sample_tool.py
+++ /dev/null
@@ -1,266 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-"""
-SAMPLE BACKEND TOOL - This file is commented out as an example.
-
-This file demonstrates how to create a backend tool for the marimo AI system.
-Backend tools are functions that run on the server and can be called by the AI
-during conversations.
-
-To create your own backend tool:
-1. Copy this file and rename it
-2. Uncomment the code
-3. Modify the tool definition and handler function
-4. Import and register it in __init__.py
-
-Backend tools are useful for:
-- Server-side operations that require access to the filesystem
-- Database queries
-- API calls to external services
-- System information gathering
-- File operations
-"""
-
-# from __future__ import annotations
-#
-# from typing import Any
-#
-# from marimo import _loggers
-# from ..tools import get_tool_manager, Tool
-#
-# LOGGER = _loggers.marimo_logger()
-#
-#
-# def validate_sample_tool_parameters(arguments: dict[str, Any]) -> tuple[bool, str]:
-# """
-# Validate parameters for the sample tool.
-#
-# This function is optional but recommended for robust parameter validation.
-#
-# Args:
-# arguments: The arguments to validate
-#
-# Returns:
-# Tuple of (is_valid, error_message). If is_valid is True, error_message is empty.
-# """
-# # Define valid parameter names and their expected types
-# valid_params = {
-# "message": str,
-# "count": int,
-# "uppercase": bool,
-# }
-#
-# # Check for required parameters
-# required_params = {"message"}
-# missing_params = required_params - set(arguments.keys())
-# if missing_params:
-# error_msg = f"Missing required parameters: {', '.join(missing_params)}"
-# return False, error_msg
-#
-# # Check for unknown parameters
-# unknown_params = set(arguments.keys()) - set(valid_params.keys())
-# if unknown_params:
-# error_msg = f"Unknown parameters: {', '.join(unknown_params)}. Valid parameters are: {', '.join(valid_params.keys())}"
-# return False, error_msg
-#
-# # Validate parameter types
-# for param_name, param_value in arguments.items():
-# expected_type = valid_params[param_name]
-# if not isinstance(param_value, expected_type):
-# error_msg = f"Parameter '{param_name}' must be of type {expected_type.__name__}, got {type(param_value).__name__}"
-# return False, error_msg
-#
-# # Custom validation logic
-# if "count" in arguments and arguments["count"] < 1:
-# return False, "Parameter 'count' must be greater than 0"
-#
-# if "count" in arguments and arguments["count"] > 10:
-# return False, "Parameter 'count' must be 10 or less"
-#
-# # All validation checks passed
-# return True, ""
-#
-#
-# def register_sample_tool() -> None:
-# """Register a sample backend tool that demonstrates the basic pattern."""
-#
-# # Define the tool with its schema
-# sample_tool = Tool(
-# name="sample_backend_tool",
-# description="A sample backend tool that processes text messages. This demonstrates how to create backend tools.",
-# parameters={
-# "type": "object",
-# "properties": {
-# "message": {
-# "type": "string",
-# "description": "The message to process"
-# },
-# "count": {
-# "type": "integer",
-# "description": "Number of times to repeat the message",
-# "default": 1,
-# "minimum": 1,
-# "maximum": 10
-# },
-# "uppercase": {
-# "type": "boolean",
-# "description": "Whether to convert the message to uppercase",
-# "default": False
-# }
-# },
-# "required": ["message"]
-# },
-# source="backend", # This indicates it's a backend tool
-# mode=["ask", "chat"] # Available in both ask and chat modes
-# )
-#
-# def sample_tool_handler(arguments: dict[str, Any]) -> dict[str, Any]:
-# """
-# Handle the sample tool execution.
-#
-# Args:
-# arguments: The validated arguments passed to the tool
-#
-# Returns:
-# Dictionary containing the tool's response
-# """
-# try:
-# # Extract parameters with defaults
-# message = arguments["message"]
-# count = arguments.get("count", 1)
-# uppercase = arguments.get("uppercase", False)
-#
-# # Process the message
-# processed_message = message.upper() if uppercase else message
-# result = [processed_message] * count
-#
-# # Return structured response
-# return {
-# "success": True,
-# "original_message": message,
-# "processed_messages": result,
-# "settings": {
-# "count": count,
-# "uppercase": uppercase
-# },
-# "total_characters": sum(len(msg) for msg in result)
-# }
-#
-# except Exception as e:
-# # Handle errors gracefully
-# LOGGER.error(f"Error in sample tool: {str(e)}")
-# return {
-# "success": False,
-# "error": f"Tool execution failed: {str(e)}"
-# }
-#
-# # Register the tool with the tool manager
-# get_tool_manager().register_backend_tool(
-# sample_tool, # Tool definition
-# sample_tool_handler, # Handler function
-# validate_sample_tool_parameters # Optional validator function
-# )
-#
-# LOGGER.debug("Registered sample backend tool")
-
-
-# ADVANCED EXAMPLE: Tool with file system access
-#
-# def register_file_info_tool() -> None:
-# """Example of a backend tool that accesses the file system."""
-#
-# file_info_tool = Tool(
-# name="get_file_info",
-# description="Get information about files in the current working directory. Only works on the server.",
-# parameters={
-# "type": "object",
-# "properties": {
-# "pattern": {
-# "type": "string",
-# "description": "File pattern to match (e.g., '*.py', '*.md')",
-# "default": "*"
-# },
-# "include_hidden": {
-# "type": "boolean",
-# "description": "Whether to include hidden files",
-# "default": False
-# }
-# },
-# "required": []
-# },
-# source="backend",
-# mode=["ask", "chat"]
-# )
-#
-# def file_info_handler(arguments: dict[str, Any]) -> dict[str, Any]:
-# """Get file information from the server's file system."""
-# import os
-# import glob
-# from pathlib import Path
-#
-# try:
-# pattern = arguments.get("pattern", "*")
-# include_hidden = arguments.get("include_hidden", False)
-#
-# # Get current working directory
-# cwd = os.getcwd()
-#
-# # Find matching files
-# files = glob.glob(pattern, recursive=False)
-#
-# # Filter hidden files if requested
-# if not include_hidden:
-# files = [f for f in files if not f.startswith('.')]
-#
-# # Get file info
-# file_info = []
-# for file_path in files[:20]: # Limit to 20 files
-# try:
-# path = Path(file_path)
-# stat = path.stat()
-# file_info.append({
-# "name": path.name,
-# "size": stat.st_size,
-# "is_file": path.is_file(),
-# "is_dir": path.is_dir(),
-# "modified": stat.st_mtime
-# })
-# except Exception:
-# continue
-#
-# return {
-# "success": True,
-# "working_directory": cwd,
-# "pattern": pattern,
-# "files_found": len(file_info),
-# "files": file_info
-# }
-#
-# except Exception as e:
-# return {
-# "success": False,
-# "error": str(e)
-# }
-#
-# get_tool_manager().register_backend_tool(
-# file_info_tool,
-# file_info_handler
-# )
-
-
-# TO USE THIS SAMPLE TOOL:
-#
-# 1. Uncomment the code above
-# 2. Add this import to __init__.py:
-# from .sample_tool import register_sample_tool
-#
-# 3. Add this to the __all__ list in __init__.py:
-# __all__ = ["register_server_debug_tool", "register_sample_tool"]
-#
-# 4. Add this to the register_all_backend_tools() function in __init__.py:
-# def register_all_backend_tools():
-# register_server_debug_tool()
-# register_sample_tool()
-#
-# 5. Restart the marimo server
-#
-# The AI will then be able to use your tool in conversations!
diff --git a/marimo/_server/ai/config.py b/marimo/_server/ai/config.py
index 4dfb91ed58..549f0c240f 100644
--- a/marimo/_server/ai/config.py
+++ b/marimo/_server/ai/config.py
@@ -19,7 +19,8 @@ from marimo._config.config import (
)
from marimo._server.ai.constants import DEFAULT_MAX_TOKENS, DEFAULT_MODEL
from marimo._server.ai.ids import AiModelId
-from marimo._server.ai.tools import Tool, get_tool_manager
+from marimo._server.ai.tools.tool_manager import get_tool_manager
+from marimo._server.ai.tools.types import Tool
from marimo._server.api.status import HTTPStatus
diff --git a/marimo/_server/ai/tools/backend_tools/sample_tool.py b/marimo/_server/ai/tools/backend_tools/sample_tool.py
new file mode 100644
index 0000000000..7a01d4fcd1
--- /dev/null
+++ b/marimo/_server/ai/tools/backend_tools/sample_tool.py
@@ -0,0 +1,262 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""
+SAMPLE BACKEND TOOL - This file is commented out as an example.
+
+This file demonstrates how to create a backend tool for the marimo AI system.
+Backend tools are functions that run on the server and can be called by the AI
+during conversations.
+
+To create your own backend tool:
+1. Copy this file and rename it
+2. Uncomment the code
+3. Modify the tool definition and handler function
+4. Import it in tools.py
+
+Backend tools are useful for:
+- Server-side operations that require access to the filesystem
+- Database queries
+- API calls to external services
+- System information gathering
+- File operations
+
+##################################################################################
+
+ To use the tools below:
+ 1. Uncomment the code below
+ 2. Add the tools to `tools.py`
+ 3. Restart the marimo server
+
+ The AI will then be able to use your tool in conversations!
+"""
+
+# from __future__ import annotations
+
+# from typing import Any, Optional, TypedDict
+
+# from marimo import _loggers
+# from marimo._server.ai.tools.types import BackendTool, Tool
+
+# LOGGER = _loggers.marimo_logger()
+
+
+# class SampleToolArgs(TypedDict):
+# message: str
+# count: int
+# uppercase: bool
+
+
+# class SampleTool(BackendTool[SampleToolArgs]):
+# """A sample backend tool that processes text messages."""
+
+# @property
+# def tool(self) -> Tool:
+# return Tool(
+# name="sample_backend_tool",
+# description="A sample backend tool that processes text messages. This demonstrates how to create backend tools.",
+# parameters={
+# "type": "object",
+# "properties": {
+# "message": {
+# "type": "string",
+# "description": "The message to process",
+# },
+# "count": {
+# "type": "integer",
+# "description": "Number of times to repeat the message",
+# "default": 1,
+# "minimum": 1,
+# "maximum": 10,
+# },
+# "uppercase": {
+# "type": "boolean",
+# "description": "Whether to convert the message to uppercase",
+# "default": False,
+# },
+# },
+# "required": ["message"],
+# },
+# source="backend", # This indicates it's a backend tool
+# mode=["ask", "chat"], # Available in both ask and chat modes
+# )
+
+# def handler(self, arguments: SampleToolArgs) -> dict[str, Any]:
+# """
+# Handle the sample tool execution.
+
+# Args:
+# arguments: The validated arguments passed to the tool
+
+# Returns:
+# Dictionary containing the tool's response
+# """
+# try:
+# # Extract parameters with defaults
+# message = arguments["message"]
+# count = arguments.get("count", 1)
+# uppercase = arguments.get("uppercase", False)
+
+# # Process the message
+# processed_message = message.upper() if uppercase else message
+# result = [processed_message] * count
+
+# # Return structured response
+# return {
+# "success": True,
+# "original_message": message,
+# "processed_messages": result,
+# "settings": {"count": count, "uppercase": uppercase},
+# "total_characters": sum(len(msg) for msg in result),
+# }
+
+# except Exception as e:
+# # Handle errors gracefully
+# LOGGER.error(f"Error in sample tool: {str(e)}")
+# return {
+# "success": False,
+# "error": f"Tool execution failed: {str(e)}",
+# }
+
+# def validator(
+# self, arguments: SampleToolArgs
+# ) -> Optional[tuple[bool, str]]:
+# """
+# Validate parameters for the sample tool.
+
+# This function is optional but recommended for robust parameter validation.
+
+# Args:
+# arguments: The arguments to validate
+
+# Returns:
+# Tuple of (is_valid, error_message). If is_valid is True, error_message is empty.
+# """
+# # Define valid parameter names and their expected types
+# valid_params = {
+# "message": str,
+# "count": int,
+# "uppercase": bool,
+# }
+
+# # Check for required parameters
+# required_params = {"message"}
+# missing_params = required_params - set(arguments.keys())
+# if missing_params:
+# error_msg = (
+# f"Missing required parameters: {', '.join(missing_params)}"
+# )
+# return False, error_msg
+
+# # Check for unknown parameters
+# unknown_params = set(arguments.keys()) - set(valid_params.keys())
+# if unknown_params:
+# error_msg = f"Unknown parameters: {', '.join(unknown_params)}. Valid parameters are: {', '.join(valid_params.keys())}"
+# return False, error_msg
+
+# # Validate parameter types
+# for param_name, param_value in arguments.items():
+# expected_type = valid_params[param_name]
+# if not isinstance(param_value, expected_type):
+# error_msg = f"Parameter '{param_name}' must be of type {expected_type.__name__}, got {type(param_value).__name__}"
+# return False, error_msg
+
+# # Custom validation logic
+# if "count" in arguments and arguments["count"] < 1:
+# return False, "Parameter 'count' must be greater than 0"
+
+# if "count" in arguments and arguments["count"] > 10:
+# return False, "Parameter 'count' must be 10 or less"
+
+# # All validation checks passed
+# return True, ""
+
+
+# # Advanced tool example
+
+
+# class FileInfoToolArgs(TypedDict):
+# pattern: str
+# include_hidden: bool
+
+
+# class FileInfoTool(BackendTool[FileInfoToolArgs]):
+# """A backend tool that gets information about files in the current working directory."""
+
+# @property
+# def tool(self) -> Tool:
+# return Tool(
+# name="get_file_info",
+# description="Get information about files in the current working directory. Only works on the server.",
+# parameters={
+# "type": "object",
+# "properties": {
+# "pattern": {
+# "type": "string",
+# "description": "File pattern to match (e.g., '*.py', '*.md')",
+# "default": "*",
+# },
+# "include_hidden": {
+# "type": "boolean",
+# "description": "Whether to include hidden files",
+# "default": False,
+# },
+# },
+# "required": [],
+# },
+# source="backend",
+# mode=["ask", "chat"],
+# )
+
+# def handler(self, arguments: FileInfoToolArgs) -> dict[str, Any]:
+# """Get file information from the server's file system."""
+# import glob
+# import os
+# from pathlib import Path
+
+# try:
+# pattern = arguments.get("pattern", "*")
+# include_hidden = arguments.get("include_hidden", False)
+
+# # Get current working directory
+# cwd = os.getcwd()
+
+# # Find matching files
+# files = glob.glob(pattern, recursive=False)
+
+# # Filter hidden files if requested
+# if not include_hidden:
+# files = [f for f in files if not f.startswith(".")]
+
+# # Get file info
+# file_info = []
+# for file_path in files[:20]: # Limit to 20 files
+# try:
+# path = Path(file_path)
+# stat = path.stat()
+# file_info.append(
+# {
+# "name": path.name,
+# "size": stat.st_size,
+# "is_file": path.is_file(),
+# "is_dir": path.is_dir(),
+# "modified": stat.st_mtime,
+# }
+# )
+# except Exception:
+# continue
+
+# return {
+# "success": True,
+# "working_directory": cwd,
+# "pattern": pattern,
+# "files_found": len(file_info),
+# "files": file_info,
+# }
+
+# except Exception as e:
+# return {"success": False, "error": str(e)}
+
+# def validator(
+# self, arguments: FileInfoToolArgs
+# ) -> Optional[tuple[bool, str]]:
+# del arguments
+# return None
diff --git a/marimo/_server/ai/tools.py b/marimo/_server/ai/tools/tool_manager.py
similarity index 81%
rename from marimo/_server/ai/tools.py
rename to marimo/_server/ai/tools/tool_manager.py
index c97e861bc3..c773f1ab2d 100644
--- a/marimo/_server/ai/tools.py
+++ b/marimo/_server/ai/tools/tool_manager.py
@@ -1,12 +1,19 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
+from typing import TYPE_CHECKING, Any, Callable, Optional
from marimo import _loggers
from marimo._config.config import CopilotMode
from marimo._config.manager import get_default_config_manager
+from marimo._server.ai.tools.types import (
+ BackendTool,
+ FunctionArgs,
+ Tool,
+ ToolResult,
+ ToolSource,
+ ValidationFunction,
+)
if TYPE_CHECKING:
from mcp.types import ( # type: ignore[import-not-found]
@@ -16,35 +23,6 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
-# Type aliases for tool system
-FunctionArgs = dict[str, Any]
-ValidationFunction = Callable[[FunctionArgs], tuple[bool, str]]
-
-ToolSource = Literal["mcp", "backend", "frontend"]
-
-
-@dataclass
-class Tool:
- """Tool definition compatible with ai-sdk-ui format."""
-
- name: str
- description: str
- parameters: dict[str, Any]
- source: ToolSource
- mode: list[CopilotMode] # tools can be available in multiple modes
-
- def __str__(self) -> str:
- return f"Tool(name={self.name}, description={self.description})"
-
-
-@dataclass
-class ToolResult:
- """Represents the result of a tool invocation."""
-
- tool_name: str
- result: Any
- error: Optional[str] = None
-
class ToolManager:
"""Centralized manager for backend and frontend tools, with dynamic MCP tool access."""
@@ -63,27 +41,23 @@ class ToolManager:
"mcp_docs", False
)
- # Don't register tools in __init__ to avoid circular imports
- # Tools will be registered when get_tool_manager() is first called
- LOGGER.info(
- "ToolManager created (tools will be registered on first access)"
- )
+ # Add backend tools here
+ # backend_tools = [SampleTool()]
+ # for tool in backend_tools:
+ # self.register_backend_tool(tool)
- def register_backend_tool(
- self,
- tool: Tool,
- handler: Callable[[FunctionArgs], Any],
- validator: Optional[ValidationFunction] = None,
- ) -> None:
+ def register_backend_tool(self, tool: BackendTool[Any]) -> None:
"""Register a backend tool with its handler function and optional validator."""
- if tool.source != "backend":
+ tool_definition = tool.tool
+ if tool_definition.source != "backend":
raise ValueError("Tool source must be 'backend'")
- self._tools[tool.name] = tool
- self._backend_handlers[tool.name] = handler
- if validator:
- self._validation_functions[tool.name] = validator
- LOGGER.debug(f"Registered backend tool: {tool.name}")
+ name = tool_definition.name
+ self._tools[name] = tool_definition
+ self._backend_handlers[name] = tool.handler
+ self._validation_functions[name] = tool.validator
+
+ LOGGER.debug(f"Registered backend tool: {name}")
def register_frontend_tool(self, tool: Tool) -> None:
"""Register a frontend tool (definition only - no handler or validator needed)."""
@@ -138,30 +112,29 @@ class ToolManager:
def validate_backend_tool_arguments(
self, tool_name: str, arguments: FunctionArgs
) -> tuple[bool, str]:
- """Validate tool arguments using tool-specific validation function or fallback to basic validation."""
+ """Validate tool arguments using tool-specific or basic validation."""
tool = self.get_tool(tool_name)
if not tool:
return False, f"Tool '{tool_name}' not found"
- # Use tool-specific validation function if available
- if tool_name in self._validation_functions:
+ validator = self._validation_functions.get(tool_name)
+ if validator:
try:
- validator = self._validation_functions[tool_name]
- is_valid, error_message = validator(arguments)
- if not is_valid:
- LOGGER.warning(
- f"Tool-specific validation failed for '{tool_name}': {error_message}"
- )
- return is_valid, error_message
+ result = validator(arguments)
+ if result is not None:
+ is_valid, error_message = result
+ if not is_valid:
+ LOGGER.warning(
+ f"Tool-specific validation failed for '{tool_name}': {error_message}"
+ )
+ return is_valid, error_message
except Exception as e:
error_msg = f"Error in tool-specific validation for '{tool_name}': {str(e)}"
LOGGER.error(error_msg)
return False, error_msg
- # Fallback to basic validation against parameters schema
+ # If no validation, use basic validation against parameters schema
required_params = tool.parameters.get("required", [])
-
- # Check required parameters
for param in required_params:
if param not in arguments:
error_msg = f"Missing required parameter '{param}'"
@@ -344,15 +317,8 @@ class ToolManager:
# Return the CallToolResult directly - let invoke_tool handle error checking
return call_result
- def _register_builtin_tools(self) -> None:
- """Register built-in backend tools."""
- # Register all backend tools from the backend_tools package
- from marimo._server.ai.backend_tools import register_all_backend_tools
-
- register_all_backend_tools()
-
-# Global tool manager instance using lazy initialization to avoid circular imports
+# Global tool manager instance
_TOOL_MANAGER: Optional[ToolManager] = None
@@ -361,8 +327,6 @@ def get_tool_manager() -> ToolManager:
global _TOOL_MANAGER
if _TOOL_MANAGER is None:
_TOOL_MANAGER = ToolManager()
- # Register tools after the manager is created to avoid circular imports
- _TOOL_MANAGER._register_builtin_tools()
LOGGER.info(
f"ToolManager initialized with {len(_TOOL_MANAGER._tools)} backend/frontend tools"
)
diff --git a/marimo/_server/ai/tools/types.py b/marimo/_server/ai/tools/types.py
new file mode 100644
index 0000000000..8902d88c9d
--- /dev/null
+++ b/marimo/_server/ai/tools/types.py
@@ -0,0 +1,62 @@
+# Copyright 2025 Marimo. All rights reserved.
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, Callable, Generic, Literal, Optional, TypeVar
+
+from marimo._config.config import CopilotMode
+
+# Type aliases for tool system
+FunctionArgs = dict[str, Any]
+ValidationFunction = Callable[[FunctionArgs], Optional[tuple[bool, str]]]
+
+ToolSource = Literal["mcp", "backend", "frontend"]
+
+
+@dataclass
+class Tool:
+ """Tool definition compatible with ai-sdk-ui format."""
+
+ name: str
+ description: str
+ parameters: dict[str, Any]
+ source: ToolSource
+ mode: list[CopilotMode] # tools can be available in multiple modes
+
+ def __str__(self) -> str:
+ return f"Tool(name={self.name}, description={self.description})"
+
+
+@dataclass
+class ToolResult:
+ """Represents the result of a tool invocation."""
+
+ tool_name: str
+ result: Any
+ error: Optional[str] = None
+
+
+T = TypeVar("T")
+
+
+class BackendTool(ABC, Generic[T]):
+ """Base class for all backend tools."""
+
+ @property
+ @abstractmethod
+ def tool(self) -> Tool:
+ """The tool definition."""
+
+ @abstractmethod
+ def handler(self, arguments: T) -> dict[str, Any]:
+ """The handler function for the tool."""
+
+ @abstractmethod
+ def validator(self, arguments: T) -> Optional[tuple[bool, str]]:
+ """The validator function for the tool parameters.
+ Strongly recommended to return a tuple of (is_valid, error_message).
+
+ If None is returned, the tool will be validated against the parameters schema.
+ """
+ del arguments
+ return None
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 6a7ab395a2..2c5d3c06eb 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -36,7 +36,7 @@ from marimo._server.ai.providers import (
get_completion_provider,
without_wrapping_backticks,
)
-from marimo._server.ai.tools import get_tool_manager
+from marimo._server.ai.tools.tool_manager import get_tool_manager
from marimo._server.api.deps import AppState
from marimo._server.api.status import HTTPStatus
from marimo._server.api.utils import parse_request
diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.py
index 5f7917f024..f1e0a35ad3 100644
--- a/tests/_ai/test_chat_convert.py
+++ b/tests/_ai/test_chat_convert.py
@@ -27,7 +27,7 @@ from marimo._ai._types import (
ToolInvocationPart,
)
from marimo._plugins.ui._impl.chat.utils import from_chat_message_dict
-from marimo._server.ai.tools import Tool
+from marimo._server.ai.tools.types import Tool
@pytest.fixture
diff --git a/tests/_server/ai/test_ai_config.py b/tests/_server/ai/test_ai_config.py
index 47c1195768..e51111230d 100644
--- a/tests/_server/ai/test_ai_config.py
+++ b/tests/_server/ai/test_ai_config.py
@@ -24,7 +24,7 @@ from marimo._server.ai.config import (
get_edit_model,
get_max_tokens,
)
-from marimo._server.ai.tools import Tool
+from marimo._server.ai.tools.types import Tool
from marimo._server.api.status import HTTPStatus
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index 218cf6aa0b..d08decf1e0 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -19,6 +19,7 @@ from marimo._server.ai.providers import (
OpenAIProvider,
without_wrapping_backticks,
)
+from marimo._server.ai.tools.types import ToolResult
from tests._server.conftest import get_session_config_manager
from tests._server.mocks import token_header, with_session
@@ -1018,7 +1019,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test successful tool invocation."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()
@@ -1067,7 +1067,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test tool invocation with error."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()
@@ -1113,7 +1112,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test tool invocation when tool doesn't exist."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()
@@ -1153,7 +1151,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test tool invocation with validation error."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()
@@ -1197,7 +1194,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test tool invocation with complex argument types."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()
@@ -1273,7 +1269,6 @@ class TestInvokeToolEndpoint:
client: TestClient, mock_get_tool_manager: Any
) -> None:
"""Test tool invocation with empty arguments."""
- from marimo._server.ai.tools import ToolResult
# Mock the tool manager and its response
mock_tool_manager = MagicMock()