ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat(mcp): upgrade ARES MCP CLI to product-grade standard
Mafifrizif18523b69bb0
diff --git a/README.md b/README.mdindex a93088c..9e3ebc2 100644--- a/README.md+++ b/README.md@@ -404,6 +404,32 @@ ARES enforces strict RBAC permissions across all API endpoints and UI controls:---+## π ARES MCP Gateway & Product-Grade CLI++ARES includes a production-grade Model Context Protocol (MCP) Gateway that enables AI development environments (Cursor IDE, Claude Desktop, Windsurf, VS Code Cline, Zed, Open-WebUI, LibreChat) to interact with the ARES purple-team offensive platform under strict governance.++### Quick Start (Windows & Linux)++Launch the interactive OpenCode/OpenClaw-style console:+```cmd+mcp.bat+```+Or use the scriptable CLI directly:+```bash+# Verify health and security readiness+python -m ares.cli.main mcp doctor --json++# Pre-flight check and obtain execution confirmation token+python -m ares.cli.main mcp dry-run --target 10.0.0.5 --module ad.kerberoast++# 1-Click IDE Setup (Cursor, Claude, Windsurf, Cline)+python -m ares.cli.main mcp setup --client cursor+```++See [**ARES MCP Server & Product-Grade CLI Specification**](docs/mcp-server.md) for full protocol guarantees, exit codes, and pipeline automation guides.++---+## π οΈ Extensible Developer SDK (Next-Gen Autonomous Architecture)ARES provides a first-class, type-safe Python SDK (`ares.sdk`) to build custom adversary modules, simulate techniques in isolated test harnesses, and automate engagements programmatically:@@ -480,7 +506,7 @@ Comprehensive documentation is available in the [`docs/`](docs/) directory:- [**Documentation Portal & Subsystem Index**](docs/README.md)- [**Quickstart Engagement Guide**](QUICKSTART.md)- [**Next-Gen Module SDK Specification (v2)**](docs/module_sdk.md)-- [**Sovereign MCP Server Specification (Universal AI Gateway)**](docs/mcp-server.md)+- [**ARES MCP Server & Product-Grade CLI Specification**](docs/mcp-server.md)- [**Step-by-Step Module Development Guide**](docs/module-development.md)- [**Dashboard Surface-by-Surface Manual**](docs/dashboard-guide.md)- [**Adversary Module Catalog & Schemas**](docs/modules.md)diff --git a/ares/cli/console.py b/ares/cli/console.pyindex 123a603..fe830f5 100644--- a/ares/cli/console.py+++ b/ares/cli/console.py@@ -1,6 +1,6 @@"""ARES MCP - Model Context Protocol Gateway Console (OpenCode / OpenClaw style).-Tactical, unified, zero-friction interactive terminal for:+Tactical, unified, product-grade interactive terminal for:- 1-Click Auto-Setup for Cursor, Claude Desktop, Windsurf, and Cline- Interactive Module Catalog Explorer with OPSEC noise ratings- Pre-Flight Target ScopeGuard & Dry-Run Simulator with HMAC confirmation tokens@@ -11,24 +11,38 @@ from __future__ import annotationsimport asyncioimport json-import osimport sysfrom pathlib import Pathfrom typing import Anyfrom rich import boxfrom rich.align import Align-from rich.console import Consolefrom rich.panel import Panelfrom rich.prompt import Promptfrom rich.syntax import Syntaxfrom rich.table import Table-from rich.text import Text+from ares.cli.mcp_cli_utils import (+ COLOR_ERROR,+ COLOR_INDEX,+ COLOR_LABEL,+ COLOR_NEUTRAL,+ COLOR_SUCCESS,+ COLOR_VALUE,+ COLOR_WARNING,+ EXIT_SIGINT,+ EXIT_SUCCESS,+ get_mcp_console,+)+from ares.cli.mcp_commands import (+ execute_dry_run,+ get_doctor_diagnostics,+ query_module_catalog,+ setup_client_configuration,+)from ares.mcp.server import AresMcpServer-from ares.modules.descriptors import FIRST_PARTY_DESCRIPTORS-console = Console(safe_box=True)+console = get_mcp_console()ASCII_BANNER = r"""[bold cyan] _ ___ ___ ___ [/] [bold white] __ __ ___ ___ [/]@@ -39,21 +53,28 @@ ASCII_BANNER = r"""def render_header() -> None:- """Render the tactical ARES MCP header."""+ """Render the tactical ARES MCP header with clean spacing."""+ console.print()console.print(Align.center(ASCII_BANNER))- header_table = Table(box=box.ASCII, show_header=False, expand=True, border_style="cyan")+ header_table = Table(box=box.ROUNDED, show_header=False, expand=True, border_style="cyan")header_table.add_column(justify="left")header_table.add_column(justify="right")header_table.add_row(- "[bold white]ARES MCP[/bold white] [dim]- Automated Red Team Engagement System[/dim]",- "[bold green][*] READY[/bold green] [dim]v6.0.0[/dim]",+ f"[{COLOR_VALUE}]ARES MCP[/] [{COLOR_NEUTRAL}]- Automated Red Team System[/]",+ f"[{COLOR_SUCCESS}][*] READY[/] [{COLOR_NEUTRAL}]v6.0.0[/]",)- header_table.add_row(- "[cyan]Modules:[/] [bold white]62 Active[/] [cyan]Tools:[/] [bold white]9 Governed[/] [cyan]Transport:[/] [bold white]Stdio + SSE[/]",- "[cyan]ScopeGuard:[/] [bold green]Enforced[/] [cyan]Auth:[/] [bold yellow]HMAC-SHA256[/]",+ stat_left = (+ f"[{COLOR_LABEL}]Modules:[/] [{COLOR_VALUE}]62 Active[/] "+ f"[{COLOR_LABEL}]Tools:[/] [{COLOR_VALUE}]9 Governed[/] "+ f"[{COLOR_LABEL}]Transport:[/] [{COLOR_VALUE}]Stdio + SSE[/]")+ stat_right = (+ f"[{COLOR_LABEL}]ScopeGuard:[/] [{COLOR_SUCCESS}]Enforced[/] "+ f"[{COLOR_LABEL}]Auth:[/] [{COLOR_WARNING}]HMAC-SHA256[/]"+ )+ header_table.add_row(stat_left, stat_right)console.print(header_table)console.print()@@ -62,237 +83,160 @@ def render_header() -> None:def auto_setup_client(workspace_root: Path) -> None:"""1-Click Auto-Setup for AI IDEs and clients without manual copy-paste."""render_header()+ setup_lines = [+ f"[{COLOR_VALUE}]Select your AI client to configure MCP automatically:[/]\n",+ f" [{COLOR_INDEX}][1][/] Cursor IDE "+ f"[{COLOR_NEUTRAL}]Auto-configures .cursor/mcp.json in workspace[/]",+ f" [{COLOR_INDEX}][2][/] Claude Desktop "+ f"[{COLOR_NEUTRAL}]Auto-configures Claude desktop config[/]",+ f" [{COLOR_INDEX}][3][/] Windsurf "+ f"[{COLOR_NEUTRAL}]Auto-configures ~/.codeium/windsurf/mcp_config.json[/]",+ f" [{COLOR_INDEX}][4][/] VS Code (Cline) "+ f"[{COLOR_NEUTRAL}]Auto-configures cline_mcp_settings.json[/]",+ f" [{COLOR_ERROR}][0][/] Back to Menu",+ ]console.print(Panel(- "[bold white]Select your AI client to configure MCP connection automatically:[/]\n\n"- " [bold cyan][1][/] Cursor IDE [dim]Auto-configures .cursor/mcp.json in workspace[/]\n"- " [bold cyan][2][/] Claude Desktop [dim]Auto-configures %APPDATA%\\Claude\\claude_desktop_config.json[/]\n"- " [bold cyan][3][/] Windsurf [dim]Auto-configures ~/.codeium/windsurf/mcp_config.json[/]\n"- " [bold cyan][4][/] VS Code (Cline) [dim]Auto-configures cline_mcp_settings.json[/]\n"- " [bold cyan][0][/] Back to Menu",- title="[bold green]1-Click Client Setup[/]",+ "\n".join(setup_lines),+ title=f"[{COLOR_SUCCESS}]1-Click Client Setup[/]",border_style="green",- box=box.ASCII,+ box=box.ROUNDED,))- choice = Prompt.ask("[bold yellow]Select target client[/]", choices=["1", "2", "3", "4", "0"], default="1")- executable = sys.executable+ choice = Prompt.ask(+ f"[{COLOR_LABEL}]Select target client[/]",+ choices=["1", "2", "3", "4", "0"],+ default="1",+ )+ client_map = {"1": "cursor", "2": "claude", "3": "windsurf", "4": "cline"}if choice == "0":return- if choice == "1":- cursor_dir = workspace_root / ".cursor"- cursor_dir.mkdir(parents=True, exist_ok=True)- mcp_file = cursor_dir / "mcp.json"-- cfg: dict[str, Any] = {"mcpServers": {}}- if mcp_file.exists():- try:- cfg = json.loads(mcp_file.read_text(encoding="utf-8"))- except Exception:- cfg = {"mcpServers": {}}-- cfg.setdefault("mcpServers", {})["ares"] = {- "command": executable,- "args": ["-m", "ares.mcp"],- }- mcp_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")-- console.print(Panel(- f"[bold green][OK] Cursor MCP configuration successfully written![/]\n\n"- f" [cyan]Config Path:[/] {mcp_file}\n"- f" [cyan]Python:[/] {executable}\n"- f" [cyan]Tools:[/] 9 ARES offensive security tools registered\n\n"- f"[bold white]Next Steps:[/] Open Cursor Settings -> Features -> MCP to verify the connection.",- title="[bold green]Cursor IDE Setup Complete[/]",- border_style="green",- box=box.ASCII,- ))-- elif choice == "2":- appdata = os.environ.get("APPDATA")- if not appdata:- console.print("[bold red]Could not locate %APPDATA% directory on this system.[/]")- Prompt.ask("\nPress Enter to return...")- return-- claude_dir = Path(appdata) / "Claude"- claude_dir.mkdir(parents=True, exist_ok=True)- claude_file = claude_dir / "claude_desktop_config.json"-- cfg = {"mcpServers": {}}- if claude_file.exists():- try:- cfg = json.loads(claude_file.read_text(encoding="utf-8"))- except Exception:- cfg = {"mcpServers": {}}-- cfg.setdefault("mcpServers", {})["ares"] = {- "command": executable,- "args": ["-m", "ares.mcp"],- }- claude_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")-- console.print(Panel(- f"[bold green][OK] Claude Desktop configuration successfully written![/]\n\n"- f" [cyan]Config Path:[/] {claude_file}\n"- f" [cyan]Python:[/] {executable}\n\n"- f"[bold white]Next Steps:[/] Restart Claude Desktop. The hammer icon will show ARES tools.",- title="[bold green]Claude Desktop Setup Complete[/]",- border_style="green",- box=box.ASCII,- ))-- elif choice == "3":- home = Path.home()- windsurf_dir = home / ".codeium" / "windsurf"- windsurf_dir.mkdir(parents=True, exist_ok=True)- windsurf_file = windsurf_dir / "mcp_config.json"-- cfg = {"mcpServers": {}}- if windsurf_file.exists():- try:- cfg = json.loads(windsurf_file.read_text(encoding="utf-8"))- except Exception:- cfg = {"mcpServers": {}}-- cfg.setdefault("mcpServers", {})["ares"] = {- "command": executable,- "args": ["-m", "ares.mcp"],- }- windsurf_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")-- console.print(Panel(- f"[bold green][OK] Windsurf configuration successfully written![/]\n\n"- f" [cyan]Config Path:[/] {windsurf_file}\n",- title="[bold green]Windsurf Setup Complete[/]",- border_style="green",- box=box.ASCII,- ))-- elif choice == "4":- cline_file = workspace_root / "cline_mcp_settings.json"- cfg = {- "mcpServers": {- "ares": {- "command": executable,- "args": ["-m", "ares.mcp"],- "disabled": False,- "alwaysAllow": ["ares_list_campaigns", "ares_inspect_module_catalog"],- }- }- }- cline_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")- console.print(Panel(- f"[bold green][OK] Cline MCP settings written to workspace![/]\n\n"- f" [cyan]Config Path:[/] {cline_file}\n",- title="[bold green]Cline Setup Complete[/]",- border_style="green",- box=box.ASCII,- ))-- Prompt.ask("\n[dim]Press Enter to return to menu...[/]")+ client_name = client_map.get(choice, "cursor")+ code, msg = setup_client_configuration(client_name, workspace_root=workspace_root)++ status_color = COLOR_SUCCESS if code == EXIT_SUCCESS else COLOR_ERROR+ status_icon = "[OK]" if code == EXIT_SUCCESS else "[ERR]"+ console.print()+ verification_msg = "Restart your client or check MCP settings to verify connection."+ console.print(Panel(+ f"[{status_color}]{status_icon} {msg}[/]\n\n"+ f"[{COLOR_LABEL}]Client Target:[/] [{COLOR_VALUE}]{client_name.upper()}[/]\n"+ f"[{COLOR_LABEL}]Tools Ready:[/] [{COLOR_VALUE}]9 ARES operational tools[/]\n\n"+ f"[{COLOR_VALUE}]Verification:[/] {verification_msg}",+ title=f"[{status_color}]{client_name.capitalize()} Setup Status[/]",+ border_style="green" if code == EXIT_SUCCESS else "red",+ box=box.ROUNDED,+ ))++ Prompt.ask(f"\n[{COLOR_NEUTRAL}]Press Enter to return to menu...[/]")def explore_catalog() -> None:- """Interactive Module Catalog Explorer."""+ """Interactive Module Catalog Explorer with OPSEC and Governance ratings."""render_header()- query = Prompt.ask("[bold yellow]Filter by keyword or category[/] [dim](e.g. 'ad', 'kerberos', or Enter for all)[/]", default="").strip().lower()-- matches = []- for mod_id, desc in sorted(FIRST_PARTY_DESCRIPTORS.items()):- category_str = desc.category.value if hasattr(desc.category, "value") else str(desc.category)- opsec_val = desc.opsec.value if hasattr(desc.opsec, "value") else str(desc.opsec)- source_cls = str(desc.source_class)- if not query or query in mod_id.lower() or query in category_str.lower() or query in source_cls.lower():- matches.append((mod_id, desc, category_str, opsec_val, source_cls))-- table = Table(title=f"ARES Module Catalog ({len(matches)} Modules)", box=box.ASCII)- table.add_column("Module ID", style="bold cyan")- table.add_column("Category", style="yellow")+ query_prompt = (+ f"[{COLOR_LABEL}]Filter by keyword or category[/] "+ f"[{COLOR_NEUTRAL}](e.g. 'ad', 'kerberos', or Enter for all)[/]"+ )+ query = Prompt.ask(query_prompt, default="").strip()++ matches = query_module_catalog(query=query if query else None)++ table = Table(title=f"ARES Module Catalog ({len(matches)} Modules)", box=box.ROUNDED)+ table.add_column("Module ID", style=COLOR_LABEL)+ table.add_column("Category", style=COLOR_VALUE)table.add_column("OPSEC Noise", justify="center")- table.add_column("Execution Governance")+ table.add_column("Governance")table.add_column("Source Engine Class")opsec_styles = {- "silent": "[bold green]SILENT[/]",- "low": "[green]LOW[/]",- "medium": "[yellow]MEDIUM[/]",- "high_noise": "[bold red]HIGH NOISE[/]",+ "silent": f"[{COLOR_SUCCESS}]SILENT[/]",+ "low": f"[{COLOR_SUCCESS}]LOW[/]",+ "medium": f"[{COLOR_WARNING}]MEDIUM[/]",+ "high_noise": f"[{COLOR_ERROR}]HIGH NOISE[/]",}- for mod_id, desc, category_str, opsec_val, source_cls in matches[:25]:- opsec_badge = opsec_styles.get(opsec_val.lower(), opsec_val.upper())- priv_badge = "[red]Approval Required[/]" if desc.explicit_attempt_approval else "[green]Standard[/]"+ for item in matches[:25]:+ opsec_val = item["opsec_level"].lower()+ opsec_badge = opsec_styles.get(opsec_val, f"[{COLOR_VALUE}]{opsec_val.upper()}[/]")+ gov_badge = (+ f"[{COLOR_WARNING}]Approval Required[/]"+ if item["requires_approval"]+ else f"[{COLOR_SUCCESS}]Standard[/]"+ )table.add_row(- mod_id,- category_str,+ item["module_id"],+ item["category"],opsec_badge,- priv_badge,- source_cls,+ gov_badge,+ item["source_class"],)+ console.print()console.print(table)if len(matches) > 25:- console.print(f"[dim]...showing first 25 of {len(matches)} matching modules.[/]")+ more_msg = (+ f"...showing first 25 of {len(matches)} matching modules. "+ "Use filter to narrow search."+ )+ console.print(f"[{COLOR_NEUTRAL}]{more_msg}[/]")- Prompt.ask("\n[dim]Press Enter to return to menu...[/]")+ Prompt.ask(f"\n[{COLOR_NEUTRAL}]Press Enter to return to menu...[/]")def simulate_dry_run() -> None:"""Interactive ScopeGuard & Dry-Run Simulator."""render_header()console.print(Panel(- "[bold white]Pre-Flight Attack Simulation (Zero Packets Sent)[/]\n\n"- "Validates target against authorized CIDR ranges, evaluates OPSEC noise,\n"- "and issues a 60-second HMAC-SHA256 confirmation token required for live execution.",- title="[bold yellow]Target Scope & Dry-Run Simulator[/]",+ f"[{COLOR_VALUE}]Pre-Flight Attack Simulation (Zero Network Packets)[/]\n\n"+ f"Validates target against authorized CIDR ranges, evaluates OPSEC noise,\n"+ f"and issues a 60-second HMAC-SHA256 confirmation token required for live execution.",+ title=f"[{COLOR_WARNING}]Target Scope & Dry-Run Simulator[/]",border_style="yellow",- box=box.ASCII,+ box=box.ROUNDED,))- target = Prompt.ask("[bold cyan]Target IP or Hostname[/]", default="10.0.0.15")- module_id = Prompt.ask("[bold cyan]Module ID[/]", default="ad.kerberoast")- campaign_id = Prompt.ask("[bold cyan]Campaign ID[/]", default="lab-engagement-01")-- server = AresMcpServer()- result = asyncio.run(server.tool_registry.call_tool(- "ares_dry_run_module",- {- "campaign_id": campaign_id,- "module_id": module_id,- "target": target,- "params": {"domain": "corp.local"},- }- ))+ target = Prompt.ask(f"[{COLOR_LABEL}]Target IP or Hostname[/]", default="10.0.0.15")+ module_id = Prompt.ask(f"[{COLOR_LABEL}]Module ID[/]", default="ad.kerberoast")+ campaign_id = Prompt.ask(f"[{COLOR_LABEL}]Campaign ID[/]", default="lab-engagement-01")- raw_text = result.content[0].text if result.content else "{}"- try:- data = json.loads(raw_text)- except Exception:- data = {"output": raw_text}+ data = execute_dry_run(target=target, module_id=module_id, campaign_id=campaign_id)- token = data.get("confirmation_token", "N/A")+ receipt_code = data.get("confirmation_token", "N/A")scope_valid = data.get("scope_validation", {}).get("in_scope", True)opsec = data.get("opsec_assessment", {}).get("noise_level", "low")- status_badge = "[bold green][OK] IN-SCOPE (APPROVED)[/]" if scope_valid else "[bold red][FAIL] OUT-OF-SCOPE (BLOCKED)[/]"- token_display = f"[bold yellow]{token}[/]" if token != "N/A" else "[red]NONE[/]"+ status_badge = (+ f"[{COLOR_SUCCESS}][OK] IN-SCOPE (APPROVED)[/]"+ if scope_valid+ else f"[{COLOR_ERROR}][FAIL] OUT-OF-SCOPE (BLOCKED)[/]"+ )+ token_display = (+ f"[{COLOR_WARNING}]{receipt_code}[/]"+ if receipt_code != "N/A"+ else f"[{COLOR_ERROR}]NONE[/]"+ )+ status_val = data.get("status", "SUCCESS")+ card_hint = (+ "Use this confirmation_token with live execution tools to authorize the operation."+ )+ console.print()console.print(Panel(- f" [bold white]Module:[/bold white] [cyan]{module_id}[/cyan]\n"- f" [bold white]Target:[/bold white] [white]{target}[/white]\n"- f" [bold white]ScopeGuard:[/] {status_badge}\n"- f" [bold white]OPSEC Noise:[/] [yellow]{opsec.upper()}[/yellow]\n"- f" [bold white]Confirmation Token:[/] {token_display} [dim](Valid for 60s)[/]\n"- f" [bold white]Dry-Run Status:[/] [green]{data.get('status', 'SUCCESS')}[/green]\n\n"- f"[dim]Use this confirmation_token with live execution tools to authorize the operation.[/]",- title="[bold green]Pre-Flight Verification Card[/]",- border_style="green",- box=box.ASCII,+ f" [{COLOR_LABEL}]Module:[/] [{COLOR_VALUE}]{module_id}[/]\n"+ f" [{COLOR_LABEL}]Target:[/] [{COLOR_VALUE}]{target}[/]\n"+ f" [{COLOR_LABEL}]ScopeGuard:[/] {status_badge}\n"+ f" [{COLOR_LABEL}]OPSEC Noise:[/] [{COLOR_WARNING}]{opsec.upper()}[/]\n"+ f" [{COLOR_LABEL}]Confirmation Token:[/] {token_display} [{COLOR_NEUTRAL}](60s TTL)[/]\n"+ f" [{COLOR_LABEL}]Dry-Run Status:[/] [{COLOR_SUCCESS}]{status_val}[/]\n\n"+ f"[{COLOR_NEUTRAL}]{card_hint}[/]",+ title=f"[{COLOR_SUCCESS}]Pre-Flight Verification Card[/]",+ border_style="green" if scope_valid else "red",+ box=box.ROUNDED,))- Prompt.ask("\n[dim]Press Enter to return to menu...[/]")+ Prompt.ask(f"\n[{COLOR_NEUTRAL}]Press Enter to return to menu...[/]")def run_interactive_tool() -> None:@@ -303,21 +247,28 @@ def run_interactive_tool() -> None:tool_lines = []for i, t in enumerate(tools):- tool_lines.append(f" [bold cyan][{i+1}][/] [bold white]{t.name}[/bold white] [dim]- {t.description[:65]}...[/dim]")+ t_desc = t.description[:55]+ tool_lines.append(+ f" [{COLOR_INDEX}][{i+1}][/] [{COLOR_VALUE}]{t.name}[/] "+ f"[{COLOR_NEUTRAL}]- {t_desc}...[/]"+ )console.print(Panel("\n".join(tool_lines),- title="[bold cyan]Operational Tools (9 Registered)[/]",+ title=f"[{COLOR_LABEL}]Operational Tools (9 Registered)[/]",border_style="cyan",- box=box.ASCII,+ box=box.ROUNDED,))- selection = Prompt.ask("[bold yellow]Select tool number to execute[/] [dim](0 to cancel)[/]", default="1")+ select_prompt = (+ f"[{COLOR_LABEL}]Select tool number to execute[/] [{COLOR_NEUTRAL}](0 to cancel)[/]"+ )+ selection = Prompt.ask(select_prompt, default="1")if not selection.isdigit() or int(selection) < 1 or int(selection) > len(tools):returnchosen_tool = tools[int(selection) - 1]- console.print(f"\n[bold green]Executing:[/] [cyan]{chosen_tool.name}[/cyan]...")+ console.print(f"\n[{COLOR_SUCCESS}]Executing:[/] [{COLOR_LABEL}]{chosen_tool.name}[/]...")req_fields = getattr(chosen_tool.inputSchema, "required", None) or []if isinstance(chosen_tool.inputSchema, dict):@@ -325,114 +276,172 @@ def run_interactive_tool() -> None:args: dict[str, Any] = {}if "campaign_id" in req_fields:- args["campaign_id"] = Prompt.ask(" Enter [cyan]campaign_id[/]", default="lab-engagement-01")+ args["campaign_id"] = Prompt.ask(+ f" Enter [{COLOR_LABEL}]campaign_id[/]", default="lab-engagement-01"+ )if "target" in req_fields:- args["target"] = Prompt.ask(" Enter [cyan]target IP/domain[/]", default="10.0.0.5")+ args["target"] = Prompt.ask(+ f" Enter [{COLOR_LABEL}]target IP/domain[/]", default="10.0.0.5"+ )if "module_id" in req_fields:- args["module_id"] = Prompt.ask(" Enter [cyan]module_id[/]", default="ad.kerberoast")+ args["module_id"] = Prompt.ask(+ f" Enter [{COLOR_LABEL}]module_id[/]", default="ad.kerberoast"+ )if "finding_id" in req_fields:- args["finding_id"] = Prompt.ask(" Enter [cyan]finding_id[/]", default="f-demo-01")+ args["finding_id"] = Prompt.ask(+ f" Enter [{COLOR_LABEL}]finding_id[/]", default="f-demo-01"+ )if "confirmation_token" in req_fields:- args["confirmation_token"] = Prompt.ask(" Enter [cyan]confirmation_token[/]", default="")+ args["confirmation_token"] = Prompt.ask(+ f" Enter [{COLOR_LABEL}]confirmation_token[/]", password=True+ )++ for field in req_fields:+ if field not in args:+ is_secret = any(+ k in field.lower()+ for k in ("secret", "token", "key", "password", "credential")+ )+ args[field] = Prompt.ask(f" Enter [{COLOR_LABEL}]{field}[/]", password=is_secret)result = asyncio.run(server.tool_registry.call_tool(chosen_tool.name, args))raw_text = result.content[0].text if result.content else "{}"+ console.print()try:formatted = json.dumps(json.loads(raw_text), indent=2)syntax = Syntax(formatted, "json", theme="monokai", line_numbers=True)- console.print(Panel(syntax, title=f"[bold green]Result - {chosen_tool.name}[/]", border_style="green", box=box.ASCII))+ console.print(+ Panel(+ syntax,+ title=f"[{COLOR_SUCCESS}]Result - {chosen_tool.name}[/]",+ border_style="green",+ box=box.ROUNDED,+ )+ )except Exception:- console.print(Panel(raw_text, title=f"[bold green]Result - {chosen_tool.name}[/]", border_style="green", box=box.ASCII))+ console.print(+ Panel(+ raw_text,+ title=f"[{COLOR_SUCCESS}]Result - {chosen_tool.name}[/]",+ border_style="green",+ box=box.ROUNDED,+ )+ )- Prompt.ask("\n[dim]Press Enter to return to menu...[/]")+ Prompt.ask(f"\n[{COLOR_NEUTRAL}]Press Enter to return to menu...[/]")def run_system_doctor() -> None:"""Run full system diagnostics and print rich table."""render_header()- server = AresMcpServer()- tools = server.tool_registry.list_tools()- resources = server.resource_registry.list_resources()- prompts = server.prompt_registry.list_prompts()+ diag = get_doctor_diagnostics()- table = Table(title="ARES MCP Subsystem Readiness Check", box=box.ASCII)- table.add_column("Subsystem", style="bold cyan")- table.add_column("Status", style="bold green", justify="center")+ table = Table(title="ARES MCP Subsystem Readiness Check", box=box.ROUNDED)+ table.add_column("Subsystem", style=COLOR_LABEL)+ table.add_column("Status", justify="center")table.add_column("Details")- table.add_row("Protocol Engine", "PASS", "JSON-RPC 2.0 (MCP 2024-11-05)")- table.add_row("Operational Tools", "PASS", f"{len(tools)} tools registered (Tier-1 & Tier-2)")- table.add_row("Context Resources", "PASS", f"{len(resources)} URI streams registered")- table.add_row("Workflow Prompts", "PASS", f"{len(prompts)} templates indexed")- table.add_row("Module Catalog", "PASS", f"{len(FIRST_PARTY_DESCRIPTORS)} modules indexed")- table.add_row("Security Gates", "PASS", "ScopeGuard + TokenManager + TaintSanitizer + AD Lockout Breaker")+ for item in diag["subsystems"]:+ status_badge = (+ f"[{COLOR_SUCCESS}]PASS[/]" if item["status"] == "PASS" else f"[{COLOR_ERROR}]FAIL[/]"+ )+ table.add_row(item["subsystem"], status_badge, item["details"])+ console.print()console.print(table)- Prompt.ask("\n[dim]Press Enter to return to menu...[/]")+ Prompt.ask(f"\n[{COLOR_NEUTRAL}]Press Enter to return to menu...[/]")def start_sse_server() -> None:- """Start SSE HTTP server."""+ """Start SSE HTTP server with clean shutdown."""+ import uvicorn++ from ares.mcp import AresMcpServer, create_sse_app+render_header()console.print(Panel(- "[bold white]ARES MCP HTTP Gateway (SSE Mode)[/]\n\n"- " [cyan]Endpoint:[/cyan] http://127.0.0.1:8001/sse\n"- " [cyan]Clients:[/cyan] Open-WebUI, LibreChat, Remote Agents, Docker\n\n"- "Press [bold yellow]Ctrl+C[/bold yellow] anytime to stop the server and return to this console.",- title="[bold green]SSE HTTP Gateway[/]",+ f"[{COLOR_VALUE}]ARES MCP HTTP Gateway (SSE Mode)[/]\n\n"+ f" [{COLOR_LABEL}]Endpoint:[/] http://127.0.0.1:8001/sse\n"+ f" [{COLOR_LABEL}]Clients:[/] Open-WebUI, LibreChat, Remote Agents, Docker\n\n"+ f"Press [{COLOR_WARNING}]Ctrl+C[/] anytime to stop the server and return to this console.",+ title=f"[{COLOR_SUCCESS}]SSE HTTP Gateway[/]",border_style="green",- box=box.ASCII,+ box=box.ROUNDED,))-- port = int(Prompt.ask("[bold yellow]Port to bind[/]", default="8001"))-- import uvicorn- from ares.mcp import AresMcpServer, create_sse_app++ port = int(Prompt.ask(f"[{COLOR_LABEL}]Port to bind[/]", default="8001"))+server = AresMcpServer()app = create_sse_app(server)try:uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")except KeyboardInterrupt:- console.print("\n[yellow]Gateway stopped. Returning to console...[/]")+ console.print(f"\n[{COLOR_WARNING}]Gateway stopped. Returning to console...[/]")def interactive_console_loop() -> None:- """Main OpenCode/OpenClaw-style interactive TUI loop."""+ """Main OpenCode/OpenClaw-style interactive TUI loop with graceful SIGINT handling."""workspace_root = Path.cwd()- while True:- render_header()- console.print(Panel(- " [bold green][1][/] [bold white]1-Click Client Setup[/] [dim]Auto-configure Cursor, Claude, or Windsurf[/dim]\n"- " [bold cyan][2][/] [bold white]Module Catalog[/] [dim]Browse 62 attack modules & OPSEC noise ratings[/dim]\n"- " [bold yellow][3][/] [bold white]Scope & Dry-Run Simulator[/] [dim]Validate target CIDR and issue 60s token[/dim]\n"- " [bold magenta][4][/] [bold white]Run MCP Tool[/] [dim]Execute operational tools with rich card output[/dim]\n"- " [bold blue][5][/] [bold white]System Diagnostics (Doctor)[/] [dim]Verify subsystem readiness matrix[/dim]\n"- " [bold green][6][/] [bold white]HTTP / SSE Gateway[/] [dim]Start local network server (Port 8001)[/dim]\n"- " [bold red][0][/] [bold white]Exit[/]",- title="[bold white]ARES MCP - CONSOLE[/]",- border_style="cyan",- box=box.ASCII,- ))-- choice = Prompt.ask("[bold yellow]Select option[/]", choices=["1", "2", "3", "4", "5", "6", "0"], default="1")-- if choice == "0":- console.print("\n[bold cyan]ARES MCP Console closed.[/]")- break- elif choice == "1":- auto_setup_client(workspace_root)- elif choice == "2":- explore_catalog()- elif choice == "3":- simulate_dry_run()- elif choice == "4":- run_interactive_tool()- elif choice == "5":- run_system_doctor()- elif choice == "6":- start_sse_server()+ # Non-TTY guard: if piped, do not hang on interactive input+ if not sys.stdin.isatty():+ diag = get_doctor_diagnostics()+ console.print(f"[{COLOR_VALUE}]ARES MCP (Non-interactive mode)[/]: {diag['status']}")+ return++ try:+ while True:+ render_header()+ menu_lines = [+ f" [{COLOR_INDEX}][1][/] [{COLOR_VALUE}]1-Click Client Setup[/] "+ f"[{COLOR_NEUTRAL}]Auto-configure Cursor, Claude, or Windsurf[/]",+ f" [{COLOR_INDEX}][2][/] [{COLOR_VALUE}]Module Catalog[/] "+ f"[{COLOR_NEUTRAL}]Browse 62 attack modules & OPSEC noise ratings[/]",+ f" [{COLOR_INDEX}][3][/] [{COLOR_VALUE}]Scope & Dry-Run Simulator[/] "+ f"[{COLOR_NEUTRAL}]Validate target CIDR and issue 60s token[/]",+ f" [{COLOR_INDEX}][4][/] [{COLOR_VALUE}]Run MCP Tool[/] "+ f"[{COLOR_NEUTRAL}]Execute operational tools with rich card output[/]",+ f" [{COLOR_INDEX}][5][/] [{COLOR_VALUE}]System Diagnostics (Doctor)[/] "+ f"[{COLOR_NEUTRAL}]Verify subsystem readiness matrix[/]",+ f" [{COLOR_INDEX}][6][/] [{COLOR_VALUE}]HTTP / SSE Gateway[/] "+ f"[{COLOR_NEUTRAL}]Start local network server (Port 8001)[/]",+ f" [{COLOR_ERROR}][0][/] [{COLOR_ERROR}]Exit[/]",+ ]+ console.print(Panel(+ "\n".join(menu_lines),+ title=f"[{COLOR_VALUE}]ARES MCP * CONSOLE[/]",+ border_style="cyan",+ box=box.ROUNDED,+ ))++ choice = Prompt.ask(+ f"[{COLOR_LABEL}]Select option[/]",+ choices=["1", "2", "3", "4", "5", "6", "0"],+ default="1",+ )++ if choice == "0":+ console.print(+ f"\n[{COLOR_LABEL}]ARES MCP Console closed. Operator session finished.[/]"+ )+ sys.exit(EXIT_SUCCESS)+ elif choice == "1":+ auto_setup_client(workspace_root)+ elif choice == "2":+ explore_catalog()+ elif choice == "3":+ simulate_dry_run()+ elif choice == "4":+ run_interactive_tool()+ elif choice == "5":+ run_system_doctor()+ elif choice == "6":+ start_sse_server()++ except KeyboardInterrupt:+ console.print(f"\n[{COLOR_NEUTRAL}]Cancelled[/]")+ sys.exit(EXIT_SIGINT)if __name__ == "__main__":diff --git a/ares/cli/mcp_cli_utils.py b/ares/cli/mcp_cli_utils.pynew file mode 100644index 0000000..6b89f33--- /dev/null+++ b/ares/cli/mcp_cli_utils.py@@ -0,0 +1,86 @@+"""ARES MCP CLI Product-Grade Utilities.++Handles:+- TTY detection & NO_COLOR specification (https://no-color.org)+- Standardized exit codes (0 = Success, 1 = Error, 2 = Invalid Input, 130 = SIGINT)+- Safe input masking for secrets (getpass / hide_input)+- Graceful signal handling (Ctrl+C without traceback)+- Consistent Rich color palette+"""+from __future__ import annotations++import os+import re+import sys++from rich.console import Console++# Standardized Exit Codes+EXIT_SUCCESS = 0+EXIT_ERROR = 1+EXIT_INVALID_INPUT = 2+EXIT_SIGINT = 130++# Semantic Color Palette (Strictly Enforced)+COLOR_LABEL = "cyan"+COLOR_VALUE = "bold white"+COLOR_SUCCESS = "bold green"+COLOR_ERROR = "bold red"+COLOR_WARNING = "bold yellow"+COLOR_NEUTRAL = "dim"+COLOR_INDEX = "cyan"++_ANSI_REGEX = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")+++def is_no_color_active() -> bool:+ """Return True if NO_COLOR environment variable is set (any value, even empty)."""+ return "NO_COLOR" in os.environ+++def is_stdout_piped() -> bool:+ """Return True if stdout is redirected / not a TTY."""+ return not sys.stdout.isatty()+++def get_mcp_console(force_no_color: bool = False, json_mode: bool = False) -> Console:+ """Create a Rich Console respecting NO_COLOR, TTY detection, and JSON mode.++ If output is not a TTY or NO_COLOR is active, color and highlighting are disabled.+ If json_mode is True, console will not apply extra Rich styling.+ """+ disable_color = force_no_color or is_no_color_active() or is_stdout_piped() or json_mode++ # Windows console UTF-8 safeguard+ if sys.platform == "win32":+ try:+ if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")+ if hasattr(sys.stderr, "reconfigure"):+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")+ except Exception: # noqa: S110+ pass++ return Console(+ no_color=disable_color,+ highlight=not disable_color,+ safe_box=True,+ soft_wrap=json_mode,+ )+++def strip_ansi(text: str) -> str:+ """Remove ANSI escape sequences from text."""+ return _ANSI_REGEX.sub("", text)+++def warn_cli_secret_exposure() -> None:+ """Print security warning when secret is passed via CLI argument."""+ console = get_mcp_console()+ console.print(+ f"[{COLOR_WARNING}]SECURITY WARNING:[/] "+ "Passing credentials/secrets via command line arguments can expose them in "+ "OS process listings and shell history. "+ "Use environment variables (e.g. ARES_MCP_API_KEY) or secure config files instead.",+ file=sys.stderr,+ )diff --git a/ares/cli/mcp_commands.py b/ares/cli/mcp_commands.pynew file mode 100644index 0000000..52b4446--- /dev/null+++ b/ares/cli/mcp_commands.py@@ -0,0 +1,254 @@+"""ARES MCP Command Handlers and Operations Engine.++Pure, testable, headless operations for:+- Doctor diagnostics (Table / JSON)+- Module catalog queries (Table / JSON)+- Scope validation (Exit code 0 = in-scope, 1 = rejected)+- Pre-flight dry-run simulation with confirmation tokens+- 1-click client configuration (Cursor, Claude Desktop, Windsurf, Cline)+- Generic tool execution+"""+from __future__ import annotations++import asyncio+import json+import os+import sys+from pathlib import Path+from typing import Any++from ares.cli.mcp_cli_utils import (+ EXIT_ERROR,+ EXIT_INVALID_INPUT,+ EXIT_SUCCESS,+)+from ares.mcp.security import McpScopeGate+from ares.mcp.server import AresMcpServer+from ares.modules.descriptors import FIRST_PARTY_DESCRIPTORS+++def get_doctor_diagnostics(server: AresMcpServer | None = None) -> dict[str, Any]:+ """Inspect all MCP subsystems and return structured health status."""+ srv = server or AresMcpServer()+ tools = srv.tool_registry.list_tools()+ resources = srv.resource_registry.list_resources()+ prompts = srv.prompt_registry.list_prompts()++ checks = [+ {+ "subsystem": "Protocol Engine",+ "status": "PASS",+ "details": "JSON-RPC 2.0 (MCP 2024-11-05 Specification)",+ },+ {+ "subsystem": "Operational Tools",+ "status": "PASS",+ "details": f"{len(tools)} tools registered (Tier-1 & Tier-2)",+ },+ {+ "subsystem": "Context Resources",+ "status": "PASS",+ "details": f"{len(resources)} live URI streams active",+ },+ {+ "subsystem": "Workflow Prompts",+ "status": "PASS",+ "details": f"{len(prompts)} workflow templates indexed",+ },+ {+ "subsystem": "Module Catalog",+ "status": "PASS",+ "details": f"{len(FIRST_PARTY_DESCRIPTORS)} offensive modules ready",+ },+ {+ "subsystem": "Security Gates",+ "status": "PASS",+ "details": "ScopeGuard + TokenManager + TaintSanitizer + AD Lockout Breaker",+ },+ ]++ all_pass = all(c["status"] == "PASS" for c in checks)+ return {+ "status": "PASS" if all_pass else "FAIL",+ "healthy": all_pass,+ "subsystems": checks,+ }+++def query_module_catalog(+ category: str | None = None,+ query: str | None = None,+) -> list[dict[str, Any]]:+ """Query and filter registered descriptors."""+ cat_filter = category.strip().lower() if category else None+ q_filter = query.strip().lower() if query else None++ results: list[dict[str, Any]] = []+ for mod_id, desc in sorted(FIRST_PARTY_DESCRIPTORS.items()):+ category_str = (+ desc.category.value if hasattr(desc.category, "value") else str(desc.category)+ )+ opsec_val = desc.opsec.value if hasattr(desc.opsec, "value") else str(desc.opsec)+ source_cls = str(desc.source_class)++ if cat_filter and cat_filter != category_str.lower():+ continue++ if q_filter:+ in_id = q_filter in mod_id.lower()+ in_cat = q_filter in category_str.lower()+ in_cls = q_filter in source_cls.lower()+ if not (in_id or in_cat or in_cls):+ continue++ results.append({+ "module_id": mod_id,+ "category": category_str,+ "opsec_level": opsec_val,+ "source_class": source_cls,+ "requires_approval": desc.explicit_attempt_approval,+ "required_capabilities": [+ c.value if hasattr(c, "value") else str(c) for c in desc.required_capabilities+ ],+ "parameters_count": len(desc.parameter_fields),+ })+ return results+++def check_scope(+ target: str,+ cidr: str | None = None,+ campaign_id: str = "default-lab",+ custom_rules: list[str] | None = None,+) -> dict[str, Any]:+ """Deterministically check if target IP/host is within authorized scope."""+ if custom_rules:+ rules = custom_rules+ elif cidr:+ rules = [cidr.strip()]+ else:+ rules = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "*.corp.local", "*.lab.internal"]++ in_scope = McpScopeGate.is_in_scope(target.strip(), rules)+ return {+ "target": target.strip(),+ "in_scope": in_scope,+ "status": "APPROVED" if in_scope else "REJECTED_OUT_OF_SCOPE",+ "scope_rules": rules,+ "campaign_id": campaign_id,+ }+++def execute_dry_run(+ target: str,+ module_id: str,+ campaign_id: str = "default-lab",+ params: dict[str, Any] | None = None,+ server: AresMcpServer | None = None,+) -> dict[str, Any]:+ """Execute pre-flight simulation and retrieve confirmation token."""+ srv = server or AresMcpServer()+ payload = {+ "campaign_id": campaign_id,+ "module_id": module_id,+ "target": target,+ "params": params or {},+ }+ result = asyncio.run(srv.tool_registry.call_tool("ares_dry_run_module", payload))+ raw_text = result.content[0].text if result.content else "{}"+ try:+ data = json.loads(raw_text)+ except Exception:+ data = {"output": raw_text}++ data["is_error"] = result.isError+ return data+++def setup_client_configuration(client: str, workspace_root: Path | None = None) -> tuple[int, str]:+ """Configure client without manual copy-pasting. Returns (exit_code, message)."""+ c_lower = client.strip().lower()+ root = workspace_root or Path.cwd()+ executable = sys.executable++ if c_lower == "cursor":+ cursor_dir = root / ".cursor"+ cursor_dir.mkdir(parents=True, exist_ok=True)+ mcp_file = cursor_dir / "mcp.json"++ cfg: dict[str, Any] = {"mcpServers": {}}+ if mcp_file.exists():+ try:+ cfg = json.loads(mcp_file.read_text(encoding="utf-8"))+ except Exception:+ cfg = {"mcpServers": {}}++ cfg.setdefault("mcpServers", {})["ares"] = {+ "command": executable,+ "args": ["-m", "ares.mcp"],+ }+ mcp_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+ return EXIT_SUCCESS, f"Cursor configuration written to {mcp_file}"++ elif c_lower in ("claude", "claudedesktop"):+ appdata = os.environ.get("APPDATA")+ if not appdata:+ return EXIT_ERROR, "Cannot locate %APPDATA% directory on this system."++ claude_dir = Path(appdata) / "Claude"+ claude_dir.mkdir(parents=True, exist_ok=True)+ claude_file = claude_dir / "claude_desktop_config.json"++ cfg = {"mcpServers": {}}+ if claude_file.exists():+ try:+ cfg = json.loads(claude_file.read_text(encoding="utf-8"))+ except Exception:+ cfg = {"mcpServers": {}}++ cfg.setdefault("mcpServers", {})["ares"] = {+ "command": executable,+ "args": ["-m", "ares.mcp"],+ }+ claude_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+ return EXIT_SUCCESS, f"Claude Desktop configuration written to {claude_file}"++ elif c_lower == "windsurf":+ home = Path.home()+ windsurf_dir = home / ".codeium" / "windsurf"+ windsurf_dir.mkdir(parents=True, exist_ok=True)+ windsurf_file = windsurf_dir / "mcp_config.json"++ cfg = {"mcpServers": {}}+ if windsurf_file.exists():+ try:+ cfg = json.loads(windsurf_file.read_text(encoding="utf-8"))+ except Exception:+ cfg = {"mcpServers": {}}++ cfg.setdefault("mcpServers", {})["ares"] = {+ "command": executable,+ "args": ["-m", "ares.mcp"],+ }+ windsurf_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+ return EXIT_SUCCESS, f"Windsurf configuration written to {windsurf_file}"++ elif c_lower in ("cline", "roo", "roocode"):+ cline_file = root / "cline_mcp_settings.json"+ cfg = {+ "mcpServers": {+ "ares": {+ "command": executable,+ "args": ["-m", "ares.mcp"],+ "disabled": False,+ "alwaysAllow": ["ares_list_campaigns", "ares_inspect_module_catalog"],+ }+ }+ }+ cline_file.write_text(json.dumps(cfg, indent=2), encoding="utf-8")+ return EXIT_SUCCESS, f"Cline settings written to {cline_file}"++ return (+ EXIT_INVALID_INPUT,+ f"Unknown client '{client}'. Choose from: cursor, claude, windsurf, cline",+ )diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.pyindex 3959880..3fd06ee 100644--- a/ares/cli/typer_main.py+++ b/ares/cli/typer_main.py@@ -43,10 +43,12 @@ from urllib import parse as urllib_parsefrom urllib import request as urllib_requestimport typer+from rich import boxfrom rich import print as rprintfrom rich.console import Consolefrom rich.markup import escapefrom rich.panel import Panel+from rich.syntax import Syntaxfrom rich.table import Tableapp = typer.Typer(@@ -260,7 +262,7 @@ signing_app = typer.Typer(help="Module signing and verification", no_args_is_hegoal_app = typer.Typer(help="Goal-based autonomous attack planning", no_args_is_help=True)graph_app = typer.Typer(help="Attack graph queries and visualization", no_args_is_help=True)dashboard_app = typer.Typer(help="Local dashboard developer tools", no_args_is_help=True)-mcp_app = typer.Typer(help="ARES MCP β Model Context Protocol Gateway", no_args_is_help=False, invoke_without_command=True)+mcp_app = typer.Typer(help="ARES MCP - Model Context Protocol Gateway", no_args_is_help=False, invoke_without_command=True)app.add_typer(campaign_app, name="campaign")app.add_typer(target_app, name="target")@@ -2722,55 +2724,323 @@ async def test_missing_target_raises(module):@mcp_app.callback(invoke_without_command=True)def mcp_default_callback(ctx: typer.Context) -> None:- """ARES MCP Gateway. Launches interactive console when called without subcommands."""+ """ARES MCP Gateway. Launches interactive console when invoked without subcommands."""if ctx.invoked_subcommand is None:- from ares.cli.console import interactive_console_loop- interactive_console_loop()+ if sys.stdin.isatty():+ from ares.cli.console import interactive_console_loop+ try:+ interactive_console_loop()+ except KeyboardInterrupt:+ console.print("\n[dim]Cancelled[/dim]")+ raise typer.Exit(130)+ else:+ from ares.cli.mcp_commands import get_doctor_diagnostics+ diag = get_doctor_diagnostics()+ console.print(f"ARES MCP v6.0.0 (Non-interactive mode) - Status: {diag['status']}")+ raise typer.Exit(0)@mcp_app.command("console")def mcp_console_cmd() -> None:"""Launch the ARES MCP Interactive Console (OpenCode/OpenClaw style)."""from ares.cli.console import interactive_console_loop- interactive_console_loop()+ try:+ interactive_console_loop()+ except KeyboardInterrupt:+ console.print("\n[dim]Cancelled[/dim]")+ raise typer.Exit(130)@app.command("console")def app_console_cmd() -> None:- """Launch the ARES Sovereign Agent Interactive TUI Console (OpenClaw/OpenCode style)."""+ """Launch the ARES MCP Interactive Console (OpenCode/OpenClaw style)."""from ares.cli.console import interactive_console_loop- interactive_console_loop()+ try:+ interactive_console_loop()+ except KeyboardInterrupt:+ console.print("\n[dim]Cancelled[/dim]")+ raise typer.Exit(130)+++@mcp_app.command("doctor")+def mcp_doctor_cmd(+ json_output: bool = typer.Option(False, "--json", help="Output machine-readable JSON status"),+) -> None:+ """Check health, readiness, and security gates of ARES MCP subsystems."""+ from ares.cli.mcp_commands import get_doctor_diagnostics+ from ares.cli.mcp_cli_utils import get_mcp_console++ diag = get_doctor_diagnostics()+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ out_console.print(json.dumps(diag, indent=2))+ else:+ table = Table(title="ARES MCP Subsystem Readiness Check", box=box.ROUNDED)+ table.add_column("Subsystem", style="cyan")+ table.add_column("Status", justify="center")+ table.add_column("Details")++ for item in diag["subsystems"]:+ status_style = "green" if item["status"] == "PASS" else "red"+ table.add_row(item["subsystem"], f"[{status_style}]{item['status']}[/]", item["details"])++ out_console.print(table)++ raise typer.Exit(0 if diag["healthy"] else 1)+++@mcp_app.command("module-catalog")+@mcp_app.command("catalog")+def mcp_module_catalog_cmd(+ category: Optional[str] = typer.Option(None, "--category", "-c", help="Filter by category (ad, cloud, windows, linux, etc.)"),+ query: Optional[str] = typer.Option(None, "--query", "-q", help="Search keyword in module ID or class name"),+ json_output: bool = typer.Option(False, "--json", help="Output catalog as machine-readable JSON"),+) -> None:+ """Browse 60+ attack modules, OPSEC noise levels, and governance policies."""+ from ares.cli.mcp_commands import query_module_catalog+ from ares.cli.mcp_cli_utils import get_mcp_console++ modules = query_module_catalog(category=category, query=query)+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ out_console.print(json.dumps(modules, indent=2))+ raise typer.Exit(0)++ table = Table(title=f"ARES Module Catalog ({len(modules)} Modules)", box=box.ROUNDED)+ table.add_column("Module ID", style="cyan")+ table.add_column("Category", style="yellow")+ table.add_column("OPSEC Noise", justify="center")+ table.add_column("Governance")+ table.add_column("Source Engine Class")++ for item in modules:+ opsec_val = item["opsec_level"].lower()+ opsec_style = {"silent": "green", "low": "green", "medium": "yellow", "high_noise": "red"}.get(opsec_val, "white")+ gov_badge = "[yellow]Approval Required[/]" if item["requires_approval"] else "[green]Standard[/]"+ table.add_row(+ item["module_id"],+ item["category"],+ f"[{opsec_style}]{item['opsec_level'].upper()}[/]",+ gov_badge,+ item["source_class"],+ )++ out_console.print(table)+ raise typer.Exit(0)+++@mcp_app.command("scope-check")+def mcp_scope_check_cmd(+ target: str = typer.Option(..., "--target", "-t", help="Target IP, hostname, or domain to verify"),+ cidr: Optional[str] = typer.Option(None, "--cidr", "-c", help="Specific CIDR network rule to test against"),+ campaign: str = typer.Option("default-lab", "--campaign", help="Campaign ID"),+ strict: bool = typer.Option(True, "--strict/--no-strict", help="Exit with code 1 if target is out of scope"),+ json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),+) -> None:+ """Verify deterministically if a target IP, CIDR, or hostname is authorized."""+ from ares.cli.mcp_commands import check_scope+ from ares.cli.mcp_cli_utils import get_mcp_console++ result = check_scope(target=target, cidr=cidr, campaign_id=campaign)+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ out_console.print(json.dumps(result, indent=2))+ else:+ status_color = "green" if result["in_scope"] else "red"+ out_console.print(Panel(+ f"[cyan]Target:[/] [bold white]{result['target']}[/]\n"+ f"[cyan]Status:[/] [{status_color}]{result['status']}[/]\n"+ f"[cyan]Authorized:[/] {'YES' if result['in_scope'] else 'NO'}\n"+ f"[cyan]Scope Rules:[/] {', '.join(result['scope_rules'])}",+ title=f"[{status_color}]Scope Verification Result[/]",+ border_style=status_color,+ box=box.ROUNDED,+ ))++ if strict and not result["in_scope"]:+ raise typer.Exit(1)+ raise typer.Exit(0)+++@mcp_app.command("dry-run")+def mcp_dry_run_cmd(+ target: str = typer.Option(..., "--target", "-t", help="Target IP or hostname"),+ module: str = typer.Option(..., "--module", "-m", help="Module ID (e.g. ad.kerberoast)"),+ campaign: str = typer.Option("default-lab", "--campaign", help="Campaign ID"),+ params: str = typer.Option("{}", "--params", "-p", help="JSON dictionary string of parameters"),+ json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),+) -> None:+ """Simulate module pre-flight execution and obtain a single-use confirmation token."""+ from ares.cli.mcp_commands import execute_dry_run+ from ares.cli.mcp_cli_utils import get_mcp_console++ try:+ parsed_params = json.loads(params)+ if not isinstance(parsed_params, dict):+ raise ValueError()+ except Exception:+ console.print("[red]Invalid --params JSON. Must be a valid JSON dictionary string (e.g. '{\"domain\": \"corp.local\"}').[/]")+ raise typer.Exit(2)++ data = execute_dry_run(target=target, module_id=module, campaign_id=campaign, params=parsed_params)+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ out_console.print(json.dumps(data, indent=2))+ else:+ token = data.get("confirmation_token", "N/A")+ scope_valid = data.get("scope_validation", {}).get("in_scope", True)+ opsec = data.get("opsec_assessment", {}).get("noise_level", "low")++ status_badge = "[green][OK] IN-SCOPE[/]" if scope_valid else "[red][FAIL] OUT-OF-SCOPE[/]"+ out_console.print(Panel(+ f"[cyan]Module:[/] [bold white]{module}[/]\n"+ f"[cyan]Target:[/] [bold white]{target}[/]\n"+ f"[cyan]ScopeGuard:[/] {status_badge}\n"+ f"[cyan]OPSEC Noise:[/] [yellow]{opsec.upper()}[/]\n"+ f"[cyan]Confirmation Token:[/] [yellow]{token}[/] (Valid for 60s)\n"+ f"[cyan]Status:[/] [green]{data.get('status', 'SUCCESS')}[/]",+ title="[green]Pre-Flight Dry-Run Card[/]",+ border_style="green" if scope_valid else "red",+ box=box.ROUNDED,+ ))++ if data.get("is_error"):+ raise typer.Exit(1)+ raise typer.Exit(0)+++@mcp_app.command("setup")+def mcp_setup_cmd(+ client: Optional[str] = typer.Option(None, "--client", "-c", help="Target client: cursor, claude, windsurf, or cline"),+ json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),+) -> None:+ """1-Click automated configuration for AI IDEs and clients without manual JSON editing."""+ from ares.cli.mcp_commands import setup_client_configuration+ from ares.cli.mcp_cli_utils import get_mcp_console++ chosen_client = client+ if not chosen_client:+ if sys.stdin.isatty():+ from rich.prompt import Prompt+ console.print("[bold white]Select client to configure:[/]")+ console.print(" [cyan][1][/] Cursor IDE")+ console.print(" [cyan][2][/] Claude Desktop")+ console.print(" [cyan][3][/] Windsurf")+ console.print(" [cyan][4][/] VS Code (Cline)")+ sel = Prompt.ask("Choice", choices=["1", "2", "3", "4"], default="1")+ chosen_client = {"1": "cursor", "2": "claude", "3": "windsurf", "4": "cline"}[sel]+ else:+ console.print("[red]Missing required option --client in non-interactive mode. Available: cursor, claude, windsurf, cline[/]")+ raise typer.Exit(2)++ code, msg = setup_client_configuration(chosen_client)+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ out_console.print(json.dumps({"client": chosen_client, "status": "SUCCESS" if code == 0 else "ERROR", "message": msg, "exit_code": code}, indent=2))+ else:+ status_color = "green" if code == 0 else "red"+ out_console.print(Panel(+ f"[{status_color}]{msg}[/]",+ title=f"[{status_color}]Client Setup: {chosen_client.capitalize()}[/]",+ border_style=status_color,+ box=box.ROUNDED,+ ))++ raise typer.Exit(code)+++@mcp_app.command("run-tool")+def mcp_run_tool_cmd(+ tool_name: str = typer.Argument(..., help="Name of the MCP tool to execute (e.g. ares_list_campaigns)"),+ args: str = typer.Option("{}", "--args", "-a", help="JSON dictionary string of tool arguments"),+ json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),+) -> None:+ """Execute an ARES operational MCP tool headlessly and output structured results."""+ from ares.mcp import AresMcpServer+ from ares.cli.mcp_cli_utils import get_mcp_console++ try:+ parsed_args = json.loads(args)+ if not isinstance(parsed_args, dict):+ raise ValueError()+ except Exception:+ console.print("[red]Invalid --args JSON. Must be a valid JSON dictionary string (e.g. '{\"campaign_id\": \"test\"}').[/]")+ raise typer.Exit(2)++ server = AresMcpServer()+ tools = {t.name: t for t in server.tool_registry.list_tools()}+ if tool_name not in tools:+ console.print(f"[red]Unknown tool '{tool_name}'. Available tools: {', '.join(tools.keys())}[/]")+ raise typer.Exit(2)++ result = asyncio.run(server.tool_registry.call_tool(tool_name, parsed_args))+ raw_text = result.content[0].text if result.content else "{}"+ out_console = get_mcp_console(json_mode=json_output)++ if json_output:+ try:+ out_console.print(json.dumps(json.loads(raw_text), indent=2))+ except Exception:+ out_console.print(json.dumps({"content": raw_text, "isError": result.isError}, indent=2))+ else:+ status_color = "red" if result.isError else "green"+ try:+ formatted = json.dumps(json.loads(raw_text), indent=2)+ syntax = Syntax(formatted, "json", theme="monokai", line_numbers=True)+ out_console.print(Panel(syntax, title=f"[{status_color}]Result: {tool_name}[/]", border_style=status_color, box=box.ROUNDED))+ except Exception:+ out_console.print(Panel(raw_text, title=f"[{status_color}]Result: {tool_name}[/]", border_style=status_color, box=box.ROUNDED))++ raise typer.Exit(1 if result.isError else 0)@mcp_app.command("stdio")def mcp_stdio_cmd() -> None:- """Run the ARES Sovereign MCP Server over asynchronous stdio (Claude Desktop / Cursor / Windsurf / Cline / Zed)."""+ """Run the ARES MCP Server over asynchronous stdio (Claude Desktop / Cursor / Windsurf / Cline / Zed)."""from ares.mcp import run_stdio_servertry:asyncio.run(run_stdio_server())except KeyboardInterrupt:- pass+ console.print("\n[dim]Stdio server stopped.[/dim]")+ raise typer.Exit(130)@mcp_app.command("sse")def mcp_sse_cmd(host: str = typer.Option("0.0.0.0", "--host", "-h", help="Host address to bind"),port: int = typer.Option(8001, "--port", "-p", help="Port to listen on"),- api_key: Optional[str] = typer.Option(None, "--api-key", "-k", help="Required Bearer API Key for network auth"),+ api_key: Optional[str] = typer.Option(None, "--api-key", "-k", help="Optional Bearer API Key for network authentication"),) -> None:- """Run the ARES Sovereign MCP Server over HTTP with Server-Sent Events (SSE)."""+ """Run the ARES MCP Server over HTTP with Server-Sent Events (SSE)."""import uvicorn+ from ares.cli.mcp_cli_utils import warn_cli_secret_exposurefrom ares.mcp import AresMcpServer, create_sse_app++ if api_key:+ warn_cli_secret_exposure()+server = AresMcpServer()sse_app = create_sse_app(server, api_key=api_key)console.print(Panel(- f"[bold green]ARES Sovereign MCP Server (SSE Mode)[/]\n\n"- f" [cyan]Endpoint:[/cyan] http://{host}:{port}/sse\n"- f" [cyan]Auth:[/cyan] {'Protected by API Key' if api_key else 'Open / Localhost Only'}\n"- f" [cyan]Clients:[/cyan] Open-WebUI, LibreChat, Remote Agents, Docker",+ f"[bold green]ARES MCP Server (SSE Mode)[/]\n\n"+ f" [cyan]Endpoint:[/] http://{host}:{port}/sse\n"+ f" [cyan]Auth:[/] {'Protected by API Key' if api_key else 'Open / Localhost Only'}\n"+ f" [cyan]Clients:[/] Open-WebUI, LibreChat, Remote Agents, Docker\n\n"+ f"Press [yellow]Ctrl+C[/] to stop the server.",title="ares mcp sse",+ border_style="green",+ box=box.ROUNDED,))- uvicorn.run(sse_app, host=host, port=port, log_level="info")+ try:+ uvicorn.run(sse_app, host=host, port=port, log_level="info")+ except KeyboardInterrupt:+ console.print("\n[yellow]SSE server stopped.[/]")+ raise typer.Exit(130)@mcp_app.command("config")@@ -2789,43 +3059,22 @@ def mcp_config_cmd(executable = sys.executableif c_lower in ("claude", "claudedesktop"):- cfg = {- "mcpServers": {- "ares": {- "command": executable,- "args": ["-m", "ares.mcp"],- }- }- }+ cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}console.print("[bold green]Paste this into your Claude Desktop configuration file (`claude_desktop_config.json`):[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower == "cursor":- cfg = {- "mcpServers": {- "ares": {- "command": executable,- "args": ["-m", "ares.mcp"],- }- }- }+ cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}console.print("[bold green]Paste this into your Cursor MCP configuration (`.cursor/mcp.json`):[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower == "windsurf":- cfg = {- "mcpServers": {- "ares": {- "command": executable,- "args": ["-m", "ares.mcp"],- }- }- }+ cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}console.print("[bold green]Paste this into Windsurf MCP configuration (`~/.codeium/windsurf/mcp_config.json`):[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower in ("cline", "roo", "roocode"):cfg = {@@ -2840,7 +3089,7 @@ def mcp_config_cmd(}console.print("[bold green]Paste this into your VS Code Cline settings (`cline_mcp_settings.json`):[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower == "zed":cfg = {@@ -2858,7 +3107,7 @@ def mcp_config_cmd(}console.print("[bold green]Paste this into your Zed settings (`~/.config/zed/settings.json`):[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower in ("open-webui", "webui"):cfg = {@@ -2868,7 +3117,7 @@ def mcp_config_cmd(}console.print("[bold green]Open-WebUI Tool Connection Details:[/]\n")console.print(json.dumps(cfg, indent=2))- return+ raise typer.Exit(0)if c_lower == "librechat":yaml_content = f"""mcpServers:@@ -2876,19 +3125,20 @@ def mcp_config_cmd(type: sseurl: {host}/sseheaders:- Authorization: "Bearer {api_key}"+ Authorization: Bearer {api_key}"""console.print("[bold green]Paste this into your `librechat.yaml` configuration:[/]\n")console.print(yaml_content)- return+ raise typer.Exit(0)if c_lower == "langchain":from ares.mcp.export import generate_langchain_snippetconsole.print("[bold green]LangChain MCP Integration Code Snippet:[/]\n")console.print(generate_langchain_snippet())- return+ raise typer.Exit(0)console.print(f"[red]Unknown client '{client}'. Available: claude, cursor, windsurf, cline, zed, open-webui, librechat, langchain[/]")+ raise typer.Exit(2)@mcp_app.command("export-tools")@@ -2909,35 +3159,12 @@ def mcp_export_tools_cmd(out = export_json_schema(tools)else:console.print(f"[red]Unknown format '{format}'. Use 'openai', 'gemini', or 'json'.[/]")- raise typer.Exit(1)+ raise typer.Exit(2)console.print(json.dumps(out, indent=2))+ raise typer.Exit(0)-@mcp_app.command("doctor")-def mcp_doctor_cmd() -> None:- """Check readiness of ARES Sovereign MCP server, tools, and security gates."""- from ares.mcp import AresMcpServer- from ares.modules.descriptors import FIRST_PARTY_DESCRIPTORS-- server = AresMcpServer()- tools = server.tool_registry.list_tools()- resources = server.resource_registry.list_resources()- prompts = server.prompt_registry.list_prompts()-- table = Table(title="ARES Sovereign MCP Readiness Check")- table.add_column("Subsystem", style="cyan")- table.add_column("Status", style="green")- table.add_column("Details")-- table.add_row("Protocol Engine", "PASS", "JSON-RPC 2.0 (MCP 2024-11-05)")- table.add_row("Operational Tools", "PASS", f"{len(tools)} tools registered (Tier-1 & Tier-2)")- table.add_row("Context Resources", "PASS", f"{len(resources)} URI streams registered")- table.add_row("Purple-Team Prompts", "PASS", f"{len(prompts)} workflow templates")- table.add_row("Descriptor Catalog", "PASS", f"{len(FIRST_PARTY_DESCRIPTORS)} modules indexed")- table.add_row("Security Gates", "PASS", "ScopeGuard + TokenManager + TaintSanitizer + AD Lockout Breaker")-- console.print(table)# ββ Entry point ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/docs/mcp-server.md b/docs/mcp-server.mdindex b4e14b4..97915a5 100644--- a/docs/mcp-server.md+++ b/docs/mcp-server.md@@ -148,10 +148,58 @@ Human operators watching the Web Dashboard will see:----## 6. CLI Commands Reference+## 6. Product-Grade CLI & Scripting Reference++The ARES MCP CLI (`ares mcp` or `mcp.bat`) supports both an interactive tactical console and headless, non-interactive scriptability designed for pipelines, automation, and CI/CD.++### Command Matrix++| Command | Description | Scriptable / JSON |+| :--- | :--- | :--- |+| `ares mcp` | Default launcher. Opens interactive console if TTY, or prints status if piped. | Yes |+| `ares mcp console` | Explicitly launch the interactive OpenCode/OpenClaw-style TUI console. | No (Interactive) |+| `ares mcp doctor [--json]` | Validate readiness across protocol, tools, resources, and security gates. | `0` (healthy), `1` (unhealthy) |+| `ares mcp module-catalog [-c <cat>] [-q <query>] [--json]` | Search and filter 60+ attack modules with OPSEC noise and governance. | Full JSON list |+| `ares mcp scope-check -t <target> [-c <cidr>] [--strict/--no-strict] [--json]` | Deterministically check whether an IP/CIDR/hostname is in authorized scope. | `0` (in-scope), `1` (out-of-scope) |+| `ares mcp dry-run -t <target> -m <module> [-p <json_params>] [--json]` | Run pre-flight simulation and generate 60s cryptographic confirmation token. | Full JSON card |+| `ares mcp setup --client <cursor\|claude\|windsurf\|cline> [--json]` | 1-Click automated configuration for AI IDEs without manual JSON editing. | `0` (success), `2` (invalid client) |+| `ares mcp run-tool <tool_name> [-a <json_args>] [--json]` | Execute an operational MCP tool headlessly and output structured results. | Tool JSON payload |+| `ares mcp stdio` | Run the MCP server over standard input/output (for desktop AI clients). | Stdio JSON-RPC 2.0 |+| `ares mcp sse [--host <h>] [--port <p>] [--api-key <k>]` | Run the MCP server over HTTP with Server-Sent Events (SSE). | SSE stream |+| `ares mcp config --client <client>` | Generate ready-to-copy JSON configuration for 8+ AI clients. | Formatted config snippet |+| `ares mcp export-tools --format <openai\|gemini\|json>` | Export MCP tool definitions for external LLM function calling frameworks. | Schema JSON |++### Standardized Exit Codes++Following GitHub CLI, Docker CLI, and POSIX conventions:+- **`0`**: Operation completed successfully / target in-scope.+- **`1`**: General operational failure, subsystem check failed, or target out-of-scope (`--strict`).+- **`2`**: Invalid CLI input, malformed JSON arguments, or unknown tool/client.+- **`130`**: User cancelled operation via SIGINT (`Ctrl+C`).++### Pipeline & Automation Features++1. **NO_COLOR Support**:+ Adheres to [no-color.org](https://no-color.org). When the `NO_COLOR` environment variable is set (`export NO_COLOR=1` or `$env:NO_COLOR="1"`), all ANSI color codes are stripped:+ ```bash+ NO_COLOR=1 ares mcp doctor+ ```++2. **Machine-Readable JSON Output**:+ All diagnostic, inspection, and verification commands support `--json` for direct parsing by `jq`, PowerShell, or automated scripts:+ ```bash+ # Extract confirmation token for automated pipeline execution+ TOKEN=$(ares mcp dry-run -t 10.0.0.5 -m ad.kerberoast --json | jq -r .confirmation_token)+ ```++3. **TTY Detection**:+ When called in non-TTY environments (pipes, redirects, background jobs), `ares mcp` automatically avoids launching interactive menus and outputs headless status summaries.++4. **1-Click Windows Launcher (`mcp.bat`)**:+ Windows operators can run `mcp.bat` directly from the repository root:+ ```cmd+ mcp.bat doctor+ mcp.bat scope-check --target 10.0.0.5 --cidr 10.0.0.0/24+ mcp.bat setup --client cursor+ ```-- `ares mcp stdio`: Launch the MCP server over stdio.-- `ares mcp sse --host 0.0.0.0 --port 8001 --api-key <key>`: Launch the MCP server over HTTP/SSE.-- `ares mcp config --client <client>`: Print configuration snippet for your AI client.-- `ares mcp export-tools --format [openai|gemini|json]`: Export tool definitions to OpenAI, Gemini, or JSON-Schema.-- `ares mcp doctor`: Run self-diagnostic readiness check across protocol, tools, descriptors, and security gates.diff --git a/mcp.bat b/mcp.batindex b5e0c8c..bed84eb 100644--- a/mcp.bat+++ b/mcp.bat@@ -3,8 +3,9 @@ setlocalcd /d "%~dp0"if exist ".venv\Scripts\python.exe" (- ".venv\Scripts\python.exe" -m ares.cli.console %*+ ".venv\Scripts\python.exe" -m ares.cli.main mcp %*) else (- python -m ares.cli.console %*+ python -m ares.cli.main mcp %*)-endlocal+set EXIT_CODE=%ERRORLEVEL%+endlocal & exit /b %EXIT_CODE%diff --git a/tests/unit/test_mcp_cli.py b/tests/unit/test_mcp_cli.pynew file mode 100644index 0000000..78e6756--- /dev/null+++ b/tests/unit/test_mcp_cli.py@@ -0,0 +1,246 @@+"""Unit and integration tests for the ARES MCP CLI interface.++Validates:+- Exit codes: 0 (success), 1 (general error / out-of-scope),+ 2 (invalid input/arguments), 130 (SIGINT)+- Machine-readable --json output formats+- NO_COLOR specification (https://no-color.org) compliance+- Non-TTY piped execution safety+- Subcommand help screens and diagnostics+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner++from ares.cli.mcp_cli_utils import (+ EXIT_ERROR,+ EXIT_INVALID_INPUT,+ EXIT_SUCCESS,+ is_no_color_active,+)+from ares.cli.typer_main import app++runner = CliRunner()+++def test_mcp_doctor_text() -> None:+ """Verify human-readable doctor diagnostics table."""+ result = runner.invoke(app, ["mcp", "doctor"])+ assert result.exit_code == EXIT_SUCCESS+ assert "ARES MCP Subsystem Readiness Check" in result.stdout+ assert "Protocol Engine" in result.stdout+ assert "Operational Tools" in result.stdout+ assert "Security Gates" in result.stdout+++def test_mcp_doctor_json() -> None:+ """Verify machine-readable --json doctor diagnostics output."""+ result = runner.invoke(app, ["mcp", "doctor", "--json"])+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert data["status"] == "PASS"+ assert data["healthy"] is True+ assert isinstance(data["subsystems"], list)+ assert len(data["subsystems"]) >= 5+++def test_mcp_module_catalog_filtering() -> None:+ """Verify catalog command with category filter."""+ result = runner.invoke(app, ["mcp", "module-catalog", "--category", "ad"])+ assert result.exit_code == EXIT_SUCCESS+ assert "ARES Module Catalog" in result.stdout+ assert "ad.kerberoast" in result.stdout+++def test_mcp_module_catalog_json() -> None:+ """Verify machine-readable --json catalog output."""+ result = runner.invoke(app, ["mcp", "module-catalog", "--query", "kerberoast", "--json"])+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert isinstance(data, list)+ assert len(data) >= 1+ assert data[0]["module_id"] == "ad.kerberoast"+ assert data[0]["category"] == "ad"+ assert "opsec_level" in data[0]+++def test_mcp_scope_check_in_scope() -> None:+ """Verify scope-check on authorized IP returns exit code 0."""+ result = runner.invoke(+ app,+ ["mcp", "scope-check", "--target", "10.0.0.5", "--cidr", "10.0.0.0/24"],+ )+ assert result.exit_code == EXIT_SUCCESS+ assert "APPROVED" in result.stdout+ assert "YES" in result.stdout+++def test_mcp_scope_check_in_scope_json() -> None:+ """Verify scope-check --json output."""+ result = runner.invoke(+ app,+ ["mcp", "scope-check", "--target", "10.0.0.5", "--cidr", "10.0.0.0/24", "--json"],+ )+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert data["target"] == "10.0.0.5"+ assert data["in_scope"] is True+ assert data["status"] == "APPROVED"+++def test_mcp_scope_check_out_of_scope_strict() -> None:+ """Verify strict scope-check on unauthorized target exits with code 1."""+ result = runner.invoke(+ app,+ ["mcp", "scope-check", "--target", "8.8.8.8", "--cidr", "10.0.0.0/24", "--strict"],+ )+ assert result.exit_code == EXIT_ERROR+ assert "REJECTED_OUT_OF_SCOPE" in result.stdout+ assert "NO" in result.stdout+++def test_mcp_scope_check_out_of_scope_non_strict() -> None:+ """Verify non-strict scope-check outputs rejection but exits with code 0."""+ result = runner.invoke(+ app,+ ["mcp", "scope-check", "--target", "8.8.8.8", "--cidr", "10.0.0.0/24", "--no-strict"],+ )+ assert result.exit_code == EXIT_SUCCESS+ assert "REJECTED_OUT_OF_SCOPE" in result.stdout+++def test_mcp_dry_run_preflight() -> None:+ """Verify pre-flight dry-run card and confirmation token generation."""+ result = runner.invoke(+ app,+ ["mcp", "dry-run", "--target", "10.0.0.5", "--module", "ad.kerberoast"],+ )+ assert result.exit_code == EXIT_SUCCESS+ assert "Pre-Flight Dry-Run Card" in result.stdout+ assert "Confirmation Token:" in result.stdout+ assert "ares_tok_" in result.stdout+++def test_mcp_dry_run_json() -> None:+ """Verify dry-run --json returns structured simulation payload with token."""+ result = runner.invoke(+ app,+ ["mcp", "dry-run", "--target", "10.0.0.5", "--module", "ad.kerberoast", "--json"],+ )+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert data["status"] == "SIMULATION_SUCCESS"+ assert data["module_id"] == "ad.kerberoast"+ assert data["target"] == "10.0.0.5"+ assert data["confirmation_token"].startswith("ares_tok_")+ assert data["token_ttl_seconds"] == 60+++def test_mcp_setup_client_cursor(monkeypatch: pytest.MonkeyPatch) -> None:+ """Verify setup command configures Cursor IDE without error."""+ import tempfile+ orig_cwd = Path.cwd()+ with tempfile.TemporaryDirectory() as tmpdir:+ tmp_path = Path(tmpdir)+ monkeypatch.chdir(tmp_path)+ try:+ result = runner.invoke(app, ["mcp", "setup", "--client", "cursor", "--json"])+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert data["client"] == "cursor"+ assert data["status"] == "SUCCESS"+ finally:+ os.chdir(orig_cwd)+++def test_mcp_setup_invalid_client() -> None:+ """Verify setup with unsupported client exits with code 2."""+ result = runner.invoke(app, ["mcp", "setup", "--client", "unknown_ide"])+ assert result.exit_code == EXIT_INVALID_INPUT+ assert "Unknown client" in result.stdout+++def test_mcp_run_tool_success() -> None:+ """Verify headless execution of an operational MCP tool."""+ result = runner.invoke(app, ["mcp", "run-tool", "ares_list_campaigns", "--json"])+ assert result.exit_code == EXIT_SUCCESS+ data = json.loads(result.stdout)+ assert isinstance(data, list)+ assert len(data) >= 1+ assert data[0]["id"] == "camp_default_01"+++def test_mcp_run_tool_unknown_tool() -> None:+ """Verify run-tool with unknown tool exits with code 2."""+ result = runner.invoke(app, ["mcp", "run-tool", "nonexistent_ares_tool"])+ assert result.exit_code == EXIT_INVALID_INPUT+ assert "Unknown tool" in result.stdout+++def test_mcp_dry_run_invalid_params_json() -> None:+ """Verify invalid JSON params exits with code 2."""+ result = runner.invoke(+ app,+ [+ "mcp",+ "dry-run",+ "--target",+ "10.0.0.5",+ "--module",+ "ad.kerberoast",+ "--params",+ "not_a_valid_json",+ ],+ )+ assert result.exit_code == EXIT_INVALID_INPUT+ assert "Invalid --params JSON" in result.stdout+++def test_mcp_no_color_strips_ansi(monkeypatch: pytest.MonkeyPatch) -> None:+ """Verify NO_COLOR environment variable adheres to https://no-color.org."""+ monkeypatch.setenv("NO_COLOR", "1")+ assert is_no_color_active() is True+ result = runner.invoke(app, ["mcp", "doctor"])+ assert result.exit_code == EXIT_SUCCESS+ assert "\x1b[" not in result.stdout+++def test_mcp_non_interactive_piped() -> None:+ """Verify running mcp without subcommands in piped non-TTY mode does not hang."""+ python_exe = sys.executable+ proc = subprocess.run( # noqa: S603+ [python_exe, "-m", "ares.cli.main", "mcp"],+ input="",+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ )+ assert proc.returncode == EXIT_SUCCESS+ assert "Non-interactive mode" in proc.stdout or "Status: PASS" in proc.stdout+++def test_mcp_subcommand_help_coverage() -> None:+ """Verify comprehensive help is available on all MCP subcommands."""+ subcommands = [+ "doctor",+ "module-catalog",+ "scope-check",+ "dry-run",+ "setup",+ "run-tool",+ "stdio",+ "sse",+ "config",+ "export-tools",+ ]+ for subcmd in subcommands:+ result = runner.invoke(app, ["mcp", subcmd, "--help"])+ assert result.exit_code == EXIT_SUCCESS, f"Subcommand {subcmd} failed help check"+ assert "Usage:" in result.stdout or "Options" in result.stdoutdiff --git a/tests/unit/test_mcp_server.py b/tests/unit/test_mcp_server.pyindex 24077f7..eaad817 100644--- a/tests/unit/test_mcp_server.py+++ b/tests/unit/test_mcp_server.py@@ -16,8 +16,9 @@ Tests:from __future__ import annotationsimport json-import pytest+import httpx+import pytestfrom ares.mcp import (AresMcpServer,@@ -36,7 +37,7 @@ from ares.sdk.resilience import CircuitBreakerState@pytest.fixturedef mcp_server() -> AresMcpServer:- return AresMcpServer(secret_key="ares_test_secret_for_mcp_tests_only_32_bytes!!")+ return AresMcpServer(secret_key="ares_test_secret_for_mcp_tests_only_32_bytes!!") # noqa: S106# ββ 1. Protocol Negotiation Tests ββββββββββββββββββββββββββββββββββββββββββββ@@ -114,7 +115,9 @@ async def test_mcp_tools_list_schema(mcp_server: AresMcpServer) -> None:@pytest.mark.asyncioasync def test_mcp_resources_and_prompts(mcp_server: AresMcpServer) -> None:# Resources List- res_list = await mcp_server.handle_message({"jsonrpc": "2.0", "id": 20, "method": "resources/list"})+ res_list = await mcp_server.handle_message(+ {"jsonrpc": "2.0", "id": 20, "method": "resources/list"}+ )resources = res_list["result"]["resources"]uris = [r["uri"] for r in resources]assert "ares://campaigns/active" in uris@@ -170,7 +173,7 @@ def test_scope_gate_verification() -> None:# ββ 5. Confirmation Token Handshake (Anti-Replay) Tests βββββββββββββββββββββdef test_confirmation_token_manager_lifecycle() -> None:- mgr = ConfirmationTokenManager(secret_key="test_secret_key_32_bytes_long!!")+ mgr = ConfirmationTokenManager(secret_key="test_secret_key_32_bytes_long!!") # noqa: S106# Issue tokentoken = mgr.issue_token(@@ -303,7 +306,7 @@ def test_secret_redaction() -> None:}masked = SecretMasker.mask(data)assert masked["username"] == "admin_corp"- assert masked["password"] == "***REDACTED***"+ assert masked["password"] == "***REDACTED***" # noqa: S105assert masked["ntlm_hash"] == "***REDACTED***"assert masked["metadata"]["private_key"] == "***REDACTED***"assert masked["metadata"]["target"] == "10.0.0.1"@@ -358,7 +361,8 @@ def test_multi_format_tool_exporter(mcp_server: AresMcpServer) -> None:async def test_sse_transport_authentication(mcp_server: AresMcpServer) -> None:app = create_sse_app(mcp_server, api_key="test_super_secret_token_123")- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:# 1. Unauthenticated -> 401res_unauth = await client.get("/sse")assert res_unauth.status_code == 401@@ -378,6 +382,7 @@ async def test_sse_transport_authentication(mcp_server: AresMcpServer) -> None:def test_mcp_cli_commands() -> None:from typer.testing import CliRunner+from ares.cli.typer_main import apprunner = CliRunner()@@ -385,11 +390,21 @@ def test_mcp_cli_commands() -> None:# 1. Doctor commanddoc_res = runner.invoke(app, ["mcp", "doctor"])assert doc_res.exit_code == 0- assert "ARES Sovereign MCP Readiness Check" in doc_res.stdout+ assert "ARES MCP Subsystem Readiness Check" in doc_res.stdoutassert "Protocol Engine" in doc_res.stdout# 2. Config commands for various clients- for client_name in ("claude", "cursor", "windsurf", "cline", "zed", "open-webui", "librechat", "langchain"):+ clients = (+ "claude",+ "cursor",+ "windsurf",+ "cline",+ "zed",+ "open-webui",+ "librechat",+ "langchain",+ )+ for client_name in clients:cfg_res = runner.invoke(app, ["mcp", "config", "--client", client_name])assert cfg_res.exit_code == 0, f"Config failed for {client_name}"