public_gateway.py 5.7 KB

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