public_gateway.py 14 KB

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