tools.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import json
  2. import requests
  3. def old_tool():
  4. """
  5. 模拟器旧工具,固定返回100
  6. """
  7. return 100
  8. class Tools:
  9. def __init__(self, mcp_api_url="http://localhost:8000"):
  10. self.mcp_api_url = mcp_api_url
  11. self.mcp_tools_cache = []
  12. def get_tool_list(self):
  13. # 首先从缓存中读取tools列表
  14. if self.mcp_tools_cache:
  15. return self.mcp_tools_cache
  16. # 基础工具,旧版tools
  17. tools = [
  18. {
  19. "type": "function",
  20. "function": {
  21. "name": "luck_num",
  22. "description": "获取幸运数字",
  23. "parameters": {"type": "object", "properties": {"choice": {"type": "string", "description": "默认传入yes"}}}
  24. }
  25. }
  26. ]
  27. # 获取所有MCP服务的实际工具
  28. try:
  29. response = requests.get(f"{self.mcp_api_url}/tools")
  30. mcp_tools = response.json()
  31. # 为每个MCP工具创建独立的工具定义
  32. for tool in mcp_tools:
  33. tools.append({
  34. "type": "function",
  35. "function": {
  36. "name": tool.get("name"), # 工具名称已经带有_mcp后缀
  37. "description": tool.get("description", "未知工具"),
  38. "parameters": tool.get("inputSchema", {
  39. "type": "object",
  40. "properties": {},
  41. "required": []
  42. })
  43. }
  44. })
  45. except Exception as e:
  46. print(f"获取MCP工具列表时出错: {e}")
  47. # 存入缓存,便于下次快速调用
  48. self.mcp_tools_cache = tools
  49. return tools
  50. def call_tool(self, tool_name, parameters):
  51. print(f"正在执行工具: {tool_name}({parameters})")
  52. # 处理原有的工具
  53. if tool_name == "luck_num":
  54. return str(old_tool())
  55. # 处理MCP工具
  56. elif tool_name.endswith("_mcp"):
  57. # 调用MCP API服务器
  58. try:
  59. # 构造请求数据
  60. data = {
  61. "name": tool_name,
  62. "arguments": parameters
  63. }
  64. # 发送POST请求到MCP API服务器
  65. response = requests.post(
  66. f"{self.mcp_api_url}/call",
  67. json=data # 使用json参数自动设置Content-Type为application/json
  68. )
  69. response.raise_for_status()
  70. result = response.json()
  71. # 检查是否有错误
  72. if "error" in result:
  73. error_msg = result['error']
  74. return f"MCP调用错误: {error_msg}"
  75. # 返回结果
  76. return json.dumps(result, ensure_ascii=False)
  77. except requests.exceptions.RequestException as e:
  78. return f"MCP调用HTTP错误: {str(e)}"
  79. except Exception as e:
  80. return f"MCP调用失败: {str(e)}"
  81. else:
  82. return f"未知工具: {tool_name}"
  83. if __name__ == "__main__":
  84. tools = Tools()
  85. print(tools.get_tool_list())