import gradio as gr import asyncio import json import logging from typing import List, Dict, Any, Tuple from dataclasses import dataclass, field import requests from smolagents.mcp_client import MCPClient # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def get_tools(url): tools = [] with MCPClient({"url": url}) as tool_objs: for t in tool_objs: tools.append(t) # Logging tool names and count logger.info(f"[get_tools] Found {len(tools)} tools:") for t in tools: logger.info(f" - {t.name}") return tools @dataclass class MCPSSEServerConfig: name: str url: str headers: Dict[str, str] = field(default_factory=dict) timeout: int = 50 sse_read_timeout: int = 50 class FastAgentMCPClient: def __init__(self, config: MCPSSEServerConfig): self.config = config self.session = None self.tools = [] self.connected = False self.client_session = None async def connect(self): """Establish connection using smolagents[mcp] MCPClient for tool listing""" try: logger.info(f"Connecting to {self.config.name} using smolagents[mcp] MCPClient for tool listing") # Use MCPClient from smolagents to list tools loop = asyncio.get_event_loop() self.tools = await loop.run_in_executor(None, lambda: get_tools(self.config.url)) self.connected = True logger.info(f"Successfully connected to {self.config.name} with {len(self.tools)} tools (smolagents)") except Exception as e: logger.error(f"Failed to connect to {self.config.name} using smolagents[mcp]: {e}") # Fallback to manual SSE implementation await self._fallback_connect() async def _fallback_connect(self): """Fallback connection method using smolagents[mcp] MCPClient for tool listing""" try: logger.info(f"Attempting fallback connection for {self.config.name} using smolagents[mcp] MCPClient") loop = asyncio.get_event_loop() self.tools = await loop.run_in_executor(None, lambda: get_tools(self.config.url)) self.connected = True logger.info(f"Fallback connection successful for {self.config.name} (smolagents)") except Exception as e: logger.warning(f"Fallback connection failed for {self.config.name}: {e}") self.connected = True self.tools = [] logger.info(f"Graceful connection established for {self.config.name} (no tools)") async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any: """Call a tool using smolagents[mcp] MCPClient only""" try: loop = asyncio.get_event_loop() def call_tool_sync(url, tool_name, arguments): with MCPClient({"url": url}) as tool_objs: tool_obj = next((t for t in tool_objs if t.name == tool_name), None) if not tool_obj: return [{"type": "text", "text": f"Error: Tool '{tool_name}' not found"}] return tool_obj.call(**arguments) result = await loop.run_in_executor(None, call_tool_sync, self.config.url, tool_name, arguments) return result except Exception as e: logger.error(f"smolagents tool call failed: {e}") return [{"type": "text", "text": f"Error: {str(e)}"}] async def close(self): self.connected = False class MCPChatbot: def __init__(self, anthropic_api_key: str, mcp_servers: Dict[str, MCPSSEServerConfig]): self.api_key = anthropic_api_key self.mcp_servers = mcp_servers self.clients = {} self.available_tools = {} async def initialize_mcp_servers(self): """Initialize connections to all MCP SSE servers using fast-agent-mcp""" for server_name, server_config in self.mcp_servers.items(): try: logger.info(f"Connecting to MCP SSE server: {server_name}") client = FastAgentMCPClient(server_config) await client.connect() self.clients[server_name] = client self.available_tools[server_name] = client.tools if client.connected: logger.info(f"Successfully connected to {server_name} with {len(client.tools)} tools") else: logger.warning(f"Partial connection to {server_name}") except Exception as e: logger.error(f"Failed to connect to {server_name}: {e}") continue def format_tools_for_claude(self) -> List[Dict]: """Format tools from MCP for Claude API with enhanced context""" claude_tools = [] for server_name, tools in self.available_tools.items(): for tool in tools: server_context = "" if server_name == "burp_mcp": server_context = " (Burp Suite - Web Security Testing)" elif server_name == "viper_mcp": server_context = " (Metasploit - Penetration Testing)" tool_description = getattr(tool, 'description', f"Tool from {server_name}") enhanced_description = f"{tool_description}{server_context}" claude_tool = { "name": f"{server_name}_{getattr(tool, 'name', 'unknown')}", "description": enhanced_description, "input_schema": getattr(tool, 'input_schema', { "type": "object", "properties": {}, "required": [] }) } claude_tools.append(claude_tool) return claude_tools def _get_server_capabilities(self, server_name: str) -> List[str]: capabilities_map = { "burp_mcp": [ "Web application security testing", "Vulnerability scanning", "HTTP request/response analysis", "Spider/crawling functionality", "Intruder attacks", "Repeater functionality" ], "viper_mcp": [ "Penetration testing", "Exploit development", "Payload generation", "Network reconnaissance", "Post-exploitation", "Metasploit module execution" ] } return capabilities_map.get(server_name, []) async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any: parts = tool_name.rsplit('_', 1) if len(parts) < 2: raise ValueError(f"Invalid tool name format: {tool_name}") server_name = parts[0] actual_tool_name = parts[1] if server_name not in self.clients: raise ValueError(f"Server {server_name} not available") client = self.clients[server_name] if not client.connected: raise ValueError(f"Server {server_name} not connected") try: result = await client.call_tool(actual_tool_name, arguments) return result except Exception as e: logger.error(f"Error executing tool {tool_name}: {e}") return [{"type": "text", "text": f"Error: {str(e)}"}] async def chat(self, message: str, history: list) -> tuple: try: # Build mcp_servers payload for Anthropic API mcp_servers = [] for server_name, server_config in self.mcp_servers.items(): mcp_server = { "type": "url", "url": server_config.url, "name": server_name } if "Authorization" in server_config.headers: mcp_server["authorization_token"] = server_config.headers["Authorization"] mcp_servers.append(mcp_server) def filter_message_fields(msg): return {"role": msg.get("role"), "content": msg.get("content")} messages = [] if history: for msg in history[-10:]: if isinstance(msg, dict) and "role" in msg and "content" in msg: messages.append(filter_message_fields(msg)) messages.append({"role": "user", "content": message}) payload = { "model": "claude-3-5-sonnet-20241022", "max_tokens": 1000, "messages": messages, "mcp_servers": mcp_servers, "temperature": 0.1, "system": "You are Klaide, a Kali Linux AI Desktop assistant." } logger.info(f"[Anthropic API] Payload: {json.dumps(payload, indent=2)}") headers = { "Content-Type": "application/json", "X-API-Key": self.api_key, "anthropic-version": "2023-06-01", "anthropic-beta": "mcp-client-2025-04-04" } url = "https://api.anthropic.com/v1/messages" resp = requests.post(url, headers=headers, data=json.dumps(payload)) if resp.status_code != 200: raise Exception(f"Anthropic API error: {resp.status_code} - {resp.text}") response = resp.json() assistant_message = "" for content in response.get("content", []): if content.get("type") == "text": assistant_message += content.get("text", "") elif content.get("type") == "mcp_tool_result": for item in content.get("content", []): if isinstance(item, dict) and item.get("type") == "text": assistant_message += f"\nšŸ“Š **Tool Result**: {item.get('text', '')}\n" else: assistant_message += f"\nšŸ“Š **Tool Result**: {json.dumps(item, indent=2, ensure_ascii=False)}\n" history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": assistant_message} ] return history, "" except Exception as e: error_msg = f"āŒ **Error**: {str(e)}" history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": error_msg} ] return history, "" async def _build_messages_with_context(self, message: str, history: List[List[str]], tools_context: str) -> Tuple[str, List[Dict]]: system_content = f"""You are Klaide, a Kali Linux AI Desktop assistant that controls cybersecurity tools through MCP servers.\nYou help users perform penetration testing, vulnerability assessment, and security analysis.\n\n{tools_context}\n\nInstructions:\n1. Analyze the user's request in the context of available MCP tools\n2. Use the appropriate tools for cybersecurity tasks\n3. Provide helpful guidance and explanations\n4. Be specific about which Kali Linux tools or techniques to use\n5. Always prioritize security and ethical hacking practices\n6. When using tools, explain what you're doing and why\n\nAvailable tool format: Use the tools provided in the tools list for executing commands.""" messages = [] if history: for user_msg, assistant_msg in history[-5:]: messages.append({"role": "user", "content": user_msg}) if assistant_msg: messages.append({"role": "assistant", "content": assistant_msg}) messages.append({"role": "user", "content": message}) return system_content, messages async def _get_tools_context(self) -> str: context_parts = [] context_parts.append("=== MCP SERVERS CONTEXT ===") for server_name, client in self.clients.items(): if not client.connected: continue context_parts.append(f"\n[{server_name.upper()} SERVER]") context_parts.append(f"URL: {client.config.url}") context_parts.append(f"Status: Connected") tools = self.available_tools.get(server_name, []) context_parts.append(f"Available Tools: {len(tools)}") if tools: context_parts.append("Tools List:") for tool in tools: tool_name = getattr(tool, 'name', 'unknown') tool_desc = getattr(tool, 'description', 'No description') context_parts.append(f" - {tool_name}: {tool_desc}") schema = getattr(tool, 'input_schema', {}) if schema and isinstance(schema, dict) and schema.get('properties'): props = list(schema['properties'].keys()) context_parts.append(f" Parameters: {', '.join(props)}") if server_name == "burp_mcp": context_parts.append("Capabilities:") context_parts.append(" - Web application security testing") context_parts.append(" - Vulnerability scanning") context_parts.append(" - HTTP request/response analysis") context_parts.append(" - Burp Suite integration") elif server_name == "viper_mcp": context_parts.append("Capabilities:") context_parts.append(" - Penetration testing") context_parts.append(" - Exploit development") context_parts.append(" - Metasploit Framework integration") context_parts.append(" - Payload generation") connected_count = sum(1 for client in self.clients.values() if client.connected) total_tools = sum(len(tools) for tools in self.available_tools.values()) context_parts.append(f"\n[SYSTEM STATUS]") context_parts.append(f"Connected Servers: {connected_count}/{len(self.clients)}") context_parts.append(f"Total Available Tools: {total_tools}") context_parts.append(f"MCP Client: Fast-Agent-MCP") return "\n".join(context_parts) async def get_server_status(self) -> str: return await self._get_tools_context() def create_mcp_servers_config(burp_url: str, viper_url: str) -> Dict[str, MCPSSEServerConfig]: servers = {} if burp_url.strip(): servers["burp_mcp"] = MCPSSEServerConfig( name="burp_mcp", url=burp_url.strip(), headers={}, timeout=50, sse_read_timeout=50 ) if viper_url.strip(): servers["viper_mcp"] = MCPSSEServerConfig( name="viper_mcp", url=viper_url.strip(), headers={}, timeout=50, sse_read_timeout=50 ) return servers chatbot = None async def initialize_chatbot(api_key: str, burp_url: str, viper_url: str): global chatbot if not api_key: return "āŒ Please enter Anthropic API Key" if not burp_url.strip() and not viper_url.strip(): return "āŒ Please enter at least one MCP server URL" try: mcp_servers = create_mcp_servers_config(burp_url, viper_url) chatbot = MCPChatbot(api_key, mcp_servers) await chatbot.initialize_mcp_servers() connected_servers = [name for name, client in chatbot.clients.items() if client.connected] total_tools = sum(len(tools) for tools in chatbot.available_tools.values()) if connected_servers: status_msg = f"āœ… Klaide successfully initialized with Fast-Agent-MCP!\n" status_msg += f"šŸ”— Connected servers: {', '.join(connected_servers)}\n" status_msg += f"šŸ› ļø Total tools available: {total_tools}\n" status_msg += f"šŸš€ MCP Client: Fast-Agent-MCP with fallback support\n" for server_name, client in chatbot.clients.items(): if client.connected: method = "Native" if client.client_session else "Fallback" status_msg += f"šŸ“” {server_name}: {method} connection\n" return status_msg else: return "āš ļø Klaide initialized but no servers connected. Please check your URLs." except Exception as e: return f"āŒ Initialization error: {str(e)}" async def chat_wrapper(message, history): if not chatbot: history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": "āŒ Klaide not initialized. Please enter API Key first."} ] return history, "" return await chatbot.chat(message, history) async def get_status(): if not chatbot: return "āŒ Klaide not initialized" return await chatbot.get_server_status() async def cleanup(): global chatbot if chatbot: await chatbot.close_all_connections() def create_interface(): with gr.Blocks(title="Klaide (Kali Linux AI Desktop)", theme=gr.themes.Soft()) as demo: gr.Markdown("# šŸ‰ Klaide (**Kali Linux AI Desktop**)") gr.Markdown("Controlling Kali Linux Desktop with AI using MCP Server.") with gr.Tab("šŸ’¬ Console"): with gr.Row(): with gr.Column(scale=3): chatbot_ui = gr.Chatbot( label="Klaide Console", height=500, show_copy_button=True, avatar_images=("assets/user.png", "assets/csalab.png"), type="messages" ) with gr.Row(): msg = gr.Textbox( placeholder="Ask Klaide to control your Kali Linux tools...", label="Command Prompt", scale=4 ) send_btn = gr.Button("Send", scale=1, variant="primary") with gr.Tab("āš™ļø Settings"): gr.Markdown("## Setup Configuration") with gr.Row(): with gr.Column(): api_key_input = gr.Textbox( label="Anthropic API Key", type="password", placeholder="sk-ant-...", info="Required: Your Anthropic Claude API key" ) burp_url_input = gr.Textbox( label="Burp MCP Server URL", placeholder="https://burp.csalab.app/sse", value="https://burp.csalab.app/sse", info="Optional: URL for Burp Suite MCP server" ) viper_url_input = gr.Textbox( label="Viper MCP Server URL", placeholder="https://msf.csalab.app/your-id/sse", value="https://msf.csalab.app/3cbf712b45cc11f0/sse", info="Optional: URL for Metasploit MCP server" ) with gr.Row(): init_btn = gr.Button("Initialize Klaide", variant="primary", scale=2) test_urls_btn = gr.Button("Test URLs", variant="secondary", scale=1) init_status = gr.Textbox( label="Klaide Status", interactive=False, lines=4 ) with gr.Accordion("Advanced Settings", open=False): gr.Markdown("### Timeout Configuration") timeout_slider = gr.Slider( minimum=10, maximum=120, value=50, step=5, label="Connection Timeout (seconds)", info="Timeout for server connections and requests" ) gr.Markdown("### Custom Headers") custom_headers = gr.Textbox( label="Custom Headers (JSON format)", placeholder='{"Authorization": "Bearer token", "X-API-Key": "key"}', info="Optional: Custom headers for server requests" ) with gr.Tab("šŸ“Š Server Status"): status_btn = gr.Button("Refresh Status") status_display = gr.Textbox( label="Status", lines=4 ) def chat_fn(message, history): try: result = asyncio.run(chat_wrapper(message, history)) if isinstance(result, tuple) and len(result) == 2: return result # fallback: return empty chat if error return history, "" except Exception as e: # fallback: return error in chat if isinstance(history, list): history = history + [ {"role": "user", "content": message}, {"role": "assistant", "content": f"āŒ Error: {str(e)}"} ] return history, "" def init_fn(api_key, burp_url, viper_url): return asyncio.run(initialize_chatbot(api_key, burp_url, viper_url)) def status_fn(): return asyncio.run(get_status()) async def test_urls_async(burp_url, viper_url): results = [] if burp_url.strip(): burp_result = await test_single_url_fast_agent("Burp", burp_url.strip()) results.append(burp_result) else: results.append("ā­ļø Burp Server: URL not provided") if viper_url.strip(): viper_result = await test_single_url_fast_agent("Viper", viper_url.strip()) results.append(viper_result) else: results.append("ā­ļø Viper Server: URL not provided") return "\n".join(results) async def test_single_url_fast_agent(server_name, url): test_results = [] try: config = MCPSSEServerConfig(name=f"test_{server_name.lower()}", url=url) test_client = FastAgentMCPClient(config) config.timeout = 10 await test_client.connect() if test_client.connected: tool_count = len(test_client.tools) if test_client.client_session: test_results.append(f"āœ… {server_name} Server: Fast-Agent-MCP native ({tool_count} tools)") else: test_results.append(f"āœ… {server_name} Server: Fast-Agent-MCP fallback ({tool_count} tools)") await test_client.close() return "\n".join(test_results) else: test_results.append(f"āš ļø {server_name} Server: Fast-Agent-MCP failed") await test_client.close() except Exception as e: test_results.append(f"āŒ {server_name} Server: Fast-Agent-MCP error - {str(e)[:50]}...") return "\n".join(test_results) def test_urls_fn(burp_url, viper_url): return asyncio.run(test_urls_async(burp_url, viper_url)) send_btn.click( chat_fn, inputs=[msg, chatbot_ui], outputs=[chatbot_ui, msg] ) msg.submit( chat_fn, inputs=[msg, chatbot_ui], outputs=[chatbot_ui, msg] ) init_btn.click( init_fn, inputs=[api_key_input, burp_url_input, viper_url_input], outputs=[init_status] ) test_urls_btn.click( test_urls_fn, inputs=[burp_url_input, viper_url_input], outputs=[init_status] ) status_btn.click( status_fn, outputs=[status_display] ) demo.load(None, None, None) return demo if __name__ == "__main__": try: demo = create_interface() demo.launch( server_name="0.0.0.0", server_port=7860, share=True, debug=True ) finally: asyncio.run(cleanup())