"""Built-in tool to list connected MCP servers and their exposed tools."""

from navi.mcp import McpManager

from .base import Tool, ToolResult


class McpStatusTool(Tool):
    name = "mcp_status"
    description = (
        "Show the status of all configured MCP servers and the tools they expose. "
        "Use this to discover what external tools are currently available."
    )
    parameters = {
        "type": "object",
        "properties": {},
        "required": [],
    }

    def __init__(self, manager: McpManager | None = None) -> None:
        self._manager = manager

    async def execute(self, params: dict) -> ToolResult:
        if self._manager is None:
            return ToolResult(
                success=False,
                output="",
                error="MCP manager not available.",
            )

        lines: list[str] = []
        for name, client in self._manager.clients.items():
            status = "connected" if client.connected else "disconnected"
            lines.append(f"Server: {name} ({status})")
            try:
                tools = await client.list_tools()
                for t in tools:
                    lines.append(f"  - {t.name}: {t.description or 'no description'}")
            except Exception as exc:
                lines.append(f"  (failed to list tools: {exc})")

        if not lines:
            return ToolResult(success=True, output="No MCP servers configured.")

        return ToolResult(success=True, output="\n".join(lines))
