Create Your First Tool

5分钟快速上手ToolUniverse!本指南将向您展示如何创建一个简单的本地工具供您个人使用。

您将构建的内容

一种文本处理工具,可将文本转换为大写——简单但展示了所有核心概念。

完整工作示例

步骤 1:创建工具文件

在您的项目目录中创建 my_text_tool.py

from tooluniverse.tool_registry import register_tool
from tooluniverse.base_tool import BaseTool
from typing import Dict, Any

@register_tool('TextProcessor', config={
    "name": "text_processor",
    "type": "TextProcessor",
    "description": "Process text with various operations",
    "parameter": {
        "type": "object",
        "properties": {
            "text": {
                "type": "string",
                "description": "Text to process"
            },
            "operation": {
                "type": "string",
                "enum": ["uppercase", "lowercase", "reverse"],
                "default": "uppercase",
                "description": "Operation to perform"
            }
        },
        "required": ["text"]
    }
})
class TextProcessor(BaseTool):
    """Process text with various operations."""

    def run(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
        """Execute the text processing."""
        text = arguments.get("text", "")
        operation = arguments.get("operation", "uppercase")

        if operation == "uppercase":
            result = text.upper()
        elif operation == "lowercase":
            result = text.lower()
        elif operation == "reverse":
            result = text[::-1]
        else:
            return {"error": f"Unknown operation: {operation}", "success": False}

        return {
            "result": result,
            "operation": operation,
            "original": text,
            "success": True
        }

步骤 2:使用工具

在同一目录下创建 main.py:

from tooluniverse import ToolUniverse
from my_text_tool import TextProcessor  # Import to register the tool

def main():
    # Initialize ToolUniverse
    tu = ToolUniverse()
    tu.load_tools()

    # Test different operations
    test_cases = [
        {"text": "Hello World", "operation": "uppercase"},
        {"text": "PYTHON", "operation": "lowercase"},
        {"text": "ToolUniverse", "operation": "reverse"},
    ]

    print("Text Processing Results:")
    print("-" * 40)

    for i, test_case in enumerate(test_cases, 1):
        print(f"\nTest {i}: {test_case['operation']}")
        print(f"Input:  '{test_case['text']}'")

        result = tu.run({
            "name": "text_processor",
            "arguments": test_case
        })

        if result.get("success"):
            print(f"Output: '{result['result']}'")
        else:
            print(f"Error:  {result.get('error', 'Unknown error')}")

if __name__ == "__main__":
    main()

步骤 3:运行它

python main.py

预期输出: .. code-block:: text

测试 1:大写 输入:’Hello World’ 输出:’HELLO WORLD’

测试 2:小写 输入:’PYTHON’ 输出:’python’

测试 3:反转 输入:’ToolUniverse’ 输出:’esrevinUlooT’

That’s It!

您已成功创建并使用了您的第一个 ToolUniverse 工具!以下是发生的情况:

  1. 工具定义@register_tool 装饰器将您的工具注册到 ToolUniverse

  2. 配置:配置字典定义了工具的界面和参数

  3. 实现run() 方法包含了工具的逻辑

  4. 使用说明:ToolUniverse 已自动发现并加载您的工具

关键概念解析

工具注册 - @register_tool('ToolType', config={...}) 用于注册您的工具 - 配置项定义了工具的名称、参数和元数据 - ToolUniverse 会自动发现已注册的工具

BaseTool 类 - 所有工具必须继承 BaseTool - 使用您的逻辑实现 run(arguments) 方法 - 返回一个包含 success 和结果数据的字典

Tool Execution - Use tu.run() to execute tools - Pass tool name and arguments as a dictionary - ToolUniverse handles parameter validation and execution

参数验证 - ToolUniverse 会根据您的配置自动验证参数 - 强制执行必需参数 - 自动进行类型检查

下一步

现在您已经拥有一个可用的工具,您可以:

** Learn More:** - Local Tools Tutorial - Comprehensive local tool development - 远程工具教程 - Create remote tools and MCP servers - Review the tool type comparison table in Contributing to ToolUniverse

** Contribute to Community:** - 将本地工具贡献至 ToolUniverse - Submit your tool to ToolUniverse (requires additional steps) - 将远程工具贡献给ToolUniverse - Submit remote tools to the community

** Advanced Features:** - Add input validation with validate_input() method - Implement error handling and retry logic - Add caching and performance optimizations - Create more complex tools with multiple operations

** Pro Tips:** - Start simple and add complexity gradually - Test your tools thoroughly before contributing - Use meaningful parameter names and descriptions - Follow the existing tool patterns in the codebase

常见问题

Q: 我可以将工具放在不同的文件中吗? A: 可以!只需确保在使用 ToolUniverse 的地方导入它即可。

问:如果我想添加更多操作怎么办? 答:只需将它们添加到配置中的``enum``列表,并在``run()``方法中实现即可。

Q: 我可以在其他项目中使用这个工具吗? A: 可以!复制工具文件并将其导入到任何安装了 ToolUniverse 的项目中。

问:如何更好地处理错误? 答:在您的工具类中添加一个``validate_input()``方法,用于自定义验证。

问:我可以将其设置为远程工具吗? 答:可以!请参阅 远程工具教程 了解创建 MCP 服务器的教程。

Ready to build something amazing? Let’s go!