app.py 21 KB

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