public_gateway.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import logging
  2. import uuid
  3. from constants import DEVICE_INVALID_MESSAGE
  4. from tools.list_order_filter_options import ListOrderFilterOptionsTool
  5. from tools.list_outbound_filter_options import ListOutboundFilterOptionsTool
  6. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  7. from tools.export_out_of_province_port_data import (
  8. ExportOutOfProvincePortDataTool,
  9. )
  10. from tools.list_pending_outbound_export_filter_options import (
  11. ListPendingOutboundExportFilterOptionsTool,
  12. )
  13. from tools.query_order import QueryOrderTool
  14. from tools.query_customs_declaration_files import (
  15. QueryCustomsDeclarationFilesTool,
  16. )
  17. from tools.query_order_exact import QueryOrderExactTool
  18. from tools.query_outbound_detail import QueryOutboundDetailTool
  19. from tools.query_outbound_list import QueryOutboundListTool
  20. from tools.query_track import QueryTrackTool
  21. from utils.security import hash_gateway_session_id
  22. logger = logging.getLogger(__name__)
  23. class PublicGatewayApp:
  24. def __init__(self, session_store, api_client, auth_client=None):
  25. self.session_store = session_store
  26. self.api_client = api_client
  27. self._tools = {
  28. 'query_order': QueryOrderTool(api_client=None),
  29. 'query_track': QueryTrackTool(api_client=None),
  30. 'query_order_exact': QueryOrderExactTool(api_client=None),
  31. 'query_customs_declaration_files':
  32. QueryCustomsDeclarationFilesTool(api_client=None),
  33. 'query_outbound_list': QueryOutboundListTool(api_client=None),
  34. 'query_outbound_detail': QueryOutboundDetailTool(api_client=None),
  35. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  36. api_client=None
  37. ),
  38. 'list_order_filter_options': ListOrderFilterOptionsTool(
  39. api_client=None
  40. ),
  41. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  42. api_client=None
  43. ),
  44. 'export_out_of_province_port_data':
  45. ExportOutOfProvincePortDataTool(api_client=None),
  46. 'list_pending_outbound_export_filter_options':
  47. ListPendingOutboundExportFilterOptionsTool(api_client=None),
  48. }
  49. def registered_tool_names(self):
  50. return tuple(self._tools.keys())
  51. def _require_session(self, gateway_session_id):
  52. session = self.session_store.get(gateway_session_id)
  53. if not session or not session.get('mcp_token'):
  54. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  55. return session
  56. def _enabled_tool_names(self, response):
  57. if not isinstance(response, dict):
  58. raise RuntimeError('invalid enabled tool response')
  59. if response.get('code') != 'MCP_0000':
  60. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  61. data = response.get('data')
  62. codes = data.get('tool_codes') if isinstance(data, dict) else None
  63. if not isinstance(codes, list):
  64. raise RuntimeError('invalid enabled tool response')
  65. return {
  66. code.strip().lower()
  67. for code in codes
  68. if isinstance(code, str) and code.strip()
  69. }
  70. def _load_enabled_tool_names(self, token, request_id=''):
  71. response = self.api_client.list_enabled_tools(
  72. token,
  73. request_id=request_id,
  74. )
  75. return self._enabled_tool_names(response)
  76. def list_tools(self, gateway_session_id, request_id=''):
  77. session = self._require_session(gateway_session_id)
  78. request_id = self.build_request_id(request_id)
  79. enabled = self._load_enabled_tool_names(
  80. session['mcp_token'],
  81. request_id,
  82. )
  83. return [
  84. tool.metadata()
  85. for name, tool in self._tools.items()
  86. if name in enabled
  87. ]
  88. def build_request_id(self, request_id=''):
  89. request_id = str(request_id or '').strip()
  90. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  91. def call_tool(self, gateway_session_id, name, arguments=None, request_id='', client_ip=''):
  92. if name not in self._tools:
  93. raise KeyError('tool not registered: {0}'.format(name))
  94. session = self._require_session(gateway_session_id)
  95. request_id = self.build_request_id(request_id)
  96. if name not in self._load_enabled_tool_names(
  97. session['mcp_token'],
  98. request_id,
  99. ):
  100. raise RuntimeError('tool disabled: {0}'.format(name))
  101. tool = self._tools[name]
  102. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  103. admin_id = session.get('admin_id')
  104. company_id = session.get('company_id')
  105. logger.info(
  106. 'MCP public tool call',
  107. extra={
  108. 'request_id': request_id,
  109. 'tool_code': name,
  110. 'session_hash': session_hash,
  111. 'admin_id': admin_id,
  112. 'company_id': company_id,
  113. },
  114. )
  115. try:
  116. result = self.api_client.call_tool(
  117. token=session['mcp_token'],
  118. tool_code=tool.name,
  119. route_path=tool.route_path,
  120. payload=arguments or {},
  121. request_id=request_id,
  122. client_ip=client_ip,
  123. )
  124. if hasattr(self.session_store, 'touch_session'):
  125. self.session_store.touch_session(gateway_session_id)
  126. logger.info(
  127. 'MCP public tool success',
  128. extra={
  129. 'request_id': request_id,
  130. 'tool_code': name,
  131. 'session_hash': session_hash,
  132. 'response_code': result.get('code'),
  133. },
  134. )
  135. return result
  136. except Exception as e:
  137. logger.error(
  138. 'MCP public tool failed',
  139. extra={
  140. 'request_id': request_id,
  141. 'tool_code': name,
  142. 'session_hash': session_hash,
  143. 'response_code': 'MCP_9001',
  144. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  145. 'exception_class': e.__class__.__name__,
  146. },
  147. )
  148. raise