public_gateway.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import logging
  2. import time
  3. import uuid
  4. from constants import DEVICE_INVALID_MESSAGE
  5. from tools.list_order_filter_options import ListOrderFilterOptionsTool
  6. from tools.list_customer_filter_options import ListCustomerFilterOptionsTool
  7. from tools.list_outbound_filter_options import ListOutboundFilterOptionsTool
  8. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  9. from tools.export_out_of_province_port_data import (
  10. ExportOutOfProvincePortDataTool,
  11. )
  12. from tools.list_pending_outbound_export_filter_options import (
  13. ListPendingOutboundExportFilterOptionsTool,
  14. )
  15. from tools.query_order import QueryOrderTool
  16. from tools.query_customs_declaration_files import (
  17. QueryCustomsDeclarationFilesTool,
  18. )
  19. from tools.query_order_exact import QueryOrderExactTool
  20. from tools.query_order_detail import QueryOrderDetailTool
  21. from tools.query_export_task import QueryExportTaskTool
  22. from tools.query_outbound_detail import QueryOutboundDetailTool
  23. from tools.query_outbound_list import QueryOutboundListTool
  24. from tools.query_track import QueryTrackTool
  25. from tools.query_customer_list import QueryCustomerListTool
  26. from tools.query_customer_payment_followup import QueryCustomerPaymentFollowupTool
  27. from tools.query_customer_unverified_bill_details import QueryCustomerUnverifiedBillDetailsTool
  28. from tools.query_customer_payment_records import QueryCustomerPaymentRecordsTool
  29. from tools.query_order_receivable_cost_details import (
  30. QueryOrderReceivableCostDetailsTool,
  31. )
  32. from utils.security import hash_gateway_session_id
  33. logger = logging.getLogger(__name__)
  34. class PublicGatewayApp:
  35. def __init__(self, session_store, api_client, auth_client=None):
  36. self.session_store = session_store
  37. self.api_client = api_client
  38. self._tools = {
  39. 'query_order': QueryOrderTool(api_client=None),
  40. 'query_track': QueryTrackTool(api_client=None),
  41. 'query_order_exact': QueryOrderExactTool(api_client=None),
  42. 'query_order_detail': QueryOrderDetailTool(api_client=None),
  43. 'query_customs_declaration_files':
  44. QueryCustomsDeclarationFilesTool(api_client=None),
  45. 'query_outbound_list': QueryOutboundListTool(api_client=None),
  46. 'query_outbound_detail': QueryOutboundDetailTool(api_client=None),
  47. 'query_customer_list': QueryCustomerListTool(api_client=None),
  48. 'query_customer_payment_followup': QueryCustomerPaymentFollowupTool(
  49. api_client=None
  50. ),
  51. 'query_customer_unverified_bill_details':
  52. QueryCustomerUnverifiedBillDetailsTool(api_client=None),
  53. 'query_customer_payment_records': QueryCustomerPaymentRecordsTool(
  54. api_client=None
  55. ),
  56. 'query_order_receivable_cost_details':
  57. QueryOrderReceivableCostDetailsTool(api_client=None),
  58. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  59. api_client=None
  60. ),
  61. 'list_order_filter_options': ListOrderFilterOptionsTool(
  62. api_client=None
  63. ),
  64. 'list_customer_filter_options': ListCustomerFilterOptionsTool(
  65. api_client=None
  66. ),
  67. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  68. api_client=None
  69. ),
  70. 'export_out_of_province_port_data':
  71. ExportOutOfProvincePortDataTool(api_client=None),
  72. 'query_export_task': QueryExportTaskTool(api_client=None),
  73. 'list_pending_outbound_export_filter_options':
  74. ListPendingOutboundExportFilterOptionsTool(api_client=None),
  75. }
  76. def registered_tool_names(self):
  77. return tuple(self._tools.keys())
  78. def _require_session(self, gateway_session_id, diagnostic_emitter=None):
  79. session = self.session_store.get(gateway_session_id)
  80. if not session or not session.get('mcp_token'):
  81. if diagnostic_emitter is not None:
  82. diagnostic_emitter.emit(
  83. stage='gateway_session',
  84. status='failed',
  85. event_code='GATEWAY_SESSION_NOT_FOUND',
  86. session_credential=gateway_session_id,
  87. context={'transport': 'http'},
  88. )
  89. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  90. if diagnostic_emitter is not None:
  91. diagnostic_emitter.set_defaults(
  92. session_credential=gateway_session_id,
  93. admin_id=session.get('admin_id'),
  94. company_id=session.get('company_id'),
  95. context={'transport': 'http'},
  96. )
  97. diagnostic_emitter.emit(
  98. stage='gateway_session',
  99. status='succeeded',
  100. event_code='GATEWAY_SESSION_RESOLVED',
  101. )
  102. return session
  103. def _enabled_tool_names(self, response):
  104. if not isinstance(response, dict):
  105. raise RuntimeError('invalid enabled tool response')
  106. if response.get('code') != 'MCP_0000':
  107. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  108. data = response.get('data')
  109. codes = data.get('tool_codes') if isinstance(data, dict) else None
  110. if not isinstance(codes, list):
  111. raise RuntimeError('invalid enabled tool response')
  112. return {
  113. code.strip().lower()
  114. for code in codes
  115. if isinstance(code, str) and code.strip()
  116. }
  117. def _load_enabled_tool_names(self, token, request_id=''):
  118. response = self.api_client.list_enabled_tools(
  119. token,
  120. request_id=request_id,
  121. )
  122. return self._enabled_tool_names(response)
  123. def list_tools(self, gateway_session_id, request_id=''):
  124. session = self._require_session(gateway_session_id)
  125. request_id = self.build_request_id(request_id)
  126. enabled = self._load_enabled_tool_names(
  127. session['mcp_token'],
  128. request_id,
  129. )
  130. return [
  131. tool.metadata()
  132. for name, tool in self._tools.items()
  133. if name in enabled
  134. ]
  135. def build_request_id(self, request_id=''):
  136. request_id = str(request_id or '').strip()
  137. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  138. def call_tool(
  139. self,
  140. gateway_session_id,
  141. name,
  142. arguments=None,
  143. request_id='',
  144. client_ip='',
  145. diagnostic_emitter=None,
  146. ):
  147. session = self._require_session(gateway_session_id, diagnostic_emitter)
  148. request_id = self.build_request_id(request_id)
  149. if name not in self._tools:
  150. if diagnostic_emitter is not None:
  151. diagnostic_emitter.emit(
  152. stage='backend_call',
  153. status='failed',
  154. event_code='TOOL_NOT_REGISTERED',
  155. context={'transport': 'http'},
  156. )
  157. raise KeyError('tool not registered: {0}'.format(name))
  158. try:
  159. enabled_tools = self._load_enabled_tool_names(
  160. session['mcp_token'],
  161. request_id,
  162. )
  163. except Exception:
  164. if diagnostic_emitter is not None:
  165. diagnostic_emitter.emit(
  166. stage='backend_call',
  167. status='failed',
  168. event_code='ENABLED_TOOL_LOOKUP_FAILED',
  169. tool_code=name,
  170. context={'transport': 'http'},
  171. )
  172. raise
  173. if name not in enabled_tools:
  174. if diagnostic_emitter is not None:
  175. diagnostic_emitter.emit(
  176. stage='backend_call',
  177. status='failed',
  178. event_code='TOOL_DISABLED',
  179. tool_code=name,
  180. context={'transport': 'http'},
  181. )
  182. raise RuntimeError('tool disabled: {0}'.format(name))
  183. tool = self._tools[name]
  184. if diagnostic_emitter is not None:
  185. diagnostic_emitter.set_defaults(tool_code=name)
  186. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  187. admin_id = session.get('admin_id')
  188. company_id = session.get('company_id')
  189. logger.info(
  190. 'MCP public tool call',
  191. extra={
  192. 'request_id': request_id,
  193. 'tool_code': name,
  194. 'session_hash': session_hash,
  195. 'admin_id': admin_id,
  196. 'company_id': company_id,
  197. },
  198. )
  199. try:
  200. started_at = time.monotonic()
  201. if diagnostic_emitter is not None:
  202. diagnostic_emitter.emit(
  203. stage='backend_call',
  204. status='started',
  205. event_code='BACKEND_CALL_STARTED',
  206. )
  207. result = self.api_client.call_tool(
  208. token=session['mcp_token'],
  209. tool_code=tool.name,
  210. route_path=tool.route_path,
  211. payload=arguments or {},
  212. request_id=request_id,
  213. client_ip=client_ip,
  214. )
  215. if hasattr(self.session_store, 'touch_session'):
  216. self.session_store.touch_session(gateway_session_id)
  217. logger.info(
  218. 'MCP public tool success',
  219. extra={
  220. 'request_id': request_id,
  221. 'tool_code': name,
  222. 'session_hash': session_hash,
  223. 'response_code': result.get('code'),
  224. },
  225. )
  226. if diagnostic_emitter is not None:
  227. diagnostic_emitter.emit(
  228. stage='backend_call',
  229. status='succeeded',
  230. event_code='BACKEND_CALL_COMPLETED',
  231. response_code=(
  232. result.get('code') if isinstance(result, dict) else None
  233. ),
  234. cost_ms=max(0, int((time.monotonic() - started_at) * 1000)),
  235. )
  236. return result
  237. except Exception as e:
  238. logger.error(
  239. 'MCP public tool failed',
  240. extra={
  241. 'request_id': request_id,
  242. 'tool_code': name,
  243. 'session_hash': session_hash,
  244. 'response_code': 'MCP_9001',
  245. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  246. 'exception_class': e.__class__.__name__,
  247. },
  248. )
  249. if diagnostic_emitter is not None:
  250. diagnostic_emitter.emit(
  251. stage='backend_call',
  252. status='failed',
  253. event_code='UNEXPECTED_EXCEPTION',
  254. response_code='MCP_9001',
  255. )
  256. raise