2
0

app_fastapi.py 31 KB

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