public_gateway.py 13 KB

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