kmcp 0.1.5.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kali_mcp/__init__.py +3 -0
- kali_mcp/__main__.py +28 -0
- kali_mcp/_version.py +24 -0
- kali_mcp/cli.py +169 -0
- kali_mcp/config.py +95 -0
- kali_mcp/db/__init__.py +1 -0
- kali_mcp/db/manager.py +248 -0
- kali_mcp/execution.py +439 -0
- kali_mcp/logging_utils.py +74 -0
- kali_mcp/models.py +51 -0
- kali_mcp/monitor/__init__.py +105 -0
- kali_mcp/monitor/sessions.py +70 -0
- kali_mcp/monitor/sse_client.py +87 -0
- kali_mcp/monitor/tui.py +364 -0
- kali_mcp/notifications.py +130 -0
- kali_mcp/prompts.py +184 -0
- kali_mcp/registry.py +33 -0
- kali_mcp/resources.py +263 -0
- kali_mcp/responses.py +39 -0
- kali_mcp/security.py +15 -0
- kali_mcp/server.py +535 -0
- kali_mcp/tools/__init__.py +125 -0
- kali_mcp/tools/amass.py +83 -0
- kali_mcp/tools/arjun.py +86 -0
- kali_mcp/tools/base.py +100 -0
- kali_mcp/tools/bettercap.py +99 -0
- kali_mcp/tools/bloodhound.py +68 -0
- kali_mcp/tools/commix.py +73 -0
- kali_mcp/tools/crackmapexec.py +100 -0
- kali_mcp/tools/dirb.py +75 -0
- kali_mcp/tools/dursgo.py +156 -0
- kali_mcp/tools/enum4linux.py +59 -0
- kali_mcp/tools/farsight.py +127 -0
- kali_mcp/tools/ffuf.py +85 -0
- kali_mcp/tools/file_download.py +119 -0
- kali_mcp/tools/file_read.py +144 -0
- kali_mcp/tools/file_write.py +141 -0
- kali_mcp/tools/flowlyt.py +88 -0
- kali_mcp/tools/generic_command.py +95 -0
- kali_mcp/tools/gobuster.py +84 -0
- kali_mcp/tools/hashcat.py +101 -0
- kali_mcp/tools/httpx.py +85 -0
- kali_mcp/tools/hydra.py +99 -0
- kali_mcp/tools/john.py +100 -0
- kali_mcp/tools/katana.py +81 -0
- kali_mcp/tools/masscan.py +85 -0
- kali_mcp/tools/medusa.py +102 -0
- kali_mcp/tools/msfconsole.py +59 -0
- kali_mcp/tools/naabu.py +100 -0
- kali_mcp/tools/netexec.py +86 -0
- kali_mcp/tools/nmap.py +94 -0
- kali_mcp/tools/normalization.py +18 -0
- kali_mcp/tools/nuclei.py +87 -0
- kali_mcp/tools/parallel_execute.py +246 -0
- kali_mcp/tools/persist.py +436 -0
- kali_mcp/tools/playbook_ad.py +99 -0
- kali_mcp/tools/playbook_engine.py +142 -0
- kali_mcp/tools/playbook_engine_tool.py +72 -0
- kali_mcp/tools/playbook_recon.py +115 -0
- kali_mcp/tools/playbook_tools.py +125 -0
- kali_mcp/tools/playbook_webapp.py +105 -0
- kali_mcp/tools/python_command.py +100 -0
- kali_mcp/tools/responder.py +85 -0
- kali_mcp/tools/searchsploit.py +123 -0
- kali_mcp/tools/spiderfoot.py +75 -0
- kali_mcp/tools/sqlmap.py +73 -0
- kali_mcp/tools/subfinder.py +69 -0
- kali_mcp/tools/theharvester.py +80 -0
- kali_mcp/tools/vault_tool.py +489 -0
- kali_mcp/tools/wfuzz.py +87 -0
- kali_mcp/tools/whatweb.py +82 -0
- kali_mcp/tools/wpscan.py +76 -0
- kali_mcp/tools/zap.py +79 -0
- kali_mcp/tools/zighound.py +139 -0
- kali_mcp/tools/zizmor.py +98 -0
- kali_mcp/utils/__init__.py +0 -0
- kali_mcp/utils/process.py +36 -0
- kali_mcp/utils/vault.py +471 -0
- kali_mcp/validation.py +82 -0
- kmcp-0.1.5.dev0.dist-info/METADATA +251 -0
- kmcp-0.1.5.dev0.dist-info/RECORD +84 -0
- kmcp-0.1.5.dev0.dist-info/WHEEL +5 -0
- kmcp-0.1.5.dev0.dist-info/entry_points.txt +4 -0
- kmcp-0.1.5.dev0.dist-info/top_level.txt +1 -0
kali_mcp/server.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
"""MCP Server — hardened SSE transport, tool registration, request handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import gc
|
|
7
|
+
import inspect
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import signal
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
from contextlib import asynccontextmanager
|
|
16
|
+
|
|
17
|
+
from mcp.server.fastmcp import FastMCP
|
|
18
|
+
from mcp.server.fastmcp.server import Context
|
|
19
|
+
from mcp.server.fastmcp.tools.base import Tool as MCPTool
|
|
20
|
+
from mcp.server.fastmcp.utilities.func_metadata import func_metadata
|
|
21
|
+
|
|
22
|
+
from kali_mcp.config import config
|
|
23
|
+
from kali_mcp.db import manager as db_manager
|
|
24
|
+
from kali_mcp.execution import engine, reset_progress_cb, set_progress_cb
|
|
25
|
+
from kali_mcp.logging_utils import setup_logging
|
|
26
|
+
from kali_mcp.monitor import Monitor
|
|
27
|
+
from kali_mcp.monitor.sessions import session_registry
|
|
28
|
+
from kali_mcp.notifications import emit_log, notify_resource_updated
|
|
29
|
+
from kali_mcp.prompts import register_prompts
|
|
30
|
+
from kali_mcp.registry import registry
|
|
31
|
+
from kali_mcp.resources import register_resources
|
|
32
|
+
|
|
33
|
+
# Import all tools (triggers registration)
|
|
34
|
+
from kali_mcp.tools import ALL_TOOLS
|
|
35
|
+
from kali_mcp.utils.vault import ensure_vault_dirs
|
|
36
|
+
|
|
37
|
+
setup_logging()
|
|
38
|
+
logger = logging.getLogger("kali_mcp.server")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ── Health Monitor ──────────────────────────────────────────────
|
|
42
|
+
class HealthMonitor:
|
|
43
|
+
"""Background thread that monitors server health and cleans up stuck state."""
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
self._running = False
|
|
47
|
+
self._last_gc = time.monotonic()
|
|
48
|
+
self._request_count = 0
|
|
49
|
+
self._error_count = 0
|
|
50
|
+
self._start_time = time.monotonic()
|
|
51
|
+
self._lock = threading.Lock()
|
|
52
|
+
|
|
53
|
+
def start(self) -> None:
|
|
54
|
+
if self._running:
|
|
55
|
+
return
|
|
56
|
+
self._running = True
|
|
57
|
+
t = threading.Thread(target=self._loop, daemon=True, name="health-monitor")
|
|
58
|
+
t.start()
|
|
59
|
+
logger.info("Health monitor started")
|
|
60
|
+
|
|
61
|
+
def stop(self) -> None:
|
|
62
|
+
self._running = False
|
|
63
|
+
|
|
64
|
+
def _loop(self) -> None:
|
|
65
|
+
while self._running:
|
|
66
|
+
time.sleep(30)
|
|
67
|
+
try:
|
|
68
|
+
self._check()
|
|
69
|
+
except Exception: # noqa: BLE001, S110
|
|
70
|
+
pass # Monitor must never crash
|
|
71
|
+
|
|
72
|
+
def _check(self) -> None:
|
|
73
|
+
now = time.monotonic()
|
|
74
|
+
|
|
75
|
+
# Periodic GC (every 5 minutes)
|
|
76
|
+
if now - self._last_gc > 300:
|
|
77
|
+
gc.collect()
|
|
78
|
+
self._last_gc = now
|
|
79
|
+
|
|
80
|
+
# Check for stuck executions
|
|
81
|
+
stuck = engine.get_stuck_executions()
|
|
82
|
+
if stuck:
|
|
83
|
+
for s in stuck:
|
|
84
|
+
logger.warning(
|
|
85
|
+
"health: stuck execution detected — request=%s tool=%s elapsed=%.0fs",
|
|
86
|
+
s["request_id"],
|
|
87
|
+
s["tool"],
|
|
88
|
+
s["elapsed_seconds"],
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Force cleanup if too many stuck
|
|
92
|
+
if len(stuck) > config.max_concurrent:
|
|
93
|
+
logger.warning("health: too many stuck executions (%d), force cleaning", len(stuck))
|
|
94
|
+
engine.force_cleanup()
|
|
95
|
+
|
|
96
|
+
# Log health metrics
|
|
97
|
+
uptime = now - self._start_time
|
|
98
|
+
active = engine.active_count
|
|
99
|
+
with self._lock:
|
|
100
|
+
req_count = self._request_count
|
|
101
|
+
err_count = self._error_count
|
|
102
|
+
if active > 0 or req_count > 0:
|
|
103
|
+
logger.info(
|
|
104
|
+
"health: uptime=%.0fs active=%d requests=%d errors=%d",
|
|
105
|
+
uptime,
|
|
106
|
+
active,
|
|
107
|
+
req_count,
|
|
108
|
+
err_count,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def record_request(self) -> None:
|
|
112
|
+
with self._lock:
|
|
113
|
+
self._request_count += 1
|
|
114
|
+
|
|
115
|
+
def record_error(self) -> None:
|
|
116
|
+
with self._lock:
|
|
117
|
+
self._error_count += 1
|
|
118
|
+
|
|
119
|
+
def get_status(self) -> dict:
|
|
120
|
+
uptime = time.monotonic() - self._start_time
|
|
121
|
+
with self._lock:
|
|
122
|
+
return {
|
|
123
|
+
"status": "healthy",
|
|
124
|
+
"uptime_seconds": round(uptime, 1),
|
|
125
|
+
"active_executions": engine.active_count,
|
|
126
|
+
"total_requests": self._request_count,
|
|
127
|
+
"total_errors": self._error_count,
|
|
128
|
+
"tools_registered": len(registry.tool_names()),
|
|
129
|
+
"memory_mb": _get_memory_mb(),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
health = HealthMonitor()
|
|
134
|
+
|
|
135
|
+
# Interactive monitor — aggregates sessions, active jobs, and health.
|
|
136
|
+
monitor = Monitor(session_registry, engine, health)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _get_memory_mb() -> float:
|
|
140
|
+
"""Get current process memory usage in MB."""
|
|
141
|
+
try:
|
|
142
|
+
import resource as _resource
|
|
143
|
+
|
|
144
|
+
usage = _resource.getrusage(_resource.RUSAGE_SELF)
|
|
145
|
+
return round(usage.ru_maxrss / 1024, 1) # Linux: bytes→MB
|
|
146
|
+
except Exception: # noqa: BLE001
|
|
147
|
+
return 0.0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# ── Lifespan ────────────────────────────────────────────────────
|
|
151
|
+
@asynccontextmanager
|
|
152
|
+
async def lifespan(app):
|
|
153
|
+
"""Server lifecycle — startup and shutdown."""
|
|
154
|
+
logger.info("Server starting up...")
|
|
155
|
+
logger.info("Registered %d tools: %s", len(ALL_TOOLS), [t.name for t in ALL_TOOLS])
|
|
156
|
+
# Initialize foundational infrastructure (Phase 1)
|
|
157
|
+
try:
|
|
158
|
+
ensure_vault_dirs()
|
|
159
|
+
logger.info("Vault directories initialized")
|
|
160
|
+
except Exception:
|
|
161
|
+
logger.exception("Vault initialization failed")
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
if getattr(config, "db_enabled", True):
|
|
165
|
+
_db = db_manager.get_db()
|
|
166
|
+
logger.info("Database initialized (path=%s)", str(config.db_path))
|
|
167
|
+
except Exception:
|
|
168
|
+
logger.exception("Database initialization failed")
|
|
169
|
+
|
|
170
|
+
# Verify critical binaries
|
|
171
|
+
import shutil
|
|
172
|
+
|
|
173
|
+
for bin_name in ["nmap", "curl"]:
|
|
174
|
+
if shutil.which(bin_name):
|
|
175
|
+
logger.info("Startup check OK: %s found", bin_name)
|
|
176
|
+
else:
|
|
177
|
+
logger.warning("Startup check WARN: %s not found in PATH", bin_name)
|
|
178
|
+
|
|
179
|
+
health.start()
|
|
180
|
+
logger.info("Health monitor active")
|
|
181
|
+
|
|
182
|
+
yield
|
|
183
|
+
|
|
184
|
+
health.stop()
|
|
185
|
+
engine.force_cleanup()
|
|
186
|
+
logger.info("Server shut down cleanly")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ── FastMCP ─────────────────────────────────────────────────────
|
|
190
|
+
mcp = FastMCP(
|
|
191
|
+
name=config.server_name,
|
|
192
|
+
instructions=(
|
|
193
|
+
"Kali MCP Server — penetration testing execution backend. "
|
|
194
|
+
"Exposes native security tools and a generic_command escape hatch. "
|
|
195
|
+
"All tools return structured JSON with stdout, stderr, exit_code, and timing."
|
|
196
|
+
),
|
|
197
|
+
lifespan=lifespan,
|
|
198
|
+
host=config.host,
|
|
199
|
+
port=config.port,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Resources + prompts (protocol-level metadata surfaced to clients)
|
|
203
|
+
register_resources(mcp, health=health)
|
|
204
|
+
register_prompts(mcp)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# Register all tools with safe_execute wrapper
|
|
208
|
+
for tool_instance in ALL_TOOLS:
|
|
209
|
+
registry.register(tool_instance)
|
|
210
|
+
|
|
211
|
+
def _make_handler(t):
|
|
212
|
+
schema = t.input_schema()
|
|
213
|
+
properties = schema.get("properties", {})
|
|
214
|
+
required = schema.get("required", [])
|
|
215
|
+
|
|
216
|
+
# Map JSON schema types to Python types
|
|
217
|
+
TYPE_MAP = {
|
|
218
|
+
"string": str,
|
|
219
|
+
"integer": int,
|
|
220
|
+
"number": float,
|
|
221
|
+
"boolean": bool,
|
|
222
|
+
"object": dict,
|
|
223
|
+
"array": list,
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
params = []
|
|
227
|
+
for name, prop in properties.items():
|
|
228
|
+
has_default = "default" in prop
|
|
229
|
+
is_required = name in required
|
|
230
|
+
json_type = prop.get("type", "string")
|
|
231
|
+
if isinstance(json_type, list):
|
|
232
|
+
# Union type (e.g. ["object", "string"])
|
|
233
|
+
py_types = tuple(TYPE_MAP.get(t, str) for t in json_type)
|
|
234
|
+
py_type = py_types[0] if len(py_types) == 1 else py_types[0] | py_types[1]
|
|
235
|
+
else:
|
|
236
|
+
py_type = TYPE_MAP.get(json_type, str)
|
|
237
|
+
|
|
238
|
+
if has_default:
|
|
239
|
+
default = prop.get("default")
|
|
240
|
+
params.append(
|
|
241
|
+
inspect.Parameter(
|
|
242
|
+
name,
|
|
243
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
244
|
+
default=default,
|
|
245
|
+
annotation=py_type,
|
|
246
|
+
)
|
|
247
|
+
)
|
|
248
|
+
elif is_required:
|
|
249
|
+
params.append(
|
|
250
|
+
inspect.Parameter(
|
|
251
|
+
name,
|
|
252
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
253
|
+
annotation=py_type,
|
|
254
|
+
)
|
|
255
|
+
)
|
|
256
|
+
else:
|
|
257
|
+
# Optional — default to None, type is Optional[py_type]
|
|
258
|
+
params.append(
|
|
259
|
+
inspect.Parameter(
|
|
260
|
+
name,
|
|
261
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
262
|
+
default=None,
|
|
263
|
+
annotation=py_type | None,
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
sig = inspect.Signature(params)
|
|
268
|
+
|
|
269
|
+
async def handler(ctx: Context, **kwargs) -> str:
|
|
270
|
+
request_id = uuid.uuid4().hex[:12]
|
|
271
|
+
health.record_request()
|
|
272
|
+
# Track MCP client session for interactive monitoring
|
|
273
|
+
_session = getattr(ctx, "session", None)
|
|
274
|
+
if _session is not None:
|
|
275
|
+
_session_id = id(_session)
|
|
276
|
+
session_registry.on_connect(_session_id)
|
|
277
|
+
session_registry.on_activity(_session_id)
|
|
278
|
+
|
|
279
|
+
async def progress(completed, total, message=None) -> None:
|
|
280
|
+
try:
|
|
281
|
+
await ctx.report_progress(completed, total, message=message)
|
|
282
|
+
except Exception: # noqa: BLE001, S110
|
|
283
|
+
pass # client didn't ask for progress — no-op
|
|
284
|
+
|
|
285
|
+
token = set_progress_cb(progress)
|
|
286
|
+
try:
|
|
287
|
+
emit_log(ctx, "info", f"Starting {t.name} ({request_id})")
|
|
288
|
+
# Coerce string values to correct types based on schema
|
|
289
|
+
for pname, prop in properties.items():
|
|
290
|
+
if pname in kwargs and kwargs[pname] is not None:
|
|
291
|
+
expected = prop.get("type")
|
|
292
|
+
val = kwargs[pname]
|
|
293
|
+
if expected == "integer" and isinstance(val, str):
|
|
294
|
+
kwargs[pname] = int(val)
|
|
295
|
+
elif expected == "number" and isinstance(val, str):
|
|
296
|
+
kwargs[pname] = float(val)
|
|
297
|
+
elif expected == "boolean" and isinstance(val, str):
|
|
298
|
+
kwargs[pname] = val.lower() in ("1", "true", "yes")
|
|
299
|
+
elif expected == "boolean" and isinstance(val, bool):
|
|
300
|
+
pass # already correct
|
|
301
|
+
elif isinstance(expected, list) and isinstance(val, str):
|
|
302
|
+
# Union type allowing object/array — coerce JSON
|
|
303
|
+
# strings; non-JSON plain text stays a string
|
|
304
|
+
if any(t in ("object", "array") for t in expected):
|
|
305
|
+
try:
|
|
306
|
+
kwargs[pname] = json.loads(val)
|
|
307
|
+
except json.JSONDecodeError:
|
|
308
|
+
pass
|
|
309
|
+
elif (
|
|
310
|
+
expected == "object"
|
|
311
|
+
and isinstance(val, str)
|
|
312
|
+
or expected == "array"
|
|
313
|
+
and isinstance(val, str)
|
|
314
|
+
):
|
|
315
|
+
kwargs[pname] = json.loads(val)
|
|
316
|
+
logger.info(
|
|
317
|
+
"request=%s tool=%s args=%s",
|
|
318
|
+
request_id,
|
|
319
|
+
t.name,
|
|
320
|
+
list(kwargs.keys()),
|
|
321
|
+
)
|
|
322
|
+
result = await t.safe_execute(kwargs)
|
|
323
|
+
emit_log(ctx, "info", f"Completed {t.name} ({request_id})")
|
|
324
|
+
if t.name == "file_write":
|
|
325
|
+
notify_resource_updated(ctx, "kali://artifacts")
|
|
326
|
+
if isinstance(result, dict) and "content" in result:
|
|
327
|
+
for block in result["content"]:
|
|
328
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
329
|
+
return block["text"]
|
|
330
|
+
return json.dumps(result, indent=2)
|
|
331
|
+
except asyncio.CancelledError:
|
|
332
|
+
logger.warning("request=%s tool=%s cancelled", request_id, t.name)
|
|
333
|
+
emit_log(ctx, "warning", f"Cancelled {t.name} ({request_id})")
|
|
334
|
+
return json.dumps({"error": "Request cancelled"})
|
|
335
|
+
except Exception:
|
|
336
|
+
health.record_error()
|
|
337
|
+
logger.exception("request=%s catastrophic error in tool %s", request_id, t.name)
|
|
338
|
+
emit_log(ctx, "error", f"Failed {t.name} ({request_id})")
|
|
339
|
+
return json.dumps({"error": "Tool execution failed"}, indent=2)
|
|
340
|
+
finally:
|
|
341
|
+
reset_progress_cb(token)
|
|
342
|
+
|
|
343
|
+
handler.__name__ = t.name
|
|
344
|
+
handler.__doc__ = t.description
|
|
345
|
+
handler.__signature__ = sig
|
|
346
|
+
return handler
|
|
347
|
+
|
|
348
|
+
tool_fn = _make_handler(tool_instance)
|
|
349
|
+
|
|
350
|
+
fm = func_metadata(tool_fn)
|
|
351
|
+
mcp_tool = MCPTool(
|
|
352
|
+
fn=tool_fn,
|
|
353
|
+
name=tool_instance.name,
|
|
354
|
+
description=tool_instance.description,
|
|
355
|
+
parameters=tool_instance.input_schema(),
|
|
356
|
+
fn_metadata=fm,
|
|
357
|
+
is_async=True,
|
|
358
|
+
context_kwarg="ctx",
|
|
359
|
+
)
|
|
360
|
+
mcp._tool_manager._tools[tool_instance.name] = mcp_tool
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
# ── Health Check Tool ───────────────────────────────────────────
|
|
364
|
+
@mcp.tool()
|
|
365
|
+
def health_check() -> str:
|
|
366
|
+
"""Check server health, memory, active executions, and registered tools."""
|
|
367
|
+
status = health.get_status()
|
|
368
|
+
status["available_tools"] = registry.tool_names()
|
|
369
|
+
stuck = engine.get_stuck_executions()
|
|
370
|
+
if stuck:
|
|
371
|
+
status["stuck_executions"] = stuck
|
|
372
|
+
return json.dumps(status, indent=2)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# ── Force Cleanup Tool ──────────────────────────────────────────
|
|
376
|
+
@mcp.tool()
|
|
377
|
+
def force_cleanup() -> str:
|
|
378
|
+
"""Force cleanup all stuck executions. Use when server appears unresponsive."""
|
|
379
|
+
count = engine.force_cleanup()
|
|
380
|
+
gc.collect()
|
|
381
|
+
return json.dumps(
|
|
382
|
+
{
|
|
383
|
+
"status": "cleaned",
|
|
384
|
+
"requests_cleaned": count,
|
|
385
|
+
"message": f"Force-cleaned {count} tracked executions and ran GC",
|
|
386
|
+
},
|
|
387
|
+
indent=2,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# ── File Download Endpoint ─────────────────────────────────────
|
|
392
|
+
async def download_file(request):
|
|
393
|
+
"""Serve a file download by path."""
|
|
394
|
+
from starlette.responses import FileResponse, JSONResponse
|
|
395
|
+
|
|
396
|
+
path = request.query_params.get("path", "")
|
|
397
|
+
if not path:
|
|
398
|
+
return JSONResponse({"error": "Missing path parameter"}, status_code=400)
|
|
399
|
+
if not os.path.isfile(path):
|
|
400
|
+
return JSONResponse({"error": "File not found"}, status_code=404)
|
|
401
|
+
return FileResponse(path, media_type="application/octet-stream")
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
# ── Monitor Endpoints ──────────────────────────────────────────────
|
|
405
|
+
async def monitor_stream(request):
|
|
406
|
+
"""Server-sent events stream of live monitor snapshots.
|
|
407
|
+
|
|
408
|
+
Connects a client to the monitor's broadcast queue. Sends an immediate
|
|
409
|
+
snapshot, then pushes new snapshots whenever state changes (or every
|
|
410
|
+
second as a heartbeat).
|
|
411
|
+
"""
|
|
412
|
+
from starlette.responses import StreamingResponse
|
|
413
|
+
|
|
414
|
+
queue = monitor.subscribe()
|
|
415
|
+
|
|
416
|
+
async def event_generator():
|
|
417
|
+
# Immediate snapshot on connect
|
|
418
|
+
snapshot = monitor.build_snapshot()
|
|
419
|
+
yield f"data: {json.dumps(snapshot)}\n\n"
|
|
420
|
+
|
|
421
|
+
try:
|
|
422
|
+
while True:
|
|
423
|
+
try:
|
|
424
|
+
snapshot = await asyncio.wait_for(queue.get(), timeout=1.0)
|
|
425
|
+
yield f"data: {json.dumps(snapshot)}\n\n"
|
|
426
|
+
except asyncio.TimeoutError:
|
|
427
|
+
# Heartbeat: send a fresh snapshot every second
|
|
428
|
+
snapshot = monitor.build_snapshot()
|
|
429
|
+
yield f"data: {json.dumps(snapshot)}\n\n"
|
|
430
|
+
except asyncio.CancelledError:
|
|
431
|
+
pass
|
|
432
|
+
finally:
|
|
433
|
+
monitor.unsubscribe(queue)
|
|
434
|
+
|
|
435
|
+
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
async def monitor_action(request):
|
|
439
|
+
"""Execute a monitor action: kill_job, force_cleanup, or get_snapshot."""
|
|
440
|
+
from starlette.requests import Request
|
|
441
|
+
from starlette.responses import JSONResponse
|
|
442
|
+
|
|
443
|
+
req = Request(request.scope, request.receive)
|
|
444
|
+
try:
|
|
445
|
+
body = await req.json()
|
|
446
|
+
except Exception: # noqa: BLE001
|
|
447
|
+
return JSONResponse({"error": "invalid JSON"}, status_code=400)
|
|
448
|
+
|
|
449
|
+
action = body.get("action")
|
|
450
|
+
if action == "kill_job":
|
|
451
|
+
result = await monitor.kill_job(body.get("request_id", ""))
|
|
452
|
+
elif action == "force_cleanup":
|
|
453
|
+
result = await monitor.force_cleanup()
|
|
454
|
+
elif action == "get_snapshot":
|
|
455
|
+
result = monitor.build_snapshot()
|
|
456
|
+
else:
|
|
457
|
+
return JSONResponse({"error": "unknown action"}, status_code=400)
|
|
458
|
+
|
|
459
|
+
return JSONResponse(result)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
# ── Middleware ───────────────────────────────────────────────────
|
|
463
|
+
class TokenAuthMiddleware:
|
|
464
|
+
def __init__(self, app, token: str):
|
|
465
|
+
self.app = app
|
|
466
|
+
self.token = token
|
|
467
|
+
|
|
468
|
+
async def __call__(self, scope, receive, send):
|
|
469
|
+
if scope["type"] == "http" and self.token:
|
|
470
|
+
from starlette.requests import Request
|
|
471
|
+
from starlette.responses import JSONResponse
|
|
472
|
+
|
|
473
|
+
request = Request(scope, receive)
|
|
474
|
+
auth = request.headers.get("authorization", "")
|
|
475
|
+
query_token = request.query_params.get("token", "")
|
|
476
|
+
provided = auth.removeprefix("Bearer ").strip() or query_token
|
|
477
|
+
if provided != self.token:
|
|
478
|
+
response = JSONResponse({"error": "Unauthorized"}, status_code=401)
|
|
479
|
+
await response(scope, receive, send)
|
|
480
|
+
return
|
|
481
|
+
|
|
482
|
+
await self.app(scope, receive, send)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# ── Main ────────────────────────────────────────────────────────
|
|
486
|
+
def main() -> None:
|
|
487
|
+
"""Run the MCP server over HTTP (SSE or streamable-http)."""
|
|
488
|
+
import uvicorn
|
|
489
|
+
from starlette.middleware.cors import CORSMiddleware
|
|
490
|
+
|
|
491
|
+
if config.transport == "streamable-http":
|
|
492
|
+
app = mcp.streamable_http_app()
|
|
493
|
+
logger.info("Transport: streamable-http")
|
|
494
|
+
else:
|
|
495
|
+
app = mcp.sse_app()
|
|
496
|
+
logger.info("Transport: sse")
|
|
497
|
+
|
|
498
|
+
origins = [o.strip() for o in config.allowed_origins.split(",") if o.strip()]
|
|
499
|
+
app.add_middleware(
|
|
500
|
+
CORSMiddleware,
|
|
501
|
+
allow_origins=origins,
|
|
502
|
+
allow_methods=["*"],
|
|
503
|
+
allow_headers=["*"],
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
api_token = os.getenv("MCP_API_TOKEN", "")
|
|
507
|
+
if api_token:
|
|
508
|
+
app.add_middleware(TokenAuthMiddleware, token=api_token)
|
|
509
|
+
logger.info("API token authentication enabled")
|
|
510
|
+
else:
|
|
511
|
+
logger.warning(
|
|
512
|
+
"No MCP_API_TOKEN set — server is open. Set MCP_API_TOKEN in .env for production."
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
# Graceful shutdown
|
|
516
|
+
def _shutdown_handler(signum, frame):
|
|
517
|
+
logger.info("Received signal %d, shutting down...", signum)
|
|
518
|
+
health.stop()
|
|
519
|
+
engine.force_cleanup()
|
|
520
|
+
|
|
521
|
+
signal.signal(signal.SIGTERM, _shutdown_handler)
|
|
522
|
+
signal.signal(signal.SIGINT, _shutdown_handler)
|
|
523
|
+
|
|
524
|
+
# File download route
|
|
525
|
+
from starlette.routing import Route
|
|
526
|
+
|
|
527
|
+
app.routes.insert(0, Route("/download", download_file, methods=["GET"]))
|
|
528
|
+
app.routes.insert(0, Route("/monitor/stream", monitor_stream, methods=["GET"]))
|
|
529
|
+
app.routes.insert(0, Route("/monitor/action", monitor_action, methods=["POST"]))
|
|
530
|
+
|
|
531
|
+
uvicorn.run(app, host=config.host, port=config.port)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
if __name__ == "__main__":
|
|
535
|
+
main()
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Auto-import all tool modules to trigger registration.
|
|
2
|
+
|
|
3
|
+
The tool registry exposes the full inventory of tool wrappers so agents get
|
|
4
|
+
maximum capability. test_comprehensive.py's TOOL_ARGS map must include an
|
|
5
|
+
entry for every registered tool.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from kali_mcp.tools.amass import AmassTool
|
|
9
|
+
from kali_mcp.tools.arjun import ArjunTool
|
|
10
|
+
from kali_mcp.tools.bettercap import BettercapTool
|
|
11
|
+
from kali_mcp.tools.bloodhound import BloodhoundTool
|
|
12
|
+
from kali_mcp.tools.commix import CommixTool
|
|
13
|
+
from kali_mcp.tools.crackmapexec import CrackmapexecTool
|
|
14
|
+
from kali_mcp.tools.dirb import DirbTool
|
|
15
|
+
from kali_mcp.tools.dursgo import DursgoTool
|
|
16
|
+
from kali_mcp.tools.enum4linux import Enum4linuxTool
|
|
17
|
+
|
|
18
|
+
## Excluded: none — full tool inventory registered
|
|
19
|
+
from kali_mcp.tools.farsight import FarsightTool
|
|
20
|
+
from kali_mcp.tools.ffuf import FfufTool
|
|
21
|
+
from kali_mcp.tools.file_download import FileDownloadTool
|
|
22
|
+
from kali_mcp.tools.file_read import FileReadTool
|
|
23
|
+
from kali_mcp.tools.file_write import FileWriteTool
|
|
24
|
+
from kali_mcp.tools.flowlyt import FlowlytTool
|
|
25
|
+
from kali_mcp.tools.generic_command import GenericCommandTool
|
|
26
|
+
from kali_mcp.tools.gobuster import GobusterTool
|
|
27
|
+
from kali_mcp.tools.hashcat import HashcatTool
|
|
28
|
+
from kali_mcp.tools.httpx import HttpxTool
|
|
29
|
+
from kali_mcp.tools.hydra import HydraTool
|
|
30
|
+
from kali_mcp.tools.john import JohnTool
|
|
31
|
+
from kali_mcp.tools.katana import KatanaTool
|
|
32
|
+
from kali_mcp.tools.masscan import MasscanTool
|
|
33
|
+
from kali_mcp.tools.medusa import MedusaTool
|
|
34
|
+
from kali_mcp.tools.msfconsole import MsfconsoleTool
|
|
35
|
+
from kali_mcp.tools.naabu import NaabuTool
|
|
36
|
+
from kali_mcp.tools.netexec import NetexecTool
|
|
37
|
+
from kali_mcp.tools.nmap import NmapTool
|
|
38
|
+
from kali_mcp.tools.nuclei import NucleiTool
|
|
39
|
+
from kali_mcp.tools.parallel_execute import ParallelExecuteTool, ParallelStatusTool
|
|
40
|
+
from kali_mcp.tools.playbook_ad import PlaybookAdTool
|
|
41
|
+
from kali_mcp.tools.playbook_engine_tool import PlaybookEngineTool
|
|
42
|
+
from kali_mcp.tools.playbook_recon import PlaybookReconTool
|
|
43
|
+
from kali_mcp.tools.playbook_tools import PlaybookListTool, PlaybookStatusTool
|
|
44
|
+
from kali_mcp.tools.playbook_webapp import PlaybookWebappTool
|
|
45
|
+
from kali_mcp.tools.python_command import PythonCommandTool
|
|
46
|
+
from kali_mcp.tools.responder import ResponderTool
|
|
47
|
+
from kali_mcp.tools.searchsploit import SearchsploitTool
|
|
48
|
+
from kali_mcp.tools.spiderfoot import SpiderfootTool
|
|
49
|
+
from kali_mcp.tools.sqlmap import SqlmapTool
|
|
50
|
+
from kali_mcp.tools.subfinder import SubfinderTool
|
|
51
|
+
from kali_mcp.tools.theharvester import TheharvesterTool
|
|
52
|
+
from kali_mcp.tools.vault_tool import (
|
|
53
|
+
VaultDeleteTool,
|
|
54
|
+
VaultListTool,
|
|
55
|
+
VaultQueryTool,
|
|
56
|
+
VaultReadTool,
|
|
57
|
+
VaultStatsTool,
|
|
58
|
+
VaultWriteTool,
|
|
59
|
+
)
|
|
60
|
+
from kali_mcp.tools.wfuzz import WfuzzTool
|
|
61
|
+
from kali_mcp.tools.whatweb import WhatwebTool
|
|
62
|
+
from kali_mcp.tools.wpscan import WpscanTool
|
|
63
|
+
from kali_mcp.tools.zap import ZapTool
|
|
64
|
+
from kali_mcp.tools.zighound import ZighoundTool
|
|
65
|
+
from kali_mcp.tools.zizmor import ZizmorTool
|
|
66
|
+
|
|
67
|
+
# Ordered list of tool instances (full inventory)
|
|
68
|
+
ALL_TOOLS = [
|
|
69
|
+
GenericCommandTool(),
|
|
70
|
+
PythonCommandTool(),
|
|
71
|
+
FileReadTool(),
|
|
72
|
+
FileWriteTool(),
|
|
73
|
+
FileDownloadTool(),
|
|
74
|
+
NmapTool(),
|
|
75
|
+
HttpxTool(),
|
|
76
|
+
NucleiTool(),
|
|
77
|
+
FfufTool(),
|
|
78
|
+
KatanaTool(),
|
|
79
|
+
SubfinderTool(),
|
|
80
|
+
AmassTool(),
|
|
81
|
+
SqlmapTool(),
|
|
82
|
+
CommixTool(),
|
|
83
|
+
WpscanTool(),
|
|
84
|
+
Enum4linuxTool(),
|
|
85
|
+
NetexecTool(),
|
|
86
|
+
CrackmapexecTool(),
|
|
87
|
+
BloodhoundTool(),
|
|
88
|
+
TheharvesterTool(),
|
|
89
|
+
SpiderfootTool(),
|
|
90
|
+
NaabuTool(),
|
|
91
|
+
ArjunTool(),
|
|
92
|
+
WhatwebTool(),
|
|
93
|
+
DursgoTool(),
|
|
94
|
+
FlowlytTool(),
|
|
95
|
+
SearchsploitTool(),
|
|
96
|
+
ZighoundTool(),
|
|
97
|
+
ZizmorTool(),
|
|
98
|
+
FarsightTool(),
|
|
99
|
+
MsfconsoleTool(),
|
|
100
|
+
HydraTool(),
|
|
101
|
+
HashcatTool(),
|
|
102
|
+
GobusterTool(),
|
|
103
|
+
MasscanTool(),
|
|
104
|
+
JohnTool(),
|
|
105
|
+
ZapTool(),
|
|
106
|
+
WfuzzTool(),
|
|
107
|
+
DirbTool(),
|
|
108
|
+
MedusaTool(),
|
|
109
|
+
BettercapTool(),
|
|
110
|
+
ResponderTool(),
|
|
111
|
+
ParallelExecuteTool(),
|
|
112
|
+
ParallelStatusTool(),
|
|
113
|
+
PlaybookReconTool(),
|
|
114
|
+
PlaybookWebappTool(),
|
|
115
|
+
PlaybookAdTool(),
|
|
116
|
+
PlaybookEngineTool(),
|
|
117
|
+
PlaybookListTool(),
|
|
118
|
+
PlaybookStatusTool(),
|
|
119
|
+
VaultWriteTool(),
|
|
120
|
+
VaultReadTool(),
|
|
121
|
+
VaultQueryTool(),
|
|
122
|
+
VaultListTool(),
|
|
123
|
+
VaultDeleteTool(),
|
|
124
|
+
VaultStatsTool(),
|
|
125
|
+
]
|