選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

mcp_tools_manage_service.py 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. 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:
  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. if "unique_mcp_provider_server_url" in error_msg:
  171. raise ValueError(f"MCP tool {server_url} already exists")
  172. if "unique_mcp_provider_server_identifier" in error_msg:
  173. raise ValueError(f"MCP tool {server_identifier} already exists")
  174. raise
  175. @classmethod
  176. def update_mcp_provider_credentials(
  177. cls, mcp_provider: MCPToolProvider, credentials: dict[str, Any], authed: bool = False
  178. ):
  179. provider_controller = MCPToolProviderController._from_db(mcp_provider)
  180. tool_configuration = ProviderConfigEncrypter(
  181. tenant_id=mcp_provider.tenant_id,
  182. config=list(provider_controller.get_credentials_schema()),
  183. provider_config_cache=NoOpProviderCredentialCache(),
  184. )
  185. credentials = tool_configuration.encrypt(credentials)
  186. mcp_provider.updated_at = datetime.now()
  187. mcp_provider.encrypted_credentials = json.dumps({**mcp_provider.credentials, **credentials})
  188. mcp_provider.authed = authed
  189. if not authed:
  190. mcp_provider.tools = "[]"
  191. db.session.commit()
  192. @classmethod
  193. def _re_connect_mcp_provider(cls, mcp_provider: MCPToolProvider, provider_id: str, tenant_id: str):
  194. """re-connect mcp provider"""
  195. try:
  196. with MCPClient(
  197. mcp_provider.decrypted_server_url,
  198. provider_id,
  199. tenant_id,
  200. authed=False,
  201. for_list=True,
  202. ) as mcp_client:
  203. tools = mcp_client.list_tools()
  204. mcp_provider.authed = True
  205. mcp_provider.tools = json.dumps([tool.model_dump() for tool in tools])
  206. except MCPAuthError:
  207. mcp_provider.authed = False
  208. mcp_provider.tools = "[]"
  209. except MCPError as e:
  210. raise ValueError(f"Failed to re-connect MCP server: {e}") from e
  211. # reset credentials
  212. mcp_provider.encrypted_credentials = "{}"