#!/usr/bin/env bash # ============================================================================= # PMDB Connector Plugin — Installer # @implements: [F454] # # Kopiert das Plugin (__init__.py, client.py, config.py, plugin.yaml, tests/) # nach ~/.hermes/profiles//plugins/pmdb_connector/ und richtet die # Token-Konfiguration ein: # # 1. mcp_tokens.json (KANONISCHE Quelle, F590) -> agenten..token # 2. config.yaml (Fallback, F526) -> pmdb_connector.auth_keys. # # Danach optionaler curl-Test gegen den get_tasks-Endpoint. # # Verwendung: # ./install.sh # ./install.sh --agent miguel --token 'mcp_miguel_...' --api-url 'https://...' # ./install.sh --source /pfad/zum/plugin --skip-curl --yes # # Hinweis zur base_url (P-NEW-CONNECTOR-MCP-SUFFIX): # Der Client haengt selbst /mcp/api/... an die base_url an. Deshalb darf die # base_url KEIN abschliessendes /mcp enthalten. Empfohlen: # - intern (LAN): http://192.168.180.49:8099 # - via Proxy: https://pmdb.myowntools.org (ohne /mcp!) # ============================================================================= set -euo pipefail # --------------------------------------------------------------------------- # Defaults + Konfiguration # --------------------------------------------------------------------------- DEFAULT_API_URL="https://pmdb.myowntools.org/mcp" PLUGIN_FILES=("__init__.py" "client.py" "config.py" "plugin.yaml") SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" AGENT="" TOKEN="" API_URL="" SOURCE_DIR="$SCRIPT_DIR" SKIP_CURL=0 ASSUME_YES=0 # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- info() { printf '\033[1;32m[INFO]\033[0m %s\n' "$*"; } warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; } error() { printf '\033[1;31m[ERROR]\033[0m %s\n' "$*" >&2; } usage() { cat <<'EOF' PMDB Connector Plugin — Installer Optionen: --agent Agent-/Profil-Name (sonst interaktiv) --token PMDB-Bearer-Token (sonst interaktiv, verdeckte Eingabe) --api-url PMDB MCP base_url (Default: https://pmdb.myowntools.org/mcp) --source Quellverzeichnis der Plugin-Dateien (Default: dieses Verzeichnis) --skip-curl curl-Verbindungstest ueberspringen --yes, -y Nicht-interaktiv (keine Rueckfragen) --help, -h Diese Hilfe EOF } # Ermittelt das aktive Profil aus HERMES_HOME (Fallback: leer -> Eingabe noetig). detect_agent() { if [[ -n "${HERMES_HOME:-}" ]]; then local parent parent="$(basename "$(dirname "$HERMES_HOME")")" if [[ "$parent" == "profiles" ]]; then basename "$HERMES_HOME" return 0 fi fi echo "" } # Basis-Verzeichnis (~/.hermes bzw. HERMES_HOME-Basis) bestimmen. hermes_base() { if [[ -n "${HERMES_HOME:-}" ]]; then local parent parent="$(basename "$(dirname "$HERMES_HOME")")" if [[ "$parent" == "profiles" ]]; then # HERMES_HOME zeigt auf ein Profil -> Basis ist parent.parent. dirname "$(dirname "$HERMES_HOME")" return 0 fi echo "$HERMES_HOME" return 0 fi echo "$HOME/.hermes" } # --------------------------------------------------------------------------- # Argument-Parsing # --------------------------------------------------------------------------- while [[ $# -gt 0 ]]; do case "$1" in --agent) AGENT="$2"; shift 2 ;; --token) TOKEN="$2"; shift 2 ;; --api-url) API_URL="$2"; shift 2 ;; --source) SOURCE_DIR="$2"; shift 2 ;; --skip-curl) SKIP_CURL=1; shift ;; --yes|-y) ASSUME_YES=1; shift ;; --help|-h) usage; exit 0 ;; *) error "Unbekannte Option: $1"; usage; exit 1 ;; esac done info "PMDB Connector Plugin — Installer" # --------------------------------------------------------------------------- # 1. Interaktive Abfragen (nur wenn nicht via Flag gesetzt) # --------------------------------------------------------------------------- if [[ -z "$AGENT" ]]; then local_detected="$(detect_agent)" if [[ -n "$local_detected" ]]; then read -r -p "Agent-/Profil-Name [${local_detected}]: " AGENT AGENT="${AGENT:-$local_detected}" else read -r -p "Agent-/Profil-Name: " AGENT fi fi [[ -z "$AGENT" ]] && { error "Agent-Name darf nicht leer sein."; exit 1; } if [[ -z "$TOKEN" ]]; then read -r -s -p "PMDB-Bearer-Token (verdeckte Eingabe): " TOKEN echo fi [[ -z "$TOKEN" ]] && { error "Token darf nicht leer sein."; exit 1; } if [[ -z "$API_URL" ]]; then read -r -p "PMDB MCP base_url [${DEFAULT_API_URL}]: " API_URL API_URL="${API_URL:-$DEFAULT_API_URL}" fi # base_url ohne abschliessenden Slash speichern (client.py rstrippt ohnehin). API_URL="$(printf '%s' "$API_URL" | sed 's#/*$##')" # --------------------------------------------------------------------------- # 2. Plugin-Dateien kopieren # --------------------------------------------------------------------------- BASE="$(hermes_base)" TARGET="$BASE/profiles/$AGENT/plugins/pmdb_connector" CONFIG_PATH="$BASE/profiles/$AGENT/config.yaml" TOKENS_PATH="$BASE/mcp_tokens.json" if [[ ! -d "$SOURCE_DIR" ]]; then error "Quellverzeichnis nicht gefunden: $SOURCE_DIR" exit 1 fi for f in "${PLUGIN_FILES[@]}"; do [[ -f "$SOURCE_DIR/$f" ]] || { error "Plugin-Datei fehlt im Quellverzeichnis: $f"; exit 1; } done info "Kopiere Plugin-Dateien nach $TARGET" mkdir -p "$TARGET" for f in "${PLUGIN_FILES[@]}"; do cp -f "$SOURCE_DIR/$f" "$TARGET/$f" done if [[ -d "$SOURCE_DIR/tests" ]]; then mkdir -p "$TARGET/tests" cp -f "$SOURCE_DIR"/tests/*.py "$TARGET/tests/" 2>/dev/null || true fi # P-001: stale __pycache__/ .pyc vor UND nach Deploy entfernen (sonst laedt # Hermes alten Bytecode statt des frischen Codes). find "$TARGET" -name __pycache__ -type d -exec rm -rf {} + 2>/dev/null || true find "$TARGET" -name '*.pyc' -delete 2>/dev/null || true info "Plugin-Dateien installiert:" for f in "${PLUGIN_FILES[@]}"; do printf ' - %s\n' "$TARGET/$f" done # --------------------------------------------------------------------------- # 3. Token-Konfiguration schreiben (config.yaml + mcp_tokens.json) # --------------------------------------------------------------------------- info "Schreibe Token-Konfiguration ..." python3 - "$CONFIG_PATH" "$TOKENS_PATH" "$AGENT" "$TOKEN" "$API_URL" <<'PYEOF' import json, os, re, shutil, sys def main(): config_path, tokens_path, agent, token, base_url = sys.argv[1:6] try: import yaml except ImportError: yaml = None # ---- config.yaml: pmdb_connector-Sektion (kommentar-erhaltend) ---- if os.path.exists(config_path): with open(config_path, encoding="utf-8") as f: lines = f.read().splitlines() else: lines = [] # Spanne der Top-Level-Sektion "pmdb_connector:" ermitteln (nur Spalte 0, # damit "plugins.entries.pmdb_connector" und "- pmdb_connector" NICHT # getroffen werden). start = end = None for i, ln in enumerate(lines): if ln and not ln[0].isspace() and ln.split(":")[0].strip() == "pmdb_connector": start = i end = len(lines) for j in range(i + 1, len(lines)): if lines[j] and not lines[j][0].isspace(): end = j break break section = {} if start is not None and yaml is not None: # Nur den Sektions-BODY parsen (ohne die "pmdb_connector:"-Kopfzeile), # sonst entsteht eine verschachtelte {"pmdb_connector": {...}}-Dict. block = "\n".join(lines[start + 1:end]) try: loaded = yaml.safe_load(block) if isinstance(loaded, dict): section = loaded except Exception: section = {} # Merge: base_url neu, Token fuer diesen Agenten, bestehende auth_keys # anderer Agenten bleiben erhalten (F526-Fallback bleibt multi-agent-faehig). section["base_url"] = base_url ak = section.get("auth_keys") if not isinstance(ak, dict): ak = {} ak[agent] = token section["auth_keys"] = ak section.setdefault("manager_profiles", ["bernd", "andreas"]) if yaml is not None: dumped = yaml.safe_dump( {"pmdb_connector": section}, sort_keys=False, allow_unicode=True, default_flow_style=False) new_block = dumped.rstrip("\n").splitlines() else: # Fallback ohne PyYAML: schlichte Zeilen (andere auth_keys gehen verloren, # aber mcp_tokens.json bleibt kanonische Quelle). new_block = ["pmdb_connector:", f" base_url: {base_url}", " auth_keys:", f" {agent}: {token}", " manager_profiles: [bernd, andreas]"] if start is not None: new_lines = lines[:start] + new_block + lines[end:] else: new_lines = list(lines) if new_lines and new_lines[-1].strip() != "": new_lines.append("") new_lines += new_block if os.path.exists(config_path): shutil.copy2(config_path, config_path + ".bak-install") with open(config_path, "w", encoding="utf-8") as f: f.write("\n".join(new_lines) + "\n") # ---- mcp_tokens.json: agenten..token (F590, kanonisch) ---- tokens = {} if os.path.exists(tokens_path): try: with open(tokens_path, encoding="utf-8") as f: tokens = json.load(f) except (OSError, ValueError): tokens = {} if not isinstance(tokens, dict): tokens = {} agenten = tokens.get("agenten") if not isinstance(agenten, dict): agenten = {} entry = agenten.get(agent) if not isinstance(entry, dict): entry = {} entry["token"] = token entry.setdefault("token_prefix", agent) agenten[agent] = entry tokens["agenten"] = agenten tokens.setdefault( "kommentar", "MCP-Bootstrap-Tokens (F531). Klartext NUR in dieser Datei \u2014 nicht " "committen, nicht in Repos, nicht in Logs. Generiert auf .49.") if os.path.exists(tokens_path): shutil.copy2(tokens_path, tokens_path + ".bak-install") with open(tokens_path, "w", encoding="utf-8") as f: json.dump(tokens, f, ensure_ascii=False, indent=2) f.write("\n") print("OK") if __name__ == "__main__": main() PYEOF info "Konfiguration geschrieben:" printf ' config.yaml -> %s\n' "$CONFIG_PATH" printf ' mcp_tokens.json -> %s\n' "$TOKENS_PATH" # --------------------------------------------------------------------------- # 4. curl-Verbindungstest (get_tasks-Endpoint, exakt wie client.py) # --------------------------------------------------------------------------- if [[ "$SKIP_CURL" -eq 1 ]]; then warn "curl-Test uebersprungen (--skip-curl)." exit 0 fi TEST_URL="$API_URL/mcp/api/tasks" info "Teste Verbindung: GET $TEST_URL" HTTP="$(curl -sS -o /tmp/pmdb_connector_test_body.json -w '%{http_code}' \ --max-time 10 -H "Authorization: Bearer $TOKEN" "$TEST_URL" 2>/tmp/pmdb_connector_test_err.txt || true)" case "$HTTP" in 200) info "Verbindung OK (HTTP 200) — Token wird akzeptiert." ;; 401) error "HTTP 401 — Token ungueltig oder widerrufen (auth_invalid)." warn "Pruefe den Token. Hinweis: Der Openresty-Proxy (pmdb.myowntools.org) " warn "blockt Bearer-Tokens (P-NEW-F563-PMDB-AUTH) — intern " warn "http://192.168.180.49:8099 verwenden." ;; 404) error "HTTP 404 — Endpoint nicht gefunden. Vermutlich doppeltes /mcp." warn "Der Client haengt selbst /mcp/api/... an die base_url an. Nutze die " warn "base_url OHNE /mcp, z.B. http://192.168.180.49:8099 oder " warn "https://pmdb.myowntools.org." ;; "") error "Keine Antwort — Netzwerk/Timeout. Detail:" cat /tmp/pmdb_connector_test_err.txt 2>/dev/null || true ;; *) warn "HTTP $HTTP — Antwort (Auszug):" head -c 300 /tmp/pmdb_connector_test_body.json 2>/dev/null || true echo ;; esac info "Installation abgeschlossen fuer Agent '$AGENT'."