You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mcp_tools_mange_service.py 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import hashlib
  2. import json
  3. from datetime import datetime
  4. from typing import Any
  5. from sqlalchemy import or_
  6. from sqlalchemy.exc import IntegrityError
  7. from core.helper import encrypter
  8. from core.mcp.error import MCPAuthError, MCPError
  9. from core.mcp.mcp_client import MCPClient
  10. from core.tools.entities.api_entities import ToolProviderApiEntity
  11. from core.tools.entities.common_entities import I18nObject
  12. from core.tools.entities.tool_entities import ToolProviderType
  13. from core.tools.mcp_tool.provider import MCPToolProviderController
  14. from core.tools.utils.configuration import ProviderConfigEncrypter
  15. from extensions.ext_database import db
  16. from models.tools import MCPToolProvider
  17. from services.tools.tools_transform_service import ToolTransformService
  18. UNCHANGED_SERVER_URL_PLACEHOLDER = "[__HIDDEN__]"
  19. class MCPToolManageService:
  20. """
  21. Service class for managing mcp tools.
  22. """
  23. @staticmethod
  24. def get_mcp_provider_by_provider_id(provider_id: str, tenant_id: str) -> MCPToolProvider:
  25. res = (
  26. db.session.query(MCPToolProvider)
  27. .filter(MCPToolProvider.tenant_id == tenant_id, MCPToolProvider.id == provider_id)
  28. .first()
  29. )
  30. if not res:
  31. raise ValueError("MCP tool not found")
  32. return res
  33. @staticmethod
  34. def get_mcp_provider_by_server_identifier(server_identifier: str, tenant_id: str) -> MCPToolProvider:
  35. res = (
  36. db.session.query(MCPToolProvider)
  37. .filter(MCPToolProvider.tenant_id == tenant_id, MCPToolProvider.server_identifier == server_identifier)
  38. .first()
  39. )
  40. if not res:
  41. raise ValueError("MCP tool not found")
  42. return res
  43. @staticmethod
  44. def create_mcp_provider(
  45. tenant_id: str,
  46. name: str,
  47. server_url: str,
  48. user_id: str,
  49. icon: str,
  50. icon_type: str,
  51. icon_background: str,
  52. server_identifier: str,
  53. ) -> ToolProviderApiEntity:
  54. server_url_hash = hashlib.sha256(server_url.encode()).hexdigest()
  55. existing_provider = (
  56. db.session.query(MCPToolProvider)
  57. .filter(
  58. MCPToolProvider.tenant_id == tenant_id,
  59. or_(
  60. MCPToolProvider.name == name,
  61. MCPToolProvider.server_url_hash == server_url_hash,
  62. MCPToolProvider.server_identifier == server_identifier,
  63. ),
  64. MCPToolProvider.tenant_id == tenant_id,
  65. )
  66. .first()
  67. )
  68. if existing_provider:
  69. if existing_provider.name == name:
  70. raise ValueError(f"MCP tool {name} already exists")
  71. elif existing_provider.server_url_hash == server_url_hash:
  72. raise ValueError(f"MCP tool {server_url} already exists")
  73. elif existing_provider.server_identifier == server_identifier:
  74. raise ValueError(f"MCP tool {server_identifier} already exists")
  75. encrypted_server_url = encrypter.encrypt_token(tenant_id, server_url)
  76. mcp_tool = MCPToolProvider(
  77. tenant_id=tenant_id,
  78. name=name,
  79. server_url=encrypted_server_url,
  80. server_url_hash=server_url_hash,
  81. user_id=user_id,
  82. authed=False,
  83. tools="[]",
  84. icon=json.dumps({"content": icon, "background": icon_background}) if icon_type == "emoji" else icon,
  85. server_identifier=server_identifier,
  86. )
  87. db.session.add(mcp_tool)
  88. db.session.commit()
  89. return ToolTransformService.mcp_provider_to_user_provider(mcp_tool, for_list=True)
  90. @staticmethod
  91. def retrieve_mcp_tools(tenant_id: str, for_list: bool = False) -> list[ToolProviderApiEntity]:
  92. mcp_providers = (
  93. db.session.query(MCPToolProvider)
  94. .filter(MCPToolProvider.tenant_id == tenant_id)
  95. .order_by(MCPToolProvider.name)
  96. .all()
  97. )
  98. return [
  99. ToolTransformService.mcp_provider_to_user_provider(mcp_provider, for_list=for_list)
  100. for mcp_provider in mcp_providers
  101. ]
  102. @classmethod
  103. def list_mcp_tool_from_remote_server(cls, tenant_id: str, provider_id: str):
  104. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  105. try:
  106. with MCPClient(
  107. mcp_provider.decrypted_server_url, provider_id, tenant_id, authed=mcp_provider.authed, for_list=True
  108. ) as mcp_client:
  109. tools = mcp_client.list_tools()
  110. except MCPAuthError as e:
  111. raise ValueError("Please auth the tool first")
  112. except MCPError as e:
  113. raise ValueError(f"Failed to connect to MCP server: {e}")
  114. mcp_provider.tools = json.dumps([tool.model_dump() for tool in tools])
  115. mcp_provider.authed = True
  116. mcp_provider.updated_at = datetime.now()
  117. db.session.commit()
  118. user = mcp_provider.load_user()
  119. return ToolProviderApiEntity(
  120. id=mcp_provider.id,
  121. name=mcp_provider.name,
  122. tools=ToolTransformService.mcp_tool_to_user_tool(mcp_provider, tools),
  123. type=ToolProviderType.MCP,
  124. icon=mcp_provider.icon,
  125. author=user.name if user else "Anonymous",
  126. server_url=mcp_provider.masked_server_url,
  127. updated_at=int(mcp_provider.updated_at.timestamp()),
  128. description=I18nObject(en_US="", zh_Hans=""),
  129. label=I18nObject(en_US=mcp_provider.name, zh_Hans=mcp_provider.name),
  130. plugin_unique_identifier=mcp_provider.server_identifier,
  131. )
  132. @classmethod
  133. def delete_mcp_tool(cls, tenant_id: str, provider_id: str):
  134. mcp_tool = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  135. db.session.delete(mcp_tool)
  136. db.session.commit()
  137. @classmethod
  138. def update_mcp_provider(
  139. cls,
  140. tenant_id: str,
  141. provider_id: str,
  142. name: str,
  143. server_url: str,
  144. icon: str,
  145. icon_type: str,
  146. icon_background: str,
  147. server_identifier: str,
  148. ):
  149. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  150. mcp_provider.updated_at = datetime.now()
  151. mcp_provider.name = name
  152. mcp_provider.icon = (
  153. json.dumps({"content": icon, "background": icon_background}) if icon_type == "emoji" else icon
  154. )
  155. mcp_provider.server_identifier = server_identifier
  156. if UNCHANGED_SERVER_URL_PLACEHOLDER not in server_url:
  157. encrypted_server_url = encrypter.encrypt_token(tenant_id, server_url)
  158. mcp_provider.server_url = encrypted_server_url
  159. server_url_hash = hashlib.sha256(server_url.encode()).hexdigest()
  160. if server_url_hash != mcp_provider.server_url_hash:
  161. cls._re_connect_mcp_provider(mcp_provider, provider_id, tenant_id)
  162. mcp_provider.server_url_hash = server_url_hash
  163. try:
  164. db.session.commit()
  165. except IntegrityError as e:
  166. db.session.rollback()
  167. error_msg = str(e.orig)
  168. if "unique_mcp_provider_name" in error_msg:
  169. raise ValueError(f"MCP tool {name} already exists")
  170. elif "unique_mcp_provider_server_url" in error_msg:
  171. raise ValueError(f"MCP tool {server_url} already exists")
  172. elif "unique_mcp_provider_server_identifier" in error_msg:
  173. raise ValueError(f"MCP tool {server_identifier} already exists")
  174. else:
  175. raise
  176. @classmethod
  177. def update_mcp_provider_credentials(
  178. cls, mcp_provider: MCPToolProvider, credentials: dict[str, Any], authed: bool = False
  179. ):
  180. provider_controller = MCPToolProviderController._from_db(mcp_provider)
  181. tool_configuration = ProviderConfigEncrypter(
  182. tenant_id=mcp_provider.tenant_id,
  183. config=list(provider_controller.get_credentials_schema()),
  184. provider_type=provider_controller.provider_type.value,
  185. provider_identity=provider_controller.provider_id,
  186. )
  187. credentials = tool_configuration.encrypt(credentials)
  188. mcp_provider.updated_at = datetime.now()
  189. mcp_provider.encrypted_credentials = json.dumps({**mcp_provider.credentials, **credentials})
  190. mcp_provider.authed = authed
  191. if not authed:
  192. mcp_provider.tools = "[]"
  193. db.session.commit()
  194. @classmethod
  195. def _re_connect_mcp_provider(cls, mcp_provider: MCPToolProvider, provider_id: str, tenant_id: str):
  196. """re-connect mcp provider"""
  197. try:
  198. with MCPClient(
  199. mcp_provider.decrypted_server_url,
  200. provider_id,
  201. tenant_id,
  202. authed=False,
  203. for_list=True,
  204. ) as mcp_client:
  205. tools = mcp_client.list_tools()
  206. mcp_provider.authed = True
  207. mcp_provider.tools = json.dumps([tool.model_dump() for tool in tools])
  208. except MCPAuthError:
  209. mcp_provider.authed = False
  210. mcp_provider.tools = "[]"
  211. except MCPError as e:
  212. raise ValueError(f"Failed to re-connect MCP server: {e}") from e
  213. # reset credentials
  214. mcp_provider.encrypted_credentials = "{}"