Available tools
【免费下载链接】marimoA 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.项目地址: https://gitcode.com/GitHub_Trending/ma/marimo
[Appropriate Category]
| Tool | Description |
|---|---|
| your_tool_name | Brief description of what the tool does. Takesparam1andparam2parameters. Returns description of output. |
选择合适分类: - **Inspection(检查)**:用于探索笔记本结构与运行时状态的工具; - **Data(数据)**:用于访问变量与数据库信息的工具; - **Debugging(调试)**:用于发现和修复问题的工具; - **Reference(参考)**:用于访问 marimo 文档的工具。 仓库中 [tools.md](https://link.gitcode.com/i/1f3709b3fc01e04fabec6e588cdcd263) 目前按此四类组织了 10 个内置工具的描述(另有 Agent 模式专属的编辑类工具与 Code mode 工具集)。注意该页面顶部标注了"Experimental"警告——工具定义与可用性仍处于活跃开发中。 ## 十三、最佳实践 ### 类型安全 - 所有输入/输出类型**使用 dataclass**; - 所有方法与属性**添加类型注解**; - 仅类型检查需要的导入放在 `if TYPE_CHECKING:` 块内(如 `Session` 仅作类型提示); - 从 marimo 类型系统导入(`SessionId`、`CellId_t` 等); - 类型定义**保留在工具文件中**,除非被多个工具共享——只有被大量文件复用时才考虑放入 [types.py](https://link.gitcode.com/i/ea8e3168904cdd1cb7427fb6b0ed500b)。 ### 文档 - 遵循模板编写清晰的 docstring(它会被用作 AI 助手看到的工具描述); - 在类 docstring 中记录**所有 Args**; - 在类 docstring 中描述 **Returns**; - 提供 **ToolGuidelines** 帮助 AI 助手; - 需要时在 docstring 中包含示例。 ### 输出设计 ```python return YourToolOutput( data=result, # Provide actionable next steps next_steps=[ "Use get_cell_runtime_data to inspect cells", "Check errors with get_notebook_errors", ], # Optional user-facing message message="Found 5 items matching your query", # Optional metadata meta={"query_time": 0.5}, )Helper 方法
- 私有方法用
_前缀; handle()保持聚焦于编排;- 复杂逻辑抽取为 helper 方法;
- 复用 ToolContext 方法而非重复实现逻辑。
十四、常见陷阱(Common Pitfalls)
❌ 不要:重复实现 ToolContext 逻辑
# Bad: Reimplementing context logic def handle(self, args: Args) -> Output: session = self.context.get_session(args.session_id) cell_notifications = session.session_view.cell_notifications errors = [] for cell_id, op in cell_notifications.items(): if op.output and op.output.channel == CellChannel.MARIMO_ERROR: errors.append(...) # Duplicating error extraction✅ 应该:使用 ToolContext 方法
# Good: Using context methods def handle(self, args: Args) -> Output: errors = self.context.get_notebook_errors( args.session_id, include_stderr=True )❌ 不要:抛出通用异常
# Bad: Using generic exceptions if not found: raise ValueError("Not found")✅ 应该:抛出 ToolExecutionError
# Good: Structured error with metadata if not found: raise ToolExecutionError( "Cell not found in session", code="CELL_NOT_FOUND", is_retryable=False, suggested_fix="Use get_lightweight_cell_map to find valid cell IDs", )❌ 不要:返回非结构化数据
# Bad: Returning raw data def handle(self, args: Args) -> Output: return {"data": [...], "count": 5} # type: ignore✅ 应该:使用类型化 dataclass 输出
# Good: Structured output with SuccessResult def handle(self, args: Args) -> Output: return YourToolOutput( data=[...], count=5, next_steps=["Review the results"], )❌ 不要:使用 TypedDict 或其他类型注解
# Bad: Using TypedDict for tool input/output from typing import TypedDict class YourToolArgs(TypedDict): session_id: str count: int✅ 应该:使用 dataclass
# Good: Using dataclasses as required from dataclasses import dataclass @dataclass class YourToolArgs: session_id: SessionId count: int = 0为什么?工具系统要求 dataclass 以保证正确的序列化、验证,以及与后端和 MCP 两个上下文的兼容性。参数转换(parse_raw)、OpenAPI schema 生成(PythonTypeToOpenAPI)与 MCP 的 pydantic 互操作都依赖这一约定。
十五、进阶主题
异步工具
对于需要 async/await 的操作:
class AsyncTool(ToolBase[Args, Output]): """Tool with async operations.""" async def handle(self, args: Args) -> Output: # type: ignore[override] """Note: Add type: ignore[override] for async handle.""" session = self.context.get_session(args.session_id) result = await self._async_work(session) return Output(result=result)异步handle之所以能透明工作,是因为统一入口__call__会通过inspect.isawaitable(result)检测并await协程返回值(base.py)。此外后端 tool_manager.py 的_call_handler也会用inspect.iscoroutinefunction区分同步与异步处理器。
带副作用的工具
通常应尽量避免在工具中产生副作用。若无法避免,务必在 guidelines 中记录:
guidelines = ToolGuidelines( side_effects=[ "Modifies notebook cells", "Triggers cell re-execution", ], )注意:仓库内置的 10 个双通道工具目前都是只读检查类工具;真正带副作用的编辑工具(edit_notebook、run_stale_cells)仅在后端 Agent 模式可用,不通过 MCP 服务器暴露,见 tools.md。
复杂返回类型
使用嵌套 dataclass 组织复杂输出:
@dataclass class CellInfo: cell_id: str code: str @dataclass class ComplexOutput(SuccessResult): cells: list[CellInfo] = field(default_factory=list) summary: dict[str, Any] = field(default_factory=dict)【免费下载链接】marimoA 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.项目地址: https://gitcode.com/GitHub_Trending/ma/marimo
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考