public_gateway.py 12 KB

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