public_gateway.py 13 KB

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