tool_converter.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. 工具转换器 - 将 MCP 工具定义转换为 Claude API 工具格式
  3. """
  4. from typing import Dict, List, Any
  5. import json
  6. class ToolConverter:
  7. """将 MCP 工具转换为 Claude API 工具格式"""
  8. @staticmethod
  9. def mcp_to_claude_tool(mcp_tool: Dict[str, Any]) -> Dict[str, Any]:
  10. """
  11. 将单个 MCP 工具转换为 Claude API 工具格式
  12. Args:
  13. mcp_tool: MCP 工具定义,包含 name, description, inputSchema
  14. Returns:
  15. Claude API 工具格式
  16. """
  17. name = mcp_tool.get("name", "")
  18. description = mcp_tool.get("description", "")
  19. input_schema = mcp_tool.get("inputSchema", {})
  20. server_id = mcp_tool.get("_server_id", "") # 获取服务器 ID
  21. # 构建 Claude 工具格式
  22. claude_tool = {
  23. "name": name,
  24. "description": description,
  25. "input_schema": {
  26. "type": "object",
  27. "properties": {},
  28. "required": []
  29. }
  30. }
  31. # 存储服务器 ID 元数据(用于后续调用时查找)
  32. if server_id:
  33. claude_tool["_server_id"] = server_id
  34. # 转换 inputSchema
  35. if isinstance(input_schema, dict):
  36. properties = input_schema.get("properties", {})
  37. required = input_schema.get("required", [])
  38. claude_tool["input_schema"]["properties"] = properties
  39. claude_tool["input_schema"]["required"] = required
  40. # 添加类型信息
  41. for prop_name, prop_def in properties.items():
  42. if isinstance(prop_def, dict) and "type" not in prop_def:
  43. # 尝试从 schema 中推断类型
  44. if "$ref" in prop_def:
  45. prop_def["type"] = "string"
  46. elif "enum" in prop_def:
  47. prop_def["type"] = "string"
  48. return claude_tool
  49. @staticmethod
  50. def convert_mcp_tools(mcp_tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  51. """
  52. 批量转换 MCP 工具列表
  53. Args:
  54. mcp_tools: MCP 工具列表
  55. Returns:
  56. Claude API 工具列表
  57. """
  58. claude_tools = []
  59. for mcp_tool in mcp_tools:
  60. try:
  61. claude_tool = ToolConverter.mcp_to_claude_tool(mcp_tool)
  62. claude_tools.append(claude_tool)
  63. except Exception as e:
  64. print(f"转换工具 {mcp_tool.get('name', 'unknown')} 失败: {e}")
  65. return claude_tools