app.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import argparse
  2. import json
  3. import sys
  4. import uuid
  5. from config import GatewayConfig
  6. from mcp_protocol import McpProtocolHandler
  7. from services.api_client import ApiClient
  8. from services.auth_client import AuthClient
  9. from services.token_store import FileTokenStore, RedisSocketClient, RedisTokenStore
  10. from tools.bind_auth_code import BindAuthCodeTool
  11. from tools.query_order import QueryOrderTool
  12. from tools.query_track import QueryTrackTool
  13. BIND_HINT = '\u8bf7\u5148\u767b\u5f55\u540e\u53f0\u83b7\u53d6 Workbuddy \u6388\u6743\u7801\uff0c\u7136\u540e\u5728 Workbuddy \u4e2d\u8f93\u5165\u201c\u7ed1\u5b9a\u6388\u6743\u7801 xxx\u201d\u5b8c\u6210\u7ed1\u5b9a\u3002'
  14. class GatewayApp:
  15. def __init__(self, auth_client=None, api_client=None, token_store=None):
  16. self.auth_client = auth_client
  17. self.api_client = api_client
  18. self.token_store = token_store
  19. self._tools = {
  20. 'bind_auth_code': BindAuthCodeTool(auth_client=auth_client),
  21. 'query_order': QueryOrderTool(api_client=api_client),
  22. 'query_track': QueryTrackTool(api_client=api_client),
  23. }
  24. @classmethod
  25. def from_config(cls, config, redis_client=None):
  26. if config.token_store_type == 'redis':
  27. redis = redis_client or RedisSocketClient(
  28. host=config.redis_host,
  29. port=config.redis_port,
  30. db=config.redis_db,
  31. password=config.redis_password,
  32. timeout=config.timeout_seconds,
  33. )
  34. token_store = RedisTokenStore(
  35. redis,
  36. prefix=config.redis_prefix,
  37. session_key=config.session_key,
  38. refresh_skew_seconds=config.refresh_skew_seconds,
  39. )
  40. elif config.token_store_type == 'file':
  41. token_store = FileTokenStore(
  42. config.token_store_path,
  43. refresh_skew_seconds=config.refresh_skew_seconds,
  44. )
  45. else:
  46. raise ValueError('unsupported token store type: {0}'.format(config.token_store_type))
  47. auth_client = AuthClient(
  48. base_url=config.auth_base_url,
  49. client_type=config.client_type,
  50. token_store=token_store,
  51. timeout=config.timeout_seconds,
  52. session_key=config.session_key,
  53. )
  54. api_client = ApiClient(
  55. base_url=config.tools_base_url,
  56. token_store=token_store,
  57. timeout=config.timeout_seconds,
  58. )
  59. return cls(auth_client=auth_client, api_client=api_client, token_store=token_store)
  60. def list_tools(self):
  61. return [tool.metadata() for tool in self._tools.values()]
  62. def bind(self, auth_code):
  63. if self.auth_client is None:
  64. raise RuntimeError('auth client is required for bind')
  65. auth_code = str(auth_code).strip()
  66. if not auth_code:
  67. raise ValueError('auth_code is required')
  68. return self.auth_client.exchange(auth_code)
  69. def build_request_id(self, request_id=''):
  70. request_id = str(request_id or '').strip()
  71. if request_id:
  72. return request_id
  73. return 'rq_{0}'.format(uuid.uuid4().hex[:16])
  74. def ensure_session(self):
  75. if self.token_store is None:
  76. return
  77. session = self.token_store.get()
  78. if not session or not session.get('token'):
  79. raise RuntimeError(BIND_HINT)
  80. if self.token_store.is_expiring():
  81. if self.auth_client is None:
  82. raise RuntimeError('mcp token expiring but auth client missing')
  83. self.auth_client.refresh(session['token'])
  84. def call_tool(self, name, arguments=None, request_id=''):
  85. if name not in self._tools:
  86. raise KeyError('tool not registered: {0}'.format(name))
  87. tool = self._tools[name]
  88. if getattr(tool, 'requires_session', True):
  89. self.ensure_session()
  90. arguments = arguments or {}
  91. request_id = self.build_request_id(request_id)
  92. return tool.call(request_id=request_id, **arguments)
  93. def create_protocol_handler(self):
  94. return McpProtocolHandler(self)
  95. def run_cli(self, argv=None, stdin=None, stdout=None):
  96. stdin = stdin or sys.stdin
  97. stdout = stdout or sys.stdout
  98. parser = argparse.ArgumentParser(prog='mcp-gateway')
  99. subparsers = parser.add_subparsers(dest='command', required=True)
  100. subparsers.add_parser('list-tools')
  101. subparsers.add_parser('serve-stdio')
  102. bind_parser = subparsers.add_parser('bind')
  103. bind_parser.add_argument('--auth-code', required=True)
  104. call_parser = subparsers.add_parser('call')
  105. call_parser.add_argument('--tool', required=True)
  106. call_parser.add_argument('--keyword', default='')
  107. call_parser.add_argument('--order-id', type=int, default=0)
  108. call_parser.add_argument('--order-number', default='')
  109. call_parser.add_argument('--tracking-number', default='')
  110. call_parser.add_argument('--page', type=int, default=1)
  111. call_parser.add_argument('--limit', type=int, default=20)
  112. call_parser.add_argument('--request-id', default='')
  113. args = parser.parse_args(argv or [])
  114. if args.command == 'list-tools':
  115. payload = self.list_tools()
  116. elif args.command == 'serve-stdio':
  117. return self.create_protocol_handler().run_stdio(stdin=stdin, stdout=stdout)
  118. elif args.command == 'bind':
  119. payload = self.bind(args.auth_code)
  120. elif args.command == 'call':
  121. tool_args = {
  122. 'page': args.page,
  123. 'limit': args.limit,
  124. }
  125. if args.tool == 'query_order':
  126. if not args.keyword:
  127. raise ValueError('--keyword is required for query_order')
  128. tool_args['keyword'] = args.keyword
  129. elif args.tool == 'query_track':
  130. if args.order_id > 0:
  131. tool_args['order_id'] = args.order_id
  132. if args.order_number:
  133. tool_args['order_number'] = args.order_number
  134. if args.tracking_number:
  135. tool_args['tracking_number'] = args.tracking_number
  136. if args.order_id <= 0 and not args.order_number and not args.tracking_number:
  137. raise ValueError('--order-id, --order-number or --tracking-number is required for query_track')
  138. else:
  139. if args.keyword:
  140. tool_args['keyword'] = args.keyword
  141. payload = self.call_tool(
  142. args.tool,
  143. tool_args,
  144. request_id=args.request_id,
  145. )
  146. else:
  147. raise RuntimeError('unsupported command')
  148. stdout.write(json.dumps(payload, ensure_ascii=False))
  149. return 0
  150. def main(argv=None):
  151. config = GatewayConfig.from_env()
  152. app = GatewayApp.from_config(config)
  153. return app.run_cli(argv=argv)
  154. if __name__ == '__main__':
  155. raise SystemExit(main(sys.argv[1:]))