from __future__ import annotations import asyncio import json import uuid from typing import Any, Callable import httpx from fastapi import HTTPException from mcp.server.mcpserver import MCPServer from app.storage.db import PulseWallDB def _serialize_tool_result(res: Any) -> tuple[str, bool]: is_err = bool(getattr(res, "is_error", False)) structured = getattr(res, "structured_content", None) if structured is not None: return json.dumps(structured, ensure_ascii=False), is_err content = getattr(res, "content", None) if isinstance(content, list) and content: parts = [] for item in content: txt = getattr(item, "text", None) parts.append(txt if txt is not None else str(item)) return "\n".join(parts), is_err return json.dumps(res, ensure_ascii=False, default=str), is_err class HubMcpChatAgent: """OpenAI-compatible tool-calling chat agent wired directly to PulseWall's live MCPServer.""" def __init__( self, db: PulseWallDB, mcp_server: MCPServer, transport: httpx.AsyncBaseTransport | None = None, ) -> None: self.db = db self.mcp_server = mcp_server self._transport = transport async def get_openai_tools(self) -> list[dict[str, Any]]: mcp_tools = await self.mcp_server.list_tools() openai_tools: list[dict[str, Any]] = [] for t in mcp_tools: schema = getattr(t, "input_schema", None) or {"type": "object", "properties": {}} openai_tools.append( { "type": "function", "function": { "name": t.name, "description": (t.description or "").strip(), "parameters": schema, }, } ) return openai_tools async def chat( self, user_message: str, history: list[dict[str, Any]] | None = None, max_steps: int | None = None, on_tool_progress: Callable[[list[dict[str, Any]]], None] | None = None, ) -> dict[str, Any]: cfg = self.db.get_config().hub_chat_ai if not cfg.base_url.strip() or not cfg.api_key.strip() or not cfg.model.strip(): return { "ok": False, "error": "请先在上方填写并保存「中心桥专用 AI 配置」(Base URL、API Key、Model)。", "tool_trace": [], } effective_max_steps = max(1, min(100, int(max_steps if max_steps is not None else getattr(cfg, "max_tool_steps", 30)))) tools = await self.get_openai_tools() messages: list[dict[str, Any]] = [{"role": "system", "content": cfg.system_prompt}] for item in history or []: role = item.get("role") if role in ("user", "assistant") and item.get("content") is not None: messages.append({"role": role, "content": str(item["content"])}) messages.append({"role": "user", "content": user_message}) endpoint = cfg.base_url.rstrip("/") + "/chat/completions" headers = { "Authorization": f"Bearer {cfg.api_key}", "Content-Type": "application/json", } tool_trace: list[dict[str, Any]] = [] client_kwargs: dict[str, Any] = {"timeout": float(cfg.timeout_sec)} if self._transport is not None: client_kwargs["transport"] = self._transport async with httpx.AsyncClient(**client_kwargs) as client: for _step in range(effective_max_steps): req_body: dict[str, Any] = { "model": cfg.model, "messages": messages, "tools": tools, "tool_choice": "auto", } try: resp = await client.post(endpoint, headers=headers, json=req_body) except Exception as exc: return { "ok": False, "error": f"请求中心桥 AI 接口失败: {exc}", "tool_trace": tool_trace, } if resp.status_code >= 400: return { "ok": False, "error": f"AI 接口返回 HTTP {resp.status_code}: {resp.text[:400]}", "tool_trace": tool_trace, } try: data = resp.json() choice_msg = data["choices"][0]["message"] except Exception as exc: return { "ok": False, "error": f"解析 AI 响应失败: {exc} · 原始响应: {resp.text[:300]}", "tool_trace": tool_trace, } tool_calls = choice_msg.get("tool_calls") or [] assistant_content = choice_msg.get("content") or "" if not tool_calls: self.db.add_audit( "hub_ai_chat", "hub", f"AI chat completed ({len(tool_trace)} MCP tool calls)", {"user_message": user_message[:200], "tools_used": [t["name"] for t in tool_trace]}, ) return { "ok": True, "reply": assistant_content, "tool_trace": tool_trace, } # Append assistant tool-call turn messages.append( { "role": "assistant", "content": assistant_content, "tool_calls": tool_calls, } ) # Execute each requested MCP tool call against live MCPServer for tc in tool_calls: tc_id = tc.get("id") or f"call_{len(tool_trace)}" fn = tc.get("function") or {} fn_name = str(fn.get("name") or "") raw_args = fn.get("arguments") or "{}" try: parsed_args = json.loads(raw_args) if isinstance(raw_args, str) else dict(raw_args) except Exception: parsed_args = {} try: mcp_res = await self.mcp_server.call_tool(fn_name, parsed_args) result_text, is_err = _serialize_tool_result(mcp_res) except Exception as exc: result_text = json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False) is_err = True tool_trace.append( { "name": fn_name, "arguments": parsed_args, "result": result_text, "is_error": is_err, } ) if on_tool_progress is not None: try: on_tool_progress(list(tool_trace)) except Exception: pass messages.append( { "role": "tool", "tool_call_id": tc_id, "name": fn_name, "content": result_text, } ) return { "ok": True, "reply": f"已达到单轮最大 MCP 工具调用次数({effective_max_steps} 步),可在「中心桥专用 AI 配置」或「全局设置」中调大上限,或继续追问。", "tool_trace": tool_trace, } class ChatSessionRunner: """Runs AI chat turns as detached Hub background tasks so closing the browser never aborts an active run.""" def __init__(self, db: PulseWallDB, agent: HubMcpChatAgent) -> None: self.db = db self.agent = agent self._tasks: dict[str, asyncio.Task[None]] = {} def is_running(self, session_id: str) -> bool: t = self._tasks.get(session_id) return t is not None and not t.done() def start_message_run(self, session_id: str, user_text: str) -> dict[str, Any]: sess = self.db.get_chat_session(session_id) if not sess: raise HTTPException(status_code=404, detail="会话不存在") if self.is_running(session_id) or sess.get("status") == "running": raise HTTPException(status_code=409, detail="该会话有 AI 回复正在后台执行中,请等待完成或切换到其他会话。") # Build prior conversation context from persisted SQLite messages before appending new turn existing_msgs = self.db.list_chat_messages(session_id) history = [ {"role": m["role"], "content": m["content"]} for m in existing_msgs if m["role"] in ("user", "assistant") and m["status"] == "done" and m["content"] ] # Auto-name untitled session using first user message if sess["title"] in ("新会话", "未命名会话", "") and len(existing_msgs) == 0: auto_title = user_text.strip().replace("\n", " ")[:24] if len(user_text.strip()) > 24: auto_title += "…" self.db.rename_chat_session(session_id, auto_title or "新会话") run_id = f"run_{uuid.uuid4().hex[:10]}" user_msg = self.db.add_chat_message(session_id, "user", user_text, status="done", run_id=run_id) assistant_msg = self.db.add_chat_message(session_id, "assistant", "", tool_trace=[], status="running", run_id=run_id) self.db.set_chat_session_status(session_id, "running", active_run_id=run_id) task = asyncio.create_task( self._execute_run( session_id=session_id, run_id=run_id, assistant_msg_id=int(assistant_msg["id"]), user_text=user_text, history=history, ) ) self._tasks[session_id] = task task.add_done_callback(lambda _t, sid=session_id: self._cleanup_task(sid, _t)) return { "ok": True, "run_id": run_id, "session": self.db.get_chat_session(session_id), "user_message": user_msg, "assistant_message": assistant_msg, } def _cleanup_task(self, session_id: str, task: asyncio.Task[None]) -> None: if self._tasks.get(session_id) is task: del self._tasks[session_id] async def _execute_run( self, session_id: str, run_id: str, assistant_msg_id: int, user_text: str, history: list[dict[str, Any]], ) -> None: def on_progress(trace: list[dict[str, Any]]) -> None: self.db.update_chat_message(assistant_msg_id, tool_trace=trace, status="running") try: res = await self.agent.chat( user_message=user_text, history=history, on_tool_progress=on_progress, ) if res.get("ok"): self.db.update_chat_message( assistant_msg_id, role="assistant", content=str(res.get("reply") or "操作已完成。"), tool_trace=res.get("tool_trace") or [], status="done", ) else: self.db.update_chat_message( assistant_msg_id, role="error", content=str(res.get("error") or "调用失败"), tool_trace=res.get("tool_trace") or [], status="error", ) except asyncio.CancelledError: self.db.update_chat_message( assistant_msg_id, role="error", content="后台任务已取消。", status="error", ) raise except Exception as exc: self.db.update_chat_message( assistant_msg_id, role="error", content=f"后台执行异常: {exc}", status="error", ) finally: self.db.set_chat_session_status(session_id, "idle", active_run_id="") def cancel_session_run(self, session_id: str) -> bool: t = self._tasks.get(session_id) if t and not t.done(): t.cancel() return True return False def cancel_all(self) -> None: for t in list(self._tasks.values()): if not t.done(): t.cancel() self._tasks.clear()