app.py 15 KB

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