跳转至

get_tool_info() 方法详解

📋 概述

get_tool_info() 方法用于获取指定工具的详细信息,包括工具的参数、描述、所属服务等完整信息。

🔧 方法签名

def get_tool_info(self, tool_name: str, service_name: Optional[str] = None) -> Dict[str, Any]:
    """
    获取指定工具的详细信息

    Args:
        tool_name: 工具名称
        service_name: 可选的服务名称,用于精确定位工具

    Returns:
        Dict[str, Any]: 工具的详细信息

    Raises:
        ToolNotFoundError: 工具不存在时抛出
        ServiceNotFoundError: 指定服务不存在时抛出
    """

📝 参数说明

tool_name (str)

  • 必需参数
  • 要查询的工具名称
  • 支持完整工具名(如 service_name_tool_name)或简短名称

service_name (Optional[str])

  • 可选参数
  • 指定工具所属的服务名称
  • 当存在同名工具时,用于精确定位

📊 返回值格式

{
    "name": "tool_name",
    "service": "service_name", 
    "description": "工具描述",
    "parameters": {
        "type": "object",
        "properties": {
            "param1": {
                "type": "string",
                "description": "参数1描述"
            },
            "param2": {
                "type": "integer", 
                "description": "参数2描述"
            }
        },
        "required": ["param1"]
    },
    "examples": [
        {
            "description": "示例1描述",
            "parameters": {"param1": "value1"}
        }
    ],
    "metadata": {
        "version": "1.0.0",
        "category": "utility",
        "tags": ["tag1", "tag2"]
    }
}

💡 使用示例

基础用法

from mcpstore import MCPStore

# 初始化 MCPStore
store = MCPStore()

# 添加服务
store.add_service({
    "mcpServers": {
        "filesystem": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
        }
    }
})

# 获取工具信息
tool_info = store.get_tool_info("read_file")
print(f"工具名称: {tool_info['name']}")
print(f"所属服务: {tool_info['service']}")
print(f"工具描述: {tool_info['description']}")

指定服务名称

# 当存在同名工具时,指定服务名称
tool_info = store.get_tool_info("read_file", service_name="filesystem")
print(tool_info)

获取工具参数信息

tool_info = store.get_tool_info("write_file")

# 查看必需参数
required_params = tool_info['parameters'].get('required', [])
print(f"必需参数: {required_params}")

# 查看所有参数
properties = tool_info['parameters'].get('properties', {})
for param_name, param_info in properties.items():
    print(f"参数 {param_name}: {param_info.get('description', '无描述')}")

🔍 高级用法

批量获取工具信息

# 获取所有工具列表
tools = store.list_tools()

# 批量获取详细信息
tool_details = []
for tool in tools:
    try:
        info = store.get_tool_info(tool['name'])
        tool_details.append(info)
    except Exception as e:
        print(f"获取工具 {tool['name']} 信息失败: {e}")

print(f"成功获取 {len(tool_details)} 个工具的详细信息")

工具信息缓存

class ToolInfoCache:
    def __init__(self, store):
        self.store = store
        self.cache = {}

    def get_tool_info(self, tool_name, service_name=None):
        cache_key = f"{service_name or 'default'}:{tool_name}"

        if cache_key not in self.cache:
            self.cache[cache_key] = self.store.get_tool_info(
                tool_name, service_name
            )

        return self.cache[cache_key]

# 使用缓存
cache = ToolInfoCache(store)
info = cache.get_tool_info("read_file")

⚠️ 错误处理

常见错误类型

from mcpstore.exceptions import ToolNotFoundError, ServiceNotFoundError

try:
    tool_info = store.get_tool_info("nonexistent_tool")
except ToolNotFoundError as e:
    print(f"工具不存在: {e}")
except ServiceNotFoundError as e:
    print(f"服务不存在: {e}")
except Exception as e:
    print(f"其他错误: {e}")

安全的工具信息获取

def safe_get_tool_info(store, tool_name, service_name=None):
    """安全地获取工具信息"""
    try:
        return store.get_tool_info(tool_name, service_name)
    except ToolNotFoundError:
        return None
    except Exception as e:
        print(f"获取工具信息时发生错误: {e}")
        return None

# 使用
info = safe_get_tool_info(store, "read_file")
if info:
    print("工具信息获取成功")
else:
    print("工具信息获取失败")

🔗 相关方法

📚 最佳实践

  1. 缓存工具信息:对于频繁查询的工具,建议使用缓存
  2. 错误处理:始终处理可能的异常情况
  3. 参数验证:使用工具信息验证调用参数
  4. 服务指定:当存在同名工具时,明确指定服务名称

更新时间: 2025-01-09
版本: 1.0.0