Repository navigation
Expand file tree
/
Copy pathmcp_console.py
More file actions
660 lines (581 loc) · 31.7 KB
/
Copy pathmcp_console.py
File metadata and controls
660 lines (581 loc) · 31.7 KB
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import os
import sys
from pathlib import Path
# Fix sys.path for robust root-relative imports
PROJECT_ROOT = Path(__file__).resolve().parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
import json
import time
import threading
import requests
import pyfiglet
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich.panel import Panel
from rich.layout import Layout
from rich.prompt import Prompt
from rich.align import Align
from rich.status import Status
import websockets
import asyncio
import argparse
# --- Configuration ---
# Read bridge port from config.yaml (single source of truth), allow env var override
_bridge_port = 8321
try:
import yaml as _yaml
_config_path = PROJECT_ROOT / "config.yaml"
if _config_path.exists():
with open(_config_path) as _f:
_cfg = _yaml.safe_load(_f)
_bridge_port = _cfg.get("bridge", {}).get("port", 8321)
except Exception:
pass
parser = argparse.ArgumentParser(description="PulseLab Agentic Console")
parser.add_argument("--url", help="Bridge API URL (e.g. http://192.168.1.100:8321)", default=None)
parser.add_argument("--session", help="Resume a specific session engagement ID", default=None)
args = parser.parse_args()
BRIDGE_URL = args.url or os.environ.get("BRIDGE_URL", f"http://localhost:{_bridge_port}")
# Ensure no trailing slash
BRIDGE_URL = BRIDGE_URL.rstrip("/")
WS_URL = BRIDGE_URL.replace("http", "ws", 1) + "/ws"
SESSION_ID = args.session
REQUEST_TIMEOUT = 300
console = Console()
class MCPConsole:
def __init__(self):
self.events = []
self.approvals = []
self.agent_status = "idle"
self.is_running = True
self.current_mission = None
self.is_chat_active = False
self.tool_status = None
self.network_mode = "SANDBOX" # Default mode
self.bridge_host = "localhost"
self.bridge_port = _bridge_port
def display_banner(self):
banner = pyfiglet.figlet_format("Pulse Hacklab", font="slant")
console.print(f"[bold cyan]{banner}[/bold cyan]")
console.print("[bold white]Pentesting MCP Interactive Command Center[/bold white]")
console.print("-" * 50)
async def listen_ws(self):
"""Listen for real-time events from the Bridge with auto-reconnect."""
while self.is_running:
try:
async with websockets.connect(WS_URL, ping_interval=20, ping_timeout=60) as ws:
while self.is_running:
msg = await ws.recv()
payload = json.loads(msg)
self.handle_event(payload)
except Exception as e:
if self.is_running:
console.print(f"[dim red]WS reconnecting... ({e})[/dim red]")
await asyncio.sleep(2)
def handle_event(self, payload):
etype = payload.get("type")
data = payload.get("data")
if etype == "APPROVAL_REQUIRED":
# Only append if not already present
if not any(a.get("request_id") == data.get("request_id") for a in self.approvals):
self.approvals.append(data)
console.print(f"\n[bold yellow]⚠️ APPROVAL REQUIRED: {data['method']}[/bold yellow]")
console.print(f" Justification: {data['justification']}")
console.print(f" Request ID: [cyan]{data['request_id']}[/cyan]\n")
elif etype == "APPROVAL_UPDATED":
# Remove from local pending list if status changed from pending_approval
req_id = data.get("request_id")
status = data.get("status")
if status != "pending_approval":
self.approvals = [a for a in self.approvals if a.get("request_id") != req_id]
color = "green" if status == "approved" else "red"
console.print(f"\n[{color}]ℹ️ APPROVAL {status.upper()}:[/{color}] {req_id} by {data.get('approver', 'system')}")
elif etype == "JOB_STARTED":
job_id = data.get("job_id")
tool = data.get("tool")
console.print(f"\n[bold magenta]⚙️ BACKGROUND JOB STARTED:[/bold magenta] [cyan]{tool}[/cyan] (Job ID: [yellow]{job_id}[/yellow])\n")
elif etype == "JOB_COMPLETED":
job_id = data.get("job_id")
tool = data.get("tool")
duration = data.get("duration", 0)
console.print(f"\n[bold green]✅ BACKGROUND JOB COMPLETED:[/bold green] [cyan]{tool}[/cyan] (Job ID: [yellow]{job_id}[/yellow]) in [white]{duration}s[/white]")
# Optionally show brief preview of the result
res = data.get("result")
if res:
res_str = str(res)
if len(res_str) > 300:
res_str = res_str[:297] + "..."
console.print(f" Result preview: [dim]{res_str}[/dim]\n")
elif etype == "JOB_FAILED":
job_id = data.get("job_id")
tool = data.get("tool")
duration = data.get("duration", 0)
err = data.get("error", "Unknown error")
console.print(f"\n[bold red]❌ BACKGROUND JOB FAILED:[/bold red] [cyan]{tool}[/cyan] (Job ID: [yellow]{job_id}[/yellow]) in [white]{duration}s[/white]")
console.print(f" Error: [red]{err}[/red]\n")
elif etype == "LIVE_PACKET_BATCH":
job_id = data.get("job_id")
count = data.get("count", 0)
batch = data.get("batch", "")
console.print(f"\n[bold yellow]📡 LIVE PACKETS CAPTURED (Job: {job_id}, Count: {count}):[/bold yellow]")
for line in batch.split("\n")[:5]:
console.print(f" [dim]{line}[/dim]")
if count > 5:
console.print(f" [dim]... and {count - 5} more packets in this batch.[/dim]\n")
elif etype.startswith("AGENT_"):
self.events.append(payload)
if etype == "AGENT_STATUS":
self.agent_status = data["status"]
if etype == "AGENT_THOUGHT":
thought = data['content'].strip()
# Simple deduplication: don't show if it's exactly what we just showed
if thought and (not hasattr(self, '_last_thought') or self._last_thought != thought):
console.print(f"\n[dim italic blue]🧠 Reasoning:[/dim italic blue] {thought}")
self._last_thought = thought
elif etype == "AGENT_TOOL_CALL":
tool_name = data['tool']
args_summary = json.dumps(data['args'])
if len(args_summary) > 60: args_summary = args_summary[:57] + "..."
# If this is a background tool, we don't block the console status spinner
from core.tool_registry import get_tool_metadata
meta = get_tool_metadata(tool_name)
if meta.get("async_mode", False):
console.print(f"[bold cyan]⚒ Triggering background tool {tool_name}...[/bold cyan] [dim]({args_summary})[/dim]")
else:
if self.tool_status:
self.tool_status.stop()
self.tool_status = console.status(f"[bold blue]⚒ Using {tool_name}...[/bold blue] [dim]({args_summary})[/dim]")
self.tool_status.start()
elif etype == "AGENT_TOOL_RESULT":
tool_name = data.get("tool", "unknown")
from core.tool_registry import get_tool_metadata
meta = get_tool_metadata(tool_name)
# If the tool completed via background job, we already handle it with JOB_COMPLETED/JOB_FAILED
if meta.get("async_mode", False):
# Just print job start ack
pass
else:
if self.tool_status:
self.tool_status.stop()
self.tool_status = None
res = data.get("result", "")
exit_code = data.get("exit_code")
if exit_code == 124:
console.print(f"[bold red]✖ Timeout:[/bold red] The tool was killed after exceeding its time limit.")
# Smart result display
try:
import ast
parsed = None
if isinstance(res, str):
try:
parsed = json.loads(res)
except ValueError:
try:
parsed = ast.literal_eval(res)
except (ValueError, SyntaxError):
pass
elif isinstance(res, dict):
parsed = res
if isinstance(parsed, dict):
# Handle job_status wrapper
if parsed.get("method") == "job_status" and "data" in parsed:
job_data = parsed["data"]
job_id = job_data.get("id", "unknown")
status = job_data.get("status", "unknown")
tool = job_data.get("tool", "unknown")
console.print(f"[bold green]✔ Job Status ({tool}):[/bold green] {status.upper()} (ID: {job_id})")
res = None # Suppress full raw output
# Handle direct hosts array
elif "hosts" in parsed:
hosts = parsed["hosts"]
up_hosts = [h for h in hosts if h.get("status") == "up"]
console.print(f"[bold green]✔ Result ({tool_name}):[/bold green] [cyan]{len(up_hosts)}[/cyan] hosts active / [dim]{len(hosts)}[/dim] scanned.")
for h in up_hosts[:10]: # Show first 10
ports = [str(p.get('port')) for p in h.get('ports', []) if isinstance(p, dict) and p.get('state') in ('open', 'filtered') or isinstance(p, dict) and p.get('status') in ('open', 'filtered')]
ports_str = f" [yellow]Ports: {', '.join(ports)}[/yellow]" if ports else ""
console.print(f" [bold white]→[/bold white] {h.get('ip')}{ports_str}")
if len(up_hosts) > 10:
console.print(f" [dim]... and {len(up_hosts)-10} more active hosts.[/dim]")
res = None # Already handled
# Generic dict summarization
elif res is not None:
# Just show the keys if it's a huge dict
if len(str(res)) > 500:
keys = list(parsed.keys())
console.print(f"[bold green]✔ Result Data:[/bold green] Collected structured data ({', '.join(keys[:10])}). Agent is analyzing...")
res = None
elif isinstance(res, str) and res:
# Fallback if literal_eval failed (e.g., due to datetime.datetime objects in the string)
if "'method': 'job_status'" in res or '"method": "job_status"' in res:
console.print(f"[bold green]✔ Job Status:[/bold green] Update received. Agent is analyzing...")
res = None
elif "'method': 'host_list'" in res or '"method": "host_list"' in res:
console.print(f"[bold green]✔ Host List:[/bold green] Data received. Agent is analyzing...")
res = None
except Exception as e:
pass
if res:
res_str = str(res)
if len(res_str) > 1000:
res_str = res_str[:1000] + "\n[dim]... (output truncated, see logs for full detail) ...[/dim]"
console.print(f"[bold green]✔ Result:[/bold green] {res_str}")
def fetch_approvals(self):
try:
res = requests.get(f"{BRIDGE_URL}/api/approvals", timeout=REQUEST_TIMEOUT)
if res.status_code == 200:
self.approvals = res.json()
except Exception:
pass
def start_mission(self, prompt):
try:
res = requests.post(
f"{BRIDGE_URL}/api/agent/mission",
json={"prompt": prompt, "max_steps": 40},
timeout=REQUEST_TIMEOUT,
)
if res.status_code == 200:
console.print(f"[bold green]Mission Started:[/bold green] {prompt}")
self.current_mission = prompt
else:
console.print(f"[bold red]Error starting mission: {res.text}[/bold red]")
except Exception as e:
console.print(f"[bold red]Connection Error: {e}[/bold red]")
def approve(self, request_id):
try:
res = requests.post(
f"{BRIDGE_URL}/api/approvals/approve",
params={"request_id": request_id},
timeout=REQUEST_TIMEOUT,
)
if res.status_code == 200:
console.print(f"[bold green]Authorized:[/bold green] {request_id}")
self.approvals = [a for a in self.approvals if a['request_id'] != request_id]
else:
console.print(f"[bold red]Error approving: {res.text}[/bold red]")
except Exception as e:
console.print(f"[bold red]Connection Error: {e}[/bold red]")
def deny(self, request_id, reason="Denied via Console"):
try:
res = requests.post(
f"{BRIDGE_URL}/api/approvals/deny",
params={"request_id": request_id, "reason": reason},
timeout=REQUEST_TIMEOUT,
)
if res.status_code == 200:
console.print(f"[bold red]Denied:[/bold red] {request_id} ({reason})")
self.approvals = [a for a in self.approvals if a['request_id'] != request_id]
else:
console.print(f"[bold red]Error denying: {res.text}[/bold red]")
except Exception as e:
console.print(f"[bold red]Connection Error: {e}[/bold red]")
def chat_with_agent(self, message):
"""Synchronous chat call to the bridge."""
try:
res = requests.post(
f"{BRIDGE_URL}/api/agent/chat",
json={"message": message, "max_steps": 15},
timeout=REQUEST_TIMEOUT,
)
if res.status_code == 200:
return res.json().get("response", "")
else:
return f"Error: {res.text}"
except Exception as e:
return f"Connection Error: {e}"
def reset_session(self):
"""Reset the current agent session history."""
try:
res = requests.post(f"{BRIDGE_URL}/api/agent/session/clear", timeout=REQUEST_TIMEOUT)
if res.status_code == 200:
console.print("[bold green]Success:[/bold green] Agent history cleared. Starting fresh.")
else:
console.print(f"[bold red]Error clearing session:[/bold red] {res.text}")
except Exception as e:
console.print(f"[bold red]Connection Error:[/bold red] {e}")
def manage_chat(self):
"""Interactive REPL for chatting with the agent."""
console.print("\n[bold cyan]Entering Interactive RE Mode[/bold cyan]")
console.print("[dim]The agent will explain its reasoning and ask for your input.[/dim]")
console.print("[dim]Type 'exit' or 'back' to return to main menu.[/dim]\n")
while True:
user_input = Prompt.ask("[bold green]You[/bold green]")
if user_input.lower() in ("exit", "back", "quit"):
break
cleaned_input = user_input.strip()
if cleaned_input.startswith("/"):
cmd_parts = cleaned_input[1:].strip().split()
if not cmd_parts:
continue
cmd_name = cmd_parts[0].lower()
if cmd_name == "approvals":
self.manage_approvals()
continue
elif cmd_name == "status":
self.show_status()
continue
elif cmd_name == "docker":
self.show_docker_status()
continue
elif cmd_name == "clear":
console.clear()
continue
elif cmd_name == "toggle":
self.toggle_network_mode()
continue
elif cmd_name == "help":
console.print("[bold yellow]Chat Mode CLI Commands (Prefix with /):[/bold yellow]")
console.print(" [cyan]/approvals[/cyan] - View and handle pending authorizations")
console.print(" [cyan]/status[/cyan] - View system and agent status")
console.print(" [cyan]/docker[/cyan] - View Docker container/image status")
console.print(" [cyan]/toggle[/cyan] - Toggle network mode (SANDBOX <-> HOST)")
console.print(" [cyan]/clear[/cyan] - Clear console screen")
console.print(" [cyan]/approve <id>[/cyan] - Approve a request directly")
console.print(" [cyan]/deny <id>[/cyan] - Deny a request directly")
console.print(" [cyan]/exit[/cyan] - Exit chat mode")
continue
elif cmd_name in ("exit", "back", "quit"):
break
elif cmd_name in ("approve", "deny"):
if len(cmd_parts) >= 2:
req_id = cmd_parts[1]
if cmd_name == "approve":
self.approve(req_id)
user_input = f"[SYSTEM] User approved request {req_id}. Please proceed with the execution."
else:
reason = " ".join(cmd_parts[2:]) if len(cmd_parts) > 2 else "Denied via Console Chat"
self.deny(req_id, reason)
user_input = f"[SYSTEM] User denied request {req_id} (Reason: {reason}). Please find an alternative approach."
else:
console.print("[red]Error: Request ID required for direct approve/deny.[/red]")
continue
else:
console.print(f"[red]Unknown CLI command: /{cmd_name}. Type /help for options.[/red]")
continue
with console.status("[bold blue]Agent is thinking...[/bold blue]"):
self.is_chat_active = True
try:
response = self.chat_with_agent(user_input)
finally:
self.is_chat_active = False
# --- Inline Approval UX ---
# Detect APPROVAL_REQUIRED and present interactive choices
if "APPROVAL_REQUIRED" in response:
self.fetch_approvals()
if self.approvals:
for appr in list(self.approvals):
req_id = appr.get("request_id", "unknown")
method = appr.get("method", "unknown")
justification = appr.get("justification", "N/A")
params = appr.get("params", {})
console.print(f"\n[bold yellow]⚠️ Action requires your approval:[/bold yellow]")
console.print(f" Tool: [bold cyan]{method}[/bold cyan]")
console.print(f" Justification: [italic]{justification}[/italic]")
if params:
params_str = json.dumps(params, indent=2)
if len(params_str) > 300:
params_str = params_str[:297] + "..."
console.print(f" Parameters: [dim]{params_str}[/dim]")
console.print(f" Request ID: [cyan]{req_id}[/cyan]\n")
action = Prompt.ask(
"[bold yellow]Your decision[/bold yellow]",
choices=["approve", "deny", "skip"],
default="approve",
)
if action == "approve":
self.approve(req_id)
system_msg = f"[SYSTEM] User approved request {req_id}. Please proceed with the execution."
with console.status("[bold blue]Agent executing approved action...[/bold blue]"):
self.is_chat_active = True
try:
followup = self.chat_with_agent(system_msg)
finally:
self.is_chat_active = False
console.print(f"\n[bold blue]Agent:[/bold blue] {followup}\n")
elif action == "deny":
reason = Prompt.ask("Reason for denial", default="Denied by operator")
self.deny(req_id, reason)
system_msg = f"[SYSTEM] User denied request {req_id} (Reason: {reason}). Please find an alternative approach."
with console.status("[bold blue]Agent adjusting...[/bold blue]"):
self.is_chat_active = True
try:
followup = self.chat_with_agent(system_msg)
finally:
self.is_chat_active = False
console.print(f"\n[bold blue]Agent:[/bold blue] {followup}\n")
else:
console.print("[yellow]⏳ Deferred. Use 'approvals' menu to handle later.[/yellow]\n")
else:
# No pending approvals found — show the raw response
console.print(f"\n[bold blue]Agent:[/bold blue] {response}\n")
else:
# Print the agent's final conversational response
console.print(f"\n[bold blue]Agent:[/bold blue] {response}\n")
def toggle_network_mode(self):
old_mode = self.network_mode
self.network_mode = "HOST" if old_mode == "SANDBOX" else "SANDBOX"
# Notify the bridge about the mode change
try:
requests.post(f"{BRIDGE_URL}/config/network_mode",
json={"mode": self.network_mode.lower()}, timeout=2)
icon = "🛡️" if self.network_mode == "SANDBOX" else "🔥"
console.print(f"\n{icon} [bold]Network Mode Toggled:[/bold] {old_mode} -> [bold magenta]{self.network_mode}[/bold magenta]")
if self.network_mode == "HOST":
console.print("[bold red]WARNING: Tools now have direct access to your local network![/bold red]\n")
else:
console.print("[bold green]SAFE: Tools are now isolated in the sandbox.[/bold green]\n")
except Exception as e:
console.print(f"[red]Error notifying bridge of mode change: {e}[/red]")
def run(self):
self.display_banner()
# Start WS listener in background thread
def ws_thread():
asyncio.run(self.listen_ws())
threading.Thread(target=ws_thread, daemon=True).start()
if SESSION_ID:
console.print(f"[bold yellow]Resuming session:[/bold yellow] {SESSION_ID}")
# We don't strictly need to call an API here if the bridge already has it,
# but it's good to have it in the future.
while self.is_running:
mode_color = "green" if self.network_mode == "SANDBOX" else "bold red"
mode_display = f"[[{mode_color}]{self.network_mode}[/{mode_color}]]"
prompt_text = f"PulseLab {mode_display} >"
try:
cmd = Prompt.ask(prompt_text, choices=["mission", "chat", "re", "toggle", "approvals", "status", "docker", "new", "exit", "clear"])
if cmd == "exit":
self.is_running = False
elif cmd == "new":
self.reset_session()
elif cmd == "toggle":
self.toggle_network_mode()
elif cmd == "clear":
console.clear()
self.display_banner()
elif cmd == "status":
self.show_status()
elif cmd == "docker":
self.show_docker_status()
elif cmd == "approvals":
self.manage_approvals()
elif cmd == "mission":
prompt = Prompt.ask("Enter objective")
self.start_mission(prompt)
elif cmd == "chat":
self.manage_chat()
elif cmd == "re":
self.manage_re()
except KeyboardInterrupt:
break
def manage_re(self):
"""Dedicated mode for live Ghidra interaction."""
console.print("\n[bold cyan]Live Ghidra Interaction Mode[/bold cyan]")
console.print("[dim]Directly trigger RE tools on the active Ghidra session.[/dim]\n")
while True:
action = Prompt.ask(
"[bold cyan]RE[/bold cyan] >",
choices=["state", "list", "decompile", "rename", "comment", "analyze", "back"],
default="state"
)
if action == "back":
break
if action == "state":
with console.status("Syncing with Ghidra..."):
res = self.chat_with_agent("Sync with my Ghidra view and tell me where I am.")
console.print(f"\n[bold blue]Ghidra State:[/bold blue] {res}\n")
elif action == "list":
with console.status("Fetching functions from Ghidra..."):
res = self.chat_with_agent("List the first 20 interesting functions from the current Ghidra session.")
console.print(f"\n[bold blue]Functions:[/bold blue]\n{res}\n")
elif action == "decompile":
func = Prompt.ask("Function name or address")
with console.status(f"Decompiling {func}..."):
res = self.chat_with_agent(f"Decompile the function '{func}' and explain its purpose.")
console.print(f"\n[bold blue]Analysis:[/bold blue]\n{res}\n")
elif action == "analyze":
target = Prompt.ask("Start analysis from (name/address)", default="SDL_main_DevilutionX")
console.print(f"[bold yellow]Starting autonomous analysis mission from {target}...[/bold yellow]")
self.start_mission(f"Realiza un análisis sistemático empezando por {target}. Decompilea cada función llamada, identifica su propósito, renómbralas en Ghidra y añade comentarios. Prioriza lógica de red y juego.")
break # Return to main menu to watch events
elif action == "rename":
old = Prompt.ask("Current name")
new = Prompt.ask("New name")
with console.status(f"Renaming {old} to {new}..."):
res = self.chat_with_agent(f"Rename the symbol '{old}' to '{new}' in Ghidra.")
console.print(f"\n[bold blue]Result:[/bold blue] {res}\n")
elif action == "comment":
addr = Prompt.ask("Address (hex)")
msg = Prompt.ask("Comment text")
with console.status(f"Setting comment at {addr}..."):
res = self.chat_with_agent(f"Add a comment at {addr} in Ghidra: '{msg}'")
console.print(f"\n[bold blue]Result:[/bold blue] {res}\n")
def show_status(self):
table = Table(title="System Status")
table.add_column("Service", style="cyan")
table.add_column("Status", style="magenta")
try:
requests.get(BRIDGE_URL, timeout=1)
table.add_row("API Bridge", "[green]Online[/green]")
except Exception:
table.add_row("API Bridge", "[red]Offline[/red]")
table.add_row("Agent State", f"[yellow]{self.agent_status}[/yellow]")
table.add_row("Pending Approvals", str(len(self.approvals)))
console.print(table)
def show_docker_status(self):
console.print("[bold yellow]Checking Docker Infrastructure...[/bold yellow]\n")
# 1. Show Images
try:
res = requests.get(f"{BRIDGE_URL}/api/docker/images", timeout=REQUEST_TIMEOUT)
if res.status_code == 200:
data = res.json().get("data", {}).get("images", [])
table = Table(title="Built Images (mcp-kali-*)")
table.add_column("Tag", style="cyan")
table.add_column("Size", style="magenta")
table.add_column("ID", style="dim")
for img in data:
table.add_row(img['tags'][0], f"{img['size_mb']} MB", img['id'][:12])
console.print(table)
else:
console.print("[red]Failed to fetch images.[/red]")
except Exception as e:
console.print(f"[red]Error: {e}[/red]")
# 2. Show Active Containers
try:
res = requests.get(f"{BRIDGE_URL}/api/docker/containers", timeout=REQUEST_TIMEOUT)
if res.status_code == 200:
data = res.json().get("data", {}).get("containers", [])
if not data:
console.print("\n[italic]No active containers found. (Containers are ephemeral and only run during tool execution.)[/italic]")
else:
table = Table(title="Active Tool Containers")
table.add_column("ID", style="cyan")
table.add_column("Image", style="magenta")
table.add_column("Status", style="green")
for c in data:
table.add_row(c['id'], c['image'], c['status'])
console.print(table)
except Exception:
pass
def manage_approvals(self):
self.fetch_approvals()
if not self.approvals:
console.print("[yellow]No pending approvals.[/yellow]")
return
table = Table(title="Pending Authorizations")
table.add_column("ID", style="cyan")
table.add_column("Tool", style="magenta")
table.add_column("Justification", style="white")
for app in self.approvals:
table.add_row(app['request_id'], app['method'], app['justification'])
console.print(table)
req_id = Prompt.ask("Enter Request ID to handle (or 'back')")
if req_id != "back":
action = Prompt.ask("Action", choices=["approve", "deny"], default="approve")
if action == "approve":
self.approve(req_id)
else:
reason = Prompt.ask("Reason for denial", default="Denied via Console")
self.deny(req_id, reason)
if __name__ == "__main__":
app = MCPConsole()
app.run()