app.py 20 KB

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