| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- """
- 工具转换器 - 将 MCP 工具定义转换为 Claude API 工具格式
- """
- from typing import Dict, List, Any
- import json
- class ToolConverter:
- """将 MCP 工具转换为 Claude API 工具格式"""
- @staticmethod
- def mcp_to_claude_tool(mcp_tool: Dict[str, Any]) -> Dict[str, Any]:
- """
- 将单个 MCP 工具转换为 Claude API 工具格式
- Args:
- mcp_tool: MCP 工具定义,包含 name, description, inputSchema
- Returns:
- Claude API 工具格式
- """
- name = mcp_tool.get("name", "")
- description = mcp_tool.get("description", "")
- input_schema = mcp_tool.get("inputSchema", {})
- # 构建 Claude 工具格式
- claude_tool = {
- "name": name,
- "description": description,
- "input_schema": {
- "type": "object",
- "properties": {},
- "required": []
- }
- }
- # 转换 inputSchema
- if isinstance(input_schema, dict):
- properties = input_schema.get("properties", {})
- required = input_schema.get("required", [])
- claude_tool["input_schema"]["properties"] = properties
- claude_tool["input_schema"]["required"] = required
- # 添加类型信息
- for prop_name, prop_def in properties.items():
- if isinstance(prop_def, dict) and "type" not in prop_def:
- # 尝试从 schema 中推断类型
- if "$ref" in prop_def:
- prop_def["type"] = "string"
- elif "enum" in prop_def:
- prop_def["type"] = "string"
- return claude_tool
- @staticmethod
- def convert_mcp_tools(mcp_tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- 批量转换 MCP 工具列表
- Args:
- mcp_tools: MCP 工具列表
- Returns:
- Claude API 工具列表
- """
- claude_tools = []
- for mcp_tool in mcp_tools:
- try:
- claude_tool = ToolConverter.mcp_to_claude_tool(mcp_tool)
- claude_tools.append(claude_tool)
- except Exception as e:
- print(f"转换工具 {mcp_tool.get('name', 'unknown')} 失败: {e}")
- return claude_tools
|