public_gateway.py 11 KB

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