app.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. BIND_HINT = '请先登录后台获取 Workbuddy 授权码,然后在 Workbuddy 中输入“绑定授权码 xxx”完成绑定。'
  13. class GatewayApp:
  14. def __init__(self, auth_client=None, api_client=None, token_store=None):
  15. self.auth_client = auth_client
  16. self.api_client = api_client
  17. self.token_store = token_store
  18. self._tools = {
  19. 'bind_auth_code': BindAuthCodeTool(auth_client=auth_client),
  20. 'query_order': QueryOrderTool(api_client=api_client),
  21. }
  22. @classmethod
  23. def from_config(cls, config, redis_client=None):
  24. if config.token_store_type == 'redis':
  25. redis = redis_client or RedisSocketClient(
  26. host=config.redis_host,
  27. port=config.redis_port,
  28. db=config.redis_db,
  29. password=config.redis_password,
  30. timeout=config.timeout_seconds,
  31. )
  32. token_store = RedisTokenStore(
  33. redis,
  34. prefix=config.redis_prefix,
  35. session_key=config.session_key,
  36. refresh_skew_seconds=config.refresh_skew_seconds,
  37. )
  38. elif config.token_store_type == 'file':
  39. token_store = FileTokenStore(
  40. config.token_store_path,
  41. refresh_skew_seconds=config.refresh_skew_seconds,
  42. )
  43. else:
  44. raise ValueError('unsupported token store type: {0}'.format(config.token_store_type))
  45. auth_client = AuthClient(
  46. base_url=config.auth_base_url,
  47. client_type=config.client_type,
  48. token_store=token_store,
  49. timeout=config.timeout_seconds,
  50. session_key=config.session_key,
  51. )
  52. api_client = ApiClient(
  53. base_url=config.tools_base_url,
  54. token_store=token_store,
  55. timeout=config.timeout_seconds,
  56. )
  57. return cls(auth_client=auth_client, api_client=api_client, token_store=token_store)
  58. def list_tools(self):
  59. return [tool.metadata() for tool in self._tools.values()]
  60. def bind(self, auth_code):
  61. if self.auth_client is None:
  62. raise RuntimeError('auth client is required for bind')
  63. auth_code = str(auth_code).strip()
  64. if not auth_code:
  65. raise ValueError('auth_code is required')
  66. return self.auth_client.exchange(auth_code)
  67. def build_request_id(self, request_id=''):
  68. request_id = str(request_id or '').strip()
  69. if request_id:
  70. return request_id
  71. return 'rq_{0}'.format(uuid.uuid4().hex[:16])
  72. def ensure_session(self):
  73. if self.token_store is None:
  74. return
  75. session = self.token_store.get()
  76. if not session or not session.get('token'):
  77. raise RuntimeError(BIND_HINT)
  78. if self.token_store.is_expiring():
  79. if self.auth_client is None:
  80. raise RuntimeError('mcp token expiring but auth client missing')
  81. self.auth_client.refresh(session['token'])
  82. def call_tool(self, name, arguments=None, request_id=''):
  83. if name not in self._tools:
  84. raise KeyError('tool not registered: {0}'.format(name))
  85. tool = self._tools[name]
  86. if getattr(tool, 'requires_session', True):
  87. self.ensure_session()
  88. arguments = arguments or {}
  89. request_id = self.build_request_id(request_id)
  90. return tool.call(request_id=request_id, **arguments)
  91. def create_protocol_handler(self):
  92. return McpProtocolHandler(self)
  93. def run_cli(self, argv=None, stdin=None, stdout=None):
  94. stdin = stdin or sys.stdin
  95. stdout = stdout or sys.stdout
  96. parser = argparse.ArgumentParser(prog='mcp-gateway')
  97. subparsers = parser.add_subparsers(dest='command', required=True)
  98. subparsers.add_parser('list-tools')
  99. subparsers.add_parser('serve-stdio')
  100. bind_parser = subparsers.add_parser('bind')
  101. bind_parser.add_argument('--auth-code', required=True)
  102. call_parser = subparsers.add_parser('call')
  103. call_parser.add_argument('--tool', required=True)
  104. call_parser.add_argument('--keyword', required=True)
  105. call_parser.add_argument('--page', type=int, default=1)
  106. call_parser.add_argument('--limit', type=int, default=20)
  107. call_parser.add_argument('--request-id', default='')
  108. args = parser.parse_args(argv or [])
  109. if args.command == 'list-tools':
  110. payload = self.list_tools()
  111. elif args.command == 'serve-stdio':
  112. return self.create_protocol_handler().run_stdio(stdin=stdin, stdout=stdout)
  113. elif args.command == 'bind':
  114. payload = self.bind(args.auth_code)
  115. elif args.command == 'call':
  116. payload = self.call_tool(
  117. args.tool,
  118. {
  119. 'keyword': args.keyword,
  120. 'page': args.page,
  121. 'limit': args.limit,
  122. },
  123. request_id=args.request_id,
  124. )
  125. else:
  126. raise RuntimeError('unsupported command')
  127. stdout.write(json.dumps(payload, ensure_ascii=False))
  128. return 0
  129. def main(argv=None):
  130. config = GatewayConfig.from_env()
  131. app = GatewayApp.from_config(config)
  132. return app.run_cli(argv=argv)
  133. if __name__ == '__main__':
  134. raise SystemExit(main(sys.argv[1:]))