public_gateway.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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.arrange_destination_trailer import ArrangeDestinationTrailerTool
  43. from tools.list_destination_trailer_filter_options import (
  44. ListDestinationTrailerFilterOptionsTool,
  45. )
  46. from tools.query_order_abnormal_list import QueryOrderAbnormalListTool
  47. from tools.list_order_abnormal_filter_options import (
  48. ListOrderAbnormalFilterOptionsTool,
  49. )
  50. from tools.query_goods_info import QueryGoodsInfoTool
  51. from tools.trial_goods_tax import TrialGoodsTaxTool
  52. from tools.query_receive_volume_list import QueryReceiveVolumeListTool
  53. from tools.list_receive_volume_filter_options import (
  54. ListReceiveVolumeFilterOptionsTool,
  55. )
  56. from tools.query_container_timeliness_list import QueryContainerTimelinessListTool
  57. from tools.export_container_timeliness_report import (
  58. ExportContainerTimelinessReportTool,
  59. )
  60. from tools.query_headhaul_document_list import QueryHeadhaulDocumentListTool
  61. from tools.list_headhaul_document_filter_options import (
  62. ListHeadhaulDocumentFilterOptionsTool,
  63. )
  64. from tools.prepare_headhaul_document_upload import (
  65. PrepareHeadhaulDocumentUploadTool,
  66. )
  67. from tools.save_headhaul_document import SaveHeadhaulDocumentTool
  68. from tools.delete_headhaul_document import DeleteHeadhaulDocumentTool
  69. from tools.list_inbound_receipt_templates import ListInboundReceiptTemplatesTool
  70. from tools.export_inbound_receipt import ExportInboundReceiptTool
  71. from tools.query_freightower_track import QueryFreightowerTrackTool
  72. from tools.query_remote_address_list import QueryRemoteAddressListTool
  73. from tools.maintain_remote_address import MaintainRemoteAddressTool
  74. from tools.save_remote_address import SaveRemoteAddressTool
  75. from tools.query_fuel_rate_list import QueryFuelRateListTool
  76. from tools.save_fuel_rate import SaveFuelRateTool
  77. from tools.enable_fuel_rate import EnableFuelRateTool
  78. from utils.security import hash_gateway_session_id
  79. logger = logging.getLogger(__name__)
  80. class PublicGatewayApp:
  81. def __init__(self, session_store, api_client, auth_client=None, base_api_client=None):
  82. self.session_store = session_store
  83. self.api_client = api_client
  84. self.base_api_client = base_api_client
  85. self._tools = {
  86. 'query_order': QueryOrderTool(api_client=None),
  87. 'query_track': QueryTrackTool(api_client=None),
  88. 'query_order_exact': QueryOrderExactTool(api_client=None),
  89. 'query_order_detail': QueryOrderDetailTool(api_client=None),
  90. 'query_customs_declaration_files':
  91. QueryCustomsDeclarationFilesTool(api_client=None),
  92. 'query_outbound_list': QueryOutboundListTool(api_client=None),
  93. 'query_outbound_detail': QueryOutboundDetailTool(api_client=None),
  94. 'query_customer_list': QueryCustomerListTool(api_client=None),
  95. 'query_customer_payment_followup': QueryCustomerPaymentFollowupTool(
  96. api_client=None
  97. ),
  98. 'query_customer_unverified_bill_details':
  99. QueryCustomerUnverifiedBillDetailsTool(api_client=None),
  100. 'query_customer_payment_records': QueryCustomerPaymentRecordsTool(
  101. api_client=None
  102. ),
  103. 'query_order_receivable_cost_details':
  104. QueryOrderReceivableCostDetailsTool(api_client=None),
  105. 'query_receivable_cost_list':
  106. QueryReceivableCostListTool(api_client=None),
  107. 'query_payable_cost_list':
  108. QueryPayableCostListTool(api_client=None),
  109. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  110. api_client=None
  111. ),
  112. 'list_order_filter_options': ListOrderFilterOptionsTool(
  113. api_client=None
  114. ),
  115. 'list_customer_filter_options': ListCustomerFilterOptionsTool(
  116. api_client=None
  117. ),
  118. 'list_receivable_cost_filter_options':
  119. ListReceivableCostFilterOptionsTool(api_client=None),
  120. 'list_payable_cost_filter_options':
  121. ListPayableCostFilterOptionsTool(api_client=None),
  122. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  123. api_client=None
  124. ),
  125. 'export_out_of_province_port_data':
  126. ExportOutOfProvincePortDataTool(api_client=None),
  127. 'export_receivable_cost_list': ExportReceivableCostListTool(
  128. api_client=None
  129. ),
  130. 'export_payable_cost_list': ExportPayableCostListTool(
  131. api_client=None
  132. ),
  133. 'export_pallet_data': ExportPalletDataTool(
  134. api_client=None
  135. ),
  136. 'query_export_task': QueryExportTaskTool(api_client=None),
  137. 'list_pending_outbound_export_filter_options':
  138. ListPendingOutboundExportFilterOptionsTool(api_client=None),
  139. 'query_destination_trailer_list': QueryDestinationTrailerListTool(
  140. api_client=None
  141. ),
  142. 'arrange_destination_trailer': ArrangeDestinationTrailerTool(
  143. api_client=None
  144. ),
  145. 'list_destination_trailer_filter_options':
  146. ListDestinationTrailerFilterOptionsTool(api_client=None),
  147. 'query_order_abnormal_list': QueryOrderAbnormalListTool(
  148. api_client=None
  149. ),
  150. 'list_order_abnormal_filter_options':
  151. ListOrderAbnormalFilterOptionsTool(api_client=None),
  152. 'query_receive_volume_list': QueryReceiveVolumeListTool(
  153. api_client=None
  154. ),
  155. 'query_goods_info': QueryGoodsInfoTool(api_client=None),
  156. 'trial_goods_tax': TrialGoodsTaxTool(api_client=None),
  157. 'list_receive_volume_filter_options':
  158. ListReceiveVolumeFilterOptionsTool(api_client=None),
  159. 'query_container_timeliness_list': QueryContainerTimelinessListTool(
  160. api_client=None
  161. ),
  162. 'export_container_timeliness_report':
  163. ExportContainerTimelinessReportTool(api_client=None),
  164. 'query_headhaul_document_list': QueryHeadhaulDocumentListTool(
  165. api_client=None
  166. ),
  167. 'list_headhaul_document_filter_options':
  168. ListHeadhaulDocumentFilterOptionsTool(api_client=None),
  169. 'prepare_headhaul_document_upload':
  170. PrepareHeadhaulDocumentUploadTool(api_client=None),
  171. 'save_headhaul_document': SaveHeadhaulDocumentTool(
  172. api_client=None
  173. ),
  174. 'delete_headhaul_document': DeleteHeadhaulDocumentTool(
  175. api_client=None
  176. ),
  177. 'list_inbound_receipt_templates': ListInboundReceiptTemplatesTool(
  178. api_client=None
  179. ),
  180. 'export_inbound_receipt': ExportInboundReceiptTool(
  181. api_client=None
  182. ),
  183. 'query_freightower_track': QueryFreightowerTrackTool(api_client=None),
  184. 'query_remote_address_list': QueryRemoteAddressListTool(api_client=None),
  185. 'maintain_remote_address': MaintainRemoteAddressTool(api_client=None),
  186. 'save_remote_address': SaveRemoteAddressTool(api_client=None),
  187. 'query_fuel_rate_list': QueryFuelRateListTool(api_client=None),
  188. 'save_fuel_rate': SaveFuelRateTool(api_client=None),
  189. 'enable_fuel_rate': EnableFuelRateTool(api_client=None),
  190. }
  191. from services.headhaul_document_app import HeadhaulSlotMemory
  192. self._headhaul_slots = HeadhaulSlotMemory()
  193. def registered_tool_names(self):
  194. return tuple(self._tools.keys())
  195. def _require_session(self, gateway_session_id, diagnostic_emitter=None):
  196. session = self.session_store.get(gateway_session_id)
  197. if not session or not session.get('mcp_token'):
  198. if diagnostic_emitter is not None:
  199. diagnostic_emitter.emit(
  200. stage='gateway_session',
  201. status='failed',
  202. event_code='GATEWAY_SESSION_NOT_FOUND',
  203. session_credential=gateway_session_id,
  204. context={'transport': 'http'},
  205. )
  206. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  207. if diagnostic_emitter is not None:
  208. diagnostic_emitter.set_defaults(
  209. session_credential=gateway_session_id,
  210. admin_id=session.get('admin_id'),
  211. company_id=session.get('company_id'),
  212. context={'transport': 'http'},
  213. )
  214. diagnostic_emitter.emit(
  215. stage='gateway_session',
  216. status='succeeded',
  217. event_code='GATEWAY_SESSION_RESOLVED',
  218. )
  219. return session
  220. def _tool_client(self, tool):
  221. if getattr(tool, 'backend', '') == 'base' and self.base_api_client is not None:
  222. return self.base_api_client
  223. return self.api_client
  224. def _enabled_tool_names(self, response):
  225. if not isinstance(response, dict):
  226. raise RuntimeError('invalid enabled tool response')
  227. if response.get('code') != 'MCP_0000':
  228. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  229. data = response.get('data')
  230. codes = data.get('tool_codes') if isinstance(data, dict) else None
  231. if not isinstance(codes, list):
  232. raise RuntimeError('invalid enabled tool response')
  233. return {
  234. code.strip().lower()
  235. for code in codes
  236. if isinstance(code, str) and code.strip()
  237. }
  238. def _load_enabled_tool_names(self, token, request_id=''):
  239. response = self.api_client.list_enabled_tools(
  240. token,
  241. request_id=request_id,
  242. )
  243. return self._enabled_tool_names(response)
  244. def list_tools(self, gateway_session_id, request_id=''):
  245. session = self._require_session(gateway_session_id)
  246. if hasattr(self.session_store, 'touch_session'):
  247. self.session_store.touch_session(gateway_session_id)
  248. request_id = self.build_request_id(request_id)
  249. enabled = self._load_enabled_tool_names(
  250. session['mcp_token'],
  251. request_id,
  252. )
  253. return [
  254. tool.metadata()
  255. for name, tool in self._tools.items()
  256. if name in enabled
  257. ]
  258. def list_resources(self):
  259. return []
  260. def remember_headhaul_slot(self, gateway_session_id, token):
  261. self._headhaul_slots.remember(gateway_session_id, token)
  262. def session_for_headhaul_token(self, token):
  263. return self._headhaul_slots.session_for_token(token)
  264. def read_resource(self, uri, gateway_session_id=''):
  265. return None
  266. def upload_headhaul_document(
  267. self,
  268. gateway_session_id,
  269. upload_token,
  270. filename,
  271. file_bytes,
  272. content_type='',
  273. request_id='',
  274. client_ip='',
  275. ):
  276. session = self._require_session(gateway_session_id)
  277. request_id = self.build_request_id(request_id)
  278. enabled = self._load_enabled_tool_names(
  279. session['mcp_token'],
  280. request_id,
  281. )
  282. if 'prepare_headhaul_document_upload' not in enabled:
  283. raise RuntimeError('tool disabled: prepare_headhaul_document_upload')
  284. if not hasattr(self.api_client, 'upload_headhaul_document'):
  285. raise RuntimeError('upload client unavailable')
  286. return self.api_client.upload_headhaul_document(
  287. token=session['mcp_token'],
  288. upload_token=upload_token,
  289. filename=filename,
  290. file_bytes=file_bytes,
  291. content_type=content_type,
  292. request_id=request_id,
  293. client_ip=client_ip,
  294. )
  295. def build_request_id(self, request_id=''):
  296. request_id = str(request_id or '').strip()
  297. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  298. def call_tool(
  299. self,
  300. gateway_session_id,
  301. name,
  302. arguments=None,
  303. request_id='',
  304. client_ip='',
  305. diagnostic_emitter=None,
  306. ):
  307. session = self._require_session(gateway_session_id, diagnostic_emitter)
  308. request_id = self.build_request_id(request_id)
  309. if name not in self._tools:
  310. if diagnostic_emitter is not None:
  311. diagnostic_emitter.emit(
  312. stage='backend_call',
  313. status='failed',
  314. event_code='TOOL_NOT_REGISTERED',
  315. context={'transport': 'http'},
  316. )
  317. raise KeyError('tool not registered: {0}'.format(name))
  318. try:
  319. enabled_tools = self._load_enabled_tool_names(
  320. session['mcp_token'],
  321. request_id,
  322. )
  323. except Exception:
  324. if diagnostic_emitter is not None:
  325. diagnostic_emitter.emit(
  326. stage='backend_call',
  327. status='failed',
  328. event_code='ENABLED_TOOL_LOOKUP_FAILED',
  329. tool_code=name,
  330. context={'transport': 'http'},
  331. )
  332. raise
  333. if name not in enabled_tools:
  334. if diagnostic_emitter is not None:
  335. diagnostic_emitter.emit(
  336. stage='backend_call',
  337. status='failed',
  338. event_code='TOOL_DISABLED',
  339. tool_code=name,
  340. context={'transport': 'http'},
  341. )
  342. raise RuntimeError('tool disabled: {0}'.format(name))
  343. tool = self._tools[name]
  344. if diagnostic_emitter is not None:
  345. diagnostic_emitter.set_defaults(tool_code=name)
  346. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  347. admin_id = session.get('admin_id')
  348. company_id = session.get('company_id')
  349. logger.info(
  350. 'MCP public tool call',
  351. extra={
  352. 'request_id': request_id,
  353. 'tool_code': name,
  354. 'session_hash': session_hash,
  355. 'admin_id': admin_id,
  356. 'company_id': company_id,
  357. },
  358. )
  359. try:
  360. started_at = time.monotonic()
  361. if diagnostic_emitter is not None:
  362. diagnostic_emitter.emit(
  363. stage='backend_call',
  364. status='started',
  365. event_code='BACKEND_CALL_STARTED',
  366. )
  367. result = self._tool_client(tool).call_tool(
  368. token=session['mcp_token'],
  369. tool_code=tool.name,
  370. route_path=tool.route_path,
  371. payload=arguments or {},
  372. request_id=request_id,
  373. client_ip=client_ip,
  374. )
  375. if hasattr(self.session_store, 'touch_session'):
  376. self.session_store.touch_session(gateway_session_id)
  377. if name == 'prepare_headhaul_document_upload' and isinstance(result, dict):
  378. data = result.get('data')
  379. token = ''
  380. if isinstance(data, dict):
  381. token = str(data.get('upload_token') or '').strip()
  382. if token:
  383. self.remember_headhaul_slot(gateway_session_id, token)
  384. logger.info(
  385. 'MCP public tool success',
  386. extra={
  387. 'request_id': request_id,
  388. 'tool_code': name,
  389. 'session_hash': session_hash,
  390. 'response_code': result.get('code'),
  391. },
  392. )
  393. if diagnostic_emitter is not None:
  394. diagnostic_emitter.emit(
  395. stage='backend_call',
  396. status='succeeded',
  397. event_code='BACKEND_CALL_COMPLETED',
  398. response_code=(
  399. result.get('code') if isinstance(result, dict) else None
  400. ),
  401. cost_ms=max(0, int((time.monotonic() - started_at) * 1000)),
  402. )
  403. return result
  404. except Exception as e:
  405. logger.error(
  406. 'MCP public tool failed',
  407. extra={
  408. 'request_id': request_id,
  409. 'tool_code': name,
  410. 'session_hash': session_hash,
  411. 'response_code': 'MCP_9001',
  412. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  413. 'exception_class': e.__class__.__name__,
  414. },
  415. )
  416. if diagnostic_emitter is not None:
  417. diagnostic_emitter.emit(
  418. stage='backend_call',
  419. status='failed',
  420. event_code='UNEXPECTED_EXCEPTION',
  421. response_code='MCP_9001',
  422. )
  423. raise