public_gateway.py 12 KB

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