JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: add toolslist of mcpserver details
huanggawab513ece7590e
diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex 97a52b0a20..e781d5c1bd 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -51,6 +51,25 @@ const PERMISSION_TOOL_RE = /工具\s+`([^`]+)`\s+需要授权/;const PERMISSION_RISK_RE = /安全风险评估:\**\s*([^\s*]+)?\s*\**([^*\n]+?风险)\**/m;const PERMISSION_QUOTE_RE = /^>\s*(.+)$/gm;const PERMISSION_JSON_BLOCK_RE = /```json\s*([\s\S]*?)\s*```/i;++function wrapText(text: string, maxWidth: number): string[] {+ if (maxWidth < 1) return [text];+ const words = text.split(/\s+/);+ const lines: string[] = [];+ let current = "";+ for (const word of words) {+ if (!word) continue;+ const test = current ? `${current} ${word}` : word;+ if (test.length > maxWidth && current) {+ lines.push(current);+ current = word;+ } else {+ current = test;+ }+ }+ if (current) lines.push(current);+ return lines.length > 0 ? lines : [""];+}const RUNNING_TIMER_RESET_GRACE_MS = 15_000;type PermissionSummary = {@@ -90,6 +109,25 @@ type McpDetailState = {actions: SelectList;};+type McpToolItem = {+ id: string;+ name: string;+ description: string;+ parameters: Record<string, unknown>;+ server_name: string;+};++type McpToolsState = {+ serverName: string;+ tools: McpToolItem[];+ list: SelectList;+};++type McpToolDetailState = {+ serverName: string;+ tool: McpToolItem;+};+type ConfigEditorPhase = "select_group" | "select_item" | "select_value" | "input_value";type ConfigEditorState = {@@ -414,6 +452,8 @@ export class AppScreen implements Component, Focusable {private modelList: ModelListState | null = null;private mcpList: McpListState | null = null;private mcpDetail: McpDetailState | null = null;+ private mcpTools: McpToolsState | null = null;+ private mcpToolDetail: McpToolDetailState | null = null;private themeList: ThemeListState | null = null;private configEditorState: ConfigEditorState | null = null;private statusViewState: StatusViewState | null = null;@@ -546,7 +586,16 @@ export class AppScreen implements Component, Focusable {? isPermissionRequest(pendingQuestion?.source, activeQuestion.question): false;- if (!pendingQuestion && snapshot.cancellableWork && matchesKey(data, "escape")) {+ const hasOverlay =+ this.mcpDetail !== null ||+ this.mcpToolDetail !== null ||+ this.mcpList !== null ||+ this.mcpTools !== null ||+ this.modelList !== null ||+ this.themeList !== null ||+ this.configEditorState !== null;++ if (!pendingQuestion && snapshot.cancellableWork && matchesKey(data, "escape") && !hasOverlay) {this.state.cancel();return;}@@ -734,8 +783,37 @@ export class AppScreen implements Component, Focusable {return;}- if (!snapshot.pendingQuestion && this.mcpDetail !== null) {- this.mcpDetail.actions.handleInput(data);+ if (this.mcpDetail !== null) {+ if (matchesKey(data, "escape")) {+ this.mcpDetail = null;+ this.openMcpList();+ return;+ }+ if (!snapshot.pendingQuestion) {+ this.mcpDetail.actions.handleInput(data);+ }+ this.tui.requestRender();+ return;+ }++ if (this.mcpToolDetail !== null) {+ if (matchesKey(data, "escape")) {+ const serverName = this.mcpToolDetail.serverName;+ this.mcpToolDetail = null;+ void this.openMcpToolsList(serverName);+ return;+ }+ return;+ }++ if (this.mcpTools !== null) {+ if (matchesKey(data, "escape")) {+ const serverName = this.mcpTools.serverName;+ this.mcpTools = null;+ void this.handleMcpSelection(serverName);+ return;+ }+ this.mcpTools.list.handleInput(data);this.tui.requestRender();return;}@@ -828,6 +906,8 @@ export class AppScreen implements Component, Focusable {...this.buildModelListLines(width),...this.buildMcpListLines(width),...this.buildMcpDetailLines(width),+ ...this.buildMcpToolsLines(width),+ ...this.buildMcpToolDetailLines(width),...this.buildThemeListLines(width),...this.buildPendingQuestionLines(snapshot, width),];@@ -1330,7 +1410,6 @@ export class AppScreen implements Component, Focusable {}private async handleMcpSelection(serverName: string): Promise<void> {- this.mcpList = null;const snapshot = this.state.getSnapshot();try {const payload = await this.state.request<{@@ -1340,6 +1419,7 @@ export class AppScreen implements Component, Focusable {if (payload.type === "detail" && payload.item) {const enabled = Boolean(payload.item.enabled !== false);const actionItems: SelectItem[] = [];+ actionItems.push({ label: "View tools", value: "view_tools", description: "Browse tools from this server" });if (enabled) {actionItems.push({ label: "Disable", value: "disable", description: "Stop and disable this server" });} else {@@ -1355,8 +1435,9 @@ export class AppScreen implements Component, Focusable {};actionsList.onCancel = () => {this.mcpDetail = null;- this.tui.requestRender();+ this.openMcpList();};+ this.mcpList = null;this.mcpDetail = {serverName,info: payload.item,@@ -1365,20 +1446,28 @@ export class AppScreen implements Component, Focusable {};this.tui.requestRender();} else {+ this.mcpList = null;this.state.addItem(addError(snapshot.sessionId, `MCP server '${serverName}' not found`));+ this.tui.requestRender();}} catch (error) {const message = error instanceof Error ? error.message : String(error);+ this.mcpList = null;this.state.addItem(addError(snapshot.sessionId, `mcp show failed: ${message}`));+ this.tui.requestRender();}}private async handleMcpDetailAction(serverName: string, action: string): Promise<void> {- this.mcpDetail = null;const snapshot = this.state.getSnapshot();try {+ if (action === "view_tools") {+ await this.openMcpToolsList(serverName);+ return;+ }if (action === "enable" || action === "disable" || action === "remove") {await this.state.request("command.mcp", { action, name: serverName });+ this.mcpDetail = null;if (action === "remove") {this.state.addItem(addInfo(snapshot.sessionId, `MCP server removed: ${serverName}`, "m"));this.tui.requestRender();@@ -1389,6 +1478,7 @@ export class AppScreen implements Component, Focusable {}} catch (error) {const message = error instanceof Error ? error.message : String(error);+ this.mcpDetail = null;this.state.addItem(addError(snapshot.sessionId, `mcp ${action} failed: ${message}`));this.tui.requestRender();}@@ -1465,6 +1555,140 @@ export class AppScreen implements Component, Focusable {return lines;}+ private async openMcpToolsList(serverName: string): Promise<void> {+ const snapshot = this.state.getSnapshot();+ try {+ const payload = await this.state.request<{+ type: string;+ tools: McpToolItem[];+ server_name: string;+ }>("command.mcp", { action: "list_tools", name: serverName });+ const tools = payload.tools ?? [];+ const toolItems: SelectItem[] = tools.map((t) => ({+ label: t.name,+ value: t.id,+ description: t.description ? (t.description.length > 60 ? t.description.slice(0, 57) + "..." : t.description) : "",+ }));+ const list = new SelectList(toolItems, Math.min(Math.max(toolItems.length, 1), 10), selectListTheme, {+ minPrimaryColumnWidth: 24,+ maxPrimaryColumnWidth: 50,+ });+ list.onSelect = (item) => {+ const tool = tools.find((t) => t.id === item.value);+ if (tool) {+ this.mcpToolDetail = { serverName, tool };+ this.tui.requestRender();+ }+ };+ list.onCancel = () => {+ this.mcpTools = null;+ void this.handleMcpSelection(serverName);+ };+ this.mcpDetail = null;+ this.mcpTools = { serverName, tools, list };+ this.tui.requestRender();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.mcpDetail = null;+ this.state.addItem(addError(snapshot.sessionId, `mcp list_tools failed: ${message}`));+ this.tui.requestRender();+ }+ }++ private buildMcpToolsLines(width: number): string[] {+ if (!this.mcpTools || this.mcpToolDetail) return [];+ const { serverName, tools, list } = this.mcpTools;+ const lines: string[] = [];++ const borderFn = palette.border.panel;+ const borderV = "│";+ const contentWidth = Math.max(1, width - 6);+ const innerWidth = contentWidth + 2;++ const boxedLines: string[] = [];+ boxedLines.push(padToWidth(palette.status.warning(`Tools for ${serverName} (${tools.length} tool${tools.length === 1 ? "" : "s"})`), contentWidth));++ if (tools.length === 0) {+ boxedLines.push(padToWidth(palette.text.dim(" No tools available. Enable the server first."), contentWidth));+ } else {+ const listLines = list.render(contentWidth);+ boxedLines.push(...listLines);+ }++ // Top border+ lines.push(" " + borderFn("╭" + "─".repeat(innerWidth) + "╮"));+ for (const bl of boxedLines) {+ lines.push(" " + borderFn(borderV) + " " + padToWidth(bl, contentWidth) + " " + borderFn(borderV));+ }+ lines.push(" " + borderFn("╰" + "─".repeat(innerWidth) + "╯"));++ lines.push(padToWidth(palette.text.dim("↑/↓ choose · Enter view detail · Esc back"), width));+ return lines;+ }++ private buildMcpToolDetailLines(width: number): string[] {+ if (!this.mcpToolDetail) return [];+ const { serverName, tool } = this.mcpToolDetail;+ const lines: string[] = [];++ const borderFn = palette.border.panel;+ const borderV = "│";+ const contentWidth = Math.max(1, width - 6);+ const innerWidth = contentWidth + 2;++ const boxedLines: string[] = [];++ // Title: toolname (serverName)+ boxedLines.push(padToWidth(palette.status.warning(`${tool.name} (${serverName})`), contentWidth));++ // Tool name / Full name+ boxedLines.push(padToWidth("", contentWidth));+ boxedLines.push(padToWidth(`Tool name: ${tool.name}`, contentWidth));+ boxedLines.push(padToWidth(`Full name: mcp__${serverName}__${tool.name}`, contentWidth));++ // Description+ if (tool.description) {+ boxedLines.push(padToWidth("", contentWidth));+ boxedLines.push(padToWidth("Description:", contentWidth));+ const descLines = wrapText(tool.description, contentWidth - 2);+ for (const dl of descLines) {+ boxedLines.push(padToWidth(` ${dl}`, contentWidth));+ }+ }++ // Parameters+ if (tool.parameters && typeof tool.parameters === "object") {+ const params = tool.parameters as Record<string, unknown>;+ const properties = params.properties as Record<string, unknown> | undefined;+ if (properties && Object.keys(properties).length > 0) {+ boxedLines.push(padToWidth("", contentWidth));+ boxedLines.push(padToWidth("Parameters:", contentWidth));+ for (const [paramName, paramDef] of Object.entries(properties)) {+ const def = paramDef as Record<string, unknown>;+ const typeStr = def.type ? String(def.type) : "any";+ const required = Array.isArray(params.required) && params.required.includes(paramName);+ const reqMark = required ? " (required)" : "";+ const descText = def.description ? ` - ${String(def.description)}` : "";+ const paramLine = ` • ${paramName}${reqMark}: ${typeStr}${descText}`;+ const paramLines = wrapText(paramLine, contentWidth - 2);+ for (const pl of paramLines) {+ boxedLines.push(padToWidth(pl, contentWidth));+ }+ }+ }+ }++ // Top border+ lines.push(" " + borderFn("╭" + "─".repeat(innerWidth) + "╮"));+ for (const bl of boxedLines) {+ lines.push(" " + borderFn(borderV) + " " + padToWidth(bl, contentWidth) + " " + borderFn(borderV));+ }+ lines.push(" " + borderFn("╰" + "─".repeat(innerWidth) + "╯"));++ lines.push(padToWidth(palette.text.dim("Esc to go back"), width));+ return lines;+ }+private openThemeList(): void {const snapshot = this.state.getSnapshot();const current = snapshot.themeName ?? "dark";diff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.pyindex dc2f51f64c..2ba51006b1 100644--- a/jiuwenclaw/server/agent_ws_server.py+++ b/jiuwenclaw/server/agent_ws_server.py@@ -1374,6 +1374,72 @@ class AgentWebSocketServer:return [AgentWebSocketServer._mask_sensitive_fields(item) for item in payload]return payload+ @staticmethod+ async def _fetch_mcp_tools_from_config(entry: dict[str, Any]) -> list[dict[str, Any]]:+ """Create a temporary MCP connection from config entry and list tools."""+ from openjiuwen.core.foundation.tool import McpServerConfig+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ name = str(entry.get("name", "")).strip()+ transport = str(entry.get("transport", "")).strip().lower()+ if not name or transport not in {"stdio", "sse"}:+ logger.warning("[command.mcp] _fetch skipped: name=%r transport=%r", name, transport)+ return []++ # Build McpServerConfig same as interface_deep._build_mcp_server_config+ payload: dict[str, Any] = {"server_name": name, "client_type": transport}+ if transport == "stdio":+ command = str(entry.get("command", "")).strip()+ if not command:+ logger.warning("[command.mcp] _fetch skipped: no command for stdio")+ return []+ params: dict[str, Any] = {"command": command}+ if isinstance(entry.get("args"), list):+ params["args"] = [str(x) for x in entry["args"]]+ if isinstance(entry.get("cwd"), str) and entry["cwd"].strip():+ params["cwd"] = entry["cwd"].strip()+ if isinstance(entry.get("env"), dict):+ params["env"] = {str(k): str(v) for k, v in entry["env"].items()}+ payload["server_path"] = f"stdio://{name}"+ payload["params"] = params+ else:+ url = str(entry.get("url", "")).strip()+ if not url:+ logger.warning("[command.mcp] _fetch skipped: no url for sse")+ return []+ payload["server_path"] = url+ params = {}+ if isinstance(entry.get("headers"), dict):+ params["headers"] = {str(k): str(v) for k, v in entry["headers"].items()}+ if params:+ payload["params"] = params++ cfg = McpServerConfig(**payload)+ client = ToolMgr._create_client(cfg)+ try:+ connected = await client.connect()+ if not connected:+ return []+ cards = await client.list_tools()+ tools_info = []+ for card in (cards or []):+ params_schema = card.input_params if hasattr(card, "input_params") else {}+ if hasattr(params_schema, "model_dump"):+ params_schema = params_schema.model_dump()+ tools_info.append({+ "id": card.id,+ "name": card.name,+ "description": card.description or "",+ "parameters": params_schema,+ "server_name": name,+ })+ return tools_info+ finally:+ try:+ await client.disconnect()+ except Exception as exc:+ logger.warning("[command.mcp] _fetch disconnect failed: %s", exc)+@staticmethoddef _normalize_mcp_payload(params: dict[str, Any], current: dict[str, Any] | None = None@@ -1450,11 +1516,43 @@ class AgentWebSocketServer:item = get_mcp_server_config(name)if item is None:raise KeyError(f"MCP server '{name}' not found")+ masked = self._mask_sensitive_fields(item)+ # Enrich with tool count+ tool_count = 0+ try:+ from openjiuwen.core.runner import Runner+ resource_registry = getattr(Runner.resource_mgr, "_resource_registry", None)+ if resource_registry is not None:+ tool_mgr = resource_registry.tool()+ server_ids = tool_mgr.get_mcp_server_ids(name)+ if not server_ids:+ for sid, res in getattr(tool_mgr, "_mcp_server_resources", {}).items():+ if getattr(res.config, "server_name", "") == name:+ server_ids.append(sid)+ _seen: set[str] = set()+ for sid in server_ids:+ for _tid in tool_mgr.get_mcp_tool_ids(sid):+ _t = getattr(tool_mgr, "_tools", {}).get(_tid)+ if _t is not None and hasattr(_t, "card"):+ _n = _t.card.name+ if _n not in _seen:+ _seen.add(_n)+ tool_count += 1+ except Exception as exc:+ logger.debug("[command.mcp] show tool_count from ToolMgr failed: %s", exc)+ # If ToolMgr has no data, try temporary connection+ if tool_count == 0 and bool(item.get("enabled", True)):+ try:+ tools = await self._fetch_mcp_tools_from_config(item)+ tool_count = len(tools)+ except Exception as exc:+ logger.warning("[command.mcp] show tool_count from temp connection failed: %s", exc)+ masked["tool_count"] = tool_countresp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,ok=True,- payload={"type": "detail", "item": self._mask_sensitive_fields(item)},+ payload={"type": "detail", "item": masked},)else:enabled_items = [@@ -1572,8 +1670,61 @@ class AgentWebSocketServer:ok=True,payload=payload,)+ elif action == "list_tools":+ name = str(params.get("name", "")).strip()+ if not name:+ raise ValueError("MCP server name is required")+ tools_info: list[dict[str, Any]] = []+ # 1) Try from ToolMgr (already registered)+ try:+ from openjiuwen.core.runner import Runner+ resource_registry = getattr(Runner.resource_mgr, "_resource_registry", None)+ if resource_registry is not None:+ tool_mgr = resource_registry.tool()+ server_ids = list(tool_mgr.get_mcp_server_ids(name))+ if not server_ids:+ for sid, res in getattr(tool_mgr, "_mcp_server_resources", {}).items():+ if getattr(res.config, "server_name", "") == name:+ server_ids.append(sid)+ seen_tool_names: set[str] = set()+ for sid in server_ids:+ tool_ids = tool_mgr.get_mcp_tool_ids(sid)+ for tid in tool_ids:+ tool = getattr(tool_mgr, "_tools", {}).get(tid)+ if tool is not None and hasattr(tool, "card"):+ card = tool.card+ if card.name in seen_tool_names:+ continue+ seen_tool_names.add(card.name)+ params_schema = card.input_params if hasattr(card, "input_params") else {}+ if hasattr(params_schema, "model_dump"):+ params_schema = params_schema.model_dump()+ tools_info.append({+ "id": card.id,+ "name": card.name,+ "description": card.description or "",+ "parameters": params_schema,+ "server_name": name,+ })+ except Exception as exc:+ logger.debug("[command.mcp] list_tools from ToolMgr failed: %s", exc)+ # 2) If no tools found, try temporary MCP connection from config+ if not tools_info:+ try:+ config_entry = get_mcp_server_config(name)+ if config_entry and bool(config_entry.get("enabled", True)):+ tools_info = await self._fetch_mcp_tools_from_config(config_entry)+ except Exception as exc:+ logger.warning("[command.mcp] list_tools from temp connection failed: %s", exc)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"type": "tools", "tools": tools_info, "server_name": name},+ )else:- raise ValueError("Unsupported action, must be one of list|show|add|update|enable|disable|remove")+ raise ValueError("Unsupported action, must be one of " \+ "list|show|add|update|enable|disable|remove|list_tools")except KeyError as exc:resp = AgentResponse(request_id=request.request_id,