1251 lines
62 KiB
HTML
1251 lines
62 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||
<meta name="generator" content="pdoc3 0.11.6">
|
||
<title>connpy.mcp_server API documentation</title>
|
||
<meta name="description" content="">
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||
hljs.highlightAll();
|
||
/* Collapse source docstrings */
|
||
setTimeout(() => {
|
||
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
|
||
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
|
||
.forEach(el => {
|
||
let d = document.createElement('details');
|
||
d.classList.add('hljs-string');
|
||
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
|
||
el.replaceWith(d);
|
||
});
|
||
}, 100);
|
||
})</script>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<article id="content">
|
||
<header>
|
||
<h1 class="title">Module <code>connpy.mcp_server</code></h1>
|
||
</header>
|
||
<section id="section-intro">
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||
<dl>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer"><code class="flex name class">
|
||
<span>class <span class="ident">ConnpyMCPServer</span></span>
|
||
<span>(</span><span>config=None, services=None, trust: bool = False)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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 '***'."""
|
||
return mask_node_secrets(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
|
||
# -------------------------------------------------------------------------
|
||
|
||
@staticmethod
|
||
def _parse_json_list_or_lines(raw_val: list[str] | str, *, allow_empty_str: bool = False) -> list[str]:
|
||
if isinstance(raw_val, str):
|
||
if len(raw_val.encode("utf-8", errors="replace")) > MAX_JSON_INPUT_BYTES:
|
||
raise ValueError(f"Input exceeds maximum size of {MAX_JSON_INPUT_BYTES} bytes")
|
||
stripped = raw_val.strip()
|
||
if stripped.startswith(("[", "{")):
|
||
parsed = validate_json_depth_and_size(
|
||
stripped,
|
||
max_bytes=MAX_JSON_INPUT_BYTES,
|
||
max_depth=MAX_JSON_INPUT_DEPTH,
|
||
)
|
||
return parsed if isinstance(parsed, list) else [raw_val]
|
||
return ([raw_val] if raw_val else []) if allow_empty_str else [
|
||
c.strip() for c in raw_val.splitlines() if c.strip()
|
||
]
|
||
if isinstance(raw_val, list):
|
||
validate_json_depth_and_size(
|
||
raw_val,
|
||
max_bytes=MAX_JSON_INPUT_BYTES,
|
||
max_depth=MAX_JSON_INPUT_DEPTH,
|
||
)
|
||
return raw_val
|
||
return [str(raw_val)] if (raw_val or not allow_empty_str) else []
|
||
|
||
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."}
|
||
|
||
try:
|
||
commands = self._parse_json_list_or_lines(commands, allow_empty_str=False)
|
||
except ValueError as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
|
||
# 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,
|
||
)
|
||
fb_used = False
|
||
if isinstance(results, dict):
|
||
fb_used = any(
|
||
isinstance(v, dict) and bool(v.get("fallback_used", False))
|
||
for v in results.values()
|
||
)
|
||
if not fb_used:
|
||
fb_map = getattr(self.services.execution, "last_fallback_used", {})
|
||
if isinstance(fb_map, dict):
|
||
fb_used = any(bool(v) for v in fb_map.values())
|
||
return {"success": True, "results": results, "fallback_used": fb_used}
|
||
except Exception as e: # noqa: BLE001
|
||
san = sanitize_exception(
|
||
e,
|
||
code="AUTH_FAILED",
|
||
context_label="command execution failed",
|
||
)
|
||
return {"success": False, "error": str(san)}
|
||
|
||
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."}
|
||
|
||
try:
|
||
commands = self._parse_json_list_or_lines(commands, allow_empty_str=False)
|
||
expected = self._parse_json_list_or_lines(expected, allow_empty_str=True)
|
||
except ValueError as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
|
||
# 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,
|
||
)
|
||
fb_map = getattr(self.services.execution, "last_fallback_used", {})
|
||
fb_used = any(bool(v) for v in fb_map.values()) if isinstance(fb_map, dict) else False
|
||
return {"success": True, "results": results, "fallback_used": fb_used}
|
||
except Exception as e: # noqa: BLE001
|
||
san = sanitize_exception(
|
||
e,
|
||
code="AUTH_FAILED",
|
||
context_label="test execution failed",
|
||
)
|
||
return {"success": False, "error": str(san)}
|
||
|
||
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)
|
||
# -------------------------------------------------------------------------
|
||
|
||
@staticmethod
|
||
def _validate_and_normalize_node_payload(node_data: dict[str, Any]) -> dict[str, Any]:
|
||
validate_json_depth_and_size(
|
||
node_data,
|
||
max_bytes=MAX_JSON_INPUT_BYTES,
|
||
max_depth=MAX_JSON_INPUT_DEPTH,
|
||
)
|
||
normalized = node_data.copy()
|
||
if "tags" in normalized and normalized["tags"] not in ("", None):
|
||
tags_val = normalized["tags"]
|
||
if isinstance(tags_val, str) and tags_val.strip().startswith("{"):
|
||
tags_val = validate_json_depth_and_size(
|
||
tags_val,
|
||
max_bytes=MAX_JSON_INPUT_BYTES,
|
||
max_depth=MAX_JSON_INPUT_DEPTH,
|
||
)
|
||
normalized["tags"] = tags_val
|
||
validate_auth_budget_tags(tags_val)
|
||
|
||
if "fallback" in normalized and normalized["fallback"] not in (None, "", []):
|
||
fb_val = normalized["fallback"]
|
||
if isinstance(fb_val, str) and fb_val.strip().startswith(("[", "{")):
|
||
fb_val = validate_json_depth_and_size(
|
||
fb_val,
|
||
max_bytes=MAX_JSON_INPUT_BYTES,
|
||
max_depth=MAX_JSON_INPUT_DEPTH,
|
||
)
|
||
normalized["fallback"] = validate_fallback_entries(
|
||
fb_val,
|
||
max_entries=MAX_FALLBACK_ENTRIES,
|
||
)
|
||
|
||
pw = normalized.get("password")
|
||
if is_compose_expression(pw):
|
||
validate_compose_syntax(pw)
|
||
elif isinstance(pw, (list, tuple)):
|
||
for item in pw:
|
||
if is_compose_expression(item):
|
||
validate_compose_syntax(item)
|
||
return normalized
|
||
|
||
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:
|
||
node_data = self._validate_and_normalize_node_payload(node_data)
|
||
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 (ValueError, TypeError, SanitizedAuthError) as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
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:
|
||
node_updates = self._validate_and_normalize_node_payload(node_updates)
|
||
self.services.nodes.update_node(unique_id, node_updates)
|
||
return {"success": True, "message": f"Node '{unique_id}' updated successfully."}
|
||
except (ValueError, TypeError, SanitizedAuthError) as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
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":
|
||
if hasattr(self.server, "settings"):
|
||
if hasattr(self.server.settings, "host"):
|
||
self.server.settings.host = host
|
||
if hasattr(self.server.settings, "port"):
|
||
self.server.settings.port = port
|
||
try:
|
||
return self.server.run(transport="sse", host=host, port=port, **kwargs)
|
||
except TypeError:
|
||
return self.server.run(transport="sse", **kwargs)
|
||
|
||
msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'"
|
||
raise ValueError(msg)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Native Model Context Protocol (MCP) Server for connpy.</p></div>
|
||
<h3>Class variables</h3>
|
||
<dl>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.SAFE_COMMANDS"><code class="name">var <span class="ident">SAFE_COMMANDS</span> : ClassVar[list[str]]</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
<h3>Methods</h3>
|
||
<dl>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.add_node"><code class="name flex">
|
||
<span>def <span class="ident">add_node</span></span>(<span>self, unique_id: str, data: dict | None = None, is_folder: bool = False, **kwargs) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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:
|
||
node_data = self._validate_and_normalize_node_payload(node_data)
|
||
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 (ValueError, TypeError, SanitizedAuthError) as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
except Exception as e: # noqa: BLE001
|
||
return {"success": False, "error": str(e)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Add a new node or folder to the inventory (requires trust=True).</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.call_tool"><code class="name flex">
|
||
<span>async def <span class="ident">call_tool</span></span>(<span>self, name: str, arguments: dict | None = None) ‑> Any</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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 {})</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Call an MCP tool asynchronously via the underlying MCP server.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.delete_node"><code class="name flex">
|
||
<span>def <span class="ident">delete_node</span></span>(<span>self, unique_id: str, is_folder: bool = False) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Delete a node or folder from the inventory (requires trust=True).</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.get_active_context"><code class="name flex">
|
||
<span>def <span class="ident">get_active_context</span></span>(<span>self) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Get the currently active context name and its matching regex patterns.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.get_node_info"><code class="name flex">
|
||
<span>def <span class="ident">get_node_info</span></span>(<span>self, node_name: str) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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}"}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Get full configuration metadata for a specific node.</p>
|
||
<p>Passwords, passphrases, and secrets are ALWAYS masked with '***'.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.is_safe_command"><code class="name flex">
|
||
<span>def <span class="ident">is_safe_command</span></span>(<span>self, cmd: str) ‑> bool</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Validate if a command is considered safe under current trust settings.</p>
|
||
<ul>
|
||
<li>If trust is True, all commands are allowed.</li>
|
||
<li>Block chaining/injection characters: ';', '&&', '||', '|', '`', '$(', '>', '<', '\n', '\r', '&'.</li>
|
||
<li>Validates against self.safe_commands (SAFE_COMMANDS + trusted_commands).</li>
|
||
</ul></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.list_folders"><code class="name flex">
|
||
<span>def <span class="ident">list_folders</span></span>(<span>self, filter_pattern: str = '') ‑> list[str]</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>List inventory folders, optionally filtered by regex pattern.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.list_nodes"><code class="name flex">
|
||
<span>def <span class="ident">list_nodes</span></span>(<span>self, filter_pattern: str = '', format_str: str = '') ‑> list[str]</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>List inventory nodes, optionally filtered by regex pattern and formatted.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.list_profiles"><code class="name flex">
|
||
<span>def <span class="ident">list_profiles</span></span>(<span>self, filter_pattern: str = '') ‑> list[str]</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>List all available node connection profiles.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.run"><code class="name flex">
|
||
<span>def <span class="ident">run</span></span>(<span>self, transport: str = 'stdio', host: str = '127.0.0.1', port: int = 8000, **kwargs)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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":
|
||
if hasattr(self.server, "settings"):
|
||
if hasattr(self.server.settings, "host"):
|
||
self.server.settings.host = host
|
||
if hasattr(self.server.settings, "port"):
|
||
self.server.settings.port = port
|
||
try:
|
||
return self.server.run(transport="sse", host=host, port=port, **kwargs)
|
||
except TypeError:
|
||
return self.server.run(transport="sse", **kwargs)
|
||
|
||
msg = f"Unknown transport: {transport}. Supported transports: 'stdio', 'sse'"
|
||
raise ValueError(msg)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Run the MCP server using either stdio or sse transport.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.run_commands"><code class="name flex">
|
||
<span>def <span class="ident">run_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: list[str] | str,<br>parallel: bool = True,<br>timeout: int = 30) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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."}
|
||
|
||
try:
|
||
commands = self._parse_json_list_or_lines(commands, allow_empty_str=False)
|
||
except ValueError as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
|
||
# 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,
|
||
)
|
||
fb_used = False
|
||
if isinstance(results, dict):
|
||
fb_used = any(
|
||
isinstance(v, dict) and bool(v.get("fallback_used", False))
|
||
for v in results.values()
|
||
)
|
||
if not fb_used:
|
||
fb_map = getattr(self.services.execution, "last_fallback_used", {})
|
||
if isinstance(fb_map, dict):
|
||
fb_used = any(bool(v) for v in fb_map.values())
|
||
return {"success": True, "results": results, "fallback_used": fb_used}
|
||
except Exception as e: # noqa: BLE001
|
||
san = sanitize_exception(
|
||
e,
|
||
code="AUTH_FAILED",
|
||
context_label="command execution failed",
|
||
)
|
||
return {"success": False, "error": str(san)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Execute commands on nodes matching the filter pattern.</p>
|
||
<p>Unsafe commands are blocked unless trust mode is enabled.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.run_playbook"><code class="name flex">
|
||
<span>def <span class="ident">run_playbook</span></span>(<span>self, playbook_yaml: str) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Validate and execute a playbook, verifying commands beforehand if trust=False.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.test_commands"><code class="name flex">
|
||
<span>def <span class="ident">test_commands</span></span>(<span>self,<br>nodes_filter: str,<br>commands: list[str] | str,<br>expected: list[str] | str = '',<br>parallel: bool = True,<br>timeout: int = 30) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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."}
|
||
|
||
try:
|
||
commands = self._parse_json_list_or_lines(commands, allow_empty_str=False)
|
||
expected = self._parse_json_list_or_lines(expected, allow_empty_str=True)
|
||
except ValueError as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
|
||
# 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,
|
||
)
|
||
fb_map = getattr(self.services.execution, "last_fallback_used", {})
|
||
fb_used = any(bool(v) for v in fb_map.values()) if isinstance(fb_map, dict) else False
|
||
return {"success": True, "results": results, "fallback_used": fb_used}
|
||
except Exception as e: # noqa: BLE001
|
||
san = sanitize_exception(
|
||
e,
|
||
code="AUTH_FAILED",
|
||
context_label="test execution failed",
|
||
)
|
||
return {"success": False, "error": str(san)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Execute commands and assert expected patterns on nodes matching the filter.</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.update_node"><code class="name flex">
|
||
<span>def <span class="ident">update_node</span></span>(<span>self, unique_id: str, updates: dict | None = None, **kwargs) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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:
|
||
node_updates = self._validate_and_normalize_node_payload(node_updates)
|
||
self.services.nodes.update_node(unique_id, node_updates)
|
||
return {"success": True, "message": f"Node '{unique_id}' updated successfully."}
|
||
except (ValueError, TypeError, SanitizedAuthError) as exc:
|
||
return {"success": False, "error": str(exc)}
|
||
except Exception as e: # noqa: BLE001
|
||
return {"success": False, "error": str(e)}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Update an existing node configuration (requires trust=True).</p></div>
|
||
</dd>
|
||
<dt id="connpy.mcp_server.ConnpyMCPServer.validate_playbook"><code class="name flex">
|
||
<span>def <span class="ident">validate_playbook</span></span>(<span>self, playbook_yaml: str) ‑> dict</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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."}</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Validate the syntax, schema, and tasks of a Connpy YAML playbook.</p></div>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
</article>
|
||
<nav id="sidebar">
|
||
<div class="toc">
|
||
<ul></ul>
|
||
</div>
|
||
<ul id="index">
|
||
<li><h3>Super-module</h3>
|
||
<ul>
|
||
<li><code><a title="connpy" href="index.html">connpy</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||
<ul>
|
||
<li>
|
||
<h4><code><a title="connpy.mcp_server.ConnpyMCPServer" href="#connpy.mcp_server.ConnpyMCPServer">ConnpyMCPServer</a></code></h4>
|
||
<ul class="two-column">
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.SAFE_COMMANDS" href="#connpy.mcp_server.ConnpyMCPServer.SAFE_COMMANDS">SAFE_COMMANDS</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.add_node" href="#connpy.mcp_server.ConnpyMCPServer.add_node">add_node</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.call_tool" href="#connpy.mcp_server.ConnpyMCPServer.call_tool">call_tool</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.delete_node" href="#connpy.mcp_server.ConnpyMCPServer.delete_node">delete_node</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.get_active_context" href="#connpy.mcp_server.ConnpyMCPServer.get_active_context">get_active_context</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.get_node_info" href="#connpy.mcp_server.ConnpyMCPServer.get_node_info">get_node_info</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.is_safe_command" href="#connpy.mcp_server.ConnpyMCPServer.is_safe_command">is_safe_command</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.list_folders" href="#connpy.mcp_server.ConnpyMCPServer.list_folders">list_folders</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.list_nodes" href="#connpy.mcp_server.ConnpyMCPServer.list_nodes">list_nodes</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.list_profiles" href="#connpy.mcp_server.ConnpyMCPServer.list_profiles">list_profiles</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.run" href="#connpy.mcp_server.ConnpyMCPServer.run">run</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.run_commands" href="#connpy.mcp_server.ConnpyMCPServer.run_commands">run_commands</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.run_playbook" href="#connpy.mcp_server.ConnpyMCPServer.run_playbook">run_playbook</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.test_commands" href="#connpy.mcp_server.ConnpyMCPServer.test_commands">test_commands</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.update_node" href="#connpy.mcp_server.ConnpyMCPServer.update_node">update_node</a></code></li>
|
||
<li><code><a title="connpy.mcp_server.ConnpyMCPServer.validate_playbook" href="#connpy.mcp_server.ConnpyMCPServer.validate_playbook">validate_playbook</a></code></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</nav>
|
||
</main>
|
||
<footer id="footer">
|
||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
|
||
</footer>
|
||
</body>
|
||
</html>
|