public_gateway.py 6.3 KB

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