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.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. MCPToolProvider.tenant_id == tenant_id,
  66. )
  67. .first()
  68. )
  69. if existing_provider:
  70. if existing_provider.name == name:
  71. raise ValueError(f"MCP tool {name} already exists")
  72. elif existing_provider.server_url_hash == server_url_hash:
  73. raise ValueError(f"MCP tool {server_url} already exists")
  74. elif existing_provider.server_identifier == server_identifier:
  75. raise ValueError(f"MCP tool {server_identifier} already exists")
  76. encrypted_server_url = encrypter.encrypt_token(tenant_id, server_url)
  77. mcp_tool = MCPToolProvider(
  78. tenant_id=tenant_id,
  79. name=name,
  80. server_url=encrypted_server_url,
  81. server_url_hash=server_url_hash,
  82. user_id=user_id,
  83. authed=False,
  84. tools="[]",
  85. icon=json.dumps({"content": icon, "background": icon_background}) if icon_type == "emoji" else icon,
  86. server_identifier=server_identifier,
  87. )
  88. db.session.add(mcp_tool)
  89. db.session.commit()
  90. return ToolTransformService.mcp_provider_to_user_provider(mcp_tool, for_list=True)
  91. @staticmethod
  92. def retrieve_mcp_tools(tenant_id: str, for_list: bool = False) -> list[ToolProviderApiEntity]:
  93. mcp_providers = (
  94. db.session.query(MCPToolProvider)
  95. .filter(MCPToolProvider.tenant_id == tenant_id)
  96. .order_by(MCPToolProvider.name)
  97. .all()
  98. )
  99. return [
  100. ToolTransformService.mcp_provider_to_user_provider(mcp_provider, for_list=for_list)
  101. for mcp_provider in mcp_providers
  102. ]
  103. @classmethod
  104. def list_mcp_tool_from_remote_server(cls, tenant_id: str, provider_id: str):
  105. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  106. try:
  107. with MCPClient(
  108. mcp_provider.decrypted_server_url, provider_id, tenant_id, authed=mcp_provider.authed, for_list=True
  109. ) as mcp_client:
  110. tools = mcp_client.list_tools()
  111. except MCPAuthError as e:
  112. raise ValueError("Please auth the tool first")
  113. except MCPError as e:
  114. raise ValueError(f"Failed to connect to MCP server: {e}")
  115. mcp_provider.tools = json.dumps([tool.model_dump() for tool in tools])
  116. mcp_provider.authed = True
  117. mcp_provider.updated_at = datetime.now()
  118. db.session.commit()
  119. user = mcp_provider.load_user()
  120. return ToolProviderApiEntity(
  121. id=mcp_provider.id,
  122. name=mcp_provider.name,
  123. tools=ToolTransformService.mcp_tool_to_user_tool(mcp_provider, tools),
  124. type=ToolProviderType.MCP,
  125. icon=mcp_provider.icon,
  126. author=user.name if user else "Anonymous",
  127. server_url=mcp_provider.masked_server_url,
  128. updated_at=int(mcp_provider.updated_at.timestamp()),
  129. description=I18nObject(en_US="", zh_Hans=""),
  130. label=I18nObject(en_US=mcp_provider.name, zh_Hans=mcp_provider.name),
  131. plugin_unique_identifier=mcp_provider.server_identifier,
  132. )
  133. @classmethod
  134. def delete_mcp_tool(cls, tenant_id: str, provider_id: str):
  135. mcp_tool = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  136. db.session.delete(mcp_tool)
  137. db.session.commit()
  138. @classmethod
  139. def update_mcp_provider(
  140. cls,
  141. tenant_id: str,
  142. provider_id: str,
  143. name: str,
  144. server_url: str,
  145. icon: str,
  146. icon_type: str,
  147. icon_background: str,
  148. server_identifier: str,
  149. ):
  150. mcp_provider = cls.get_mcp_provider_by_provider_id(provider_id, tenant_id)
  151. mcp_provider.updated_at = datetime.now()
  152. mcp_provider.name = name
  153. mcp_provider.icon = (
  154. json.dumps({"content": icon, "background": icon_background}) if icon_type == "emoji" else icon
  155. )
  156. mcp_provider.server_identifier = server_identifier
  157. if UNCHANGED_SERVER_URL_PLACEHOLDER not in server_url:
  158. encrypted_server_url = encrypter.encrypt_token(tenant_id, server_url)
  159. mcp_provider.server_url = encrypted_server_url
  160. server_url_hash = hashlib.sha256(server_url.encode()).hexdigest()
  161. if server_url_hash != mcp_provider.server_url_hash:
  162. cls._re_connect_mcp_provider(mcp_provider, provider_id, tenant_id)
  163. mcp_provider.server_url_hash = server_url_hash
  164. try:
  165. db.session.commit()
  166. except IntegrityError as e:
  167. db.session.rollback()
  168. error_msg = str(e.orig)
  169. if "unique_mcp_provider_name" in error_msg:
  170. raise ValueError(f"MCP tool {name} already exists")
  171. elif "unique_mcp_provider_server_url" in error_msg:
  172. raise ValueError(f"MCP tool {server_url} already exists")
  173. elif "unique_mcp_provider_server_identifier" in error_msg:
  174. raise ValueError(f"MCP tool {server_identifier} already exists")
  175. else:
  176. raise
  177. @classmethod
  178. def update_mcp_provider_credentials(
  179. cls, mcp_provider: MCPToolProvider, credentials: dict[str, Any], authed: bool = False
  180. ):
  181. provider_controller = MCPToolProviderController._from_db(mcp_provider)
  182. tool_configuration = ProviderConfigEncrypter(
  183. tenant_id=mcp_provider.tenant_id,
  184. config=list(provider_controller.get_credentials_schema()),
  185. provider_config_cache=NoOpProviderCredentialCache(),
  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 = "{}"