tools.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import json
  2. import urllib.request
  3. import urllib.parse
  4. from html.parser import HTMLParser
  5. from mcp_tools import MCPTools
  6. class MLStripper(HTMLParser):
  7. def __init__(self):
  8. super().__init__()
  9. self.reset()
  10. self.fed = []
  11. def handle_data(self, d):
  12. self.fed.append(d)
  13. def get_data(self):
  14. return ''.join(self.fed)
  15. def strip_tags(html):
  16. s = MLStripper()
  17. s.feed(html)
  18. return s.get_data()
  19. class Tools:
  20. def __init__(self):
  21. self.mcp_tools = MCPTools()
  22. def get_tool_list(self):
  23. tools = [
  24. {
  25. "type": "function",
  26. "function": {
  27. "name": "read_webpage",
  28. "description": "读取指定URL网页的文本内容",
  29. "parameters": {"type": "object", "properties": {"url": {"type": "string", "description": "要读取的网页URL"}}}
  30. }
  31. }
  32. ]
  33. # 添加MCP工具
  34. tools.extend(self.mcp_tools.get_mcp_tool_list())
  35. return tools
  36. def call_tool(self, tool_name, parameters):
  37. print(f"🔧 正在执行工具: {tool_name}({parameters})")
  38. # 处理原有的工具
  39. if tool_name == "read_webpage":
  40. # 实现读取网页内容功能
  41. try:
  42. url = parameters["url"]
  43. req = urllib.request.Request(url, headers={
  44. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  45. })
  46. with urllib.request.urlopen(req) as response:
  47. html = response.read().decode('utf-8')
  48. text = strip_tags(html)
  49. return text
  50. except Exception as e:
  51. return f"读取网页错误: {str(e)}"
  52. # 处理MCP工具
  53. elif tool_name.endswith("_mcp"):
  54. result = self.mcp_tools.call_mcp_tool(tool_name, parameters)
  55. # 解析结果并检查是否有错误
  56. try:
  57. result_dict = json.loads(result)
  58. if "error" in result_dict:
  59. error_msg = result_dict['error']
  60. # 提供更详细的错误信息和建议
  61. if "unhandled errors in a TaskGroup" in error_msg:
  62. server_name = tool_name[5:-4] # 提取服务名
  63. return f"MCP调用错误: {server_name}服务内部出现未处理的异常。这通常表示服务端存在问题。错误详情: {error_msg}"
  64. return f"MCP调用错误: {error_msg}"
  65. except json.JSONDecodeError:
  66. pass # 如果不是JSON格式,直接返回原始结果
  67. return result
  68. return f"工具 {tool_name} 执行完成"
  69. if __name__ == "__main__":
  70. tools = Tools()
  71. print(tools.get_tool_list())
  72. print(tools.call_tool("read_webpage", {"url": "https://www.baidu.com"}))