390 lines
21 KiB
Python
390 lines
21 KiB
Python
#!/usr/bin/env python3
|
|
"""Bitwarden-backed Windows Server administration over WinRM and RDP metadata."""
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import ssl
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from urllib.parse import urlparse
|
|
|
|
DEPENDENCIES = os.environ.get("WINDOWS_PYTHON_PATH", "/home/node/.openclaw/windows-python")
|
|
sys.path.insert(0, DEPENDENCIES)
|
|
|
|
BW_DATA_DIR = os.environ.get("BW_DATA_DIR", "/home/node/.openclaw/bw-data")
|
|
BW_CLI = os.environ.get("BW_CLI", "/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js")
|
|
BW_MP_FILE = os.environ.get("BW_MP_FILE", "/home/node/.openclaw/mcp/.bw-masterpass")
|
|
AUDIT_FILE = os.environ.get("WINDOWS_AUDIT_FILE", "/home/node/.openclaw/mcp/.windows-audit.jsonl")
|
|
MAX_OUTPUT = 60000
|
|
TARGET_CACHE_SECONDS = 120
|
|
|
|
_bw_session = None
|
|
_target_cache = None
|
|
_target_cache_at = 0.0
|
|
|
|
|
|
def _safe_error(value):
|
|
return re.sub(r"(?i)(password|secret|token|session)\S*", "[redacted]", str(value))[:2000]
|
|
|
|
|
|
def _read_masterpass():
|
|
st = os.stat(BW_MP_FILE)
|
|
if stat.S_IMODE(st.st_mode) & 0o077 or st.st_uid != 1000:
|
|
raise RuntimeError("Bitwarden-Masterpasswortdatei hat unsichere Berechtigungen.")
|
|
value = open(BW_MP_FILE, encoding="utf-8").read().strip()
|
|
if not value:
|
|
raise RuntimeError("Bitwarden-Masterpasswortdatei ist leer.")
|
|
|
|
|
|
def _bw(args, with_session=True, timeout=120):
|
|
env = dict(os.environ)
|
|
env["BITWARDENCLI_APPDATA_DIR"] = BW_DATA_DIR
|
|
if with_session and _bw_session:
|
|
env["BW_SESSION"] = _bw_session
|
|
completed = subprocess.run(
|
|
[BW_CLI] + list(args),
|
|
env=env,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
timeout=timeout,
|
|
check=False,
|
|
)
|
|
if completed.returncode:
|
|
raise RuntimeError(_safe_error(completed.stderr.decode("utf-8", errors="replace") or "Bitwarden CLI fehlgeschlagen"))
|
|
return completed.stdout.decode("utf-8", errors="replace")
|
|
|
|
|
|
def _ensure_bw():
|
|
global _bw_session
|
|
if _bw_session:
|
|
return
|
|
_read_masterpass()
|
|
_bw_session = _bw(["unlock", "--raw", "--passwordfile", BW_MP_FILE], with_session=False).strip()
|
|
if not _bw_session:
|
|
raise RuntimeError("Bitwarden lieferte keine Session.")
|
|
try:
|
|
_bw(["sync"])
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _fields(item):
|
|
return {str(field.get("name", "")).strip().lower(): str(field.get("value", "")).strip() for field in item.get("fields", []) if field.get("name")}
|
|
|
|
|
|
def _endpoint_from_uri(uri):
|
|
parsed = urlparse(uri)
|
|
scheme = parsed.scheme.lower()
|
|
if scheme == "winrm":
|
|
return f"http://{parsed.hostname}:{parsed.port or 5985}{parsed.path or '/wsman'}"
|
|
if scheme == "winrms":
|
|
return f"https://{parsed.hostname}:{parsed.port or 5986}{parsed.path or '/wsman'}"
|
|
if scheme in {"http", "https"} and (parsed.port in {5985, 5986} or parsed.path.rstrip("/").endswith("wsman")):
|
|
return uri
|
|
return None
|
|
|
|
|
|
def _parse_target(item):
|
|
name = str(item.get("name", "")).strip()
|
|
fields = _fields(item)
|
|
login = item.get("login") or {}
|
|
uris = [str(value.get("uri", "")).strip() for value in login.get("uris", []) if value.get("uri")]
|
|
marked = fields.get("jarvis.windows.target", "").lower() in {"1", "true", "yes", "ja"}
|
|
domain_account = bool(re.match(r"^pdev\s*-\s*dom", name, re.I))
|
|
if not marked and not domain_account and not re.match(r"^(windows|winrm)\s*[-:]", name, re.I) and not any(urlparse(uri).scheme.lower() in {"winrm", "winrms", "rdp"} for uri in uris):
|
|
return None
|
|
bare_host = next((uri for uri in uris if re.match(r"^[A-Za-z0-9._-]+$", uri)), "")
|
|
endpoint = fields.get("winrm_url") or next((value for value in (_endpoint_from_uri(uri) for uri in uris) if value), "") or (f"http://{bare_host}:5985/wsman" if bare_host else "")
|
|
rdp_uri = next((urlparse(uri) for uri in uris if urlparse(uri).scheme.lower() == "rdp"), None)
|
|
endpoint_uri = urlparse(endpoint) if endpoint else None
|
|
host = fields.get("rdp_host") or (rdp_uri.hostname if rdp_uri else None) or (endpoint_uri.hostname if endpoint_uri else None) or bare_host
|
|
if not host or not re.match(r"^[A-Za-z0-9._:-]+$", host):
|
|
return None
|
|
alias = fields.get("alias") or (name.split("-", 1)[0].strip() if domain_account else re.sub(r"^(windows|winrm)\s*[-:]\s*", "", name, flags=re.I).strip()) or host
|
|
username = str(login.get("username", "")).strip()
|
|
password = str(login.get("password", ""))
|
|
if not username or not password:
|
|
return None
|
|
fingerprint = re.sub(r"[^0-9a-f]", "", fields.get("winrm_cert_sha256", ""), flags=re.I).upper()
|
|
return {
|
|
"alias": alias[:80],
|
|
"name": name[:120],
|
|
"host": host,
|
|
"rdp_port": int(fields.get("rdp_port", rdp_uri.port if rdp_uri else 3389)),
|
|
"endpoint": endpoint,
|
|
"fingerprint": fingerprint,
|
|
"username": username,
|
|
"password": password,
|
|
"transport": "ntlm",
|
|
}
|
|
|
|
|
|
def targets(force=False):
|
|
global _target_cache, _target_cache_at
|
|
if not force and _target_cache is not None and time.monotonic() - _target_cache_at < TARGET_CACHE_SECONDS:
|
|
return _target_cache
|
|
_ensure_bw()
|
|
if force:
|
|
try:
|
|
_bw(["sync"])
|
|
except Exception:
|
|
pass
|
|
items = json.loads(_bw(["list", "items"]))
|
|
parsed = [target for item in items if (target := _parse_target(item))]
|
|
aliases = set()
|
|
for target in parsed:
|
|
key = target["alias"].casefold()
|
|
if key in aliases:
|
|
raise RuntimeError(f"Bitwarden enthaelt den Windows-Alias mehrfach: {target['alias']}")
|
|
aliases.add(key)
|
|
_target_cache = parsed
|
|
_target_cache_at = time.monotonic()
|
|
return parsed
|
|
|
|
|
|
def target_for(alias):
|
|
wanted = str(alias or "").strip().casefold()
|
|
found = next((target for target in targets() if target["alias"].casefold() == wanted), None)
|
|
if not found:
|
|
raise RuntimeError("Windows-Ziel nicht gefunden. Zuerst windows_targets verwenden und den Bitwarden-Alias exakt uebernehmen.")
|
|
return found
|
|
|
|
|
|
def _tcp(host, port, timeout=5):
|
|
started = time.monotonic()
|
|
try:
|
|
with socket.create_connection((host, port), timeout=timeout):
|
|
return True, round((time.monotonic() - started) * 1000)
|
|
except OSError:
|
|
return False, round((time.monotonic() - started) * 1000)
|
|
|
|
|
|
def _verify_certificate(target):
|
|
endpoint = target["endpoint"]
|
|
parsed = urlparse(endpoint)
|
|
if parsed.scheme != "https":
|
|
return None
|
|
if len(target["fingerprint"]) != 64:
|
|
raise RuntimeError("HTTPS-WinRM benoetigt im Bitwarden-Eintrag das Feld winrm_cert_sha256.")
|
|
context = ssl.create_default_context()
|
|
context.check_hostname = False
|
|
context.verify_mode = ssl.CERT_NONE
|
|
with socket.create_connection((parsed.hostname, parsed.port or 5986), timeout=8) as raw:
|
|
with context.wrap_socket(raw, server_hostname=parsed.hostname) as tls:
|
|
actual = hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest().upper()
|
|
if actual != target["fingerprint"]:
|
|
raise RuntimeError("Windows-WinRM-Zertifikat stimmt nicht mit dem Bitwarden-Fingerprint ueberein.")
|
|
return actual
|
|
|
|
|
|
def _run_ps(target, script):
|
|
if not target["endpoint"]:
|
|
raise RuntimeError("Der Bitwarden-Eintrag enthaelt keine WinRM-URL.")
|
|
_verify_certificate(target)
|
|
try:
|
|
import winrm
|
|
except ImportError as exc:
|
|
raise RuntimeError(f"pywinrm fehlt unter {DEPENDENCIES}.") from exc
|
|
session = winrm.Session(
|
|
target["endpoint"],
|
|
auth=(target["username"], target["password"]),
|
|
transport=target["transport"],
|
|
server_cert_validation="ignore",
|
|
operation_timeout_sec=60,
|
|
read_timeout_sec=75,
|
|
)
|
|
response = session.run_ps("$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; " + script)
|
|
stdout = response.std_out.decode("utf-8", errors="replace").strip()
|
|
stderr = response.std_err.decode("utf-8", errors="replace").strip()
|
|
if response.status_code != 0:
|
|
raise RuntimeError(f"Remote PowerShell endete mit Code {response.status_code}: {(stderr or stdout or 'keine Details')[:4000]}")
|
|
if stderr:
|
|
stdout = f"{stdout}\n\nWarnungen:\n{stderr}".strip()
|
|
return stdout[:MAX_OUTPUT] + ("\n... (Ausgabe gekuerzt)" if len(stdout) > MAX_OUTPUT else "")
|
|
|
|
|
|
def _ps_literal(value):
|
|
return "'" + str(value).replace("'", "''") + "'"
|
|
|
|
|
|
def _json_result(title, target, script):
|
|
output = _run_ps(target, script)
|
|
try:
|
|
output = json.dumps(json.loads(output), ensure_ascii=False, indent=2)
|
|
except (json.JSONDecodeError, TypeError):
|
|
pass
|
|
return f"## {title}\n\n```json\n{output or '(keine Daten)'}\n```"
|
|
|
|
|
|
def _audit(action, target, details):
|
|
record = {"timestamp": datetime.now(timezone.utc).isoformat(), "action": action, "target": target["alias"], "endpoint": target["endpoint"], "details": details}
|
|
fd = os.open(AUDIT_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
with os.fdopen(fd, "a", encoding="utf-8") as handle:
|
|
handle.write(json.dumps(record, ensure_ascii=True) + "\n")
|
|
os.chmod(AUDIT_FILE, 0o600)
|
|
|
|
|
|
def windows_targets(_args):
|
|
data = [{"alias": t["alias"], "name": t["name"], "host": t["host"], "winrm": t["endpoint"] or None, "rdpPort": t["rdp_port"], "httpsPinned": bool(t["fingerprint"])} for t in targets(force=True)]
|
|
if not data:
|
|
return "Keine Windows-Ziele in Bitwarden freigegeben. Erwartet wird ein Login-Eintrag 'Windows - <Alias>' mit winrm://, winrms:// oder rdp:// URI."
|
|
return "## Freigegebene Windows-Ziele\n\n```json\n" + json.dumps(data, ensure_ascii=False, indent=2) + "\n```"
|
|
|
|
|
|
def windows_probe(args):
|
|
target = target_for(args.get("target"))
|
|
parsed = urlparse(target["endpoint"]) if target["endpoint"] else None
|
|
winrm_port = parsed.port or (5986 if parsed and parsed.scheme == "https" else 5985)
|
|
winrm_ok, winrm_ms = _tcp(target["host"], winrm_port) if parsed else (False, 0)
|
|
rdp_ok, rdp_ms = _tcp(target["host"], target["rdp_port"])
|
|
fingerprint = None
|
|
if winrm_ok and parsed and parsed.scheme == "https":
|
|
fingerprint = _verify_certificate(target)
|
|
return json.dumps({"target": target["alias"], "host": target["host"], "winrm": {"configured": bool(parsed), "reachable": winrm_ok, "port": winrm_port, "latencyMs": winrm_ms, "certificateSha256": fingerprint}, "rdp": {"reachable": rdp_ok, "port": target["rdp_port"], "latencyMs": rdp_ms}}, indent=2)
|
|
|
|
|
|
def windows_status(args):
|
|
target = target_for(args.get("target"))
|
|
return _json_result("Windows Server Status", target, r"""
|
|
$os = Get-CimInstance Win32_OperatingSystem
|
|
$cs = Get-CimInstance Win32_ComputerSystem
|
|
$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1
|
|
[pscustomobject]@{ ComputerName=$env:COMPUTERNAME; Domain=$cs.Domain; Windows=$os.Caption; Version=$os.Version; Build=$os.BuildNumber; LastBoot=$os.LastBootUpTime.ToString('o'); UptimeHours=[math]::Round(((Get-Date)-$os.LastBootUpTime).TotalHours,1); Cpu=$cpu.Name; LogicalProcessors=$cs.NumberOfLogicalProcessors; MemoryTotalGiB=[math]::Round($cs.TotalPhysicalMemory/1GB,2); MemoryFreeGiB=[math]::Round($os.FreePhysicalMemory*1KB/1GB,2) } | ConvertTo-Json -Compress
|
|
""")
|
|
|
|
|
|
def windows_services(args):
|
|
target = target_for(args.get("target"))
|
|
search = _ps_literal(str(args.get("search", "")).strip())
|
|
limit = max(1, min(500, int(args.get("limit", 100))))
|
|
return _json_result("Windows Dienste", target, f"$q={search}; @(Get-CimInstance Win32_Service | Where-Object {{ -not $q -or $_.Name -like \"*$q*\" -or $_.DisplayName -like \"*$q*\" }} | Sort-Object DisplayName | Select-Object -First {limit} Name,DisplayName,State,StartMode,StartName) | ConvertTo-Json -Compress")
|
|
|
|
|
|
def windows_service_control(args):
|
|
target = target_for(args.get("target"))
|
|
name = str(args.get("service", ""))
|
|
action = str(args.get("action", ""))
|
|
if args.get("confirm") != "APPLY" or action not in {"start", "stop", "restart"} or not re.match(r"^[A-Za-z0-9_.-]{1,128}$", name):
|
|
raise RuntimeError('Dienststeuerung erfordert gueltigen Dienst, Aktion und confirm="APPLY".')
|
|
command = {"start": "Start-Service", "stop": "Stop-Service", "restart": "Restart-Service"}[action]
|
|
_audit("service." + action, target, {"service": name})
|
|
return _json_result("Windows Dienststeuerung", target, f"{command} -Name {_ps_literal(name)}; Get-Service -Name {_ps_literal(name)} | Select-Object Name,DisplayName,Status,StartType | ConvertTo-Json -Compress")
|
|
|
|
|
|
def windows_event_log(args):
|
|
target = target_for(args.get("target"))
|
|
log_name = str(args.get("log_name", "System"))
|
|
if log_name not in {"System", "Application", "Security"}:
|
|
raise RuntimeError("Ungueltiges Event Log.")
|
|
hours = max(1, min(168, int(args.get("hours", 24))))
|
|
limit = max(1, min(200, int(args.get("limit", 50))))
|
|
return _json_result(f"Windows Event Log: {log_name}", target, f"$start=(Get-Date).AddHours(-{hours}); @(Get-WinEvent -FilterHashtable @{{LogName={_ps_literal(log_name)};StartTime=$start;Level=@(1,2,3)}} -ErrorAction SilentlyContinue | Select-Object -First {limit} TimeCreated,Id,LevelDisplayName,ProviderName,MachineName,Message) | ConvertTo-Json -Compress -Depth 3")
|
|
|
|
|
|
def windows_storage(args):
|
|
target = target_for(args.get("target"))
|
|
return _json_result("Windows Datentraeger", target, r"""@(Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { [pscustomobject]@{ Drive=$_.DeviceID; Label=$_.VolumeName; FileSystem=$_.FileSystem; SizeGiB=[math]::Round($_.Size/1GB,2); FreeGiB=[math]::Round($_.FreeSpace/1GB,2); FreePercent=if($_.Size){[math]::Round($_.FreeSpace*100/$_.Size,1)}else{$null} } }) | ConvertTo-Json -Compress""")
|
|
|
|
|
|
def windows_processes(args):
|
|
target = target_for(args.get("target"))
|
|
limit = max(1, min(100, int(args.get("limit", 25))))
|
|
sort_by = str(args.get("sort_by", "memory"))
|
|
prop = "WorkingSet64" if sort_by == "memory" else "CPU"
|
|
if sort_by not in {"memory", "cpu"}:
|
|
raise RuntimeError("sort_by muss memory oder cpu sein.")
|
|
return _json_result("Windows Prozesse", target, f"@(Get-Process | Sort-Object {prop} -Descending | Select-Object -First {limit} Id,ProcessName,@{{N='CpuSeconds';E={{if($_.CPU){{[math]::Round($_.CPU,1)}}else{{$null}}}}}},@{{N='MemoryMiB';E={{[math]::Round($_.WorkingSet64/1MB,1)}}}},StartTime) | ConvertTo-Json -Compress")
|
|
|
|
|
|
def windows_rdp_sessions(args):
|
|
target = target_for(args.get("target"))
|
|
output = _run_ps(target, "$rows = quser.exe 2>$null; [pscustomobject]@{ RdpHost=$env:COMPUTERNAME; RdpPort=" + str(target["rdp_port"]) + "; Sessions=@($rows) } | ConvertTo-Json -Compress")
|
|
return f"## RDP-Sitzungen\n\n```json\n{output}\n```"
|
|
|
|
|
|
def windows_rdp_logoff(args):
|
|
target = target_for(args.get("target"))
|
|
session_id = int(args.get("session_id", -1))
|
|
if args.get("confirm") != "LOGOFF" or session_id < 0 or session_id > 65535:
|
|
raise RuntimeError('RDP-Abmeldung erfordert session_id und confirm="LOGOFF".')
|
|
_audit("rdp.logoff", target, {"sessionId": session_id})
|
|
_run_ps(target, f"logoff.exe {session_id}")
|
|
return f"RDP-Sitzung {session_id} auf {target['alias']} wurde abgemeldet."
|
|
|
|
|
|
def windows_run_powershell(args):
|
|
target = target_for(args.get("target"))
|
|
script = str(args.get("script", "")).strip()
|
|
if args.get("confirm") != "EXECUTE" or not script or len(script) > 20000:
|
|
raise RuntimeError('Administrative PowerShell erfordert ein Skript bis 20000 Zeichen und confirm="EXECUTE".')
|
|
_audit("powershell", target, {"sha256": hashlib.sha256(script.encode()).hexdigest(), "script": script})
|
|
output = _run_ps(target, script)
|
|
return f"## Administrative PowerShell-Ausgabe\n\n```text\n{output or '(keine Ausgabe)'}\n```"
|
|
|
|
|
|
TARGET = {"target": {"type": "string", "description": "Exakter Alias aus windows_targets."}}
|
|
TOOLS = [
|
|
{"name": "windows_targets", "description": "Listet die in Bitwarden fuer Jarvis freigegebenen Windows-Ziele ohne Zugangsdaten.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
|
|
{"name": "windows_probe", "description": "Prueft WinRM- und RDP-Erreichbarkeit eines freigegebenen Windows-Ziels. Lesend.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_status", "description": "Liest OS, Domaene, Uptime, CPU und RAM ueber WinRM.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_services", "description": "Listet Windows-Dienste. Lesend.", "inputSchema": {"type": "object", "properties": {**TARGET, "search": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 500}}, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_service_control", "description": "Startet, stoppt oder startet einen Windows-Dienst nach expliziter Bestaetigung neu.", "inputSchema": {"type": "object", "properties": {**TARGET, "service": {"type": "string"}, "action": {"type": "string", "enum": ["start", "stop", "restart"]}, "confirm": {"type": "string", "enum": ["APPLY"]}}, "required": ["target", "service", "action", "confirm"], "additionalProperties": False}},
|
|
{"name": "windows_event_log", "description": "Liest Warnungen und Fehler aus Windows Event Logs.", "inputSchema": {"type": "object", "properties": {**TARGET, "log_name": {"type": "string", "enum": ["System", "Application", "Security"]}, "hours": {"type": "integer", "minimum": 1, "maximum": 168}, "limit": {"type": "integer", "minimum": 1, "maximum": 200}}, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_storage", "description": "Liest Windows-Datentraeger und freien Speicher.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_processes", "description": "Listet Prozesse nach CPU oder Speicher. Lesend.", "inputSchema": {"type": "object", "properties": {**TARGET, "sort_by": {"type": "string", "enum": ["memory", "cpu"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}}, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_rdp_sessions", "description": "Liest aktive RDP-Sitzungen ueber WinRM und gibt RDP-Verbindungsdaten ohne Passwort aus.", "inputSchema": {"type": "object", "properties": TARGET, "required": ["target"], "additionalProperties": False}},
|
|
{"name": "windows_rdp_logoff", "description": "Meldet eine RDP-Sitzung nach expliziter Bestaetigung ab.", "inputSchema": {"type": "object", "properties": {**TARGET, "session_id": {"type": "integer"}, "confirm": {"type": "string", "enum": ["LOGOFF"]}}, "required": ["target", "session_id", "confirm"], "additionalProperties": False}},
|
|
{"name": "windows_run_powershell", "description": "Fuehrt nach expliziter Bestaetigung administrative PowerShell auf einem freigegebenen Bitwarden-Ziel aus. Vollstaendig auditiert.", "inputSchema": {"type": "object", "properties": {**TARGET, "script": {"type": "string"}, "confirm": {"type": "string", "enum": ["EXECUTE"]}}, "required": ["target", "script", "confirm"], "additionalProperties": False}},
|
|
]
|
|
DISPATCH = {name: fn for name, fn in {
|
|
"windows_targets": windows_targets, "windows_probe": windows_probe, "windows_status": windows_status,
|
|
"windows_services": windows_services, "windows_service_control": windows_service_control,
|
|
"windows_event_log": windows_event_log, "windows_storage": windows_storage,
|
|
"windows_processes": windows_processes, "windows_rdp_sessions": windows_rdp_sessions,
|
|
"windows_rdp_logoff": windows_rdp_logoff, "windows_run_powershell": windows_run_powershell,
|
|
}.items()}
|
|
|
|
|
|
def send(message):
|
|
sys.stdout.write(json.dumps(message, ensure_ascii=True, separators=(",", ":")) + "\n")
|
|
sys.stdout.flush()
|
|
|
|
|
|
def handle(message):
|
|
request_id = message.get("id")
|
|
method = message.get("method")
|
|
params = message.get("params") or {}
|
|
if method == "notifications/initialized" or (request_id is None and method):
|
|
return
|
|
if method == "initialize":
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"protocolVersion": params.get("protocolVersion", "2024-11-05"), "capabilities": {"tools": {}}, "serverInfo": {"name": "windows", "version": "2.0.0"}}})
|
|
elif method == "ping":
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {}})
|
|
elif method == "tools/list":
|
|
destructive = {"windows_service_control", "windows_rdp_logoff", "windows_run_powershell"}
|
|
tools = [{**tool, "annotations": {"title": tool["name"].replace("_", " "), "readOnlyHint": tool["name"] not in destructive, "destructiveHint": tool["name"] in destructive, "idempotentHint": tool["name"] not in destructive, "openWorldHint": True}} for tool in TOOLS]
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"tools": tools}})
|
|
elif method == "tools/call":
|
|
name = params.get("name")
|
|
try:
|
|
if name not in DISPATCH:
|
|
raise RuntimeError("Unbekanntes Windows-Werkzeug.")
|
|
text = DISPATCH[name](params.get("arguments") or {})
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": text}], "isError": False}})
|
|
except Exception as exc:
|
|
send({"jsonrpc": "2.0", "id": request_id, "result": {"content": [{"type": "text", "text": _safe_error(exc)}], "isError": True}})
|
|
|
|
|
|
for line in sys.stdin:
|
|
try:
|
|
handle(json.loads(line))
|
|
except Exception:
|
|
continue
|