Merge feature/spec-03-mcp-server: Native MCP Server (stdio/sse) with 3-tier security

This commit is contained in:
fluzzi32 committed 2026-11-09 16:08:02 -03:00
commit 388d042eba
4 files changed
+1024 -28

No files matched your search

+54 -11
View File
@@ -1,7 +1,8 @@
import sys
from rich.panel import Panel
from rich.rule import Rule
from rich.prompt import Prompt
from rich.rule import Rule
from .. import printer
@@ -36,7 +37,7 @@ class AIHandler:
try:
self.app.services.ai.delete_session(args.delete_session[0])
printer.success(f"Session {args.delete_session[0]} deleted.")
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(str(e))
return
@@ -189,7 +190,7 @@ class AIHandler:
try:
self.app.services.ai.configure_mcp(name, url=url, auto_load_on_os=os_filter)
printer.success(f"MCP server '{name}' added/updated.")
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(str(e))
return
@@ -201,7 +202,7 @@ class AIHandler:
try:
self.app.services.ai.configure_mcp(name, remove=True)
printer.success(f"MCP server '{name}' removed.")
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(str(e))
return
@@ -214,13 +215,54 @@ class AIHandler:
try:
self.app.services.ai.configure_mcp(name, enabled=enabled)
printer.success(f"MCP server '{name}' {'enabled' if enabled else 'disabled'}.")
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(str(e))
return
elif action == "serve":
transport = "stdio"
host = "127.0.0.1"
port = 8000
trust = getattr(args, "trust", False)
idx = 1
while idx < len(mcp_args):
tok = mcp_args[idx]
if tok in ["--sse", "sse"]:
transport = "sse"
elif tok in ["--stdio", "stdio"]:
transport = "stdio"
elif tok in ["--trust", "trust"]:
trust = True
elif tok in ["--port", "-p"]:
idx += 1
if idx < len(mcp_args):
try:
port = int(mcp_args[idx])
except ValueError:
printer.error(f"Invalid port: {mcp_args[idx]}")
return
elif tok.startswith("--port="):
try:
port = int(tok.split("=", 1)[1])
except ValueError:
printer.error(f"Invalid port: {tok}")
return
elif tok in ["--host", "-h"]:
idx += 1
if idx < len(mcp_args):
host = mcp_args[idx]
elif tok.startswith("--host="):
host = tok.split("=", 1)[1]
idx += 1
from ..mcp_server import ConnpyMCPServer
server = ConnpyMCPServer(config=self.app.config, services=self.app.services, trust=trust)
return server.run(transport=transport, host=host, port=port)
else:
printer.error(f"Unknown MCP action: {action}")
printer.info("Available actions: list, add, remove, enable, disable")
printer.info("Available actions: list, add, remove, enable, disable, serve")
return
# 2. Interactive Wizard Mode (if no arguments provided)
@@ -262,15 +304,16 @@ class AIHandler:
self.app.services.ai.configure_mcp(result["name"], remove=True)
printer.success(f"MCP server '{result['name']}' removed.")
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(str(e))
def _parse_auth_value(self, value):
if not value or value.lower() in ["none", "clear"]:
return None
import os
import yaml
import json
import os
import yaml
if os.path.exists(value):
try:
with open(value, "r") as f:
@@ -279,7 +322,7 @@ class AIHandler:
return json.loads(content)
except ValueError:
return yaml.safe_load(content)
except Exception as e:
except Exception as e: # noqa: BLE001
printer.error(f"Failed to read/parse auth file '{value}': {e}")
sys.exit(1)
@@ -291,6 +334,6 @@ class AIHandler:
if isinstance(parsed, dict):
return parsed
raise ValueError()
except Exception:
except Exception: # noqa: BLE001
printer.error("Auth parameter must be a valid JSON/YAML string, or a path to a JSON/YAML file.")
sys.exit(1)
+29 -17
View File
@@ -1,5 +1,7 @@
import sys
#!/usr/bin/env python3
import os
import sys
def load_txt_cache(filepath):
try:
@@ -27,7 +29,7 @@ def get_cwd(words, option=None, folderonly=False):
for i in range(len(pathstrings)):
if os.path.isdir(pathstrings[i]):
pathstrings[i] += '/'
pathstrings = [s[2:] if s.startswith('./') else s for s in pathstrings]
pathstrings = [s.removeprefix('./') for s in pathstrings]
if folderonly:
pathstrings = [s for s in pathstrings if os.path.isdir(s)]
return pathstrings
@@ -43,7 +45,7 @@ def _get_plugins(which, defaultdir):
try:
with open(pref_path) as f:
preferences = json.load(f)
except Exception:
except Exception: # noqa: BLE001
preferences = {}
# Load service mode
@@ -71,8 +73,8 @@ def _get_plugins(which, defaultdir):
# Get plugins from all directories
user_enabled, user_disabled, user_all_plugins = get_plugins_from_directory(defaultdir + "/plugins")
core_enabled, core_disabled, core_all_plugins = get_plugins_from_directory(core_path)
remote_enabled, remote_disabled, remote_all_plugins = get_plugins_from_directory(remote_path)
_core_enabled, _core_disabled, core_all_plugins = get_plugins_from_directory(core_path)
_remote_enabled, _remote_disabled, remote_all_plugins = get_plugins_from_directory(remote_path)
# Calculate final paths respecting priorities and preferences
# Priority: User Local > Core Local > Remote (unless preferred)
@@ -115,7 +117,7 @@ def _get_users(configdir):
data = yaml.safe_load(f) or {}
if isinstance(data, dict) and "users" in data:
return list(data["users"].keys())
except Exception:
except Exception: # noqa: BLE001, S110
pass
return []
@@ -135,7 +137,7 @@ def _get_sso_providers(configdir):
providers = sso.get("providers", {})
if isinstance(providers, dict):
return list(providers.keys())
except Exception:
except Exception: # noqa: BLE001, S110
pass
return []
@@ -210,12 +212,22 @@ def _build_tree(nodes, folders, profiles, plugins, configdir):
}
# State Machine Definitions
serve_dict = {"__exclude_used__": True}
serve_dict.update({
"--sse": serve_dict,
"--port": {"*": serve_dict},
"--trust": serve_dict,
"--help": None,
"-h": None
})
mcp_dict = {
"list": None,
"add": {"*": {"*": {"*": None}}}, # name url [os]
"remove": {"*": None},
"enable": {"*": None},
"disable": {"*": None},
"serve": serve_dict,
"--help": None, "-h": None
}
@@ -291,7 +303,7 @@ def _build_tree(nodes, folders, profiles, plugins, configdir):
# Long flags are offered; short forms (-d/-t) only used for navigation.
# Two states: before node (offer nodes + remaining long flags)
# after node (offer only remaining long flags, no more nodes)
connect_flags_long = ["--debug", "--sftp"]
_connect_flags_long = ["--debug", "--sftp"]
connect_flags_all = ["--debug", "-d", "--sftp", "-t"]
# Post-node: only offer remaining long flags
@@ -443,7 +455,7 @@ def main():
try:
with open(pathfile, "r") as f:
configdir = f.read().strip()
except (FileNotFoundError, IOError):
except (OSError, FileNotFoundError):
configdir = defaultdir
cachefile = configdir + '/.config.cache.json'
@@ -477,8 +489,8 @@ def main():
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.get_cwd = get_cwd
except Exception:
exit()
except Exception: # noqa: BLE001
sys.exit()
# New API: _connpy_tree → integrate into main tree and use resolver
if hasattr(module, "_connpy_tree"):
@@ -493,20 +505,20 @@ def main():
try:
with open(cachefile, "r") as jsonconf:
info["config"] = json.load(jsonconf)
except Exception:
except Exception: # noqa: BLE001
try:
import yaml
with open(configdir + '/config.yaml', "r") as yamlconf:
info["config"] = yaml.safe_load(yamlconf)
except Exception:
except Exception: # noqa: BLE001
info["config"] = {}
try:
plugin_completion = getattr(module, "_connpy_completion")
plugin_completion = module._connpy_completion
strings = plugin_completion(wordsnumber, words, info)
except Exception:
exit()
except Exception: # noqa: BLE001
sys.exit()
else:
exit()
sys.exit()
# --- Tree-based completion ---
else:
+528
View File
@@ -0,0 +1,528 @@
import contextlib
import logging
import re
import sys
from typing import Any, ClassVar
import yaml
try:
from mcp.server.mcpserver import MCPServer
except ImportError:
try:
from mcp.server.fastmcp import FastMCP as MCPServer
except ImportError:
MCPServer = None
logger = logging.getLogger("connpy.mcp_server")
class ConnpyMCPServer:
"""Native Model Context Protocol (MCP) Server for connpy."""
SAFE_COMMANDS: ClassVar[list[str]] = [
r"^show\s+",
r"^ls\s*",
r"^cat\s+",
r"^ip\s+",
r"^pwd$",
r"^hostname$",
r"^uname",
r"^df\s*",
r"^free\s*",
r"^ps\s*",
r"^ping\s+",
r"^traceroute\s+",
r"^whois\s+",
r"^kubectl\s+(get|describe|version|logs|top|explain|cluster-info|api-resources|api-versions)\s+",
r"^systemctl\s+status\s+",
r"^journalctl\s+",
]
def __init__(self, config=None, services=None, trust: bool = False):
self.config = config
self.services = services
if self.services is None:
if self.config is not None:
from .services.provider import ServiceProvider
self.services = ServiceProvider(self.config)
elif self.config is None and hasattr(self.services, "config"):
self.config = self.services.config
self.trust = bool(trust)
# Build list of safe commands (SAFE_COMMANDS + trusted_commands from config)
aiconfig = {}
if self.config:
if hasattr(self.config, "get_effective_setting"):
aiconfig = self.config.get_effective_setting("ai", {})
elif hasattr(self.config, "config") and isinstance(self.config.config, dict):
aiconfig = self.config.config.get("ai", {})
custom_trusted = aiconfig.get("trusted_commands", []) if isinstance(aiconfig, dict) else []
if isinstance(custom_trusted, str):
custom_trusted = [c.strip() for c in custom_trusted.split(",") if c.strip()]
self.safe_commands = list(self.SAFE_COMMANDS) + (
custom_trusted if isinstance(custom_trusted, list) else []
)
# Initialize MCP Server
if MCPServer is not None:
self.server = MCPServer("connpy")
self._register_tools()
else:
self.server = None
def _register_tools(self):
"""Register the 3 tiers of MCP tools."""
if not self.server:
return
# Level 1 Tools (Read-Only)
self.server.tool()(self.list_nodes)
self.server.tool()(self.list_folders)
self.server.tool()(self.get_node_info)
self.server.tool()(self.list_profiles)
self.server.tool()(self.get_active_context)
# Level 2 Tools (Execution, Testing, Playbooks)
self.server.tool()(self.run_commands)
self.server.tool()(self.test_commands)
self.server.tool()(self.validate_playbook)
self.server.tool()(self.run_playbook)
# Level 3 Tools (CRUD - Requires trust=True)
self.server.tool()(self.add_node)
self.server.tool()(self.update_node)
self.server.tool()(self.delete_node)
# -------------------------------------------------------------------------
# Security Validation
# -------------------------------------------------------------------------
def is_safe_command(self, cmd: str) -> bool:
"""Validate if a command is considered safe under current trust settings.
- If trust is True, all commands are allowed.
- Block chaining/injection characters: ';', '&&', '||', '|', '`', '$(', '>', '<', '\\n', '\\r', '&'.
- Validates against self.safe_commands (SAFE_COMMANDS + trusted_commands).
"""
if self.trust:
return True
if not isinstance(cmd, str):
cmd = str(cmd)
# Check for shell chaining and redirection injection tokens
injection_tokens = [";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r", "&"]
if any(tok in cmd for tok in injection_tokens):
return False
clean_cmd = cmd.strip()
return any(re.match(pattern, clean_cmd, re.IGNORECASE) for pattern in self.safe_commands)
def _mask_secrets(self, val: Any) -> Any:
"""Recursively mask passwords, passphrases, secrets, and auth tokens with '***'."""
if isinstance(val, dict):
masked = {}
for k, v in val.items():
k_lower = str(k).lower()
if any(sec in k_lower for sec in ["password", "passphrase", "secret", "token"]):
masked[k] = "***"
elif isinstance(v, (dict, list)):
masked[k] = self._mask_secrets(v)
else:
masked[k] = v
return masked
if isinstance(val, list):
return [self._mask_secrets(item) for item in val]
return val
# -------------------------------------------------------------------------
# Level 1: Read-Only Inventory and Context Tools
# -------------------------------------------------------------------------
def list_nodes(self, filter_pattern: str = "", format_str: str = "") -> list[str]:
"""List inventory nodes, optionally filtered by regex pattern and formatted."""
if not self.services or not hasattr(self.services, "nodes"):
return []
f = filter_pattern if filter_pattern else None
fmt = format_str if format_str else None
return self.services.nodes.list_nodes(filter_str=f, format_str=fmt)
def list_folders(self, filter_pattern: str = "") -> list[str]:
"""List inventory folders, optionally filtered by regex pattern."""
if not self.services or not hasattr(self.services, "nodes"):
return []
f = filter_pattern if filter_pattern else None
return self.services.nodes.list_folders(filter_str=f)
def get_node_info(self, node_name: str) -> dict:
"""Get full configuration metadata for a specific node.
Passwords, passphrases, and secrets are ALWAYS masked with '***'.
"""
if not self.services or not hasattr(self.services, "nodes"):
return {"error": "Node service unavailable."}
try:
details = self.services.nodes.get_node_details(node_name)
if hasattr(self.services, "profiles"):
with contextlib.suppress(Exception):
details = self.services.profiles.resolve_node_data(details)
return self._mask_secrets(details)
except Exception as e: # noqa: BLE001
return {"error": f"Node '{node_name}' not found: {e}"}
def list_profiles(self, filter_pattern: str = "") -> list[str]:
"""List all available node connection profiles."""
if not self.services or not hasattr(self.services, "profiles"):
return []
f = filter_pattern if filter_pattern else None
return self.services.profiles.list_profiles(filter_str=f)
def get_active_context(self) -> dict:
"""Get the currently active context name and its matching regex patterns."""
if not self.services or not hasattr(self.services, "context"):
return {"context": "all", "patterns": [".*"]}
try:
ctx_name = self.services.context.current_context
patterns = [p.pattern for p in self.services.context.get_active_regexes()]
return {"context": ctx_name, "patterns": patterns}
except Exception as e: # noqa: BLE001
return {"context": "unknown", "error": str(e)}
# -------------------------------------------------------------------------
# Level 2: Execution, Testing, and Playbooks Tools
# -------------------------------------------------------------------------
def run_commands(
self,
nodes_filter: str,
commands: list[str] | str,
parallel: bool = True,
timeout: int = 30,
) -> dict:
"""Execute commands on nodes matching the filter pattern.
Unsafe commands are blocked unless trust mode is enabled.
"""
if not self.services or not hasattr(self.services, "execution"):
return {"success": False, "error": "Execution service unavailable."}
# Normalize commands list
if isinstance(commands, str):
try:
import json
parsed = json.loads(commands)
commands = parsed if isinstance(parsed, list) else [commands]
except Exception: # noqa: BLE001
commands = [c.strip() for c in commands.splitlines() if c.strip()]
elif not isinstance(commands, list):
commands = [str(commands)]
# Check safety
if not self.trust:
unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
if unsafe:
return {
"success": False,
"error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
}
par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
try:
results = self.services.execution.run_commands(
nodes_filter=nodes_filter,
commands=commands,
parallel=par_count,
timeout=timeout,
)
return {"success": True, "results": results}
except Exception as e: # noqa: BLE001
return {"success": False, "error": str(e)}
def test_commands(
self,
nodes_filter: str,
commands: list[str] | str,
expected: list[str] | str = "",
parallel: bool = True,
timeout: int = 30,
) -> dict:
"""Execute commands and assert expected patterns on nodes matching the filter."""
if not self.services or not hasattr(self.services, "execution"):
return {"success": False, "error": "Execution service unavailable."}
# Normalize commands
if isinstance(commands, str):
try:
import json
parsed = json.loads(commands)
commands = parsed if isinstance(parsed, list) else [commands]
except Exception: # noqa: BLE001
commands = [c.strip() for c in commands.splitlines() if c.strip()]
elif not isinstance(commands, list):
commands = [str(commands)]
# Normalize expected
if isinstance(expected, str):
try:
import json
parsed = json.loads(expected)
expected = parsed if isinstance(parsed, list) else ([expected] if expected else [])
except Exception: # noqa: BLE001
expected = [expected] if expected else []
elif not isinstance(expected, list):
expected = [str(expected)] if expected else []
# Check safety
if not self.trust:
unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
if unsafe:
return {
"success": False,
"error": f"Permission denied: unsafe commands detected: {unsafe}. Requires trust=True.",
}
par_count = 10 if parallel is True else (parallel if isinstance(parallel, int) else 1)
try:
results = self.services.execution.test_commands(
nodes_filter=nodes_filter,
commands=commands,
expected=expected,
parallel=par_count,
timeout=timeout,
)
return {"success": True, "results": results}
except Exception as e: # noqa: BLE001
return {"success": False, "error": str(e)}
def validate_playbook(self, playbook_yaml: str) -> dict:
"""Validate the syntax, schema, and tasks of a Connpy YAML playbook."""
try:
data = yaml.safe_load(playbook_yaml)
except Exception as e: # noqa: BLE001
return {"valid": False, "error": f"YAML Syntax Error: {e}"}
if not isinstance(data, dict):
return {"valid": False, "error": "Playbook must be a YAML dictionary."}
if "tasks" not in data:
return {"valid": False, "error": "Playbook missing mandatory root 'tasks' key."}
tasks = data["tasks"]
if not isinstance(tasks, list):
return {"valid": False, "error": "'tasks' must be a list of tasks."}
for idx, task in enumerate(tasks):
if not isinstance(task, dict):
return {"valid": False, "error": f"Task index {idx} must be a dictionary."}
name = task.get("name", f"Task {idx}")
mandatory = ["name", "action", "nodes", "commands", "output"]
missing = [f for f in mandatory if f not in task]
if missing:
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) is missing mandatory fields: {missing}",
}
nodes = task["nodes"]
if not isinstance(nodes, (str, list)):
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) 'nodes' must be a string or list of strings.",
}
if isinstance(nodes, list):
for n_idx, node_item in enumerate(nodes):
if not isinstance(node_item, str):
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) 'nodes' contains non-string at index {n_idx}: {node_item}",
}
action = task["action"]
if action not in ["run", "test"]:
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) invalid action '{action}'. Choices: 'run', 'test'.",
}
if action == "test" and "expected" not in task:
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) action 'test' requires 'expected' key.",
}
output = task["output"]
if output not in [None, "stdout", "null"] and not str(output).startswith("/"):
return {
"valid": False,
"error": f"Task '{name}' (index {idx}) output '{output}' must be 'stdout', 'null' or an absolute path.",
}
return {"valid": True, "message": "Playbook schema and syntax is valid."}
def run_playbook(self, playbook_yaml: str) -> dict:
"""Validate and execute a playbook, verifying commands beforehand if trust=False."""
val = self.validate_playbook(playbook_yaml)
if not val.get("valid"):
return {"success": False, "error": f"Invalid playbook: {val.get('error')}"}
data = yaml.safe_load(playbook_yaml)
tasks = data.get("tasks", [])
# Pre-verify commands if not trusted
if not self.trust:
for idx, task in enumerate(tasks):
name = task.get("name", f"Task {idx}")
commands = task.get("commands", [])
if isinstance(commands, str):
commands = [commands]
unsafe = [cmd for cmd in commands if not self.is_safe_command(cmd)]
if unsafe:
return {
"success": False,
"error": f"Permission denied: unsafe commands detected in task '{name}': {unsafe}. Requires trust=True.",
}
# Execute tasks
results = {}
for idx, task in enumerate(tasks):
name = task.get("name", f"task_{idx}")
action = task.get("action")
nodes = task.get("nodes")
commands = task.get("commands")
if isinstance(commands, str):
commands = [commands]
try:
if action == "run":
res = self.services.execution.run_commands(nodes_filter=nodes, commands=commands)
elif action == "test":
expected = task.get("expected", [])
if isinstance(expected, str):
expected = [expected]
res = self.services.execution.test_commands(
nodes_filter=nodes, commands=commands, expected=expected
)
else:
res = f"Unsupported action: {action}"
results[name] = res
except Exception as e: # noqa: BLE001
return {
"success": False,
"error": f"Execution failed at task '{name}': {e}",
"partial_results": results,
}
return {"success": True, "results": results}
# -------------------------------------------------------------------------
# Level 3: Inventory Mutation Tools (CRUD - Requires trust=True)
# -------------------------------------------------------------------------
def add_node(
self, unique_id: str, data: dict | None = None, is_folder: bool = False, **kwargs
) -> dict:
"""Add a new node or folder to the inventory (requires trust=True)."""
if not self.trust:
return {
"success": False,
"error": "Permission denied: CRUD operations require trust mode (--trust).",
}
if not self.services or not hasattr(self.services, "nodes"):
return {"success": False, "error": "Node service unavailable."}
node_data = (data or {}).copy()
node_data.update(kwargs)
try:
self.services.nodes.add_node(unique_id, node_data, is_folder=is_folder)
return {
"success": True,
"message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' created successfully.",
}
except Exception as e: # noqa: BLE001
return {"success": False, "error": str(e)}
def update_node(self, unique_id: str, updates: dict | None = None, **kwargs) -> dict:
"""Update an existing node configuration (requires trust=True)."""
if not self.trust:
return {
"success": False,
"error": "Permission denied: CRUD operations require trust mode (--trust).",
}
if not self.services or not hasattr(self.services, "nodes"):
return {"success": False, "error": "Node service unavailable."}
node_updates = (updates or {}).copy()
node_updates.update(kwargs)
try:
self.services.nodes.update_node(unique_id, node_updates)
return {"success": True, "message": f"Node '{unique_id}' updated successfully."}
except Exception as e: # noqa: BLE001
return {"success": False, "error": str(e)}
def delete_node(self, unique_id: str, is_folder: bool = False) -> dict:
"""Delete a node or folder from the inventory (requires trust=True)."""
if not self.trust:
return {
"success": False,
"error": "Permission denied: CRUD operations require trust mode (--trust).",
}
if not self.services or not hasattr(self.services, "nodes"):
return {"success": False, "error": "Node service unavailable."}
try:
self.services.nodes.delete_node(unique_id, is_folder=is_folder)
return {
"success": True,
"message": f"{'Folder' if is_folder else 'Node'} '{unique_id}' deleted successfully.",
}
except Exception as e: # noqa: BLE001
return {"success": False, "error": str(e)}
# -------------------------------------------------------------------------
# Server Execution and Async Helper
# -------------------------------------------------------------------------
async def call_tool(self, name: str, arguments: dict | None = None) -> Any:
"""Call an MCP tool asynchronously via the underlying MCP server."""
if not self.server:
raise RuntimeError("MCP SDK is not initialized.")
return await self.server.call_tool(name, arguments or {})
def run(self, transport: str = "stdio", host: str = "127.0.0.1", port: int = 8000, **kwargs):
"""Run the MCP server using either stdio or sse transport."""
if not self.server:
raise RuntimeError("MCP server cannot start: 'mcp' package is not installed.")
if transport == "stdio":
# Redirect logs and printer outputs to sys.stderr for JSON-RPC
with contextlib.suppress(Exception):
from . import printer
printer.set_thread_stream(sys.stderr)
for handler in logging.root.handlers:
if hasattr(handler, "stream") and handler.stream == sys.stdout:
handler.stream = sys.stderr
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
return self.server.run(transport="stdio", **kwargs)
if transport == "sse":
return self.server.run(transport="sse", host=host, port=port, **kwargs)
msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'"
raise ValueError(msg)
+413
View File
@@ -0,0 +1,413 @@
"""Tests for ConnpyMCPServer (spec-03-mcp-server)."""
import sys
from unittest.mock import MagicMock, patch
import pytest
from connpy.mcp_server import ConnpyMCPServer
from connpy.services.provider import ServiceProvider
@pytest.fixture
def services(populated_config):
"""Provide ServiceProvider initialized with sample connections/profiles."""
return ServiceProvider(populated_config)
@pytest.fixture
def mcp_server(populated_config, services):
"""Provide ConnpyMCPServer in untrusted mode."""
return ConnpyMCPServer(config=populated_config, services=services, trust=False)
@pytest.fixture
def trusted_mcp_server(populated_config, services):
"""Provide ConnpyMCPServer in trusted mode."""
return ConnpyMCPServer(config=populated_config, services=services, trust=True)
# =============================================================================
# Level 1 (Read-Only) Tools & Password Masking Tests
# =============================================================================
class TestLevel1Tools:
def test_list_nodes_all(self, mcp_server):
nodes = mcp_server.list_nodes()
assert isinstance(nodes, list)
assert "router1" in nodes
assert "server1@office" in nodes
assert "db1@datacenter@office" in nodes
def test_list_nodes_filtered(self, mcp_server):
nodes = mcp_server.list_nodes(filter_pattern="router.*")
assert "router1" in nodes
assert "server1@office" not in nodes
def test_list_nodes_formatted(self, mcp_server):
fmt = "{name} - {location}"
formatted = mcp_server.list_nodes(filter_pattern="router1", format_str=fmt)
assert len(formatted) == 1
assert formatted[0] == "router1 - root"
def test_list_folders(self, mcp_server):
folders = mcp_server.list_folders()
assert "@office" in folders
assert "@datacenter@office" in folders
def test_list_folders_filtered(self, mcp_server):
folders = mcp_server.list_folders(filter_pattern="datacenter")
assert "@datacenter@office" in folders
assert "@office" not in folders
def test_get_node_info_masks_password(self, mcp_server):
info = mcp_server.get_node_info("router1")
assert isinstance(info, dict)
assert info["host"] == "10.0.0.1"
assert info["user"] == "admin"
# CRITICAL requirement: ALWAYS mask password/passphrase/secret with "***"
assert info["password"] == "***"
assert "pass1" not in str(info)
def test_get_node_info_masks_nested_secrets(self, mcp_server):
test_data = {
"password": "plain_password",
"secret": "enable_secret",
"passphrase": "ssh_passphrase",
"api_token": "bearer_token",
"nested": {
"admin_password": "secret_nested",
"normal_key": "safe_value",
},
}
masked = mcp_server._mask_secrets(test_data)
assert masked["password"] == "***"
assert masked["secret"] == "***"
assert masked["passphrase"] == "***"
assert masked["api_token"] == "***"
assert masked["nested"]["admin_password"] == "***"
assert masked["nested"]["normal_key"] == "safe_value"
def test_get_node_info_not_found(self, mcp_server):
res = mcp_server.get_node_info("non_existent_node")
assert "error" in res
assert "not found" in res["error"].lower()
def test_list_profiles(self, mcp_server):
profiles = mcp_server.list_profiles()
assert "default" in profiles
assert "office-user" in profiles
def test_list_profiles_filtered(self, mcp_server):
profiles = mcp_server.list_profiles(filter_pattern="office")
assert "office-user" in profiles
assert "default" not in profiles
def test_get_active_context(self, mcp_server):
ctx = mcp_server.get_active_context()
assert isinstance(ctx, dict)
assert "context" in ctx
assert ctx["context"] == "all"
assert "patterns" in ctx
assert ".*" in ctx["patterns"]
# =============================================================================
# Level 2 Security & Execution Tests (is_safe_command, run, test, playbooks)
# =============================================================================
class TestLevel2Tools:
def test_is_safe_command_allowed_patterns(self, mcp_server):
safe_samples = [
"show version",
"show ip route",
"ls -la /var/log",
"cat /etc/hosts",
"ip address",
"pwd",
"hostname",
"uname -a",
"df -h",
"free -m",
"ps aux",
"ping -c 4 8.8.8.8",
"traceroute 1.1.1.1",
"whois example.com",
"kubectl get pods -n default",
"systemctl status nginx",
"journalctl -u ssh -n 50",
]
for cmd in safe_samples:
assert mcp_server.is_safe_command(cmd) is True, f"Expected safe: {cmd}"
def test_is_safe_command_blocks_unsafe_in_untrusted_mode(self, mcp_server):
unsafe_samples = [
"reboot",
"rm -rf /",
"shutdown -h now",
"configure terminal",
"set system host-name bad",
"echo hacked",
"dd if=/dev/zero of=/dev/sda",
]
for cmd in unsafe_samples:
assert mcp_server.is_safe_command(cmd) is False, f"Expected unsafe: {cmd}"
def test_is_safe_command_blocks_injection_characters(self, mcp_server):
injection_samples = [
"show version; rm -rf /",
"show version && reboot",
"show version || reboot",
"cat /etc/hosts | grep root",
"show `whoami`",
"cat $(id)",
"echo test > /tmp/bad",
"cat < /etc/shadow",
"show ip\nreboot",
"show ip\rreboot",
"show version & reboot",
]
for cmd in injection_samples:
assert not mcp_server.is_safe_command(cmd), f"Injection allowed: {cmd}"
def test_is_safe_command_allows_all_in_trusted_mode(self, trusted_mcp_server):
commands = [
"reboot",
"rm -rf /",
"configure terminal",
"show version; reboot",
"cat /etc/hosts | grep foo",
]
for cmd in commands:
assert trusted_mcp_server.is_safe_command(cmd) is True
def test_run_commands_blocks_unsafe_when_untrusted(self, mcp_server):
res = mcp_server.run_commands("router1", ["show version", "reboot"])
assert res["success"] is False
assert "Permission denied" in res["error"]
assert "reboot" in res["error"]
def test_run_commands_executes_when_trusted(self, trusted_mcp_server):
exec_svc = trusted_mcp_server.services.execution
with patch.object(exec_svc, "run_commands") as mock_exec:
mock_exec.return_value = {"router1": {"output": "ok", "status": 0}}
res = trusted_mcp_server.run_commands("router1", ["reboot"])
assert res["success"] is True
assert res["results"]["router1"]["output"] == "ok"
mock_exec.assert_called_once()
def test_test_commands_blocks_unsafe_when_untrusted(self, mcp_server):
res = mcp_server.test_commands("router1", ["rm -rf /"], expected=["root"])
assert res["success"] is False
assert "Permission denied" in res["error"]
def test_test_commands_executes_when_trusted(self, trusted_mcp_server):
exec_svc = trusted_mcp_server.services.execution
with patch.object(exec_svc, "test_commands") as mock_test:
mock_test.return_value = {"router1": {"rm -rf /": True}}
res = trusted_mcp_server.test_commands(
"router1", ["rm -rf /"], expected=["root"]
)
assert res["success"] is True
assert res["results"]["router1"]["rm -rf /"] is True
def test_validate_playbook_valid(self, mcp_server):
valid_yaml = """
tasks:
- name: Check Status
action: run
nodes: router1
commands:
- show version
output: stdout
- name: Assert Interface
action: test
nodes: router1
commands:
- show ip int brief
expected:
- GigabitEthernet0/0
output: stdout
"""
res = mcp_server.validate_playbook(valid_yaml)
assert res["valid"] is True
def test_validate_playbook_invalid(self, mcp_server):
# Missing root tasks key
res1 = mcp_server.validate_playbook("name: invalid")
assert res1["valid"] is False
assert "tasks" in res1["error"]
# Missing expected in test action
invalid_yaml = """
tasks:
- name: Bad Test
action: test
nodes: router1
commands:
- show version
output: stdout
"""
res2 = mcp_server.validate_playbook(invalid_yaml)
assert res2["valid"] is False
assert "expected" in res2["error"]
def test_run_playbook_blocks_unsafe_commands_when_untrusted(self, mcp_server):
unsafe_playbook = """
tasks:
- name: Reboot Device
action: run
nodes: router1
commands:
- reboot
output: stdout
"""
res = mcp_server.run_playbook(unsafe_playbook)
assert res["success"] is False
assert "Permission denied" in res["error"]
assert "reboot" in res["error"]
def test_run_playbook_executes_when_trusted(self, trusted_mcp_server):
playbook = """
tasks:
- name: Safe Task
action: run
nodes: router1
commands:
- reboot
output: stdout
"""
exec_svc = trusted_mcp_server.services.execution
with patch.object(exec_svc, "run_commands") as mock_exec:
mock_exec.return_value = {"router1": {"output": "ok", "status": 0}}
res = trusted_mcp_server.run_playbook(playbook)
assert res["success"] is True
assert "Safe Task" in res["results"]
# =============================================================================
# Level 3 (CRUD) Inventory Mutation Tests
# =============================================================================
class TestLevel3CRUD:
def test_add_node_blocked_when_untrusted(self, mcp_server):
res = mcp_server.add_node("router99", {"host": "10.0.0.99"})
assert res["success"] is False
assert "Permission denied" in res["error"]
def test_add_node_allowed_when_trusted(self, trusted_mcp_server):
data = {"host": "10.0.0.99", "protocol": "ssh"}
res = trusted_mcp_server.add_node("router99", data)
assert res["success"] is True
nodes = trusted_mcp_server.list_nodes()
assert "router99" in nodes
def test_update_node_blocked_when_untrusted(self, mcp_server):
res = mcp_server.update_node("router1", {"host": "10.0.0.254"})
assert res["success"] is False
assert "Permission denied" in res["error"]
def test_update_node_allowed_when_trusted(self, trusted_mcp_server):
res = trusted_mcp_server.update_node("router1", {"host": "10.0.0.254"})
assert res["success"] is True
info = trusted_mcp_server.get_node_info("router1")
assert info["host"] == "10.0.0.254"
def test_delete_node_blocked_when_untrusted(self, mcp_server):
res = mcp_server.delete_node("router1")
assert res["success"] is False
assert "Permission denied" in res["error"]
def test_delete_node_allowed_when_trusted(self, trusted_mcp_server):
res = trusted_mcp_server.delete_node("router1")
assert res["success"] is True
nodes = trusted_mcp_server.list_nodes()
assert "router1" not in nodes
# =============================================================================
# Transport & Logging Redirection Tests
# =============================================================================
class TestTransportAndRedirection:
def test_stdio_redirects_stdout_and_calls_run(self, mcp_server):
with patch.object(mcp_server.server, "run") as mock_run, \
patch("connpy.printer.set_thread_stream") as mock_set_stream:
mcp_server.run(transport="stdio")
mock_set_stream.assert_called_once_with(sys.stderr)
mock_run.assert_called_once_with(transport="stdio")
def test_sse_passes_host_and_port(self, mcp_server):
with patch.object(mcp_server.server, "run") as mock_run:
mcp_server.run(transport="sse", host="0.0.0.0", port=9090)
mock_run.assert_called_once_with(transport="sse", host="0.0.0.0", port=9090)
# =============================================================================
# Async MCP Protocol Tool Invocation Tests
# =============================================================================
class TestMCPProtocolAsyncCall:
@pytest.mark.asyncio
async def test_async_call_tool_list_nodes(self, mcp_server):
res = await mcp_server.call_tool("list_nodes", {"filter_pattern": "router1"})
assert not res.is_error
text = res.content[0].text
assert "router1" in text
@pytest.mark.asyncio
async def test_async_call_tool_get_node_info_masks_password(self, mcp_server):
res = await mcp_server.call_tool("get_node_info", {"node_name": "router1"})
assert not res.is_error
text = res.content[0].text
assert '"password": "***"' in text
assert "pass1" not in text
# =============================================================================
# CLI Dispatch & Completion Tests
# =============================================================================
class TestCLIDispatchAndCompletion:
def test_ai_handler_configure_mcp_serve_dispatch(self, populated_config, services):
from connpy.cli.ai_handler import AIHandler
class DummyApp:
def __init__(self, conf, svcs):
self.config = conf
self.services = svcs
app = DummyApp(populated_config, services)
handler = AIHandler(app)
args = MagicMock()
args.mcp = ["serve", "--sse", "--port", "9191", "--trust"]
args.trust = False
with patch("connpy.mcp_server.ConnpyMCPServer.run") as mock_run:
handler.configure_mcp(args)
mock_run.assert_called_once_with(
transport="sse", host="127.0.0.1", port=9191
)
def test_completion_contains_serve_flags(self):
from connpy.completion import _build_tree, resolve_completion
tree = _build_tree([], [], [], {}, "/tmp")
# Verify tree hierarchy
assert "serve" in tree["ai"]["--mcp"]
serve_sub = tree["ai"]["--mcp"]["serve"]
assert "--sse" in serve_sub
assert "--port" in serve_sub
assert "--trust" in serve_sub
# Verify completions resolution
comp_base = resolve_completion(["ai", "--mcp", "serve", ""], tree)
assert "--sse" in comp_base
assert "--port" in comp_base
assert "--trust" in comp_base
# After --sse, remaining flags are suggested
comp_after_sse = resolve_completion(["ai", "--mcp", "serve", "--sse", ""], tree)
assert "--port" in comp_after_sse
assert "--trust" in comp_after_sse