File size: 24,421 Bytes
ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 e39b1bb ae1f568 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
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()) |