public_gateway.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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_receivable_cost_filter_options import (
  8. ListReceivableCostFilterOptionsTool,
  9. )
  10. from tools.list_outbound_filter_options import ListOutboundFilterOptionsTool
  11. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  12. from tools.export_out_of_province_port_data import (
  13. ExportOutOfProvincePortDataTool,
  14. )
  15. from tools.export_receivable_cost_list import ExportReceivableCostListTool
  16. from tools.list_pending_outbound_export_filter_options import (
  17. ListPendingOutboundExportFilterOptionsTool,
  18. )
  19. from tools.query_order import QueryOrderTool
  20. from tools.query_customs_declaration_files import (
  21. QueryCustomsDeclarationFilesTool,
  22. )
  23. from tools.query_order_exact import QueryOrderExactTool
  24. from tools.query_order_detail import QueryOrderDetailTool
  25. from tools.query_export_task import QueryExportTaskTool
  26. from tools.query_outbound_detail import QueryOutboundDetailTool
  27. from tools.query_outbound_list import QueryOutboundListTool
  28. from tools.query_track import QueryTrackTool
  29. from tools.query_customer_list import QueryCustomerListTool
  30. from tools.query_customer_payment_followup import QueryCustomerPaymentFollowupTool
  31. from tools.query_customer_unverified_bill_details import QueryCustomerUnverifiedBillDetailsTool
  32. from tools.query_customer_payment_records import QueryCustomerPaymentRecordsTool
  33. from tools.query_order_receivable_cost_details import (
  34. QueryOrderReceivableCostDetailsTool,
  35. )
  36. from tools.query_receivable_cost_list import QueryReceivableCostListTool
  37. from tools.query_payable_cost_list import QueryPayableCostListTool
  38. from tools.list_payable_cost_filter_options import ListPayableCostFilterOptionsTool
  39. from tools.export_payable_cost_list import ExportPayableCostListTool
  40. from tools.export_pallet_data import ExportPalletDataTool
  41. from tools.query_destination_trailer_list import QueryDestinationTrailerListTool
  42. from tools.list_destination_trailer_filter_options import (
  43. ListDestinationTrailerFilterOptionsTool,
  44. )
  45. from tools.query_order_abnormal_list import QueryOrderAbnormalListTool
  46. from tools.list_order_abnormal_filter_options import (
  47. ListOrderAbnormalFilterOptionsTool,
  48. )
  49. from tools.query_receive_volume_list import QueryReceiveVolumeListTool
  50. from tools.list_receive_volume_filter_options import (
  51. ListReceiveVolumeFilterOptionsTool,
  52. )
  53. from tools.query_container_timeliness_list import QueryContainerTimelinessListTool
  54. from tools.export_container_timeliness_report import (
  55. ExportContainerTimelinessReportTool,
  56. )
  57. from utils.security import hash_gateway_session_id
  58. logger = logging.getLogger(__name__)
  59. class PublicGatewayApp:
  60. def __init__(self, session_store, api_client, auth_client=None):
  61. self.session_store = session_store
  62. self.api_client = api_client
  63. self._tools = {
  64. 'query_order': QueryOrderTool(api_client=None),
  65. 'query_track': QueryTrackTool(api_client=None),
  66. 'query_order_exact': QueryOrderExactTool(api_client=None),
  67. 'query_order_detail': QueryOrderDetailTool(api_client=None),
  68. 'query_customs_declaration_files':
  69. QueryCustomsDeclarationFilesTool(api_client=None),
  70. 'query_outbound_list': QueryOutboundListTool(api_client=None),
  71. 'query_outbound_detail': QueryOutboundDetailTool(api_client=None),
  72. 'query_customer_list': QueryCustomerListTool(api_client=None),
  73. 'query_customer_payment_followup': QueryCustomerPaymentFollowupTool(
  74. api_client=None
  75. ),
  76. 'query_customer_unverified_bill_details':
  77. QueryCustomerUnverifiedBillDetailsTool(api_client=None),
  78. 'query_customer_payment_records': QueryCustomerPaymentRecordsTool(
  79. api_client=None
  80. ),
  81. 'query_order_receivable_cost_details':
  82. QueryOrderReceivableCostDetailsTool(api_client=None),
  83. 'query_receivable_cost_list':
  84. QueryReceivableCostListTool(api_client=None),
  85. 'query_payable_cost_list':
  86. QueryPayableCostListTool(api_client=None),
  87. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  88. api_client=None
  89. ),
  90. 'list_order_filter_options': ListOrderFilterOptionsTool(
  91. api_client=None
  92. ),
  93. 'list_customer_filter_options': ListCustomerFilterOptionsTool(
  94. api_client=None
  95. ),
  96. 'list_receivable_cost_filter_options':
  97. ListReceivableCostFilterOptionsTool(api_client=None),
  98. 'list_payable_cost_filter_options':
  99. ListPayableCostFilterOptionsTool(api_client=None),
  100. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  101. api_client=None
  102. ),
  103. 'export_out_of_province_port_data':
  104. ExportOutOfProvincePortDataTool(api_client=None),
  105. 'export_receivable_cost_list': ExportReceivableCostListTool(
  106. api_client=None
  107. ),
  108. 'export_payable_cost_list': ExportPayableCostListTool(
  109. api_client=None
  110. ),
  111. 'export_pallet_data': ExportPalletDataTool(
  112. api_client=None
  113. ),
  114. 'query_export_task': QueryExportTaskTool(api_client=None),
  115. 'list_pending_outbound_export_filter_options':
  116. ListPendingOutboundExportFilterOptionsTool(api_client=None),
  117. 'query_destination_trailer_list': QueryDestinationTrailerListTool(
  118. api_client=None
  119. ),
  120. 'list_destination_trailer_filter_options':
  121. ListDestinationTrailerFilterOptionsTool(api_client=None),
  122. 'query_order_abnormal_list': QueryOrderAbnormalListTool(
  123. api_client=None
  124. ),
  125. 'list_order_abnormal_filter_options':
  126. ListOrderAbnormalFilterOptionsTool(api_client=None),
  127. 'query_receive_volume_list': QueryReceiveVolumeListTool(
  128. api_client=None
  129. ),
  130. 'list_receive_volume_filter_options':
  131. ListReceiveVolumeFilterOptionsTool(api_client=None),
  132. 'query_container_timeliness_list': QueryContainerTimelinessListTool(
  133. api_client=None
  134. ),
  135. 'export_container_timeliness_report':
  136. ExportContainerTimelinessReportTool(api_client=None),
  137. }
  138. def registered_tool_names(self):
  139. return tuple(self._tools.keys())
  140. def _require_session(self, gateway_session_id, diagnostic_emitter=None):
  141. session = self.session_store.get(gateway_session_id)
  142. if not session or not session.get('mcp_token'):
  143. if diagnostic_emitter is not None:
  144. diagnostic_emitter.emit(
  145. stage='gateway_session',
  146. status='failed',
  147. event_code='GATEWAY_SESSION_NOT_FOUND',
  148. session_credential=gateway_session_id,
  149. context={'transport': 'http'},
  150. )
  151. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  152. if diagnostic_emitter is not None:
  153. diagnostic_emitter.set_defaults(
  154. session_credential=gateway_session_id,
  155. admin_id=session.get('admin_id'),
  156. company_id=session.get('company_id'),
  157. context={'transport': 'http'},
  158. )
  159. diagnostic_emitter.emit(
  160. stage='gateway_session',
  161. status='succeeded',
  162. event_code='GATEWAY_SESSION_RESOLVED',
  163. )
  164. return session
  165. def _enabled_tool_names(self, response):
  166. if not isinstance(response, dict):
  167. raise RuntimeError('invalid enabled tool response')
  168. if response.get('code') != 'MCP_0000':
  169. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  170. data = response.get('data')
  171. codes = data.get('tool_codes') if isinstance(data, dict) else None
  172. if not isinstance(codes, list):
  173. raise RuntimeError('invalid enabled tool response')
  174. return {
  175. code.strip().lower()
  176. for code in codes
  177. if isinstance(code, str) and code.strip()
  178. }
  179. def _load_enabled_tool_names(self, token, request_id=''):
  180. response = self.api_client.list_enabled_tools(
  181. token,
  182. request_id=request_id,
  183. )
  184. return self._enabled_tool_names(response)
  185. def list_tools(self, gateway_session_id, request_id=''):
  186. session = self._require_session(gateway_session_id)
  187. if hasattr(self.session_store, 'touch_session'):
  188. self.session_store.touch_session(gateway_session_id)
  189. request_id = self.build_request_id(request_id)
  190. enabled = self._load_enabled_tool_names(
  191. session['mcp_token'],
  192. request_id,
  193. )
  194. return [
  195. tool.metadata()
  196. for name, tool in self._tools.items()
  197. if name in enabled
  198. ]
  199. def build_request_id(self, request_id=''):
  200. request_id = str(request_id or '').strip()
  201. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  202. def call_tool(
  203. self,
  204. gateway_session_id,
  205. name,
  206. arguments=None,
  207. request_id='',
  208. client_ip='',
  209. diagnostic_emitter=None,
  210. ):
  211. session = self._require_session(gateway_session_id, diagnostic_emitter)
  212. request_id = self.build_request_id(request_id)
  213. if name not in self._tools:
  214. if diagnostic_emitter is not None:
  215. diagnostic_emitter.emit(
  216. stage='backend_call',
  217. status='failed',
  218. event_code='TOOL_NOT_REGISTERED',
  219. context={'transport': 'http'},
  220. )
  221. raise KeyError('tool not registered: {0}'.format(name))
  222. try:
  223. enabled_tools = self._load_enabled_tool_names(
  224. session['mcp_token'],
  225. request_id,
  226. )
  227. except Exception:
  228. if diagnostic_emitter is not None:
  229. diagnostic_emitter.emit(
  230. stage='backend_call',
  231. status='failed',
  232. event_code='ENABLED_TOOL_LOOKUP_FAILED',
  233. tool_code=name,
  234. context={'transport': 'http'},
  235. )
  236. raise
  237. if name not in enabled_tools:
  238. if diagnostic_emitter is not None:
  239. diagnostic_emitter.emit(
  240. stage='backend_call',
  241. status='failed',
  242. event_code='TOOL_DISABLED',
  243. tool_code=name,
  244. context={'transport': 'http'},
  245. )
  246. raise RuntimeError('tool disabled: {0}'.format(name))
  247. tool = self._tools[name]
  248. if diagnostic_emitter is not None:
  249. diagnostic_emitter.set_defaults(tool_code=name)
  250. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  251. admin_id = session.get('admin_id')
  252. company_id = session.get('company_id')
  253. logger.info(
  254. 'MCP public tool call',
  255. extra={
  256. 'request_id': request_id,
  257. 'tool_code': name,
  258. 'session_hash': session_hash,
  259. 'admin_id': admin_id,
  260. 'company_id': company_id,
  261. },
  262. )
  263. try:
  264. started_at = time.monotonic()
  265. if diagnostic_emitter is not None:
  266. diagnostic_emitter.emit(
  267. stage='backend_call',
  268. status='started',
  269. event_code='BACKEND_CALL_STARTED',
  270. )
  271. result = self.api_client.call_tool(
  272. token=session['mcp_token'],
  273. tool_code=tool.name,
  274. route_path=tool.route_path,
  275. payload=arguments or {},
  276. request_id=request_id,
  277. client_ip=client_ip,
  278. )
  279. if hasattr(self.session_store, 'touch_session'):
  280. self.session_store.touch_session(gateway_session_id)
  281. logger.info(
  282. 'MCP public tool success',
  283. extra={
  284. 'request_id': request_id,
  285. 'tool_code': name,
  286. 'session_hash': session_hash,
  287. 'response_code': result.get('code'),
  288. },
  289. )
  290. if diagnostic_emitter is not None:
  291. diagnostic_emitter.emit(
  292. stage='backend_call',
  293. status='succeeded',
  294. event_code='BACKEND_CALL_COMPLETED',
  295. response_code=(
  296. result.get('code') if isinstance(result, dict) else None
  297. ),
  298. cost_ms=max(0, int((time.monotonic() - started_at) * 1000)),
  299. )
  300. return result
  301. except Exception as e:
  302. logger.error(
  303. 'MCP public tool failed',
  304. extra={
  305. 'request_id': request_id,
  306. 'tool_code': name,
  307. 'session_hash': session_hash,
  308. 'response_code': 'MCP_9001',
  309. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  310. 'exception_class': e.__class__.__name__,
  311. },
  312. )
  313. if diagnostic_emitter is not None:
  314. diagnostic_emitter.emit(
  315. stage='backend_call',
  316. status='failed',
  317. event_code='UNEXPECTED_EXCEPTION',
  318. response_code='MCP_9001',
  319. )
  320. raise