工具调用教程

Tool Caller 是 ToolUniverse 的执行引擎,负责工具的实例化、验证和执行。它通过动态加载高效管理数百种工具,而无需在启动时加载所有工具。

Python API Usage

ToolUniverse通过其Python API提供了三种调用工具的方式:

  1. **直接导入**(最简单)

  2. **动态访问**(便捷)

  3. **JSON 格式**(最灵活)

直接导入

直接导入并调用工具:

from tooluniverse.tools import UniProt_get_entry_by_accession

result = UniProt_get_entry_by_accession(accession="P05067")
print(result)

动态访问

通过 ToolUniverse 实例访问工具:

from tooluniverse import ToolUniverse

tu = ToolUniverse()
result = tu.tools.UniProt_get_entry_by_accession(accession="P05067")
print(result)

Error Handling

The Tool Caller provides comprehensive error handling and validation:

from tooluniverse import ToolUniverse

tu = ToolUniverse()

# Example: Invalid tool name
try:
    result = tu.run({
        "name": "nonexistent_tool",
        "arguments": {"param": "value"}
    })
except Exception as e:
    print(f"Tool execution failed: {e}")

# Example: Missing required parameter
result = tu.run({
    "name": "UniProt_get_entry_by_accession",
    "arguments": {"wrong_param": "value"}  # Missing required 'accession'
})
# Returns: "Invalid function call: Missing required parameter: accession"

工具执行流程

The Tool Caller follows this systematic process:

  1. 解析请求:提取工具名称和参数

  2. 验证工具:检查工具是否存在且可用

  3. Validate Arguments: Ensure arguments match tool’s parameter schema

  4. 加载工具:如果未缓存,则动态加载工具

  5. Execute: Call the tool’s run() method

  6. Return Result: Format and return the output

Performance Features

动态加载:工具仅在首次请求时加载,并在后续调用中进行缓存,从而最大限度地减少内存使用。

线程安全:多个工具可以并发执行且不会发生冲突。

Caching: Loaded tools are cached to improve performance for repeated calls.

MCP服务器集成

ToolUniverse provides MCP (Model Context Protocol) server capabilities for AI agent integration. This allows AI agents to discover and execute tools through a standardized protocol.

SMCP服务器概述

SMCP(科学模型上下文协议)服务器扩展了标准MCP,结合了科学领域专业知识和智能工具发现功能。

Key Features: - Scientific Tool Integration: Access to 1000+ specialized tools - AI-Powered Tool Discovery: Multi-tiered intelligent search system - Full MCP Protocol Support: Complete implementation of MCP specification - High-Performance Architecture: Production-ready features

服务器设置

Python 配置

from tooluniverse.smcp import SMCP

# Create a basic MCP server
server = SMCP(
    name="Scientific Research Server",
    tool_categories=["uniprot", "opentarget", "ChEMBL"],
    search_enabled=True,
    max_workers=10
)

# Start the server
server.run_simple(
    transport="http",
    host="localhost",
    port=8000
)

命令行设置

# Start MCP server with specific configuration
tooluniverse-smcp \
    --port 8000 \
    --host 0.0.0.0 \
    --categories "uniprot" "opentarget" "ChEMBL" \
    --max-workers 10 \
    --verbose

# List all available tools
tooluniverse-smcp --list-tools

# List available categories
tooluniverse-smcp --list-categories

MCP客户端集成

Python MCP 客户端示例

STDIO 客户端:

from mcp.client.stdio import stdio_client
from mcp.client.session import ClientSession
from mcp import StdioServerParameters
import asyncio

async def connect_to_tooluniverse():
    # Create stdio server parameters
    server_params = StdioServerParameters(
        command="tooluniverse-smcp-stdio",
        args=[]
    )

    # Create stdio client transport
    async with stdio_client(server_params) as (read, write):
        # Create client session
        async with ClientSession(read, write) as session:
            # Initialize the session
            await session.initialize()

            # List available tools
            tools_result = await session.list_tools()
            print(f"Available tools: {len(tools_result.tools)}")

            # Call a tool
            result = await session.call_tool(
                "UniProt_get_entry_by_accession",
                {"accession": "P05067"}
            )

            return result

# Run the client
result = asyncio.run(connect_to_tooluniverse())

HTTP 客户端:

from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamablehttp_client
import asyncio

async def connect_via_http():
    # Connect to HTTP MCP server
    async with streamablehttp_client("http://localhost:8000/mcp") as (read, write, get_session_id):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available tools
            tools_result = await session.list_tools()
            print(f"Available tools: {len(tools_result.tools)}")

            # Call a tool
            result = await session.call_tool(
                "UniProt_get_entry_by_accession",
                {"accession": "P05067"}
            )

            return result

# Run the client
result = asyncio.run(connect_via_http())

cURL 客户端示例

您还可以使用 cURL 命令直接与 ToolUniverse MCP 服务器进行交互:

# List available tools
curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list",
    "params": {}
  }'

# Call a tool
curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "UniProt_get_entry_by_accession",
      "arguments": {
        "accession": "P05067"
      }
    }
  }'

MCP客户重要注意事项

  1. 必需的请求头:ToolUniverse MCP 服务器使用 streamable-http 协议,要求:- Content-Type: application/json - Accept: application/json, text/event-stream

  2. JSON-RPC 2.0 格式:所有请求必须遵循 JSON-RPC 2.0 规范,包含以下内容: - jsonrpc: “2.0” - id:唯一请求标识符 - method:调用的 MCP 方法 - params:方法参数

  3. 工具参数:调用工具时,参数必须与工具的参数结构完全匹配。

参见

For detailed MCP server setup and usage, see MCP Support

参见

API参考 - Complete API reference