SAUSERLA commited on
Commit
37f9172
·
verified ·
1 Parent(s): 33b7766

Upload 5 files

Browse files
Files changed (3) hide show
  1. Dockerfile +4 -1
  2. README.md +26 -1
  3. mcp_server.py +169 -0
Dockerfile CHANGED
@@ -1,6 +1,6 @@
1
  FROM kalilinux/kali-rolling
2
 
3
- # Install Python and Flask
4
  RUN apt-get update && apt-get install -y \
5
  python3 \
6
  python3-pip \
@@ -8,6 +8,9 @@ RUN apt-get update && apt-get install -y \
8
  python3-requests \
9
  && rm -rf /var/lib/apt/lists/*
10
 
 
 
 
11
  # Install essential Kali tools
12
  RUN apt-get update && apt-get install -y \
13
  nmap \
 
1
  FROM kalilinux/kali-rolling
2
 
3
+ # Install Python and dependencies
4
  RUN apt-get update && apt-get install -y \
5
  python3 \
6
  python3-pip \
 
8
  python3-requests \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
+ # Install MCP SDK
12
+ RUN pip3 install --break-system-packages mcp requests
13
+
14
  # Install essential Kali tools
15
  RUN apt-get update && apt-get install -y \
16
  nmap \
README.md CHANGED
@@ -86,9 +86,34 @@ GET /mcp/capabilities
86
 
87
  ## Usage with Cline
88
 
 
 
 
 
 
 
 
89
  1. **Deploy to Hugging Face Spaces**
90
  2. **Get your Space URL**: `https://your-username-kali-mcp.hf.space`
91
- 3. **Configure Cline** (if needed for custom MCP setup)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  The server exposes MCP-compatible endpoints that allow AI assistants to discover and execute Kali Linux tools.
94
 
 
86
 
87
  ## Usage with Cline
88
 
89
+ ### Local Development
90
+ ```bash
91
+ # Run the MCP server locally
92
+ python3 mcp_server.py
93
+ ```
94
+
95
+ ### Production Deployment
96
  1. **Deploy to Hugging Face Spaces**
97
  2. **Get your Space URL**: `https://your-username-kali-mcp.hf.space`
98
+ 3. **Configure Cline MCP settings**:
99
+
100
+ ```json
101
+ {
102
+ "mcpServers": {
103
+ "kali-tools": {
104
+ "command": "python3",
105
+ "args": ["/path/to/mcp_server.py"],
106
+ "env": {
107
+ "KALI_API_URL": "https://your-username-kali-mcp.hf.space"
108
+ }
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ ### Available Tools
115
+ - **execute_command**: Execute any shell command on Kali Linux
116
+ - **server_health**: Check server status and tool availability
117
 
118
  The server exposes MCP-compatible endpoints that allow AI assistants to discover and execute Kali Linux tools.
119
 
mcp_server.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import os
7
+ import sys
8
+ from typing import Any, Dict, List, Sequence
9
+
10
+ # MCP SDK imports
11
+ from mcp import Tool
12
+ from mcp.server import Server
13
+ from mcp.types import (
14
+ TextContent,
15
+ ImageContent,
16
+ EmbeddedResource,
17
+ LoggingLevel
18
+ )
19
+
20
+ # HTTP client for API calls
21
+ import requests
22
+
23
+ # Configure logging
24
+ logging.basicConfig(level=logging.INFO)
25
+ logger = logging.getLogger("kali-mcp-server")
26
+
27
+ # Configuration
28
+ KALI_API_URL = os.environ.get("KALI_API_URL", "https://sauserla-kali.hf.space")
29
+
30
+ class KaliMCPServer:
31
+ """MCP Server for Kali Linux tools"""
32
+
33
+ def __init__(self, api_url: str = KALI_API_URL):
34
+ self.api_url = api_url.rstrip('/')
35
+ self.session = requests.Session()
36
+ logger.info(f"Initialized Kali MCP Server with API: {self.api_url}")
37
+
38
+ def _call_api(self, endpoint: str, method: str = "GET", data: Dict = None) -> Dict[str, Any]:
39
+ """Make API call to Kali server"""
40
+ url = f"{self.api_url}{endpoint}"
41
+
42
+ try:
43
+ if method.upper() == "POST":
44
+ response = self.session.post(url, json=data, timeout=300)
45
+ else:
46
+ response = self.session.get(url, timeout=30)
47
+
48
+ response.raise_for_status()
49
+ return response.json()
50
+
51
+ except requests.exceptions.RequestException as e:
52
+ logger.error(f"API call failed: {str(e)}")
53
+ return {"error": str(e)}
54
+
55
+ def get_capabilities(self) -> Dict[str, Any]:
56
+ """Get MCP tool capabilities"""
57
+ return self._call_api("/mcp/capabilities")
58
+
59
+ def execute_command(self, command: str) -> Dict[str, Any]:
60
+ """Execute a command via the API"""
61
+ data = {"command": command}
62
+ return self._call_api("/api/command", "POST", data)
63
+
64
+ def health_check(self) -> Dict[str, Any]:
65
+ """Check server health"""
66
+ return self._call_api("/health")
67
+
68
+ # Global server instance
69
+ kali_server = KaliMCPServer()
70
+
71
+ # MCP Server setup
72
+ server = Server("kali-mcp-server")
73
+
74
+ @server.tool()
75
+ async def execute_command(command: str) -> str:
76
+ """Execute arbitrary commands on Kali Linux
77
+
78
+ Args:
79
+ command: The shell command to execute on the Kali Linux system
80
+
81
+ Returns:
82
+ Command execution results including stdout, stderr, and exit code
83
+ """
84
+ logger.info(f"Executing command: {command}")
85
+
86
+ try:
87
+ result = kali_server.execute_command(command)
88
+
89
+ if result.get("error"):
90
+ return f"Error: {result['error']}"
91
+
92
+ output = []
93
+ if result.get("stdout"):
94
+ output.append(f"STDOUT:\n{result['stdout']}")
95
+ if result.get("stderr"):
96
+ output.append(f"STDERR:\n{result['stderr']}")
97
+
98
+ status = "SUCCESS" if result.get("success") else "FAILED"
99
+ output.append(f"Exit Code: {result.get('return_code', 'unknown')}")
100
+ output.append(f"Status: {status}")
101
+
102
+ if result.get("timed_out"):
103
+ output.append("WARNING: Command timed out after 180 seconds")
104
+
105
+ return "\n\n".join(output)
106
+
107
+ except Exception as e:
108
+ logger.error(f"Tool execution error: {str(e)}")
109
+ return f"Execution failed: {str(e)}"
110
+
111
+ @server.tool()
112
+ async def server_health() -> str:
113
+ """Check the health status of the Kali Linux server and available tools
114
+
115
+ Returns:
116
+ Server health information and tool availability status
117
+ """
118
+ try:
119
+ health = kali_server.health_check()
120
+
121
+ if health.get("error"):
122
+ return f"Health check failed: {health['error']}"
123
+
124
+ output = []
125
+ output.append(f"Status: {health.get('status', 'unknown')}")
126
+ output.append(f"Message: {health.get('message', '')}")
127
+ output.append(f"All Essential Tools Available: {health.get('all_essential_tools_available', False)}")
128
+
129
+ tools_status = health.get('tools_status', {})
130
+ if tools_status:
131
+ output.append("\nTool Status:")
132
+ for tool, available in tools_status.items():
133
+ status_icon = "✅" if available else "❌"
134
+ output.append(f" {status_icon} {tool}")
135
+
136
+ return "\n".join(output)
137
+
138
+ except Exception as e:
139
+ logger.error(f"Health check error: {str(e)}")
140
+ return f"Health check failed: {str(e)}"
141
+
142
+ async def main():
143
+ """Main server entry point"""
144
+ # Import here to avoid issues if MCP SDK is not available
145
+ from mcp.server.stdio import stdio_server
146
+
147
+ logger.info("Starting Kali Linux MCP Server")
148
+
149
+ # Test connection on startup
150
+ try:
151
+ health = kali_server.health_check()
152
+ if health.get("error"):
153
+ logger.error(f"Failed to connect to Kali API: {health['error']}")
154
+ sys.exit(1)
155
+ else:
156
+ logger.info("✅ Successfully connected to Kali API server")
157
+ except Exception as e:
158
+ logger.error(f"Connection test failed: {str(e)}")
159
+ sys.exit(1)
160
+
161
+ async with stdio_server() as (read_stream, write_stream):
162
+ await server.run(
163
+ read_stream,
164
+ write_stream,
165
+ server.create_initialization_options()
166
+ )
167
+
168
+ if __name__ == "__main__":
169
+ asyncio.run(main())