public_gateway.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import logging
  2. import uuid
  3. from constants import DEVICE_INVALID_MESSAGE
  4. from tools.list_order_filter_options import ListOrderFilterOptionsTool
  5. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  6. from tools.export_out_of_province_port_data import (
  7. ExportOutOfProvincePortDataTool,
  8. )
  9. from tools.list_pending_outbound_export_filter_options import (
  10. ListPendingOutboundExportFilterOptionsTool,
  11. )
  12. from tools.query_order import QueryOrderTool
  13. from tools.query_customs_declaration_files import (
  14. QueryCustomsDeclarationFilesTool,
  15. )
  16. from tools.query_order_exact import QueryOrderExactTool
  17. from tools.query_track import QueryTrackTool
  18. from utils.security import hash_gateway_session_id
  19. logger = logging.getLogger(__name__)
  20. class PublicGatewayApp:
  21. def __init__(self, session_store, api_client, auth_client=None):
  22. self.session_store = session_store
  23. self.api_client = api_client
  24. self._tools = {
  25. 'query_order': QueryOrderTool(api_client=None),
  26. 'query_track': QueryTrackTool(api_client=None),
  27. 'query_order_exact': QueryOrderExactTool(api_client=None),
  28. 'query_customs_declaration_files':
  29. QueryCustomsDeclarationFilesTool(api_client=None),
  30. 'list_order_filter_options': ListOrderFilterOptionsTool(
  31. api_client=None
  32. ),
  33. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  34. api_client=None
  35. ),
  36. 'export_out_of_province_port_data':
  37. ExportOutOfProvincePortDataTool(api_client=None),
  38. 'list_pending_outbound_export_filter_options':
  39. ListPendingOutboundExportFilterOptionsTool(api_client=None),
  40. }
  41. def registered_tool_names(self):
  42. return tuple(self._tools.keys())
  43. def _require_session(self, gateway_session_id):
  44. session = self.session_store.get(gateway_session_id)
  45. if not session or not session.get('mcp_token'):
  46. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  47. return session
  48. def _enabled_tool_names(self, response):
  49. if not isinstance(response, dict):
  50. raise RuntimeError('invalid enabled tool response')
  51. if response.get('code') != 'MCP_0000':
  52. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  53. data = response.get('data')
  54. codes = data.get('tool_codes') if isinstance(data, dict) else None
  55. if not isinstance(codes, list):
  56. raise RuntimeError('invalid enabled tool response')
  57. return {
  58. code.strip().lower()
  59. for code in codes
  60. if isinstance(code, str) and code.strip()
  61. }
  62. def _load_enabled_tool_names(self, token):
  63. response = self.api_client.list_enabled_tools(token)
  64. return self._enabled_tool_names(response)
  65. def list_tools(self, gateway_session_id):
  66. session = self._require_session(gateway_session_id)
  67. enabled = self._load_enabled_tool_names(session['mcp_token'])
  68. return [
  69. tool.metadata()
  70. for name, tool in self._tools.items()
  71. if name in enabled
  72. ]
  73. def build_request_id(self, request_id=''):
  74. request_id = str(request_id or '').strip()
  75. return request_id or 'rq_{0}'.format(uuid.uuid4().hex[:16])
  76. def call_tool(self, gateway_session_id, name, arguments=None, request_id='', client_ip=''):
  77. if name not in self._tools:
  78. raise KeyError('tool not registered: {0}'.format(name))
  79. session = self._require_session(gateway_session_id)
  80. if name not in self._load_enabled_tool_names(session['mcp_token']):
  81. raise RuntimeError('tool disabled: {0}'.format(name))
  82. tool = self._tools[name]
  83. request_id = self.build_request_id(request_id)
  84. session_hash = hash_gateway_session_id(gateway_session_id)[:12]
  85. admin_id = session.get('admin_id')
  86. company_id = session.get('company_id')
  87. logger.info(f"[AUDIT] tool_call: session_hash={session_hash}, admin_id={admin_id}, company_id={company_id}, tool={name}, request_id={request_id}")
  88. try:
  89. result = self.api_client.call_tool(
  90. token=session['mcp_token'],
  91. tool_code=tool.name,
  92. route_path=tool.route_path,
  93. payload=arguments or {},
  94. request_id=request_id,
  95. client_ip=client_ip,
  96. )
  97. if hasattr(self.session_store, 'touch_session'):
  98. self.session_store.touch_session(gateway_session_id)
  99. logger.info(f"[AUDIT] tool_success: session_hash={session_hash}, tool={name}, request_id={request_id}, code={result.get('code')}")
  100. return result
  101. except Exception as e:
  102. logger.error(f"[AUDIT] tool_error: session_hash={session_hash}, tool={name}, request_id={request_id}, error={str(e)}")
  103. raise