public_gateway.py 18 KB

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