public_gateway.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. request_id = self.build_request_id(request_id)
  148. enabled = self._load_enabled_tool_names(
  149. session['mcp_token'],
  150. request_id,
  151. )
  152. return [
  153. tool.metadata()
  154. for name, tool in self._tools.items()
  155. if name in enabled
  156. ]
  157. def build_request_id(self, request_id=''):
  158. request_id = str(request_id or '').strip()
  159. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  160. def call_tool(
  161. self,
  162. gateway_session_id,
  163. name,
  164. arguments=None,
  165. request_id='',
  166. client_ip='',
  167. diagnostic_emitter=None,
  168. ):
  169. session = self._require_session(gateway_session_id, diagnostic_emitter)
  170. request_id = self.build_request_id(request_id)
  171. if name not in self._tools:
  172. if diagnostic_emitter is not None:
  173. diagnostic_emitter.emit(
  174. stage='backend_call',
  175. status='failed',
  176. event_code='TOOL_NOT_REGISTERED',
  177. context={'transport': 'http'},
  178. )
  179. raise KeyError('tool not registered: {0}'.format(name))
  180. try:
  181. enabled_tools = self._load_enabled_tool_names(
  182. session['mcp_token'],
  183. request_id,
  184. )
  185. except Exception:
  186. if diagnostic_emitter is not None:
  187. diagnostic_emitter.emit(
  188. stage='backend_call',
  189. status='failed',
  190. event_code='ENABLED_TOOL_LOOKUP_FAILED',
  191. tool_code=name,
  192. context={'transport': 'http'},
  193. )
  194. raise
  195. if name not in enabled_tools:
  196. if diagnostic_emitter is not None:
  197. diagnostic_emitter.emit(
  198. stage='backend_call',
  199. status='failed',
  200. event_code='TOOL_DISABLED',
  201. tool_code=name,
  202. context={'transport': 'http'},
  203. )
  204. raise RuntimeError('tool disabled: {0}'.format(name))
  205. tool = self._tools[name]
  206. if diagnostic_emitter is not None:
  207. diagnostic_emitter.set_defaults(tool_code=name)
  208. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  209. admin_id = session.get('admin_id')
  210. company_id = session.get('company_id')
  211. logger.info(
  212. 'MCP public tool call',
  213. extra={
  214. 'request_id': request_id,
  215. 'tool_code': name,
  216. 'session_hash': session_hash,
  217. 'admin_id': admin_id,
  218. 'company_id': company_id,
  219. },
  220. )
  221. try:
  222. started_at = time.monotonic()
  223. if diagnostic_emitter is not None:
  224. diagnostic_emitter.emit(
  225. stage='backend_call',
  226. status='started',
  227. event_code='BACKEND_CALL_STARTED',
  228. )
  229. result = self.api_client.call_tool(
  230. token=session['mcp_token'],
  231. tool_code=tool.name,
  232. route_path=tool.route_path,
  233. payload=arguments or {},
  234. request_id=request_id,
  235. client_ip=client_ip,
  236. )
  237. if hasattr(self.session_store, 'touch_session'):
  238. self.session_store.touch_session(gateway_session_id)
  239. logger.info(
  240. 'MCP public tool success',
  241. extra={
  242. 'request_id': request_id,
  243. 'tool_code': name,
  244. 'session_hash': session_hash,
  245. 'response_code': result.get('code'),
  246. },
  247. )
  248. if diagnostic_emitter is not None:
  249. diagnostic_emitter.emit(
  250. stage='backend_call',
  251. status='succeeded',
  252. event_code='BACKEND_CALL_COMPLETED',
  253. response_code=(
  254. result.get('code') if isinstance(result, dict) else None
  255. ),
  256. cost_ms=max(0, int((time.monotonic() - started_at) * 1000)),
  257. )
  258. return result
  259. except Exception as e:
  260. logger.error(
  261. 'MCP public tool failed',
  262. extra={
  263. 'request_id': request_id,
  264. 'tool_code': name,
  265. 'session_hash': session_hash,
  266. 'response_code': 'MCP_9001',
  267. 'diagnostic_reason': 'UNEXPECTED_EXCEPTION',
  268. 'exception_class': e.__class__.__name__,
  269. },
  270. )
  271. if diagnostic_emitter is not None:
  272. diagnostic_emitter.emit(
  273. stage='backend_call',
  274. status='failed',
  275. event_code='UNEXPECTED_EXCEPTION',
  276. response_code='MCP_9001',
  277. )
  278. raise