app_fastapi.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. """
  2. AI MCP Web UI - FastAPI 后端
  3. 提供聊天界面与 MCP 工具调用的桥梁
  4. """
  5. import os
  6. import asyncio
  7. import uuid
  8. import json as json_module
  9. from typing import Optional, Dict, List, Any
  10. from contextlib import asynccontextmanager
  11. from fastapi import FastAPI, Request, HTTPException, Header
  12. from fastapi.middleware.cors import CORSMiddleware
  13. from fastapi.responses import StreamingResponse, JSONResponse
  14. from fastapi.staticfiles import StaticFiles
  15. import httpx
  16. from anthropic import Anthropic
  17. from config import MCP_SERVERS, ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL, ANTHROPIC_MODEL
  18. from conversation_manager import ConversationManager
  19. from tool_handler import ToolCallHandler
  20. from tool_converter import ToolConverter
  21. from mcp_client import MCPClient
  22. # 存储认证会话 (生产环境应使用 Redis 或数据库)
  23. auth_sessions: Dict[str, dict] = {}
  24. def create_anthropic_client(api_key: str, base_url: str) -> Anthropic:
  25. """
  26. 创建 Anthropic 客户端,支持自定义认证格式
  27. 自定义 API 代理需要 'Authorization: Bearer <token>' 格式,
  28. 而不是 Anthropic SDK 默认的 'x-api-key' header。
  29. """
  30. # 创建自定义 httpx client,设置正确的 Authorization header
  31. http_client = httpx.Client(
  32. headers={"Authorization": f"Bearer {api_key}"},
  33. timeout=120.0
  34. )
  35. return Anthropic(base_url=base_url, http_client=http_client)
  36. # 初始化 Claude 客户端(使用自定义认证格式)
  37. client = create_anthropic_client(
  38. api_key=ANTHROPIC_API_KEY,
  39. base_url=ANTHROPIC_BASE_URL
  40. )
  41. @asynccontextmanager
  42. async def lifespan(app: FastAPI):
  43. """应用生命周期管理"""
  44. # 启动时执行
  45. print(f"FastAPI 应用启动 - 模型: {ANTHROPIC_MODEL}")
  46. print(f"MCP 服务器: {list(MCP_SERVERS.keys())}")
  47. yield
  48. # 关闭时执行
  49. print("FastAPI 应用关闭")
  50. # 创建 FastAPI 应用
  51. app = FastAPI(
  52. title="AI MCP Web UI Backend",
  53. description="AI MCP Web UI 后端服务 - 支持 Claude AI 和 MCP 工具调用",
  54. version="2.0.0",
  55. lifespan=lifespan
  56. )
  57. # CORS 配置
  58. app.add_middleware(
  59. CORSMiddleware,
  60. allow_origins=["*"],
  61. allow_credentials=True,
  62. allow_methods=["*"],
  63. allow_headers=["*"],
  64. )
  65. # 挂载静态文件 - 支持 frontend-v2 (Next.js 静态导出)
  66. frontend_v2_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "frontend-v2-static")
  67. frontend_v1_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "frontend")
  68. # 优先使用 frontend-v2,如果不存在则回退到 frontend
  69. frontend_path = frontend_v2_path if os.path.exists(frontend_v2_path) else frontend_v1_path
  70. # 挂载静态资源目录 (_next 等)
  71. app.mount("/_next", StaticFiles(directory=os.path.join(frontend_v2_path, "_next")), name="next_static")
  72. # ========== 根路由 ==========
  73. @app.get("/")
  74. async def index():
  75. """返回前端主页 (frontend-v2)"""
  76. from fastapi.responses import FileResponse
  77. index_path = os.path.join(frontend_path, "index.html")
  78. return FileResponse(index_path)
  79. @app.get("/auth")
  80. async def auth_page():
  81. """返回登录页面 (frontend-v2)"""
  82. from fastapi.responses import FileResponse
  83. auth_path = os.path.join(frontend_path, "auth.html")
  84. if os.path.exists(auth_path):
  85. return FileResponse(auth_path)
  86. # 回退到主页
  87. return await index()
  88. # ========== 健康检查 ==========
  89. @app.get("/api/health")
  90. async def health():
  91. """健康检查端点"""
  92. return {
  93. "status": "ok",
  94. "model": ANTHROPIC_MODEL,
  95. "mcp_servers": list(MCP_SERVERS.keys())
  96. }
  97. # ========== 聊天 API ==========
  98. @app.post("/api/chat")
  99. async def chat(request: Request):
  100. """
  101. 聊天端点 - 接收用户消息,返回 Claude 响应(支持 MCP 工具调用)
  102. 支持 MCP 认证:通过 X-MCP-Tokens header 传递 JWT tokens
  103. """
  104. try:
  105. data = await request.json()
  106. message = data.get('message', '')
  107. conversation_history = data.get('history', [])
  108. session_id = request.headers.get('X-Session-ID')
  109. mcp_tokens = request.headers.get('X-MCP-Tokens') # MCP tokens (JSON string)
  110. if not message:
  111. raise HTTPException(status_code=400, detail="Message is required")
  112. # 解析 MCP tokens
  113. parsed_tokens = {}
  114. if mcp_tokens:
  115. if isinstance(mcp_tokens, str):
  116. try:
  117. parsed_tokens = json_module.loads(mcp_tokens)
  118. except:
  119. parsed_tokens = {}
  120. else:
  121. parsed_tokens = mcp_tokens
  122. # DEBUG: 打印收到的 token
  123. print(f"[DEBUG /api/chat] Received mcp_tokens: {list(parsed_tokens.keys()) if parsed_tokens else 'None'}")
  124. for k, v in parsed_tokens.items():
  125. print(f"[DEBUG /api/chat] {k}: {v[:30] if v else 'None'}...")
  126. # 获取前端发送的组件列表(实现动态组件注册)
  127. available_components = data.get('availableComponents')
  128. enabled_mcp_list = data.get('enabledMcpList') # 前端发送的已启用 MCP 列表
  129. if available_components:
  130. print(f"[DEBUG /api/chat] Using dynamic components from frontend ({len(available_components)} chars)")
  131. # DEBUG: 打印已启用的 MCP 列表
  132. if enabled_mcp_list is not None:
  133. print(f"[DEBUG /api/chat] Enabled MCP list from frontend: {enabled_mcp_list}")
  134. else:
  135. print(f"[DEBUG /api/chat] No enabled MCP list from frontend, using all configured MCPs")
  136. # 创建对话管理器(带 token 和组件提示)
  137. conv_manager = ConversationManager(
  138. api_key=ANTHROPIC_API_KEY,
  139. base_url=ANTHROPIC_BASE_URL,
  140. model=ANTHROPIC_MODEL,
  141. session_id=session_id,
  142. mcp_tokens=parsed_tokens,
  143. components_prompt=available_components, # 动态组件提示
  144. enabled_mcp_list=enabled_mcp_list # 前端传递的已启用 MCP 列表
  145. )
  146. # 格式化对话历史
  147. formatted_history = ConversationManager.format_history_for_claude(conversation_history)
  148. # 执行多轮对话(自动处理工具调用)
  149. result = await conv_manager.chat(
  150. user_message=message,
  151. conversation_history=formatted_history,
  152. max_turns=5
  153. )
  154. # 提取响应文本
  155. response_text = result.get("response", "")
  156. tool_calls = result.get("tool_calls", [])
  157. return {
  158. "response": response_text,
  159. "model": ANTHROPIC_MODEL,
  160. "tool_calls": tool_calls,
  161. "has_tools": len(tool_calls) > 0
  162. }
  163. except HTTPException:
  164. raise
  165. except Exception as e:
  166. import traceback
  167. return JSONResponse(
  168. status_code=500,
  169. content={
  170. "error": str(e),
  171. "traceback": traceback.format_exc()
  172. }
  173. )
  174. async def generate_chat_stream(
  175. message: str,
  176. conversation_history: List[Dict[str, Any]],
  177. session_id: Optional[str],
  178. mcp_tokens: Optional[Dict[str, str]] = None,
  179. available_components: Optional[str] = None, # 新增:前端发送的组件列表
  180. enabled_mcp_list: Optional[List[str]] = None # 新增:前端发送的已启用 MCP 列表
  181. ):
  182. """生成 SSE 流式响应的异步生成器"""
  183. try:
  184. # 发送开始事件
  185. yield f"event: start\ndata: {json_module.dumps({'status': 'started'})}\n\n"
  186. # 解析 MCP tokens (从 JSON 字符串)
  187. parsed_tokens = {}
  188. if mcp_tokens:
  189. if isinstance(mcp_tokens, str):
  190. try:
  191. parsed_tokens = json_module.loads(mcp_tokens)
  192. except Exception as e:
  193. parsed_tokens = {}
  194. else:
  195. parsed_tokens = mcp_tokens
  196. # DEBUG: 打印解析后的 token
  197. print(f"[DEBUG generate_chat_stream] Parsed mcp_tokens keys: {list(parsed_tokens.keys())}")
  198. for k, v in parsed_tokens.items():
  199. print(f"[DEBUG generate_chat_stream] {k}: {v[:30] if v else 'None'}...")
  200. # DEBUG: 打印组件提示
  201. if available_components:
  202. print(f"[DEBUG generate_chat_stream] Using dynamic components from frontend ({len(available_components)} chars)")
  203. else:
  204. print(f"[DEBUG generate_chat_stream] Using default components")
  205. # DEBUG: 打印已启用的 MCP 列表
  206. if enabled_mcp_list is not None:
  207. print(f"[DEBUG generate_chat_stream] Enabled MCP list from frontend: {enabled_mcp_list}")
  208. else:
  209. print(f"[DEBUG generate_chat_stream] No enabled MCP list from frontend, using all configured MCPs")
  210. # 创建对话管理器(带 token 和组件提示)
  211. conv_manager = ConversationManager(
  212. api_key=ANTHROPIC_API_KEY,
  213. base_url=ANTHROPIC_BASE_URL,
  214. model=ANTHROPIC_MODEL,
  215. session_id=session_id,
  216. mcp_tokens=parsed_tokens,
  217. components_prompt=available_components, # 动态组件提示
  218. enabled_mcp_list=enabled_mcp_list # 前端传递的已启用 MCP 列表
  219. )
  220. # 格式化对话历史
  221. formatted_history = ConversationManager.format_history_for_claude(conversation_history)
  222. messages = formatted_history + [{"role": "user", "content": message}]
  223. current_messages = messages
  224. tool_calls_info = []
  225. for turn in range(5): # 最多 5 轮
  226. # 获取可用工具
  227. tools = await conv_manager.get_available_tools()
  228. # 发送工具列表
  229. yield f"event: tools\ndata: {json_module.dumps({'count': len(tools), 'tools': [t['name'] for t in tools[:5]]})}\n\n"
  230. # 调用 Claude API(流式)
  231. if tools:
  232. response_stream = conv_manager.client.messages.create(
  233. model=conv_manager.model,
  234. max_tokens=4096,
  235. system=conv_manager.system_prompt, # 使用动态系统提示
  236. messages=current_messages,
  237. tools=tools,
  238. stream=True
  239. )
  240. else:
  241. response_stream = conv_manager.client.messages.create(
  242. model=conv_manager.model,
  243. max_tokens=4096,
  244. system=conv_manager.system_prompt, # 使用动态系统提示
  245. messages=current_messages,
  246. stream=True
  247. )
  248. # 处理流式响应
  249. content_blocks = []
  250. tool_use_blocks = []
  251. response_text = ""
  252. current_block_type = None
  253. current_tool_index = -1
  254. partial_json = ""
  255. for event in response_stream:
  256. # 处理内容块开始 - 检查是否是工具调用
  257. if event.type == "content_block_start":
  258. # 检查块的类型
  259. if hasattr(event, "content_block"):
  260. current_block_type = getattr(event.content_block, "type", None)
  261. if current_block_type == "tool_use":
  262. # 这是工具调用块的开始
  263. tool_use_id = getattr(event.content_block, "id", "")
  264. # content_block 包含 name
  265. tool_name = getattr(event.content_block, "name", "")
  266. tool_use_blocks.append({
  267. "type": "tool_use",
  268. "id": tool_use_id,
  269. "name": tool_name,
  270. "input": {}
  271. })
  272. current_tool_index = len(tool_use_blocks) - 1
  273. partial_json = ""
  274. # 处理内容块增量
  275. elif event.type == "content_block_delta":
  276. delta_type = getattr(event.delta, "type", "")
  277. # 文本增量
  278. if delta_type == "text_delta":
  279. text = event.delta.text
  280. response_text += text
  281. yield f"event: token\ndata: {json_module.dumps({'text': text})}\n\n"
  282. # 工具名称增量
  283. elif delta_type == "tool_use_delta":
  284. # 获取工具名称和参数增量
  285. delta_name = getattr(event.delta, "name", None)
  286. delta_input = getattr(event.delta, "input", None)
  287. if current_tool_index >= 0 and current_tool_index < len(tool_use_blocks):
  288. if delta_name is not None:
  289. tool_use_blocks[current_tool_index]["name"] = delta_name
  290. if delta_input is not None:
  291. # 更新输入参数
  292. current_input = tool_use_blocks[current_tool_index]["input"]
  293. if isinstance(delta_input, dict):
  294. current_input.update(delta_input)
  295. tool_use_blocks[current_tool_index]["input"] = current_input
  296. # 工具参数增量 - input_json_delta
  297. elif delta_type == "input_json_delta":
  298. # 累积 partial_json 构建完整参数
  299. partial_json_str = getattr(event.delta, "partial_json", "")
  300. if partial_json_str:
  301. partial_json += partial_json_str
  302. try:
  303. # 尝试解析累积的 JSON
  304. parsed_input = json_module.loads(partial_json)
  305. if current_tool_index >= 0 and current_tool_index < len(tool_use_blocks):
  306. tool_use_blocks[current_tool_index]["input"] = parsed_input
  307. except json_module.JSONDecodeError:
  308. # JSON 还不完整,继续累积
  309. pass
  310. # 处理内容块停止
  311. elif event.type == "content_block_stop":
  312. current_block_type = None
  313. current_tool_index = -1
  314. partial_json = ""
  315. # 如果没有工具调用,发送完成事件
  316. if not tool_use_blocks:
  317. yield f"event: complete\ndata: {json_module.dumps({'response': response_text, 'tool_calls': tool_calls_info})}\n\n"
  318. return
  319. # 处理工具调用
  320. yield f"event: tools_start\ndata: {json_module.dumps({'count': len(tool_use_blocks)})}\n\n"
  321. # 为每个工具调用发送 tool_call 事件
  322. for tool_block in tool_use_blocks:
  323. yield f"event: tool_call\ndata: {json_module.dumps({'tool': tool_block['name'], 'args': tool_block['input'], 'tool_id': tool_block['id']})}\n\n"
  324. tool_results = await conv_manager.tool_handler.process_tool_use_blocks(
  325. tool_use_blocks,
  326. conv_manager._tool_to_server_map
  327. )
  328. for tr in tool_results:
  329. tool_name = tr.get("tool_name", "")
  330. tool_result = tr.get("result", {})
  331. tool_use_id = tr.get("tool_use_id", "")
  332. # 发送工具完成事件
  333. if "error" in tool_result:
  334. yield f"event: tool_error\ndata: {json_module.dumps({'tool': tool_name, 'tool_id': tool_use_id, 'error': tool_result['error']})}\n\n"
  335. else:
  336. result_data = tool_result.get('result', '')
  337. # 限制结果长度避免传输过大
  338. if isinstance(result_data, str) and len(result_data) > 500:
  339. result_data = result_data[:500] + '...'
  340. yield f"event: tool_done\ndata: {json_module.dumps({'tool': tool_name, 'tool_id': tool_use_id, 'result': result_data})}\n\n"
  341. tool_calls_info.append({
  342. "tool": tool_name,
  343. "result": tool_result
  344. })
  345. # 构建工具结果消息
  346. tool_result_message = ToolCallHandler.create_tool_result_message(
  347. tool_results
  348. )
  349. # 添加到消息历史
  350. current_messages.append({
  351. "role": "assistant",
  352. "content": content_blocks
  353. })
  354. current_messages.append(tool_result_message)
  355. # 达到最大轮数
  356. yield f"event: complete\ndata: {json_module.dumps({'response': response_text, 'tool_calls': tool_calls_info, 'warning': '达到最大对话轮数'})}\n\n"
  357. except Exception as e:
  358. import traceback
  359. yield f"event: error\ndata: {json_module.dumps({'error': str(e), 'traceback': traceback.format_exc()})}\n\n"
  360. @app.post("/api/chat/stream")
  361. async def chat_stream(request: Request):
  362. """
  363. 聊天端点 - 流式输出版本(解决超时问题)
  364. 使用 Server-Sent Events (SSE) 实时返回:
  365. 1. Claude 的思考过程
  366. 2. 工具调用状态
  367. 3. 最终响应
  368. 支持 MCP 认证:通过 X-MCP-Tokens header 传递 JWT tokens
  369. """
  370. try:
  371. data = await request.json()
  372. message = data.get('message', '')
  373. conversation_history = data.get('history', [])
  374. session_id = request.headers.get('X-Session-ID')
  375. mcp_tokens = request.headers.get('X-MCP-Tokens') # MCP tokens (JSON string)
  376. available_components = data.get('availableComponents') # 前端发送的组件列表
  377. enabled_mcp_list = data.get('enabledMcpList') # 前端发送的已启用 MCP 列表
  378. # DEBUG: 打印收到的 token
  379. print(f"[DEBUG /api/chat/stream] mcp_tokens type: {type(mcp_tokens)}")
  380. print(f"[DEBUG /api/chat/stream] mcp_tokens value: {mcp_tokens[:150] if mcp_tokens else 'None'}...")
  381. print(f"[DEBUG /api/chat/stream] available_components: {len(available_components) if available_components else 0} chars")
  382. print(f"[DEBUG /api/chat/stream] enabled_mcp_list: {enabled_mcp_list}")
  383. if not message:
  384. raise HTTPException(status_code=400, detail="Message is required")
  385. return StreamingResponse(
  386. generate_chat_stream(message, conversation_history, session_id, mcp_tokens, available_components, enabled_mcp_list),
  387. media_type="text/event-stream",
  388. headers={
  389. 'Cache-Control': 'no-cache',
  390. 'X-Accel-Buffering': 'no' # 禁用 Nginx 缓冲
  391. }
  392. )
  393. except HTTPException:
  394. raise
  395. except Exception as e:
  396. import traceback
  397. return JSONResponse(
  398. status_code=500,
  399. content={
  400. "error": str(e),
  401. "traceback": traceback.format_exc()
  402. }
  403. )
  404. # ========== MCP API ==========
  405. @app.get("/api/mcp/servers")
  406. async def list_mcp_servers():
  407. """获取已配置的 MCP 服务器列表"""
  408. servers = []
  409. for name, server in MCP_SERVERS.items():
  410. servers.append({
  411. "id": name,
  412. "name": server.get("name", name),
  413. "url": server.get("url", ""),
  414. "auth_type": server.get("auth_type", "none"),
  415. "enabled": server.get("enabled", False)
  416. })
  417. return {"servers": servers}
  418. @app.get("/api/mcp/tools")
  419. async def list_mcp_tools(
  420. x_session_id: Optional[str] = Header(None, alias='X-Session-ID'),
  421. x_mcp_tokens: Optional[str] = Header(None, alias='X-MCP-Tokens')
  422. ):
  423. """获取可用的 MCP 工具列表(支持带 token 的认证)"""
  424. try:
  425. # 解析 MCP tokens
  426. parsed_tokens = {}
  427. if x_mcp_tokens:
  428. try:
  429. parsed_tokens = json_module.loads(x_mcp_tokens)
  430. except:
  431. parsed_tokens = {}
  432. # 使用带 token 的方法获取工具
  433. tools = await MCPClient.get_all_tools_with_tokens_async(
  434. session_id=x_session_id,
  435. mcp_tokens=parsed_tokens
  436. )
  437. claude_tools = ToolConverter.convert_mcp_tools(tools)
  438. return {
  439. "tools": claude_tools,
  440. "count": len(claude_tools)
  441. }
  442. except Exception as e:
  443. import traceback
  444. return JSONResponse(
  445. status_code=500,
  446. content={
  447. "error": str(e),
  448. "traceback": traceback.format_exc(),
  449. "tools": []
  450. }
  451. )
  452. @app.get("/api/mcp/health/{mcp_type}")
  453. async def check_mcp_health(mcp_type: str):
  454. """
  455. 检查 MCP 服务器健康状态
  456. 使用 HEAD 请求检查 MCP 服务器是否在线
  457. 返回健康状态和响应延迟
  458. """
  459. import time
  460. import urllib.parse
  461. try:
  462. # 查找 MCP 服务器配置
  463. target_server = MCP_SERVERS.get(mcp_type)
  464. if not target_server:
  465. return JSONResponse(
  466. status_code=404,
  467. content={"status": "error", "message": f"Unknown MCP type: {mcp_type}"}
  468. )
  469. # 获取 MCP URL
  470. mcp_url = target_server.get('url', '')
  471. if not mcp_url:
  472. return JSONResponse(
  473. status_code=400,
  474. content={"status": "error", "message": f"No URL configured for {mcp_type}"}
  475. )
  476. # 使用 HEAD 请求检查服务器是否在线
  477. start_time = time.time()
  478. try:
  479. async with httpx.AsyncClient(timeout=10.0) as http_client:
  480. # 使用 HEAD 请求检查服务器可达性
  481. response = await http_client.head(
  482. mcp_url,
  483. timeout=10.0
  484. )
  485. latency = int((time.time() - start_time) * 1000)
  486. # 只要能收到响应(无论什么状态码),说明服务器在线
  487. # MCP SSE 端点可能返回 405 (不允许 HEAD),但服务器仍健康
  488. return {
  489. "status": "healthy",
  490. "healthy": True,
  491. "mcp_type": mcp_type,
  492. "latency": latency,
  493. "url": mcp_url,
  494. "http_status": response.status_code
  495. }
  496. except httpx.TimeoutException:
  497. return {
  498. "status": "timeout",
  499. "healthy": False,
  500. "mcp_type": mcp_type,
  501. "error": "Connection timeout",
  502. "latency": 10000
  503. }
  504. except httpx.ConnectError as e:
  505. return {
  506. "status": "unreachable",
  507. "healthy": False,
  508. "mcp_type": mcp_type,
  509. "error": f"Connection error: {str(e)}",
  510. "latency": 0
  511. }
  512. except httpx.ConnectTimeout as e:
  513. return {
  514. "status": "timeout",
  515. "healthy": False,
  516. "mcp_type": mcp_type,
  517. "error": f"Connection timeout: {str(e)}",
  518. "latency": 10000
  519. }
  520. except Exception as e:
  521. import traceback
  522. return JSONResponse(
  523. status_code=500,
  524. content={
  525. "status": "error",
  526. "healthy": False,
  527. "mcp_type": mcp_type,
  528. "error": str(e),
  529. "traceback": traceback.format_exc()
  530. }
  531. )
  532. # ========== 认证 API ==========
  533. @app.post("/api/auth/login")
  534. async def login(request: Request):
  535. """
  536. Novel Platform 用户登录
  537. 代理到实际的登录端点并返回 JWT Token
  538. """
  539. try:
  540. data = await request.json()
  541. # 支持 email 和 username 两种参数名
  542. email = data.get('email') or data.get('username')
  543. password = data.get('password')
  544. if not email or not password:
  545. raise HTTPException(status_code=400, detail="Email and password are required")
  546. # 查找用户 MCP 服务器
  547. target_server = MCP_SERVERS.get('novel-platform-user')
  548. if not target_server:
  549. raise HTTPException(status_code=400, detail="Novel Platform User server not configured")
  550. # 构建登录 URL
  551. base_url = target_server.get('base_url', '')
  552. login_path = target_server.get('login_url', '/api/v1/auth/login')
  553. login_url = f"{base_url}{login_path}"
  554. # 调用实际的登录接口(异步版本)
  555. async with httpx.AsyncClient(timeout=30.0) as http_client:
  556. response = await http_client.post(
  557. login_url,
  558. json={"email": email, "password": password}
  559. )
  560. if response.status_code == 200:
  561. result = response.json()
  562. session_id = str(uuid.uuid4())
  563. # Novel Platform API 返回 access_token 和 user 对象
  564. access_token = result.get("access_token")
  565. user_info = result.get("user", {})
  566. # 获取用户角色
  567. user_role = user_info.get("role", "reader")
  568. # 存储会话信息
  569. auth_sessions[session_id] = {
  570. "username": user_info.get("username") or user_info.get("email", email),
  571. "email": email,
  572. "role": user_role,
  573. "token": access_token,
  574. "refresh_token": result.get("refresh_token"),
  575. "server": target_server.get("name")
  576. }
  577. return {
  578. "success": True,
  579. "session_id": session_id,
  580. "username": user_info.get("username") or user_info.get("email", email),
  581. "role": user_role,
  582. "server": target_server.get("name"),
  583. "token": access_token
  584. }
  585. else:
  586. raise HTTPException(
  587. status_code=response.status_code,
  588. detail=f"Login failed: {response.text}"
  589. )
  590. except HTTPException:
  591. raise
  592. except Exception as e:
  593. raise HTTPException(status_code=500, detail=str(e))
  594. @app.post("/api/auth/admin-login")
  595. async def admin_login(request: Request):
  596. """
  597. Novel Platform 管理员登录
  598. 代理到实际的管理员登录端点并返回 JWT Token
  599. """
  600. try:
  601. data = await request.json()
  602. # 支持 email 和 username 两种参数名
  603. email = data.get('email') or data.get('username')
  604. password = data.get('password')
  605. if not email or not password:
  606. raise HTTPException(status_code=400, detail="Email and password are required")
  607. # 查找管理员 MCP 服务器
  608. target_server = MCP_SERVERS.get('novel-platform-admin')
  609. if not target_server:
  610. raise HTTPException(status_code=400, detail="Admin server not configured")
  611. # 构建登录 URL
  612. base_url = target_server.get('base_url', '')
  613. login_path = target_server.get('login_url', '/api/v1/auth/admin-login')
  614. login_url = f"{base_url}{login_path}"
  615. # 调用实际的登录接口(异步版本)
  616. async with httpx.AsyncClient(timeout=30.0) as http_client:
  617. response = await http_client.post(
  618. login_url,
  619. json={"email": email, "password": password}
  620. )
  621. if response.status_code == 200:
  622. result = response.json()
  623. session_id = str(uuid.uuid4())
  624. # Novel Platform API 返回 access_token 和 user 对象
  625. access_token = result.get("access_token")
  626. user_info = result.get("user", {})
  627. auth_sessions[session_id] = {
  628. "username": user_info.get("username") or user_info.get("email", email),
  629. "email": email,
  630. "token": access_token,
  631. "refresh_token": result.get("refresh_token"),
  632. "server": target_server.get("name"),
  633. "role": "admin"
  634. }
  635. return {
  636. "success": True,
  637. "session_id": session_id,
  638. "username": user_info.get("username") or user_info.get("email", email),
  639. "server": target_server.get("name"),
  640. "role": "admin",
  641. "token": access_token
  642. }
  643. else:
  644. raise HTTPException(
  645. status_code=response.status_code,
  646. detail=f"Admin login failed: {response.text}"
  647. )
  648. except HTTPException:
  649. raise
  650. except Exception as e:
  651. raise HTTPException(status_code=500, detail=str(e))
  652. @app.post("/api/auth/register")
  653. async def register(request: Request):
  654. """
  655. Novel Platform 用户注册
  656. 代理到实际的注册端点
  657. """
  658. try:
  659. data = await request.json()
  660. email = data.get('email')
  661. username = data.get('username')
  662. password = data.get('password')
  663. if not email or not username or not password:
  664. raise HTTPException(status_code=400, detail="Email, username and password are required")
  665. # 查找用户 MCP 服务器
  666. target_server = MCP_SERVERS.get('novel-platform-user')
  667. if not target_server:
  668. # 如果没有专门的用户服务器,尝试找到任何需要 JWT 认证的服务器
  669. for server_id, config in MCP_SERVERS.items():
  670. if config.get('auth_type') == 'jwt' and 'base_url' in config:
  671. if 'user' in server_id:
  672. target_server = config
  673. break
  674. elif target_server is None:
  675. target_server = config
  676. if not target_server:
  677. raise HTTPException(status_code=400, detail="No JWT-authenticated server configured")
  678. # 构建注册 URL
  679. base_url = target_server.get('base_url', '')
  680. register_url = f"{base_url}/api/v1/auth/register"
  681. # 调用实际的注册接口(异步版本)
  682. async with httpx.AsyncClient(timeout=30.0) as http_client:
  683. response = await http_client.post(
  684. register_url,
  685. json={"email": email, "username": username, "password": password}
  686. )
  687. if response.status_code in (200, 201):
  688. result = response.json()
  689. # Novel Platform API 返回用户对象
  690. return {
  691. "success": True,
  692. "message": "注册成功",
  693. "user": {
  694. "id": result.get("id"),
  695. "email": result.get("email"),
  696. "username": result.get("username"),
  697. "role": result.get("role")
  698. }
  699. }
  700. else:
  701. # 尝试解析错误响应
  702. try:
  703. error_detail = response.json()
  704. error_msg = error_detail.get("detail", response.text)
  705. except:
  706. error_msg = response.text
  707. raise HTTPException(
  708. status_code=response.status_code,
  709. detail=error_msg
  710. )
  711. except HTTPException:
  712. raise
  713. except Exception as e:
  714. raise HTTPException(status_code=500, detail=str(e))
  715. @app.post("/api/auth/logout")
  716. async def logout(request: Request):
  717. """登出并清除会话"""
  718. try:
  719. data = await request.json()
  720. session_id = data.get('session_id')
  721. if session_id and session_id in auth_sessions:
  722. del auth_sessions[session_id]
  723. return {"success": True}
  724. except Exception as e:
  725. raise HTTPException(status_code=500, detail=str(e))
  726. @app.get("/api/auth/status")
  727. async def auth_status(x_session_id: Optional[str] = Header(None, alias='X-Session-ID')):
  728. """检查认证状态"""
  729. if x_session_id and x_session_id in auth_sessions:
  730. session = auth_sessions[x_session_id]
  731. return {
  732. "authenticated": True,
  733. "username": session.get("username"),
  734. "server": session.get("server"),
  735. "role": session.get("role", "user")
  736. }
  737. return {"authenticated": False}
  738. # ========== 测试 API ==========
  739. @app.get("/api/test-mcp")
  740. async def test_mcp_get(
  741. tool_name: str = "get_system_stats",
  742. server_id: str = "novel-platform-admin",
  743. auth_token: Optional[str] = None
  744. ):
  745. """
  746. GET 方式测试 MCP 工具调用(用于 curl 测试)
  747. 参数:
  748. - tool_name: 工具名称 (默认: get_system_stats)
  749. - server_id: 服务器 ID (默认: novel-platform-admin)
  750. - auth_token: JWT token (通过 query 参数或 header 传递)
  751. """
  752. try:
  753. # 如果 query 参数没有 token,尝试从 header 获取
  754. if not auth_token:
  755. # 这个处理会在实际请求时通过 FastAPI 的 Header 参数处理
  756. pass
  757. print("\n" + "="*60)
  758. print("[TEST-MCP GET] MCP 工具调用测试")
  759. print("="*60)
  760. print(f"[TEST-MCP GET] server_id: {server_id}")
  761. print(f"[TEST-MCP GET] tool_name: {tool_name}")
  762. print(f"[TEST-MCP GET] auth_token present: {bool(auth_token)}")
  763. if auth_token:
  764. print(f"[TEST-MCP GET] auth_token (前50字符): {auth_token[:50]}...")
  765. print("="*60 + "\n")
  766. # 创建 MCP 客户端
  767. client = MCPClient(
  768. server_id=server_id,
  769. session_id="test-session",
  770. auth_token=auth_token
  771. )
  772. # 调用工具(无参数)
  773. print(f"[TEST-MCP GET] 开始调用工具...")
  774. result = await client.call_tool(tool_name, {})
  775. print(f"[TEST-MCP GET] 调用完成")
  776. print(f"[TEST-MCP GET] success: {result.get('success', False)}")
  777. print("="*60 + "\n")
  778. return {
  779. "success": True,
  780. "server_id": server_id,
  781. "tool_name": tool_name,
  782. "result": result
  783. }
  784. except Exception as e:
  785. import traceback
  786. print(f"[TEST-MCP GET] 异常: {e}")
  787. traceback.print_exc()
  788. return JSONResponse(
  789. status_code=500,
  790. content={
  791. "success": False,
  792. "error": str(e),
  793. "traceback": traceback.format_exc()
  794. }
  795. )
  796. @app.post("/api/test-mcp")
  797. async def test_mcp_call(request: Request):
  798. """
  799. 直接测试 MCP 工具调用(绕过 CORS,用于调试)
  800. 请求体:
  801. {
  802. "server_id": "novel-platform-admin", // 可选,默认使用 admin
  803. "tool_name": "get_system_stats", // 工具名称
  804. "arguments": {}, // 工具参数
  805. "auth_token": "jwt-token" // JWT 认证 token
  806. }
  807. """
  808. try:
  809. data = await request.json()
  810. server_id = data.get('server_id', 'novel-platform-admin')
  811. tool_name = data.get('tool_name', '')
  812. arguments = data.get('arguments', {})
  813. auth_token = data.get('auth_token')
  814. print("\n" + "="*60)
  815. print("[TEST-MCP] MCP 工具调用测试")
  816. print("="*60)
  817. print(f"[TEST-MCP] server_id: {server_id}")
  818. print(f"[TEST-MCP] tool_name: {tool_name}")
  819. print(f"[TEST-MCP] arguments: {arguments}")
  820. print(f"[TEST-MCP] auth_token present: {bool(auth_token)}")
  821. if auth_token:
  822. print(f"[TEST-MCP] auth_token (前50字符): {auth_token[:50]}...")
  823. print("="*60 + "\n")
  824. if not tool_name:
  825. raise HTTPException(status_code=400, detail="tool_name is required")
  826. # 创建 MCP 客户端
  827. client = MCPClient(
  828. server_id=server_id,
  829. session_id="test-session",
  830. auth_token=auth_token
  831. )
  832. # 调用工具
  833. print(f"[TEST-MCP] 开始调用工具...")
  834. result = await client.call_tool(tool_name, arguments)
  835. print(f"[TEST-MCP] 调用结果:")
  836. print(f"[TEST-MCP] success: {result.get('success', False)}")
  837. print(f"[TEST-MCP] has_error: {'error' in result}")
  838. if 'error' in result:
  839. print(f"[TEST-MCP] error: {result['error']}")
  840. else:
  841. result_preview = result.get('result', '')[:100]
  842. print(f"[TEST-MCP] result (预览): {result_preview}...")
  843. print("="*60 + "\n")
  844. return {
  845. "success": True,
  846. "server_id": server_id,
  847. "tool_name": tool_name,
  848. "arguments": arguments,
  849. "result": result,
  850. "debug": {
  851. "auth_token_present": bool(auth_token),
  852. "auth_token_length": len(auth_token) if auth_token else 0
  853. }
  854. }
  855. except HTTPException:
  856. raise
  857. except Exception as e:
  858. import traceback
  859. print(f"[TEST-MCP] 异常: {e}")
  860. traceback.print_exc()
  861. return JSONResponse(
  862. status_code=500,
  863. content={
  864. "success": False,
  865. "error": str(e),
  866. "traceback": traceback.format_exc()
  867. }
  868. )
  869. # ========== 主程序入口 ==========
  870. if __name__ == '__main__':
  871. import uvicorn
  872. port = int(os.getenv('PORT', 8081)) # 改为 8081,Next.js 使用 8080
  873. debug = os.getenv('DEBUG', 'False').lower() == 'true'
  874. uvicorn.run(
  875. "app_fastapi:app",
  876. host='0.0.0.0',
  877. port=port,
  878. reload=debug
  879. )