app.py 14 KB

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