public_gateway.py 4.7 KB

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