2
0

app_fastapi.py 35 KB

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