app.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import argparse
  2. import json
  3. import sys
  4. import uuid
  5. from config import GatewayConfig
  6. from constants import DEVICE_INVALID_MESSAGE
  7. from mcp_protocol import McpProtocolHandler
  8. from public_gateway import PublicGatewayApp
  9. from public_server import serve_public
  10. from services.api_client import ApiClient
  11. from services.auth_client import AuthClient
  12. from services.gateway_session_store import GatewaySessionStore
  13. from services.scoped_api_client import ScopedApiClient
  14. from services.token_store import FileTokenStore, RedisSocketClient, RedisTokenStore
  15. from tools.list_order_filter_options import ListOrderFilterOptionsTool
  16. from tools.list_outbound_filter_options import ListOutboundFilterOptionsTool
  17. from tools.export_pending_outbound_orders import ExportPendingOutboundOrdersTool
  18. from tools.export_out_of_province_port_data import (
  19. ExportOutOfProvincePortDataTool,
  20. )
  21. from tools.list_pending_outbound_export_filter_options import (
  22. ListPendingOutboundExportFilterOptionsTool,
  23. )
  24. from tools.query_order import QueryOrderTool
  25. from tools.query_customs_declaration_files import (
  26. QueryCustomsDeclarationFilesTool,
  27. )
  28. from tools.query_order_exact import QueryOrderExactTool
  29. from tools.query_outbound_detail import QueryOutboundDetailTool
  30. from tools.query_outbound_list import QueryOutboundListTool
  31. from tools.query_track import QueryTrackTool
  32. def parse_int_list(value):
  33. if not value:
  34. return []
  35. return [int(item.strip()) for item in value.split(',') if item.strip()]
  36. def parse_string_list(value):
  37. result = []
  38. for item in (value or '').split(','):
  39. item = item.strip()
  40. if item and item not in result:
  41. result.append(item)
  42. return result
  43. class GatewayApp:
  44. def __init__(self, auth_client=None, api_client=None, token_store=None):
  45. self.auth_client = auth_client
  46. self.api_client = api_client
  47. self.token_store = token_store
  48. self._tools = {
  49. 'query_order': QueryOrderTool(api_client=api_client),
  50. 'query_track': QueryTrackTool(api_client=api_client),
  51. 'query_order_exact': QueryOrderExactTool(api_client=api_client),
  52. 'query_customs_declaration_files':
  53. QueryCustomsDeclarationFilesTool(api_client=api_client),
  54. 'query_outbound_list': QueryOutboundListTool(api_client=api_client),
  55. 'query_outbound_detail': QueryOutboundDetailTool(api_client=api_client),
  56. 'list_outbound_filter_options': ListOutboundFilterOptionsTool(
  57. api_client=api_client
  58. ),
  59. 'list_order_filter_options': ListOrderFilterOptionsTool(
  60. api_client=api_client
  61. ),
  62. 'export_pending_outbound_orders': ExportPendingOutboundOrdersTool(
  63. api_client=api_client
  64. ),
  65. 'export_out_of_province_port_data':
  66. ExportOutOfProvincePortDataTool(api_client=api_client),
  67. 'list_pending_outbound_export_filter_options':
  68. ListPendingOutboundExportFilterOptionsTool(api_client=api_client),
  69. }
  70. @classmethod
  71. def from_config(cls, config, redis_client=None):
  72. if config.token_store_type == 'redis':
  73. redis = redis_client or RedisSocketClient(
  74. host=config.redis_host,
  75. port=config.redis_port,
  76. db=config.redis_db,
  77. password=config.redis_password,
  78. timeout=config.timeout_seconds,
  79. )
  80. token_store = RedisTokenStore(
  81. redis,
  82. prefix=config.redis_prefix,
  83. session_key=config.session_key,
  84. refresh_skew_seconds=config.refresh_skew_seconds,
  85. )
  86. elif config.token_store_type == 'file':
  87. token_store = FileTokenStore(
  88. config.token_store_path,
  89. refresh_skew_seconds=config.refresh_skew_seconds,
  90. )
  91. else:
  92. raise ValueError('unsupported token store type: {0}'.format(config.token_store_type))
  93. auth_client = AuthClient(
  94. base_url=config.auth_base_url,
  95. client_type=config.client_type,
  96. token_store=token_store,
  97. timeout=config.timeout_seconds,
  98. session_key=config.session_key,
  99. )
  100. api_client = ApiClient(
  101. base_url=config.tools_base_url,
  102. token_store=token_store,
  103. timeout=config.timeout_seconds,
  104. )
  105. return cls(auth_client=auth_client, api_client=api_client, token_store=token_store)
  106. def registered_tool_names(self):
  107. return tuple(self._tools.keys())
  108. def _enabled_tool_names(self, response):
  109. if not isinstance(response, dict):
  110. raise RuntimeError('invalid enabled tool response')
  111. if response.get('code') != 'MCP_0000':
  112. raise RuntimeError(response.get('msg') or 'list enabled tools failed')
  113. data = response.get('data')
  114. codes = data.get('tool_codes') if isinstance(data, dict) else None
  115. if not isinstance(codes, list):
  116. raise RuntimeError('invalid enabled tool response')
  117. return {
  118. code.strip().lower()
  119. for code in codes
  120. if isinstance(code, str) and code.strip()
  121. }
  122. def _load_enabled_tool_names(self, request_id=''):
  123. if self.api_client is None or not hasattr(self.api_client, 'list_enabled_tools'):
  124. raise RuntimeError('enabled tool client unavailable')
  125. return self._enabled_tool_names(
  126. self.api_client.list_enabled_tools(request_id=request_id)
  127. )
  128. def list_tools(self, request_id=''):
  129. request_id = self.build_request_id(request_id)
  130. enabled = self._load_enabled_tool_names(request_id)
  131. return [
  132. tool.metadata()
  133. for name, tool in self._tools.items()
  134. if name in enabled
  135. ]
  136. def build_request_id(self, request_id=''):
  137. request_id = str(request_id or '').strip()
  138. if request_id:
  139. return request_id
  140. return 'rq_{0}'.format(uuid.uuid4().hex[:16])
  141. def ensure_session(self):
  142. if self.token_store is None:
  143. return
  144. session = self.token_store.get()
  145. if not session or not session.get('token'):
  146. raise RuntimeError(DEVICE_INVALID_MESSAGE)
  147. if self.token_store.is_expiring():
  148. if self.auth_client is None:
  149. raise RuntimeError('mcp token expiring but auth client missing')
  150. self.auth_client.refresh(session['token'])
  151. def call_tool(self, name, arguments=None, request_id=''):
  152. if name not in self._tools:
  153. raise KeyError('tool not registered: {0}'.format(name))
  154. tool = self._tools[name]
  155. if getattr(tool, 'requires_session', True):
  156. self.ensure_session()
  157. request_id = self.build_request_id(request_id)
  158. if name not in self._load_enabled_tool_names(request_id):
  159. raise RuntimeError('tool disabled: {0}'.format(name))
  160. arguments = arguments or {}
  161. return tool.call(request_id=request_id, **arguments)
  162. def create_protocol_handler(self):
  163. return McpProtocolHandler(self)
  164. def run_cli(self, argv=None, stdin=None, stdout=None):
  165. stdin = stdin or sys.stdin
  166. stdout = stdout or sys.stdout
  167. parser = argparse.ArgumentParser(prog='mcp-gateway')
  168. subparsers = parser.add_subparsers(dest='command', required=True)
  169. subparsers.add_parser('list-tools')
  170. subparsers.add_parser('serve-stdio')
  171. public_parser = subparsers.add_parser('serve-public')
  172. public_parser.add_argument('--host', default='0.0.0.0')
  173. public_parser.add_argument('--port', type=int, default=8765)
  174. call_parser = subparsers.add_parser('call')
  175. call_parser.add_argument('--tool', required=True)
  176. call_parser.add_argument('--keyword', default='')
  177. call_parser.add_argument('--order-id', type=int, default=0)
  178. call_parser.add_argument('--order-number', default='')
  179. call_parser.add_argument('--order-numbers', default='')
  180. call_parser.add_argument('--tracking-number', default='')
  181. call_parser.add_argument('--tracking-numbers', default='')
  182. call_parser.add_argument('--reference-number', default='')
  183. call_parser.add_argument('--reference-numbers', default='')
  184. call_parser.add_argument('--outbound-number', default='')
  185. call_parser.add_argument('--outbound-numbers', default='')
  186. call_parser.add_argument('--bl-numbers', default='')
  187. call_parser.add_argument('--container-code', default='')
  188. call_parser.add_argument('--container-codes', default='')
  189. call_parser.add_argument('--so-number', default='')
  190. call_parser.add_argument('--so-numbers', default='')
  191. call_parser.add_argument('--shipment-id', default='')
  192. call_parser.add_argument('--receiver-country', default='')
  193. call_parser.add_argument('--product-ids', default='')
  194. call_parser.add_argument('--customer-ids', default='')
  195. call_parser.add_argument('--sales-id', type=int, default=0)
  196. call_parser.add_argument('--warehouse-ids', default='')
  197. call_parser.add_argument('--warehouse-id', type=int, default=0)
  198. call_parser.add_argument('--department-id', type=int, default=0)
  199. call_parser.add_argument('--outbound-status', type=int, default=0)
  200. call_parser.add_argument('--shipping-method', type=int, default=0)
  201. call_parser.add_argument('--is-direct-send', type=int, default=None)
  202. call_parser.add_argument('--trailer-types', default='')
  203. call_parser.add_argument('--declaration-types', default='')
  204. call_parser.add_argument('--clearance-types', default='')
  205. call_parser.add_argument('--closing-time-start', default='')
  206. call_parser.add_argument('--closing-time-end', default='')
  207. call_parser.add_argument('--est-loading-time-start', default='')
  208. call_parser.add_argument('--est-loading-time-end', default='')
  209. call_parser.add_argument('--create-date-start', default='')
  210. call_parser.add_argument('--create-date-end', default='')
  211. call_parser.add_argument('--loading-time-start', default='')
  212. call_parser.add_argument('--loading-time-end', default='')
  213. call_parser.add_argument('--inbound-date-start', default='')
  214. call_parser.add_argument('--inbound-date-end', default='')
  215. call_parser.add_argument('--outbound-date-start', default='')
  216. call_parser.add_argument('--outbound-date-end', default='')
  217. call_parser.add_argument('--filter-type', default='')
  218. call_parser.add_argument('--page', type=int, default=1)
  219. call_parser.add_argument('--limit', type=int, default=20)
  220. call_parser.add_argument('--request-id', default='')
  221. args = parser.parse_args(argv or [])
  222. if args.command == 'list-tools':
  223. payload = self.list_tools()
  224. elif args.command == 'serve-stdio':
  225. return self.create_protocol_handler().run_stdio(stdin=stdin, stdout=stdout)
  226. elif args.command == 'serve-public':
  227. config = GatewayConfig.from_env()
  228. redis = RedisSocketClient(
  229. host=config.redis_host,
  230. port=config.redis_port,
  231. db=config.redis_db,
  232. password=config.redis_password,
  233. timeout=config.timeout_seconds,
  234. )
  235. session_store = GatewaySessionStore(
  236. redis,
  237. prefix=config.redis_prefix,
  238. ttl_seconds=config.gateway_session_ttl_seconds,
  239. )
  240. public_app = PublicGatewayApp(
  241. session_store=session_store,
  242. api_client=ScopedApiClient(config.tools_base_url, timeout=config.timeout_seconds),
  243. )
  244. return serve_public(
  245. public_app,
  246. host=args.host,
  247. port=args.port,
  248. enable_rate_limit=config.rate_limit_enabled,
  249. rate_limit_max_requests=config.rate_limit_max_requests,
  250. rate_limit_window_seconds=config.rate_limit_window_seconds,
  251. )
  252. elif args.command == 'call':
  253. tool_args = {
  254. 'page': args.page,
  255. 'limit': args.limit,
  256. }
  257. if args.tool == 'query_order':
  258. if not args.keyword:
  259. raise ValueError('--keyword is required for query_order')
  260. tool_args['keyword'] = args.keyword
  261. elif args.tool == 'query_track':
  262. if args.order_id > 0:
  263. tool_args['order_id'] = args.order_id
  264. if args.order_number:
  265. tool_args['order_number'] = args.order_number
  266. if args.tracking_number:
  267. tool_args['tracking_number'] = args.tracking_number
  268. if args.order_id <= 0 and not args.order_number and not args.tracking_number:
  269. raise ValueError('--order-id, --order-number or --tracking-number is required for query_track')
  270. elif args.tool == 'query_order_exact':
  271. exact_strings = {
  272. 'order_number': args.order_number,
  273. 'reference_number': args.reference_number,
  274. 'tracking_number': args.tracking_number,
  275. 'outbound_number': args.outbound_number,
  276. 'container_code': args.container_code,
  277. 'so_number': args.so_number,
  278. 'shipment_id': args.shipment_id,
  279. 'receiver_country': args.receiver_country,
  280. 'inbound_date_start': args.inbound_date_start,
  281. 'inbound_date_end': args.inbound_date_end,
  282. 'outbound_date_start': args.outbound_date_start,
  283. 'outbound_date_end': args.outbound_date_end,
  284. }
  285. for field, value in exact_strings.items():
  286. if value:
  287. tool_args[field] = value
  288. exact_number_lists = {
  289. 'order_numbers': args.order_numbers,
  290. 'reference_numbers': args.reference_numbers,
  291. 'tracking_numbers': args.tracking_numbers,
  292. 'outbound_numbers': args.outbound_numbers,
  293. 'container_codes': args.container_codes,
  294. 'so_numbers': args.so_numbers,
  295. }
  296. for field, value in exact_number_lists.items():
  297. if value:
  298. tool_args[field] = parse_string_list(value)
  299. exact_lists = {
  300. 'product_ids': args.product_ids,
  301. 'customer_ids': args.customer_ids,
  302. 'warehouse_ids': args.warehouse_ids,
  303. }
  304. for field, value in exact_lists.items():
  305. if value:
  306. tool_args[field] = parse_int_list(value)
  307. if args.sales_id > 0:
  308. tool_args['sales_id'] = args.sales_id
  309. if args.department_id > 0:
  310. tool_args['department_id'] = args.department_id
  311. elif args.tool == 'query_customs_declaration_files':
  312. if args.outbound_numbers:
  313. tool_args['outbound_numbers'] = parse_string_list(
  314. args.outbound_numbers
  315. )
  316. if args.order_numbers:
  317. tool_args['order_numbers'] = parse_string_list(
  318. args.order_numbers
  319. )
  320. elif args.tool == 'query_outbound_list':
  321. outbound_number_lists = {
  322. 'outbound_numbers': args.outbound_numbers,
  323. 'order_numbers': args.order_numbers,
  324. 'container_codes': args.container_codes,
  325. 'so_numbers': args.so_numbers,
  326. 'bl_numbers': args.bl_numbers,
  327. }
  328. for field, value in outbound_number_lists.items():
  329. if value:
  330. tool_args[field] = parse_string_list(value)
  331. outbound_mode_lists = {
  332. 'trailer_types': args.trailer_types,
  333. 'declaration_types': args.declaration_types,
  334. 'clearance_types': args.clearance_types,
  335. }
  336. for field, value in outbound_mode_lists.items():
  337. if value:
  338. tool_args[field] = parse_int_list(value)
  339. outbound_dates = {
  340. 'closing_time_start': args.closing_time_start,
  341. 'closing_time_end': args.closing_time_end,
  342. 'est_loading_time_start': args.est_loading_time_start,
  343. 'est_loading_time_end': args.est_loading_time_end,
  344. 'create_date_start': args.create_date_start,
  345. 'create_date_end': args.create_date_end,
  346. 'loading_time_start': args.loading_time_start,
  347. 'loading_time_end': args.loading_time_end,
  348. }
  349. for field, value in outbound_dates.items():
  350. if value:
  351. tool_args[field] = value
  352. if args.outbound_status > 0:
  353. tool_args['outbound_status'] = args.outbound_status
  354. if args.shipping_method > 0:
  355. tool_args['shipping_method'] = args.shipping_method
  356. if args.warehouse_id == -1 or args.warehouse_id > 0:
  357. tool_args['warehouse_id'] = args.warehouse_id
  358. if args.is_direct_send is not None:
  359. tool_args['is_direct_send'] = args.is_direct_send
  360. elif args.tool == 'query_outbound_detail':
  361. if not args.outbound_number:
  362. raise ValueError(
  363. '--outbound-number is required for '
  364. 'query_outbound_detail'
  365. )
  366. tool_args['outbound_number'] = args.outbound_number
  367. elif args.tool in (
  368. 'list_order_filter_options', 'list_outbound_filter_options'
  369. ):
  370. if not args.filter_type:
  371. raise ValueError(
  372. '--filter-type is required for '
  373. + args.tool
  374. )
  375. tool_args['filter_type'] = args.filter_type
  376. tool_args['keyword'] = args.keyword
  377. else:
  378. if args.keyword:
  379. tool_args['keyword'] = args.keyword
  380. payload = self.call_tool(
  381. args.tool,
  382. tool_args,
  383. request_id=args.request_id,
  384. )
  385. else:
  386. raise RuntimeError('unsupported command')
  387. stdout.write(json.dumps(payload, ensure_ascii=False))
  388. return 0
  389. def main(argv=None):
  390. config = GatewayConfig.from_env()
  391. app = GatewayApp.from_config(config)
  392. return app.run_cli(argv=argv)
  393. if __name__ == '__main__':
  394. raise SystemExit(main(sys.argv[1:]))