tool_converter.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. # 构建 Claude 工具格式
  21. claude_tool = {
  22. "name": name,
  23. "description": description,
  24. "input_schema": {
  25. "type": "object",
  26. "properties": {},
  27. "required": []
  28. }
  29. }
  30. # 转换 inputSchema
  31. if isinstance(input_schema, dict):
  32. properties = input_schema.get("properties", {})
  33. required = input_schema.get("required", [])
  34. claude_tool["input_schema"]["properties"] = properties
  35. claude_tool["input_schema"]["required"] = required
  36. # 添加类型信息
  37. for prop_name, prop_def in properties.items():
  38. if isinstance(prop_def, dict) and "type" not in prop_def:
  39. # 尝试从 schema 中推断类型
  40. if "$ref" in prop_def:
  41. prop_def["type"] = "string"
  42. elif "enum" in prop_def:
  43. prop_def["type"] = "string"
  44. return claude_tool
  45. @staticmethod
  46. def convert_mcp_tools(mcp_tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  47. """
  48. 批量转换 MCP 工具列表
  49. Args:
  50. mcp_tools: MCP 工具列表
  51. Returns:
  52. Claude API 工具列表
  53. """
  54. claude_tools = []
  55. for mcp_tool in mcp_tools:
  56. try:
  57. claude_tool = ToolConverter.mcp_to_claude_tool(mcp_tool)
  58. claude_tools.append(claude_tool)
  59. except Exception as e:
  60. print(f"转换工具 {mcp_tool.get('name', 'unknown')} 失败: {e}")
  61. return claude_tools