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_manage_service.py 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.helper.provider_cache import NoOpProviderCredentialCache
  9. from core.mcp.error import MCPAuthError, MCPError
  10. from core.mcp.mcp_client import MCPClient
  11. from core.tools.entities.api_entities import ToolProviderApiEntity
  12. from core.tools.entities.common_entities import I18nObject
  13. from core.tools.entities.tool_entities import ToolProviderType
  14. from core.tools.mcp_tool.provider import MCPToolProviderController
  15. from core.tools.utils.encryption import ProviderConfigEncrypter
  16. from extensions.ext_database import db
  17. from models.tools import MCPToolProvider
  18. from services.tools.tools_transform_service import ToolTransformService
  19. UNCHANGED_SERVER_URL_PLACEHOLDER = "[__HIDDEN__]"
  20. class MCPToolManageService:
  21. """
  22. Service class for managing mcp tools.
  23. """
  24. @staticmethod
  25. def get_mcp_provider_by_provider_id(provider_id: str, tenant_id: str) -> MCPToolProvider:
  26. res = (
  27. db.session.query(MCPToolProvider)
  28. .filter(MCPToolProvider.tenant_id == tenant_id, MCPToolProvider.id == provider_id)
  29. .first()
  30. )
  31. if not res:
  32. raise ValueError("MCP tool not found")
  33. return res
  34. @staticmethod
  35. def get_mcp_provider_by_server_identifier(server_identifier: str, tenant_id: str) -> MCPToolProvider:
  36. res = (
  37. db.session.query(MCPToolProvider)
  38. .filter(MCPToolProvider.tenant_id == tenant_id, MCPToolProvider.server_identifier == server_identifier)
  39. .first()
  40. )
  41. if not res:
  42. raise ValueError("MCP tool not found")
  43. return res
  44. @staticmethod
  45. def create_mcp_provider(
  46. tenant_id: str,
  47. name: str,
  48. server_url: str,
  49. user_id: str,
  50. icon: str,
  51. icon_type: str,
  52. icon_background: str,
  53. server_identifier: str,
  54. ) -> ToolProviderApiEntity:
  55. server_url_hash = hashlib.sha256(server_url.encode()).hexdigest()
  56. existing_provider = (
  57. db.session.query(MCPToolProvider)
  58. .filter(
  59. MCPToolProvider.tenant_id == tenant_id,
  60. or_(
  61. MCPToolProvider.name == name,
  62. MCPToolProvider.server_url_hash == server_url_hash,
  63. MCPToolProvider.server_identifier == server_identifier,
  64. ),
  65. )
  66. .first()
  67. )
  68. if existing_provider:
  69. if existing_provider.name == name:
  70. raise ValueError(f"MCP tool {name} already exists")
  71. if existing_provider.server_url_hash == server_url_hash:
  72. raise ValueError(f"MCP tool {server_url} already exists")
  73. if 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) -> ToolProviderApiEntity:
  104. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  105. server_url = mcp_provider.decrypted_server_url
  106. authed = mcp_provider.authed
  107. try:
  108. with MCPClient(server_url, provider_id, tenant_id, authed=authed, for_list=True) as mcp_client:
  109. tools = mcp_client.list_tools()
  110. except MCPAuthError:
  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. try:
  115. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  116. mcp_provider.tools = json.dumps([tool.model_dump() for tool in tools])
  117. mcp_provider.authed = True
  118. mcp_provider.updated_at = datetime.now()
  119. db.session.commit()
  120. except Exception:
  121. db.session.rollback()
  122. raise
  123. user = mcp_provider.load_user()
  124. return ToolProviderApiEntity(
  125. id=mcp_provider.id,
  126. name=mcp_provider.name,
  127. tools=ToolTransformService.mcp_tool_to_user_tool(mcp_provider, tools),
  128. type=ToolProviderType.MCP,
  129. icon=mcp_provider.icon,
  130. author=user.name if user else "Anonymous",
  131. server_url=mcp_provider.masked_server_url,
  132. updated_at=int(mcp_provider.updated_at.timestamp()),
  133. description=I18nObject(en_US="", zh_Hans=""),
  134. label=I18nObject(en_US=mcp_provider.name, zh_Hans=mcp_provider.name),
  135. plugin_unique_identifier=mcp_provider.server_identifier,
  136. )
  137. @classmethod
  138. def delete_mcp_tool(cls, tenant_id: str, provider_id: str):
  139. mcp_tool = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  140. db.session.delete(mcp_tool)
  141. db.session.commit()
  142. @classmethod
  143. def update_mcp_provider(
  144. cls,
  145. tenant_id: str,
  146. provider_id: str,
  147. name: str,
  148. server_url: str,
  149. icon: str,
  150. icon_type: str,
  151. icon_background: str,
  152. server_identifier: str,
  153. ):
  154. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  155. reconnect_result = None
  156. encrypted_server_url = None
  157. server_url_hash = None
  158. if UNCHANGED_SERVER_URL_PLACEHOLDER not in server_url:
  159. encrypted_server_url = encrypter.encrypt_token(tenant_id, server_url)
  160. server_url_hash = hashlib.sha256(server_url.encode()).hexdigest()
  161. if server_url_hash != mcp_provider.server_url_hash:
  162. reconnect_result = cls._re_connect_mcp_provider(server_url, provider_id, tenant_id)
  163. try:
  164. mcp_provider.updated_at = datetime.now()
  165. mcp_provider.name = name
  166. mcp_provider.icon = (
  167. json.dumps({"content": icon, "background": icon_background}) if icon_type == "emoji" else icon
  168. )
  169. mcp_provider.server_identifier = server_identifier
  170. if encrypted_server_url is not None and server_url_hash is not None:
  171. mcp_provider.server_url = encrypted_server_url
  172. mcp_provider.server_url_hash = server_url_hash
  173. if reconnect_result:
  174. mcp_provider.authed = reconnect_result["authed"]
  175. mcp_provider.tools = reconnect_result["tools"]
  176. mcp_provider.encrypted_credentials = reconnect_result["encrypted_credentials"]
  177. db.session.commit()
  178. except IntegrityError as e:
  179. db.session.rollback()
  180. error_msg = str(e.orig)
  181. if "unique_mcp_provider_name" in error_msg:
  182. raise ValueError(f"MCP tool {name} already exists")
  183. if "unique_mcp_provider_server_url" in error_msg:
  184. raise ValueError(f"MCP tool {server_url} already exists")
  185. if "unique_mcp_provider_server_identifier" in error_msg:
  186. raise ValueError(f"MCP tool {server_identifier} already exists")
  187. raise
  188. except Exception:
  189. db.session.rollback()
  190. raise
  191. @classmethod
  192. def update_mcp_provider_credentials(
  193. cls, mcp_provider: MCPToolProvider, credentials: dict[str, Any], authed: bool = False
  194. ):
  195. provider_controller = MCPToolProviderController._from_db(mcp_provider)
  196. tool_configuration = ProviderConfigEncrypter(
  197. tenant_id=mcp_provider.tenant_id,
  198. config=list(provider_controller.get_credentials_schema()),
  199. provider_config_cache=NoOpProviderCredentialCache(),
  200. )
  201. credentials = tool_configuration.encrypt(credentials)
  202. mcp_provider.updated_at = datetime.now()
  203. mcp_provider.encrypted_credentials = json.dumps({**mcp_provider.credentials, **credentials})
  204. mcp_provider.authed = authed
  205. if not authed:
  206. mcp_provider.tools = "[]"
  207. db.session.commit()
  208. @classmethod
  209. def _re_connect_mcp_provider(cls, server_url: str, provider_id: str, tenant_id: str):
  210. try:
  211. with MCPClient(
  212. server_url,
  213. provider_id,
  214. tenant_id,
  215. authed=False,
  216. for_list=True,
  217. ) as mcp_client:
  218. tools = mcp_client.list_tools()
  219. return {
  220. "authed": True,
  221. "tools": json.dumps([tool.model_dump() for tool in tools]),
  222. "encrypted_credentials": "{}",
  223. }
  224. except MCPAuthError:
  225. return {"authed": False, "tools": "[]", "encrypted_credentials": "{}"}
  226. except MCPError as e:
  227. raise ValueError(f"Failed to re-connect MCP server: {e}") from e