app_fastapi.py 31 KB

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