PMDB Connector Plugin + Installer
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
# Python-Cache + Test-Cache (P-001: stale .pyc nie committen)
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.pyo
|
||||||
|
.pytest_cache/
|
||||||
|
.cache/
|
||||||
|
|
||||||
|
# Backups (install.sh legt .bak-install / .bak-<ts> an)
|
||||||
|
*.bak*
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
# PMDB Connector Plugin
|
||||||
|
|
||||||
|
Profil-aware Anbindung an den PMDB MCP-Server als Hermes-Backend-Plugin
|
||||||
|
(`kind: backend`). Liest das aktive Hermes-Profil, wählt den zugehörigen
|
||||||
|
Bearer-Token aus der Profil-Config und registriert die `pmdb_*`-Tools im
|
||||||
|
Toolset `pmdb`.
|
||||||
|
|
||||||
|
- Feature: `F454` (Plugin-Anbindung), `F621` (SSE-Stream), `F719` (Anlagen)
|
||||||
|
- Repo: `Andreas/PMDB-Connector.git` auf Gitea (.47)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Was das Plugin bietet
|
||||||
|
|
||||||
|
| Phase | Tools |
|
||||||
|
|-------|-------|
|
||||||
|
| Task-Lifecycle | `pmdb_get_tasks`, `pmdb_accept_task`, `pmdb_decline_task`, `pmdb_submit_task`, `pmdb_return_for_revision`, `pmdb_manager_decision` |
|
||||||
|
| Query + Management | `pmdb_get_mask`, `pmdb_search`, `pmdb_get_baustein`, `pmdb_get_pipeline_status`, `pmdb_get_task_evidence` |
|
||||||
|
| Manager-only | `pmdb_set_bit`, `pmdb_create_task`, `pmdb_get_submitted_tasks`, `pmdb_manager_dashboard`, `pmdb_submit_on_behalf` |
|
||||||
|
| Task-Anlagen (F719) | `pmdb_get_anlagen`, `pmdb_download_anlage`, `pmdb_upload_ergebnis_anlage`, `pmdb_upload_anlage` |
|
||||||
|
| Diagnose | `pmdb_stream_status` |
|
||||||
|
|
||||||
|
Manager-only-Tools sind doppelt abgesichert (Plugin-Guard *und* Server-
|
||||||
|
Rollen-Check, F453).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Voraussetzungen
|
||||||
|
|
||||||
|
- Hermes-Instanz mit aktivem Profil
|
||||||
|
- `python3` mit `PyYAML` (das Plugin importiert `yaml` in `config.py`)
|
||||||
|
- Ein PMDB-Bearer-Token für den Agenten (generiert auf `.49`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Interaktiv werden abgefragt:
|
||||||
|
|
||||||
|
1. **Agent-/Profil-Name** (Default: automatisch aus `HERMES_HOME` erkannt)
|
||||||
|
2. **PMDB-Bearer-Token** (verdeckte Eingabe)
|
||||||
|
3. **PMDB MCP `base_url`** (Default `https://pmdb.myowntools.org/mcp`)
|
||||||
|
|
||||||
|
Nicht-interaktiv (für Automatisierung/CI):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./install.sh \
|
||||||
|
--agent miguel \
|
||||||
|
--token 'mcp_miguel_...' \
|
||||||
|
--api-url 'http://192.168.180.49:8099' \
|
||||||
|
--yes
|
||||||
|
```
|
||||||
|
|
||||||
|
Alle Optionen:
|
||||||
|
|
||||||
|
```
|
||||||
|
--agent <name> Agent-/Profil-Name
|
||||||
|
--token <token> PMDB-Bearer-Token
|
||||||
|
--api-url <url> PMDB MCP base_url (Default: https://pmdb.myowntools.org/mcp)
|
||||||
|
--source <dir> Quellverzeichnis der Plugin-Dateien
|
||||||
|
--skip-curl curl-Verbindungstest überspringen
|
||||||
|
--yes, -y nicht-interaktiv
|
||||||
|
--help, -h Hilfe
|
||||||
|
```
|
||||||
|
|
||||||
|
### Was `install.sh` tut
|
||||||
|
|
||||||
|
1. Kopiert `__init__.py`, `client.py`, `config.py`, `plugin.yaml` (+ `tests/`)
|
||||||
|
nach `~/.hermes/profiles/<agent>/plugins/pmdb_connector/`.
|
||||||
|
2. Entfernt stale `__pycache__`/`.pyc` (P-001).
|
||||||
|
3. Schreibt den Token in **zwei** Quellen:
|
||||||
|
- `~/.hermes/mcp_tokens.json` → `agenten.<agent>.token` (kanonisch, F590)
|
||||||
|
- `~/.hermes/profiles/<agent>/config.yaml` → `pmdb_connector.auth_keys.<agent>` (Fallback, F526)
|
||||||
|
4. Legt vor jedem Schreibvorgang ein Backup an (`.bak-install`).
|
||||||
|
5. Testet die Verbindung per `curl` gegen `GET <base_url>/mcp/api/tasks`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Token-Quellen (Auflösungsreihenfolge)
|
||||||
|
|
||||||
|
Die KANONISCHE Quelle ist `mcp_tokens.json` (F590, Single Source of Truth).
|
||||||
|
`config.yaml`-`auth_keys` ist nur Fallback (Backward-Compat).
|
||||||
|
|
||||||
|
```
|
||||||
|
resolve_token(profile):
|
||||||
|
1. mcp_tokens.json agenten[<profile>].token <- kanonisch
|
||||||
|
2. config.yaml pmdb_connector.auth_keys[<profile>]
|
||||||
|
3. config.yaml pmdb_connector.auth_keys["default"]
|
||||||
|
4. Basis-Config ~/.hermes/config.yaml
|
||||||
|
5. Profil-Config ~/.hermes/profiles/<profile>/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Konfigurations-Referenz (`pmdb_connector`-Sektion)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
pmdb_connector:
|
||||||
|
base_url: "http://192.168.180.49:8099" # PMDB MCP base_url (OHNE /mcp!)
|
||||||
|
auth_keys: # Fallback-Tokens (F526)
|
||||||
|
default: "mcp_bernd_..."
|
||||||
|
miguel: "mcp_miguel_..."
|
||||||
|
rainer: "mcp_rainer_..."
|
||||||
|
manager_profiles: [bernd, andreas] # Manager-only-Tools (F453)
|
||||||
|
stream_enabled: false # SSE-Listener (F621, opt-in, Default aus)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ base_url-Falle (doppeltes `/mcp`)
|
||||||
|
|
||||||
|
Der Client hängt **selbst** `/mcp/api/...` an `base_url` an
|
||||||
|
(`client.py` → `self.base_url + "/mcp/api/tasks"`). Deshalb darf `base_url`
|
||||||
|
**kein** abschließendes `/mcp` enthalten:
|
||||||
|
|
||||||
|
| `base_url` | effektiver get_tasks-Aufruf | Ergebnis |
|
||||||
|
|------------|-----------------------------|----------|
|
||||||
|
| `https://pmdb.myowntools.org` | `.../mcp/api/tasks` | ✅ 200 |
|
||||||
|
| `http://192.168.180.49:8099` (intern) | `.../mcp/api/tasks` | ✅ 200 |
|
||||||
|
| `https://pmdb.myowntools.org/mcp` (Default) | `.../mcp/mcp/api/tasks` | ❌ 404 |
|
||||||
|
|
||||||
|
Zusätzlich blockt der Openresty-Proxy (`pmdb.myowntools.org`) Bearer-Tokens
|
||||||
|
mit HTTP 401 (P-NEW-F563-PMDB-AUTH). **Empfehlung:** intern
|
||||||
|
`http://192.168.180.49:8099` verwenden. `install.sh` warnt bei einem
|
||||||
|
curl-404 explizit vor dieser Falle.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Unit-Tests (stdlib-only, laufen überall, kein Netzwerk):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd tests
|
||||||
|
python3 -m pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
Integration-Tests (gegen Live-PMDB auf `.49`) werden nur mit
|
||||||
|
`PMDB_TEST_TOKEN` aktiviert:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PMDB_TEST_TOKEN='mcp_...' PMDB_TEST_BASE='http://192.168.180.49:8099' \
|
||||||
|
python3 -m pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Datei-Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
pmdb_connector/
|
||||||
|
├── install.sh # Installer (diese Anleitung)
|
||||||
|
├── README.md
|
||||||
|
├── __init__.py # Tool-Registrierung + Handler (F454, F621, F719)
|
||||||
|
├── client.py # stdlib-only HTTP-Client (F454, F727)
|
||||||
|
├── config.py # Profil-Config + Token-Auflösung (F454, F590)
|
||||||
|
├── plugin.yaml # Plugin-Metadaten (kind: backend)
|
||||||
|
└── tests/
|
||||||
|
└── test_plugin.py # Unit- + Integration-Tests
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pitfalls-Referenz
|
||||||
|
|
||||||
|
- **P-001** stale `__pycache__` → `install.sh` räumt vor/nach Deploy auf.
|
||||||
|
- **P-NEW-F563-PMDB-AUTH** Proxy blockt Bearer-Tokens (401) → intern `.49:8099`.
|
||||||
|
- **P-191** Token nie in Logs/Responses (nur maskierter Prefix).
|
||||||
|
- **F590** `mcp_tokens.json` ist kanonisch → verhindert Token-Drift.
|
||||||
+693
@@ -0,0 +1,693 @@
|
|||||||
|
"""F454 PMDB Connector Plugin — Hermes Backend-Plugin (kind: backend).
|
||||||
|
|
||||||
|
@implements: [F454]
|
||||||
|
@implements: [F-621]
|
||||||
|
@implements: [F-719]
|
||||||
|
|
||||||
|
Profil-aware Anbindung an den PMDB MCP-Server (https://pmdb.myowntools.org/mcp).
|
||||||
|
Liest das aktive Hermes-Profil (V1 Option A: 1:1 = PMDB-Agent-Name), waehlt den
|
||||||
|
zugehoerigen Bearer-Token aus der Profile-Config (V2 Stufe 1 Plaintext) und
|
||||||
|
registriert die pmdb-*-Tools im Toolset "pmdb".
|
||||||
|
|
||||||
|
Tools (Rainers Architektur §2.7):
|
||||||
|
Phase 1 (Task-Lifecycle):
|
||||||
|
pmdb_get_tasks() — eigene Tasks (F455 Hybrid-Anzeige)
|
||||||
|
pmdb_accept_task(task_id) — akzeptieren
|
||||||
|
pmdb_decline_task(task_id, reason) — ablehnen
|
||||||
|
pmdb_submit_task(task_id, result) — Ergebnis einreichen (ReturnValue)
|
||||||
|
Phase 2 (Query + Management):
|
||||||
|
pmdb_get_mask(feature_id) — EK-Stand als Bit-Kette
|
||||||
|
pmdb_search(type, query) — PMDB durchsuchen
|
||||||
|
pmdb_get_baustein(baustein_id) — Baustein-Detail
|
||||||
|
pmdb_set_bit(feature_id, bit_nr) — Bit setzen (Manager-only)
|
||||||
|
pmdb_create_task(...) — Task erstellen (Manager-only)
|
||||||
|
|
||||||
|
Pull-on-Start (Option 1): KEIN Auto-Pull. Der Agent ruft pmdb_get_tasks()
|
||||||
|
explizit auf, wenn er arbeiten will (Andreas 10.09.: "Pull on Start").
|
||||||
|
|
||||||
|
Manager-only-Check (Defense-in-Depth): pmdb_set_bit + pmdb_create_task pruefen
|
||||||
|
`get_active_profile_name() in manager_profiles`. Der F449-Server hat einen
|
||||||
|
ZUSAETZLICHEN Rollen-Check (F453, P-218-Schutz).
|
||||||
|
|
||||||
|
Fehlender Token -> Plugin registriert sich mit WARNING und deaktiviert alle
|
||||||
|
Tools (Handler returnt strukturierten token_missing-Error).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from . import config as pmdb_config
|
||||||
|
from .client import PMDBClient
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TOOLSET = "pmdb"
|
||||||
|
EMOJI = "\U0001F4CB" # 📋
|
||||||
|
|
||||||
|
# Manager-only-Tools (Defense-in-Depth, Rainers Architektur §2.7).
|
||||||
|
_MANAGER_ONLY = {"pmdb_set_bit", "pmdb_create_task", "pmdb_get_submitted_tasks", "pmdb_manager_dashboard"}
|
||||||
|
|
||||||
|
|
||||||
|
def _str(description: str) -> dict:
|
||||||
|
return {"type": "string", "description": description}
|
||||||
|
|
||||||
|
|
||||||
|
def _int(description: str) -> dict:
|
||||||
|
return {"type": "integer", "description": description}
|
||||||
|
|
||||||
|
|
||||||
|
def _obj(description: str) -> dict:
|
||||||
|
return {"type": "object", "description": description}
|
||||||
|
|
||||||
|
|
||||||
|
def _downloads_dir(profile: str) -> str:
|
||||||
|
"""F-719: Default-Zielverzeichnis fuer Anlagen-Downloads (pro Profil).
|
||||||
|
|
||||||
|
Analog zur Config-Pfad-Aufloesung (P-119/P-147): HERMES_HOME kann auf ein
|
||||||
|
Profil- oder Basis-Verzeichnis zeigen. Downloads landen unter
|
||||||
|
``<profil>/downloads`` und werden nicht automatisch geraeumt (stabiler
|
||||||
|
Ablageort fuer den Agenten, kein Temp-File).
|
||||||
|
"""
|
||||||
|
home = os.environ.get("HERMES_HOME")
|
||||||
|
if home:
|
||||||
|
base = Path(home)
|
||||||
|
if base.parent.name == "profiles":
|
||||||
|
return str(base / "downloads")
|
||||||
|
return str(base / "profiles" / profile / "downloads")
|
||||||
|
return str(Path.home() / ".hermes" / "profiles" / profile / "downloads")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Tool-Handler (sync — HTTP via urllib, kein asyncio noetig)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _make_handlers(client: PMDBClient, profile: str, managers: list) -> dict:
|
||||||
|
"""Baut die Handler-Dicts. Jeder Handler liefert einen JSON-String.
|
||||||
|
|
||||||
|
Hermes Tool-Framework erwartet einen serialisierten Return-Typ (str),
|
||||||
|
kein rohes dict — sonst crasht der Tool-Handler mit
|
||||||
|
``Tool handler returned unsupported result type: dict``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _dump(result: dict) -> str:
|
||||||
|
return json.dumps(result, ensure_ascii=False)
|
||||||
|
|
||||||
|
def _guard_manager() -> Optional[dict]:
|
||||||
|
# Case-insensitive (P-194: Profil-/Agent-Namen sind case-inkonsistent).
|
||||||
|
if profile.lower() not in managers:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error_code": "forbidden",
|
||||||
|
"error": f"Profil '{profile}' ist kein Manager. Nur Manager "
|
||||||
|
f"duerfen diese Aktion ausfuehren.",
|
||||||
|
"action": "contact_manager",
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_tasks(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.get_tasks())
|
||||||
|
|
||||||
|
def get_submitted_tasks(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.get_submitted_tasks())
|
||||||
|
|
||||||
|
def manager_dashboard(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.manager_dashboard())
|
||||||
|
|
||||||
|
def accept_task(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.accept_task(args.get("task_id")))
|
||||||
|
|
||||||
|
def decline_task(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.decline_task(args.get("task_id"),
|
||||||
|
args.get("reason", "")))
|
||||||
|
|
||||||
|
def submit_task(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.submit_task(args.get("task_id"),
|
||||||
|
args.get("result", {})))
|
||||||
|
|
||||||
|
def get_mask(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.get_mask(args.get("feature_id")))
|
||||||
|
|
||||||
|
def search(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.search(
|
||||||
|
projekt=args.get("projekt"),
|
||||||
|
ziel=args.get("ziel"),
|
||||||
|
funktionsbereich=args.get("funktionsbereich"),
|
||||||
|
feature=args.get("feature"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def get_baustein(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.get_baustein(args.get("baustein_id")))
|
||||||
|
|
||||||
|
def set_bit(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.set_bit(
|
||||||
|
args.get("feature_id"),
|
||||||
|
args.get("bit_nr"),
|
||||||
|
args.get("begruendung"),
|
||||||
|
artefakt_typ=args.get("artefakt_typ"),
|
||||||
|
artefakt_inhalt=args.get("artefakt_inhalt"),
|
||||||
|
artefakt_titel=args.get("artefakt_titel"),
|
||||||
|
artefakte=args.get("artefakte"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def create_task(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.create_task(
|
||||||
|
agent=args.get("agent"),
|
||||||
|
feature_id=args.get("feature_id"),
|
||||||
|
baustein_id=args.get("baustein_id"),
|
||||||
|
pitch=args.get("pitch", ""),
|
||||||
|
frist=args.get("frist"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def get_pipeline_status(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.get_pipeline_status(
|
||||||
|
projekt_id=args.get("projekt_id"),
|
||||||
|
feature_status_filter=args.get("feature_status_filter"),
|
||||||
|
include_terminal=bool(args.get("include_terminal", False)),
|
||||||
|
))
|
||||||
|
|
||||||
|
def submit_on_behalf(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.submit_on_behalf(
|
||||||
|
task_id=args.get("task_id"),
|
||||||
|
agent_name=args.get("agent_name"),
|
||||||
|
payload=args.get("result", {}),
|
||||||
|
))
|
||||||
|
|
||||||
|
def get_task_evidence(args: dict, **kw) -> str:
|
||||||
|
return _dump(client.get_task_evidence(
|
||||||
|
task_id=args.get("task_id"),
|
||||||
|
include_sources=args.get("include_sources"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def return_for_revision(args: dict, **kw) -> str:
|
||||||
|
# F-705: QG-Rueckdelegation. KEIN Plugin-Level-Guard — der Server
|
||||||
|
# prueft die QG-/Manager-Rolle + Separation of Duties (P-218).
|
||||||
|
return _dump(client.return_for_revision(
|
||||||
|
task_id=args.get("task_id"),
|
||||||
|
reason=args.get("reason", ""),
|
||||||
|
auflagen=args.get("auflagen"),
|
||||||
|
zusammenfassung=args.get("zusammenfassung"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def manager_decision(args: dict, **kw) -> str:
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.manager_decision(
|
||||||
|
task_id=args.get("task_id"),
|
||||||
|
entscheidung=args.get("entscheidung"),
|
||||||
|
begruendung=args.get("begruendung", ""),
|
||||||
|
auflagen=args.get("auflagen"),
|
||||||
|
timebox_runden=args.get("timebox_runden"),
|
||||||
|
ziel_architektur_notiz=args.get("ziel_architektur_notiz"),
|
||||||
|
auftraggeber_zusammenfassung=args.get("auftraggeber_zusammenfassung"),
|
||||||
|
))
|
||||||
|
|
||||||
|
def stream_status(args: dict, **kw) -> str:
|
||||||
|
# F-621: Listener-Status (enabled/running/connected/event_count).
|
||||||
|
return _dump(_stream_status())
|
||||||
|
|
||||||
|
def get_anlagen(args: dict, **kw) -> str:
|
||||||
|
# F-719: Anlagen eines Tasks auflisten (Owner ODER Manager).
|
||||||
|
return _dump(client.get_anlagen(args.get("task_id")))
|
||||||
|
|
||||||
|
def download_anlage(args: dict, **kw) -> str:
|
||||||
|
# F-719: Binär-Download — Bytes auf Platte schreiben, sha256 client-seitig.
|
||||||
|
task_id = args.get("task_id")
|
||||||
|
att_id = args.get("att_id")
|
||||||
|
ziel_pfad = args.get("ziel_pfad")
|
||||||
|
result = client.download_anlage(task_id, att_id)
|
||||||
|
if isinstance(result, dict):
|
||||||
|
return _dump(result) # strukturierter Fehler (P-191)
|
||||||
|
meta = getattr(client, "_last_download", {}) or {}
|
||||||
|
filename = meta.get("filename") or f"anlage_{att_id}"
|
||||||
|
if not ziel_pfad:
|
||||||
|
ziel_pfad = os.path.join(_downloads_dir(profile), filename)
|
||||||
|
ziel_dir = os.path.dirname(ziel_pfad)
|
||||||
|
if ziel_dir:
|
||||||
|
os.makedirs(ziel_dir, exist_ok=True)
|
||||||
|
try:
|
||||||
|
with open(ziel_pfad, "wb") as fh:
|
||||||
|
fh.write(result)
|
||||||
|
except OSError as exc:
|
||||||
|
return _dump({
|
||||||
|
"success": False, "error_code": "write_error",
|
||||||
|
"error": f"Download konnte nicht gespeichert werden: {exc}",
|
||||||
|
"ziel_pfad": ziel_pfad,
|
||||||
|
})
|
||||||
|
return _dump({
|
||||||
|
"success": True,
|
||||||
|
"saved_path": ziel_pfad,
|
||||||
|
"filename": filename,
|
||||||
|
"sha256": hashlib.sha256(result).hexdigest(),
|
||||||
|
"groesse_bytes": len(result),
|
||||||
|
"content_type": meta.get("content_type", ""),
|
||||||
|
})
|
||||||
|
|
||||||
|
def upload_anlage(args: dict, **kw) -> str:
|
||||||
|
# F-719: Eingang-Anlage (Manager-only, Defense-in-Depth).
|
||||||
|
guard = _guard_manager()
|
||||||
|
if guard:
|
||||||
|
return _dump(guard)
|
||||||
|
return _dump(client.upload_anlage(
|
||||||
|
args.get("task_id"), args.get("file_path"), args.get("mime_type")))
|
||||||
|
|
||||||
|
def upload_ergebnis_anlage(args: dict, **kw) -> str:
|
||||||
|
# F-719: Ergebnis-Anlage (Owner-only, KEIN Plugin-Guard — Server prueft).
|
||||||
|
return _dump(client.upload_ergebnis_anlage(
|
||||||
|
args.get("task_id"), args.get("file_path"), args.get("mime_type")))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"pmdb_get_tasks": get_tasks,
|
||||||
|
"pmdb_get_submitted_tasks": get_submitted_tasks,
|
||||||
|
"pmdb_manager_dashboard": manager_dashboard,
|
||||||
|
"pmdb_accept_task": accept_task,
|
||||||
|
"pmdb_decline_task": decline_task,
|
||||||
|
"pmdb_submit_task": submit_task,
|
||||||
|
"pmdb_get_mask": get_mask,
|
||||||
|
"pmdb_search": search,
|
||||||
|
"pmdb_get_baustein": get_baustein,
|
||||||
|
"pmdb_set_bit": set_bit,
|
||||||
|
"pmdb_create_task": create_task,
|
||||||
|
"pmdb_get_pipeline_status": get_pipeline_status,
|
||||||
|
"pmdb_submit_on_behalf": submit_on_behalf,
|
||||||
|
"pmdb_get_task_evidence": get_task_evidence,
|
||||||
|
"pmdb_return_for_revision": return_for_revision,
|
||||||
|
"pmdb_manager_decision": manager_decision,
|
||||||
|
"pmdb_stream_status": stream_status,
|
||||||
|
"pmdb_get_anlagen": get_anlagen,
|
||||||
|
"pmdb_download_anlage": download_anlage,
|
||||||
|
"pmdb_upload_ergebnis_anlage": upload_ergebnis_anlage,
|
||||||
|
"pmdb_upload_anlage": upload_anlage,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Tool-Schemas (name, description, properties, required)
|
||||||
|
_TOOLS: dict[str, tuple[str, dict, list]] = {
|
||||||
|
"pmdb_get_tasks": (
|
||||||
|
"Eigene PMDB-Auftraege abrufen (F455 Hybrid-Anzeige: freie Tasks als "
|
||||||
|
"Liste, blockierte als Counter). Kein Input — die Agent-Identitaet wird "
|
||||||
|
"aus dem Bearer-Token abgeleitet.",
|
||||||
|
{}, [],
|
||||||
|
),
|
||||||
|
"pmdb_get_submitted_tasks": (
|
||||||
|
"Submitted PMDB-Tasks abrufen (Manager-only). Zeigt alle Tasks, "
|
||||||
|
"die auf Manager-Entscheidung warten, inkl. unblocks (F455-DAG).",
|
||||||
|
{}, [],
|
||||||
|
),
|
||||||
|
"pmdb_manager_dashboard": (
|
||||||
|
"Manager-Dashboard (Manager-only). Ein einziger Call liefert die vier "
|
||||||
|
"Bereiche: offene Fragen (diskussionsbedarf), ausstehende Freigaben, "
|
||||||
|
"eingereichte Tasks (mit Feature, ohne Test-Muell) und Wuensche/Change "
|
||||||
|
"Requests — je mit Klarschrift-Name + klickbarer Setcard-URL.",
|
||||||
|
{}, [],
|
||||||
|
),
|
||||||
|
"pmdb_accept_task": (
|
||||||
|
"Einen PMDB-Task akzeptieren (status pitched -> accepted).",
|
||||||
|
{"task_id": _str("ID des Tasks (z.B. 42 oder 'T-042')")}, ["task_id"],
|
||||||
|
),
|
||||||
|
"pmdb_decline_task": (
|
||||||
|
"Einen PMDB-Task ablehnen (status pitched -> declined, mit Grund).",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"reason": _str("Ablehnungsgrund (kurz)")}, ["task_id"],
|
||||||
|
),
|
||||||
|
"pmdb_submit_task": (
|
||||||
|
"Ergebnis eines PMDB-Tasks einreichen (ReturnValue-Payload, "
|
||||||
|
"status -> submitted). F522: Wenn der Task-Baustein ein Pflicht-Bit "
|
||||||
|
"hat (Bits 5-10, 15-17), MUSS der result-Payload einen Beleg "
|
||||||
|
"mitsenden: entweder result.artefakte als Liste von "
|
||||||
|
"{artefakt_typ, artefakt_inhalt, artefakt_titel} ODER die Einzelfelder "
|
||||||
|
"artefakt_typ/artefakt_inhalt/artefakt_titel. Fehlt der Beleg -> 422.",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"result": _obj("Ergebnis-Payload (ReturnValue-Struktur). "
|
||||||
|
"Optional: artefakte / artefakt_typ / artefakt_inhalt / "
|
||||||
|
"artefakt_titel (Pflicht fuer Bits 5-10, 15-17).")},
|
||||||
|
["task_id", "result"],
|
||||||
|
),
|
||||||
|
"pmdb_get_mask": (
|
||||||
|
"EK-Stand eines Features als visuelle Bit-Kette (17 Bits).",
|
||||||
|
{"feature_id": _str("Feature-ID oder F-Nummer (z.B. 'F454' oder '454')")},
|
||||||
|
["feature_id"],
|
||||||
|
),
|
||||||
|
"pmdb_search": (
|
||||||
|
"PMDB durchsuchen (Projekt/Ziel/Funktionsbereich/Feature, AND-verknuepft).",
|
||||||
|
{"projekt": _str("Projekt-Name (optional)"),
|
||||||
|
"ziel": _str("Strategisches Ziel (optional)"),
|
||||||
|
"funktionsbereich": _str("Funktionsbereich (optional)"),
|
||||||
|
"feature": _str("Feature-Name oder F-Nummer (optional)")},
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
"pmdb_get_baustein": (
|
||||||
|
"Baustein-Detail (Get/ReturnValue/Ausfuehrung + MCP-Funktionen).",
|
||||||
|
{"baustein_id": _int("Baustein-ID")}, ["baustein_id"],
|
||||||
|
),
|
||||||
|
"pmdb_set_bit": (
|
||||||
|
"Bit eines Features setzen (Manager-only). Braucht B8 Bearer-Endpoint. "
|
||||||
|
"F183: Pflicht-Bits (z.B. Bit 6=Implementierung) brauchen einen Beleg "
|
||||||
|
"via artefakt_typ/artefakt_inhalt/artefakt_titel (oder artefakte-Liste).",
|
||||||
|
{"feature_id": _int("Feature-ID"),
|
||||||
|
"bit_nr": _int("Bit-Nummer (1-17)"),
|
||||||
|
"begruendung": _str("Begruendung (optional)"),
|
||||||
|
"artefakt_typ": _str("Artefakt-Typ (commit/vault_pfad/url/datei/setcard/review)"),
|
||||||
|
"artefakt_inhalt": _str("Beleg-Inhalt (Commit-Hash, Pfad, URL, ...)"),
|
||||||
|
"artefakt_titel": _str("Anzeige-Titel des Belegs"),
|
||||||
|
"artefakte": _obj("Liste von {artefakt_typ, artefakt_inhalt, artefakt_titel} fuer 1:N")},
|
||||||
|
["feature_id", "bit_nr"],
|
||||||
|
),
|
||||||
|
"pmdb_create_task": (
|
||||||
|
"Neuen PMDB-Task erstellen (Manager-only).",
|
||||||
|
{"agent": _str("Ziel-Agent (PMDB-Agent-Name)"),
|
||||||
|
"feature_id": _int("Feature-ID"),
|
||||||
|
"baustein_id": _int("Baustein-ID"),
|
||||||
|
"pitch": _str("Auftragsbeschreibung (Pitch)"),
|
||||||
|
"frist": _str("Frist (ISO8601, optional)")},
|
||||||
|
["agent", "feature_id", "baustein_id", "pitch"],
|
||||||
|
),
|
||||||
|
"pmdb_get_pipeline_status": (
|
||||||
|
"Manager Pipeline-Overview (F523): alle Features mit Bit-Stand, "
|
||||||
|
"pending Tasks und naechsten Schritten in EINEM Aufruf. Read-only. "
|
||||||
|
"Optional: projekt_id, feature_status_filter (csv, default "
|
||||||
|
"pitched,accepted), include_terminal (default false).",
|
||||||
|
{"projekt_id": _int("Projekt-ID (optional, filtert auf ein Projekt)"),
|
||||||
|
"feature_status_filter": _str("CSV Task-Status-Filter (optional)"),
|
||||||
|
"include_terminal": _obj("Terminal-Bits 16/17 einbeziehen (optional)")},
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
"pmdb_submit_on_behalf": (
|
||||||
|
"Task fuer einen anderen Agenten einreichen (Manager-only, F525). "
|
||||||
|
"Der Manager (Executer) submittet den Task des on_behalf-Agenten. "
|
||||||
|
"Audit-Trail via submitted_by/on_behalf_of. F522: Pflicht-Bits brauchen "
|
||||||
|
"einen Beleg im result-Payload (artefakte/artefakt_typ/inhalt/titel).",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"agent_name": _str("Ziel-Agent (wem der Task gehoert)"),
|
||||||
|
"result": _obj("Ergebnis-Payload (ReturnValue-Struktur, inkl. Beleg)")},
|
||||||
|
["task_id", "agent_name", "result"],
|
||||||
|
),
|
||||||
|
"pmdb_get_task_evidence": (
|
||||||
|
"Evidence-Collection fuer QG (F528): sammelt alle Beweise zu einem "
|
||||||
|
"Task strukturiert (pytest-Logs, Migration-Status, Deploy-Verifikation, "
|
||||||
|
"Git-Log, Spike-Logs, Artefakte). Read-only. Optional: include_sources "
|
||||||
|
"(csv, default alle). data_quality='high'/'partial'.",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"include_sources": _str("CSV Quellen-Filter (optional)")},
|
||||||
|
["task_id"],
|
||||||
|
),
|
||||||
|
"pmdb_return_for_revision": (
|
||||||
|
"QG-Rueckdelegation mit Auflagen (F-705). QG-/Manager-Rolle: einen "
|
||||||
|
"submitted Task zur Nacharbeit zurueckgeben. Auflagen sind bei einem "
|
||||||
|
"QG-Call Pflicht (Ebene-Pflicht: backend/frontend/belege/dokumentation, "
|
||||||
|
"bei backend/frontend zusaetzlich ort). zusammenfassung ist Pflicht, "
|
||||||
|
"wenn der Call die Eskalation ausloest (ab der 3. Rueckdelegation).",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"reason": _str("Korrekturanweisung (Grund)"),
|
||||||
|
"auflagen": _obj("Liste von {nr, text, ebene, ort?, verifikation?, "
|
||||||
|
"zustaendig?} — Pflicht bei QG-Call"),
|
||||||
|
"zusammenfassung": _str("Gesamtdarstellung aller Runden (Pflicht bei "
|
||||||
|
"Eskalation)")},
|
||||||
|
["task_id"],
|
||||||
|
),
|
||||||
|
"pmdb_manager_decision": (
|
||||||
|
"Manager-Entscheidung fuer ein offenes Eskalations-Fenster (F-705, "
|
||||||
|
"Manager-only). entscheidung a/b/c/d: a=weiter (Auflagen + Re-Review), "
|
||||||
|
"b=Architektur, c=Auftraggeber-Eskalation, d=pausieren. begruendung "
|
||||||
|
"Pflicht; auflagen+timebox_runden bei a; auftraggeber_zusammenfassung "
|
||||||
|
"bei c.",
|
||||||
|
{"task_id": _str("ID des eskalierten Tasks"),
|
||||||
|
"entscheidung": _str("a/b/c/d"),
|
||||||
|
"begruendung": _str("Begruendung (Pflicht)"),
|
||||||
|
"auflagen": _obj("Liste (Pflicht bei a)"),
|
||||||
|
"timebox_runden": _obj("Ganzzahl (bei a, Default 1)"),
|
||||||
|
"ziel_architektur_notiz": _str("bei b"),
|
||||||
|
"auftraggeber_zusammenfassung": _str("Pflicht bei c")},
|
||||||
|
["task_id", "entscheidung"],
|
||||||
|
),
|
||||||
|
"pmdb_stream_status": (
|
||||||
|
"Status des SSE-Task-Dispatch-Listeners (F621 Stufe 1). Liefert "
|
||||||
|
"enabled/running/connected/event_count/last_event/last_error — "
|
||||||
|
"Read-only, fuer Diagnose und Verifikation des Streams.",
|
||||||
|
{}, [],
|
||||||
|
),
|
||||||
|
"pmdb_get_anlagen": (
|
||||||
|
"Anlagen eines Tasks auflisten (F-719, Owner ODER Manager). Liefert "
|
||||||
|
"alle Attachments beider Richtungen (eingang/ergebnis) mit id, name, "
|
||||||
|
"mime_type (Tag: pdf/png/jpeg/txt/csv/md), groesse_bytes, sha256, "
|
||||||
|
"richtung, hochgeladen_von, upload_am. Read-only.",
|
||||||
|
{"task_id": _str("ID des Tasks")}, ["task_id"],
|
||||||
|
),
|
||||||
|
"pmdb_download_anlage": (
|
||||||
|
"Eine Anlage herunterladen (F-719, Owner ODER Manager). Binaer-Download: "
|
||||||
|
"schreibt die Datei auf Platte und liefert saved_path + sha256 + "
|
||||||
|
"groesse_bytes (client-seitig berechnet, zur Integritaets-Pruefung "
|
||||||
|
"gegen den Server-Beleg). Optional ziel_pfad; Default ist "
|
||||||
|
"<profil>/downloads/<dateiname>.",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"att_id": _str("Anlagen-ID (UUID)"),
|
||||||
|
"ziel_pfad": _str("Zieldatei-Pfad (optional)")},
|
||||||
|
["task_id", "att_id"],
|
||||||
|
),
|
||||||
|
"pmdb_upload_ergebnis_anlage": (
|
||||||
|
"Ergebnis-Anlage hochladen (F-719, Owner-Agent). Multipart-Upload einer "
|
||||||
|
"Datei als Ergebnis-Anlage zu einem submitted Task. sha256 + mime-Tag "
|
||||||
|
"werden server-seitig bestimmt (Magic/Endung); erlaubte Typen: "
|
||||||
|
"pdf/png/jpeg/txt/csv/md. Nur nach submit (Status-Guard).",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"file_path": _str("Lokaler Pfad der Datei"),
|
||||||
|
"mime_type": _str("MIME-Typ (optional, server-seitig ueberschrieben)")},
|
||||||
|
["task_id", "file_path"],
|
||||||
|
),
|
||||||
|
"pmdb_upload_anlage": (
|
||||||
|
"Eingang-Anlage hochladen (F-719, Manager-only). Multipart-Upload einer "
|
||||||
|
"Datei als Eingang-Anlage zu einem pitched Task. Gleiche Mechanik wie "
|
||||||
|
"pmdb_upload_ergebnis_anlage, anderer Endpunkt. Nur vor dem Dispatch "
|
||||||
|
"(Status-Guard: pitched).",
|
||||||
|
{"task_id": _str("ID des Tasks"),
|
||||||
|
"file_path": _str("Lokaler Pfad der Datei"),
|
||||||
|
"mime_type": _str("MIME-Typ (optional, server-seitig ueberschrieben)")},
|
||||||
|
["task_id", "file_path"],
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F-621: SSE-Task-Dispatch-Stream-Listener (Stufe 1, opt-in)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Modul-Level-State fuer Diagnose/Observability (pmdb_stream_status-Tool).
|
||||||
|
_stream_state: dict = {
|
||||||
|
"enabled": False,
|
||||||
|
"running": False,
|
||||||
|
"profile": None,
|
||||||
|
"connected": False,
|
||||||
|
"event_count": 0,
|
||||||
|
"last_event": None,
|
||||||
|
"last_error": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _start_stream_listener(client: PMDBClient, profile: str) -> dict:
|
||||||
|
"""F-621 Stufe 1: startet einen daemon SSE-Listener-Thread.
|
||||||
|
|
||||||
|
Der Thread haelt eine persistente SSE-Verbindung zum Task-Dispatch-Stream
|
||||||
|
(client.stream_tasks) und verarbeitet task.dispatched-Events. Reconnect
|
||||||
|
mit exponentiellem Backoff (1s/4s/16s/60s). Der Listener ist best-effort:
|
||||||
|
ein Stream-Fehler blockt nie das Plugin; das Polling (pmdb_get_tasks)
|
||||||
|
bleibt als Sicherheitsnetz aktiv (Stufe 1).
|
||||||
|
|
||||||
|
KEIN Set-Bit-Trigger (A1): der Stream loest NUR Task-Lifecycle aus
|
||||||
|
(get_tasks + accept_task via _handle_stream_event), niemals ein
|
||||||
|
pmdb_set_bit. Liefert das stop_event fuer spaetere Stufen (graceful
|
||||||
|
shutdown).
|
||||||
|
"""
|
||||||
|
import threading
|
||||||
|
|
||||||
|
stop_event = threading.Event()
|
||||||
|
_stream_state.update({
|
||||||
|
"enabled": True, "running": True, "profile": profile,
|
||||||
|
"connected": False, "event_count": 0, "last_event": None,
|
||||||
|
"last_error": None,
|
||||||
|
})
|
||||||
|
|
||||||
|
backoff = [1, 4, 16, 60]
|
||||||
|
|
||||||
|
def _run():
|
||||||
|
idx = 0
|
||||||
|
while not stop_event.is_set():
|
||||||
|
try:
|
||||||
|
_stream_state["connected"] = True
|
||||||
|
for ev in client.stream_tasks(profile):
|
||||||
|
if stop_event.is_set():
|
||||||
|
break
|
||||||
|
_handle_stream_event(client, profile, ev)
|
||||||
|
# Stream sauber beendet -> kurz warten, dann reconnect.
|
||||||
|
_stream_state["connected"] = False
|
||||||
|
idx = 0
|
||||||
|
except Exception as exc: # noqa: BLE001 — reconnect
|
||||||
|
_stream_state["connected"] = False
|
||||||
|
_stream_state["last_error"] = f"{type(exc).__name__}: {exc}"
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: Stream-Listener fuer '%s' abgebrochen "
|
||||||
|
"(%s) — Reconnect in %ss", profile,
|
||||||
|
type(exc).__name__, backoff[idx])
|
||||||
|
if stop_event.is_set():
|
||||||
|
break
|
||||||
|
if stop_event.wait(backoff[idx]):
|
||||||
|
break
|
||||||
|
idx = min(idx + 1, len(backoff) - 1)
|
||||||
|
_stream_state["running"] = False
|
||||||
|
|
||||||
|
t = threading.Thread(target=_run, name=f"pmdb-sse-{profile}", daemon=True)
|
||||||
|
t.start()
|
||||||
|
return {"stop_event": stop_event, "thread": t}
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_stream_event(client: PMDBClient, profile: str, event: dict) -> None:
|
||||||
|
"""F-621 Stufe 1: verarbeitet ein task.dispatched-Event (Dispatch).
|
||||||
|
|
||||||
|
Bei einem neuen Task-Event dispatcht der Listener an pmdb_get_tasks
|
||||||
|
(Refresh der eigenen Task-Liste) und pmdb_accept_task (den neuen Task
|
||||||
|
akzeptieren). KEIN Set-Bit-Trigger (A1): accept ist Task-Lifecycle,
|
||||||
|
KEIN Bit-Setzen — der Stream loest nie ein pmdb_set_bit aus. Beide Calls
|
||||||
|
sind best-effort: ein Fehler loggt, wirft aber nie (der Listener-Thread
|
||||||
|
bleibt am Leben, das Polling bleibt als Sicherheitsnetz aktiv).
|
||||||
|
"""
|
||||||
|
data = (event or {}).get("data")
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return
|
||||||
|
if data.get("type") != "task.dispatched":
|
||||||
|
return
|
||||||
|
task_id = data.get("task_id")
|
||||||
|
_stream_state["event_count"] += 1
|
||||||
|
_stream_state["last_event"] = data
|
||||||
|
logger.info(
|
||||||
|
"pmdb_connector: Stream-Event task.dispatched fuer '%s': task_id=%s "
|
||||||
|
"feature_id=%s target_bit=%s",
|
||||||
|
profile, task_id, data.get("feature_id"), data.get("target_bit"))
|
||||||
|
|
||||||
|
# 1. Dispatch an pmdb_get_tasks: eigene Task-Liste refreshen (Pull).
|
||||||
|
try:
|
||||||
|
result = client.get_tasks()
|
||||||
|
if not (isinstance(result, dict) and result.get("success")):
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: get_tasks-Dispatch fuer '%s' fehlgeschlagen: %s",
|
||||||
|
profile, (result or {}).get("error_code", "unknown"))
|
||||||
|
except Exception as exc: # noqa: BLE001 — best-effort
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: get_tasks-Dispatch Exception fuer '%s': %s",
|
||||||
|
profile, exc)
|
||||||
|
|
||||||
|
# 2. Dispatch an pmdb_accept_task: den neuen Task akzeptieren.
|
||||||
|
if task_id is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
result = client.accept_task(task_id)
|
||||||
|
if isinstance(result, dict) and result.get("success"):
|
||||||
|
logger.info(
|
||||||
|
"pmdb_connector: Task %s fuer '%s' via Stream akzeptiert.",
|
||||||
|
task_id, profile)
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: accept_task(%s) fuer '%s' fehlgeschlagen: %s",
|
||||||
|
task_id, profile, (result or {}).get("error_code", "unknown"))
|
||||||
|
except Exception as exc: # noqa: BLE001 — best-effort
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: accept_task(%s) Exception fuer '%s': %s",
|
||||||
|
task_id, profile, exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _stream_status() -> dict:
|
||||||
|
"""F-621: Snapshot des Listener-Status (fuer pmdb_stream_status-Tool)."""
|
||||||
|
return dict(_stream_state)
|
||||||
|
|
||||||
|
|
||||||
|
def register(ctx) -> None:
|
||||||
|
"""Plugin-Entry-Point: Token aufloesen, alle pmdb-Tools registrieren."""
|
||||||
|
profile = pmdb_config.get_active_profile_name()
|
||||||
|
cfg = pmdb_config.load_pmdb_config(profile)
|
||||||
|
token = pmdb_config.resolve_token(profile, cfg)
|
||||||
|
|
||||||
|
# F526 Layer 2 (Diagnostik-Logging): welcher profile, welcher config_path,
|
||||||
|
# welcher Token-Prefix — damit strukturelle Auth-Bugs sichtbar werden
|
||||||
|
# (P-191: nur Prefix, nie Klartext).
|
||||||
|
logger.info(
|
||||||
|
"pmdb_connector: profile=%r, config_path=%r, token=%s, probierte_pfade=%s",
|
||||||
|
profile, str(pmdb_config._profile_config_path(profile)),
|
||||||
|
pmdb_config.token_prefix(token) if token else "<none>",
|
||||||
|
pmdb_config.probierte_pfade(profile, cfg),
|
||||||
|
)
|
||||||
|
|
||||||
|
if not token:
|
||||||
|
# F526 Layer 3 (strukturierter Fehler): statt nur token_missing ->
|
||||||
|
# token_not_found_for_profile mit probierte_pfade + action.
|
||||||
|
logger.warning(
|
||||||
|
"pmdb_connector: Kein Token fuer Profil '%s' — probierte Pfade: %s",
|
||||||
|
profile, pmdb_config.probierte_pfade(profile, cfg))
|
||||||
|
|
||||||
|
def _missing(args: dict, **kw) -> str:
|
||||||
|
return json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error_code": "token_not_found_for_profile",
|
||||||
|
"error": f"PMDB-Token fuer Profil '{profile}' nicht konfiguriert.",
|
||||||
|
"probierte_pfade": pmdb_config.probierte_pfade(profile, cfg),
|
||||||
|
"action": "check_config_or_hermes_home",
|
||||||
|
}, ensure_ascii=False)
|
||||||
|
|
||||||
|
for name, (desc, props, required) in _TOOLS.items():
|
||||||
|
parameters = {"type": "object", "properties": props}
|
||||||
|
if required:
|
||||||
|
parameters["required"] = required
|
||||||
|
ctx.register_tool(
|
||||||
|
name=name, toolset=TOOLSET, handler=_missing,
|
||||||
|
schema={"name": name, "description": desc,
|
||||||
|
"parameters": parameters},
|
||||||
|
emoji=EMOJI, description=desc,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
client = PMDBClient(
|
||||||
|
base_url=pmdb_config.base_url(cfg), token=token,
|
||||||
|
stream_base_url=pmdb_config.stream_base_url(cfg),
|
||||||
|
internal_base_url=pmdb_config.internal_base_url(cfg),
|
||||||
|
)
|
||||||
|
managers = pmdb_config.manager_profiles(cfg)
|
||||||
|
handlers = _make_handlers(client, profile, managers)
|
||||||
|
|
||||||
|
logger.info("pmdb_connector: Profil '%s', Token %s, %d Tools registriert.",
|
||||||
|
profile, pmdb_config.token_prefix(token), len(handlers))
|
||||||
|
|
||||||
|
for name, (desc, props, required) in _TOOLS.items():
|
||||||
|
parameters = {"type": "object", "properties": props}
|
||||||
|
if required:
|
||||||
|
parameters["required"] = required
|
||||||
|
ctx.register_tool(
|
||||||
|
name=name, toolset=TOOLSET, handler=handlers[name],
|
||||||
|
schema={"name": name, "description": desc,
|
||||||
|
"parameters": parameters},
|
||||||
|
emoji=EMOJI, description=desc,
|
||||||
|
)
|
||||||
|
|
||||||
|
# F-621 Stufe 1: SSE-Task-Dispatch-Listener (opt-in via config, Default aus).
|
||||||
|
# Der Listener laeuft parallel zum Polling (Sicherheitsnetz) und
|
||||||
|
# protokolliert task.dispatched-Events. KEIN Set-Bit-Trigger (A1).
|
||||||
|
if pmdb_config.stream_enabled(cfg):
|
||||||
|
_start_stream_listener(client, profile)
|
||||||
|
logger.info("pmdb_connector: SSE-Stream-Listener fuer '%s' gestartet "
|
||||||
|
"(stream_base_url=%s).", profile,
|
||||||
|
pmdb_config.stream_base_url(cfg))
|
||||||
@@ -0,0 +1,568 @@
|
|||||||
|
"""F454 PMDB Connector Plugin — HTTP-Client (stdlib-only, keine Hermes-Abhaengigkeit).
|
||||||
|
|
||||||
|
@implements: [F454, F-727]
|
||||||
|
|
||||||
|
Dieser Client ist die EINZIGE Wahrheitsquelle fuer die HTTP-Kommunikation mit
|
||||||
|
dem PMDB MCP-Server (https://pmdb.myowntools.org/mcp). Er ist bewusst
|
||||||
|
stdlib-only (urllib + json), damit er (a) auf jeder Hermes-Instanz laeuft und
|
||||||
|
(b) auf .49 ohne Hermes-Installation gegen die Live-PMDB getestet werden kann.
|
||||||
|
|
||||||
|
Error-Handling (Rainers Architektur §2.5): Jede HTTP-Antwort wird auf einen
|
||||||
|
strukturierten Tool-Response gemappt — KEINE Stacktraces, KEINE HTML-Seiten,
|
||||||
|
sondern JSON mit `success: false` + `error_code` + `action` (P-191-Schutz:
|
||||||
|
LLM-parsebar).
|
||||||
|
|
||||||
|
Mapping:
|
||||||
|
401 -> auth_invalid (action: renew_token)
|
||||||
|
403 -> forbidden (action: contact_manager)
|
||||||
|
404 -> not_found (resource + id)
|
||||||
|
409 -> state_conflict (current_status)
|
||||||
|
429 -> rate_limited (retry_after_seconds)
|
||||||
|
5xx -> pmdb_unavailable (action: fallback_to_terminal)
|
||||||
|
Netzwerkfehler -> network_error
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
DEFAULT_BASE_URL = "https://pmdb.myowntools.org/mcp"
|
||||||
|
DEFAULT_TIMEOUT = 30
|
||||||
|
|
||||||
|
# F-621: interner Stream-Basis (Openresty-Proxy blockt Bearer-Stream, 401).
|
||||||
|
# Der Task-Dispatch-Stream laeuft NUR via direktem 192.168.180.49:8099.
|
||||||
|
DEFAULT_STREAM_BASE_URL = "http://192.168.180.49:8099"
|
||||||
|
|
||||||
|
# F-719: interne Basis fuer Anlagen-Endpunkte (Upload/Liste/Download). Der
|
||||||
|
# Openresty-Proxy (pmdb.myowntools.org) blockt Bearer-Tokens (401) — deshalb
|
||||||
|
# laufen Task-Anlagen IMMER ueber die direkte IPv4 (P-NEW-F563-PMDB-AUTH).
|
||||||
|
DEFAULT_INTERNAL_BASE_URL = "http://192.168.180.49:8099"
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_content_disposition(header: str) -> str:
|
||||||
|
"""Extrahiert den Dateinamen aus einem Content-Disposition-Header.
|
||||||
|
|
||||||
|
RFC 5987 ``filename*=UTF-8''<name>`` hat Vorrang vor ``filename=``.
|
||||||
|
Liefert "" bei fehlendem/leerem Header.
|
||||||
|
"""
|
||||||
|
if not header:
|
||||||
|
return ""
|
||||||
|
for part in header.split(";"):
|
||||||
|
part = part.strip()
|
||||||
|
if part.startswith("filename*="):
|
||||||
|
val = part[len("filename*="):].strip().strip('"')
|
||||||
|
if "''" in val:
|
||||||
|
val = val.split("''", 1)[1]
|
||||||
|
return val
|
||||||
|
if part.startswith("filename="):
|
||||||
|
return part[len("filename="):].strip().strip('"')
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
class PMDBClient:
|
||||||
|
"""Synchroner HTTP-Client fuer den PMDB MCP-Server (Bearer-Token-Auth)."""
|
||||||
|
|
||||||
|
def __init__(self, base_url: str = DEFAULT_BASE_URL, token: str = "",
|
||||||
|
timeout: float = DEFAULT_TIMEOUT,
|
||||||
|
stream_base_url: str = DEFAULT_STREAM_BASE_URL,
|
||||||
|
internal_base_url: str = DEFAULT_INTERNAL_BASE_URL) -> None:
|
||||||
|
self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
||||||
|
self.token = token
|
||||||
|
self.timeout = timeout
|
||||||
|
self.stream_base_url = (stream_base_url or DEFAULT_STREAM_BASE_URL).rstrip("/")
|
||||||
|
self.internal_base_url = (internal_base_url or DEFAULT_INTERNAL_BASE_URL).rstrip("/")
|
||||||
|
# F-719: Metadaten des letzten Downloads (Filename/Content-Type) —
|
||||||
|
# fuer den Tool-Handler, der die Bytes auf Platte schreiben muss.
|
||||||
|
self._last_download: dict = {}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# HTTP-Kern
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _headers(self, with_json: bool = False) -> dict:
|
||||||
|
h = {"Authorization": f"Bearer {self.token}"}
|
||||||
|
if with_json:
|
||||||
|
h["Content-Type"] = "application/json"
|
||||||
|
return h
|
||||||
|
|
||||||
|
def _request(self, method: str, path: str, body: Optional[dict] = None,
|
||||||
|
base: Optional[str] = None) -> dict:
|
||||||
|
"""Fuehrt einen HTTP-Request aus. Liefert IMMER ein strukturiertes Dict.
|
||||||
|
|
||||||
|
Erfolg: {"success": True, "status": <int>, "data": <parsed-json>}
|
||||||
|
Fehler: {"success": False, "error_code": ..., "error": ..., ...}
|
||||||
|
|
||||||
|
``base`` ueberschreibt die Ziel-Basis (fuer Endpunkte, die ueber die
|
||||||
|
INTERNE IPv4 statt ueber den Proxy laufen muessen — F-719 Anlagen).
|
||||||
|
"""
|
||||||
|
url = (base or self.base_url) + path
|
||||||
|
data = None
|
||||||
|
if body is not None:
|
||||||
|
data = json.dumps(body).encode("utf-8")
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=data, headers=self._headers(with_json=body is not None),
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||||
|
status = resp.status
|
||||||
|
raw = resp.read().decode("utf-8", errors="replace")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
status = e.code
|
||||||
|
raw = e.read().decode("utf-8", errors="replace")
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error_code": "network_error",
|
||||||
|
"error": "PMDB nicht erreichbar",
|
||||||
|
"detail": str(e.reason)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error_code": "network_error",
|
||||||
|
"error": "PMDB-Request fehlgeschlagen",
|
||||||
|
"detail": str(e)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed = self._parse_json(raw)
|
||||||
|
if 200 <= status < 300:
|
||||||
|
return {"success": True, "status": status, "data": parsed}
|
||||||
|
return self._map_error(status, parsed)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_json(raw: str) -> Any:
|
||||||
|
try:
|
||||||
|
return json.loads(raw)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return {"raw": raw[:500]}
|
||||||
|
|
||||||
|
def _map_error(self, status: int, body: Any) -> dict:
|
||||||
|
"""Mappt einen HTTP-Fehlerstatus auf einen strukturierten Tool-Response."""
|
||||||
|
body = body if isinstance(body, dict) else {}
|
||||||
|
server_error = body.get("error", "")
|
||||||
|
if status == 401:
|
||||||
|
return {"success": False, "error_code": "auth_invalid",
|
||||||
|
"error": server_error or "Token ungueltig oder widerrufen",
|
||||||
|
"action": "renew_token"}
|
||||||
|
if status == 403:
|
||||||
|
return {"success": False, "error_code": "forbidden",
|
||||||
|
"error": server_error or "Rolle fehlt fuer diese Aktion",
|
||||||
|
"action": "contact_manager"}
|
||||||
|
if status == 404:
|
||||||
|
return {"success": False, "error_code": "not_found",
|
||||||
|
"error": server_error or "Ressource nicht gefunden"}
|
||||||
|
if status == 409:
|
||||||
|
return {"success": False, "error_code": "state_conflict",
|
||||||
|
"error": server_error or "Status-Konflikt",
|
||||||
|
"current_status": body.get("status")}
|
||||||
|
if status == 422:
|
||||||
|
# F524: Vorgaenger-Pre-Check beim Pitching.
|
||||||
|
if body.get("error_code") == "vorgaenger_fehlen":
|
||||||
|
return {"success": False, "error_code": "vorgaenger_fehlen",
|
||||||
|
"error": server_error or "Vorgaenger-Bits fehlen",
|
||||||
|
"fehlende_bits": body.get("fehlende_bits", []),
|
||||||
|
"action": "set_bits_first"}
|
||||||
|
return {"success": False, "error_code": "unprocessable",
|
||||||
|
"error": server_error or "Ungueltige Eingabe (422)",
|
||||||
|
"detail": body}
|
||||||
|
if status == 429:
|
||||||
|
return {"success": False, "error_code": "rate_limited",
|
||||||
|
"error": server_error or "Rate-Limit ueberschritten",
|
||||||
|
"retry_after_seconds": 60}
|
||||||
|
if status >= 500:
|
||||||
|
return {"success": False, "error_code": "pmdb_unavailable",
|
||||||
|
"error": server_error or "PMDB-Server nicht verfuegbar",
|
||||||
|
"action": "fallback_to_terminal"}
|
||||||
|
return {"success": False, "error_code": "http_error",
|
||||||
|
"error": server_error or f"HTTP {status}",
|
||||||
|
"status": status}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Task-Lifecycle (Phase 1)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def get_tasks(self) -> dict:
|
||||||
|
"""Eigene Tasks (F455 Hybrid-Anzeige: freie Tasks + blockierte als Counter)."""
|
||||||
|
return self._request("GET", "/mcp/api/tasks")
|
||||||
|
|
||||||
|
def get_task(self, task_id) -> dict:
|
||||||
|
"""Task-Detail + Status (GET /mcp/api/tasks/{id}, Bearer-Token).
|
||||||
|
|
||||||
|
@implements: [F-452, F-702]
|
||||||
|
|
||||||
|
Liefert den vollen Task-Row (inkl. ``pitch``). Wird vom SSE-Connector
|
||||||
|
(F-702) genutzt, um den Pitch nachzuladen: der Task-Dispatch-Broadcast
|
||||||
|
trägt KEIN pitch-Feld, der Pitch kommt aus diesem Detail-Endpoint.
|
||||||
|
"""
|
||||||
|
return self._request("GET", f"/mcp/api/tasks/{task_id}")
|
||||||
|
|
||||||
|
def get_submitted_tasks(self) -> dict:
|
||||||
|
"""F456: Submitted Tasks (Manager-View, Bearer-Token + rolle_id=1)."""
|
||||||
|
return self._request("GET", "/mcp/api/tasks/submitted")
|
||||||
|
|
||||||
|
def manager_dashboard(self) -> dict:
|
||||||
|
"""F514: Manager-Dashboard (Bearer-Token + rolle_id=1, 4 Bereiche)."""
|
||||||
|
return self._request("GET", "/mcp/api/dashboard")
|
||||||
|
|
||||||
|
def accept_task(self, task_id) -> dict:
|
||||||
|
return self._request("POST", f"/mcp/api/tasks/{task_id}/accept")
|
||||||
|
|
||||||
|
def decline_task(self, task_id, reason: str) -> dict:
|
||||||
|
return self._request("POST", f"/mcp/api/tasks/{task_id}/decline",
|
||||||
|
{"reason": reason or ""})
|
||||||
|
|
||||||
|
def submit_task(self, task_id, result: dict) -> dict:
|
||||||
|
return self._request("POST", f"/mcp/api/tasks/{task_id}/submit",
|
||||||
|
{"payload": result})
|
||||||
|
|
||||||
|
def return_for_revision(self, task_id, reason: str,
|
||||||
|
auflagen=None, zusammenfassung=None) -> dict:
|
||||||
|
"""F-705: QG-Rueckdelegation mit Auflagen + Eskalations-Zusammenfassung.
|
||||||
|
|
||||||
|
@implements: [F-705]
|
||||||
|
|
||||||
|
QG-Rolle: Rueckdelegation eines submitted Tasks mit strukturierten
|
||||||
|
Auflagen (Ebene-Pflicht) und — wenn der Call die Eskalation ausloest —
|
||||||
|
einer Pflicht-Zusammenfassung. Der Server prueft die QG-Rolle und die
|
||||||
|
Separation of Duties (Aufrufer != Task-Owner).
|
||||||
|
"""
|
||||||
|
body = {"reason": reason or ""}
|
||||||
|
if auflagen is not None:
|
||||||
|
body["auflagen"] = auflagen
|
||||||
|
if zusammenfassung:
|
||||||
|
body["zusammenfassung"] = zusammenfassung
|
||||||
|
return self._request("POST", f"/mcp/api/tasks/{task_id}/return-for-revision",
|
||||||
|
body)
|
||||||
|
|
||||||
|
def manager_decision(self, task_id, entscheidung: str, begruendung: str,
|
||||||
|
auflagen=None, timebox_runden=None,
|
||||||
|
ziel_architektur_notiz=None,
|
||||||
|
auftraggeber_zusammenfassung=None) -> dict:
|
||||||
|
"""F-705: Manager-Entscheidung fuer ein offenes Eskalations-Fenster.
|
||||||
|
|
||||||
|
@implements: [F-705]
|
||||||
|
|
||||||
|
entscheidung a/b/c/d; begruendung Pflicht. auflagen + timebox_runden
|
||||||
|
bei a; ziel_architektur_notiz bei b; auftraggeber_zusammenfassung bei c.
|
||||||
|
"""
|
||||||
|
body = {"entscheidung": entscheidung, "begruendung": begruendung or ""}
|
||||||
|
if auflagen is not None:
|
||||||
|
body["auflagen"] = auflagen
|
||||||
|
if timebox_runden is not None:
|
||||||
|
body["timebox_runden"] = timebox_runden
|
||||||
|
if ziel_architektur_notiz is not None:
|
||||||
|
body["ziel_architektur_notiz"] = ziel_architektur_notiz
|
||||||
|
if auftraggeber_zusammenfassung is not None:
|
||||||
|
body["auftraggeber_zusammenfassung"] = auftraggeber_zusammenfassung
|
||||||
|
return self._request(
|
||||||
|
"POST", f"/mcp/api/tasks/eskaliert/{task_id}/entscheidung", body)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Query + Management (Phase 2)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def get_mask(self, feature_id) -> dict:
|
||||||
|
return self._request("GET", f"/mcp/api/getmask/{feature_id}")
|
||||||
|
|
||||||
|
def search(self, projekt=None, ziel=None, funktionsbereich=None,
|
||||||
|
feature=None) -> dict:
|
||||||
|
body = {}
|
||||||
|
if projekt:
|
||||||
|
body["projekt"] = projekt
|
||||||
|
if ziel:
|
||||||
|
body["ziel"] = ziel
|
||||||
|
if funktionsbereich:
|
||||||
|
body["funktionsbereich"] = funktionsbereich
|
||||||
|
if feature:
|
||||||
|
body["feature"] = feature
|
||||||
|
return self._request("POST", "/mcp/api/search", body)
|
||||||
|
|
||||||
|
def get_baustein(self, baustein_id) -> dict:
|
||||||
|
return self._request("GET", f"/mcp/api/bausteine/{baustein_id}")
|
||||||
|
|
||||||
|
def set_bit(self, feature_id, bit_nr, begruendung: Optional[str] = None,
|
||||||
|
artefakt_typ: Optional[str] = None,
|
||||||
|
artefakt_inhalt: Optional[str] = None,
|
||||||
|
artefakt_titel: Optional[str] = None,
|
||||||
|
artefakte: Optional[list] = None) -> dict:
|
||||||
|
body = {"feature_id": feature_id, "bit_nr": bit_nr}
|
||||||
|
if begruendung:
|
||||||
|
body["begruendung"] = begruendung
|
||||||
|
# F183: Artefakt-Belege (Einzelfelder ODER Liste fuer 1:N).
|
||||||
|
if artefakte:
|
||||||
|
body["artefakte"] = artefakte
|
||||||
|
elif artefakt_typ or artefakt_inhalt or artefakt_titel:
|
||||||
|
body["artefakt_typ"] = artefakt_typ
|
||||||
|
body["artefakt_inhalt"] = artefakt_inhalt
|
||||||
|
body["artefakt_titel"] = artefakt_titel
|
||||||
|
return self._request("POST", "/mcp/api/set-bit", body)
|
||||||
|
|
||||||
|
def create_task(self, agent: str, feature_id, baustein_id, pitch: str,
|
||||||
|
frist: Optional[str] = None) -> dict:
|
||||||
|
body = {"agent": agent, "feature_id": feature_id,
|
||||||
|
"baustein_id": baustein_id, "pitch": pitch}
|
||||||
|
if frist:
|
||||||
|
body["frist"] = frist
|
||||||
|
return self._request("POST", "/mcp/api/tasks", body)
|
||||||
|
|
||||||
|
def get_pipeline_status(self, projekt_id=None, feature_status_filter=None,
|
||||||
|
include_terminal=False) -> dict:
|
||||||
|
"""F523: Pipeline-Overview — alle Features mit Bit-Stand + pending Tasks."""
|
||||||
|
parts = []
|
||||||
|
if projekt_id is not None:
|
||||||
|
parts.append(f"projekt_id={projekt_id}")
|
||||||
|
if feature_status_filter:
|
||||||
|
parts.append(f"feature_status_filter={feature_status_filter}")
|
||||||
|
if include_terminal:
|
||||||
|
parts.append("include_terminal=true")
|
||||||
|
path = "/mcp/api/pipeline-status"
|
||||||
|
if parts:
|
||||||
|
path += "?" + "&".join(parts)
|
||||||
|
return self._request("GET", path)
|
||||||
|
|
||||||
|
def submit_on_behalf(self, task_id, agent_name: str, payload: dict) -> dict:
|
||||||
|
"""F525 Teil 1: Manager submittet Task fuer anderen Agenten."""
|
||||||
|
return self._request(
|
||||||
|
"POST", f"/mcp/api/tasks/{task_id}/submit-on-behalf",
|
||||||
|
{"agent_name": agent_name, "payload": payload},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_task_evidence(self, task_id, include_sources=None) -> dict:
|
||||||
|
"""F528: Evidence-Collection fuer QG (read-only)."""
|
||||||
|
path = f"/mcp/api/tasks/{task_id}/evidence"
|
||||||
|
if include_sources:
|
||||||
|
path += f"?include_sources={include_sources}"
|
||||||
|
return self._request("GET", path)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# F-719: Task-Anlagen (Upload/Liste/Download) — MCP Broker 4.0
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def get_anlagen(self, task_id) -> dict:
|
||||||
|
"""F-719: Liste aller Anlagen eines Tasks (Owner ODER Manager).
|
||||||
|
|
||||||
|
@implements: [F-719]
|
||||||
|
|
||||||
|
GET /mcp/api/tasks/{task_id}/anlagen — liefert
|
||||||
|
``{"task_id": ..., "anlagen": [{id, richtung, name, mime_type,
|
||||||
|
groesse_bytes, sha256, pfad, hochgeladen_von, upload_am, ...}]}``.
|
||||||
|
``mime_type`` ist ein canonisches Tag (pdf/png/jpeg/txt/csv/md),
|
||||||
|
KEIN full-MIME-String.
|
||||||
|
"""
|
||||||
|
return self._request("GET", f"/mcp/api/tasks/{task_id}/anlagen",
|
||||||
|
base=self.internal_base_url)
|
||||||
|
|
||||||
|
def download_anlage(self, task_id, att_id):
|
||||||
|
"""F-719: Binaer-Download einer einzelnen Anlage.
|
||||||
|
|
||||||
|
@implements: [F-719]
|
||||||
|
|
||||||
|
GET /mcp/api/tasks/{task_id}/anlagen/{att_id} — die Antwort ist der
|
||||||
|
DATEI-INHALT (Bytes), KEIN JSON. Deshalb NICHT ``_request`` (das parst
|
||||||
|
JSON), sondern direkter urllib-Read. Liefert die Bytes bei Erfolg oder
|
||||||
|
ein strukturiertes Fehler-Dict (P-191). Filename/Content-Type stehen
|
||||||
|
danach in ``self._last_download`` (fuer den Tool-Handler).
|
||||||
|
"""
|
||||||
|
url = f"{self.internal_base_url}/mcp/api/tasks/{task_id}/anlagen/{att_id}"
|
||||||
|
req = urllib.request.Request(url, method="GET", headers=self._headers())
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
self._last_download = {
|
||||||
|
"content_type": resp.headers.get("Content-Type", ""),
|
||||||
|
"filename": _parse_content_disposition(
|
||||||
|
resp.headers.get("Content-Disposition", "")),
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return self._map_error(
|
||||||
|
e.code,
|
||||||
|
self._parse_json(e.read().decode("utf-8", errors="replace")))
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
return {
|
||||||
|
"success": False, "error_code": "network_error",
|
||||||
|
"error": "PMDB nicht erreichbar",
|
||||||
|
"detail": str(e.reason)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||||
|
return {
|
||||||
|
"success": False, "error_code": "network_error",
|
||||||
|
"error": "PMDB-Download fehlgeschlagen",
|
||||||
|
"detail": str(e)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
|
||||||
|
def upload_anlage(self, task_id, file_path,
|
||||||
|
mime_type: Optional[str] = None) -> dict:
|
||||||
|
"""F-719: Eingang-Anlage hochladen (Manager oder Agent mit Manager-Recht).
|
||||||
|
|
||||||
|
@implements: [F-719]
|
||||||
|
|
||||||
|
POST /mcp/api/tasks/{task_id}/anlagen — multipart/form-data, Feld
|
||||||
|
'datei'. Status-Guard: nur bei ``status=pitched``. sha256 + mime-Tag
|
||||||
|
werden SERVER-seitig bestimmt (Magic/Endung), der Client-Parameter
|
||||||
|
``mime_type`` setzt nur den Part-Content-Type (nicht verbindlich).
|
||||||
|
"""
|
||||||
|
return self._multipart_upload(
|
||||||
|
f"/mcp/api/tasks/{task_id}/anlagen", file_path, mime_type)
|
||||||
|
|
||||||
|
def upload_ergebnis_anlage(self, task_id, file_path,
|
||||||
|
mime_type: Optional[str] = None) -> dict:
|
||||||
|
"""F-719: Ergebnis-Anlage hochladen (Owner-Agent, nach submit).
|
||||||
|
|
||||||
|
@implements: [F-719]
|
||||||
|
|
||||||
|
POST /mcp/api/tasks/{task_id}/ergebnis-anlagen — multipart/form-data,
|
||||||
|
Feld 'datei'. Status-Guard: nur bei ``status=submitted``. Owner-only
|
||||||
|
(der Server prueft die Bearer-Identitaet, KEIN Body-Feld).
|
||||||
|
"""
|
||||||
|
return self._multipart_upload(
|
||||||
|
f"/mcp/api/tasks/{task_id}/ergebnis-anlagen", file_path, mime_type)
|
||||||
|
|
||||||
|
def _multipart_upload(self, path: str, file_path: str,
|
||||||
|
mime_type: Optional[str] = None) -> dict:
|
||||||
|
"""F-719: Multipart-Upload einer Datei (stdlib, manuell konstruierter Body).
|
||||||
|
|
||||||
|
Liesst die Datei vom Dateisystem, baut einen multipart/form-data-Body
|
||||||
|
mit zufaelliger Boundary und einem ``datei``-Part. Der Body wird
|
||||||
|
bytes-korrekt aufgebaut (keine Requests-Lib). Erfolg liefert
|
||||||
|
``{"success": True, "status": 201, "data": {"success": ..., "anlagen": [...]}}``;
|
||||||
|
Fehler sind strukturierte Dicts (P-191).
|
||||||
|
"""
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
return {
|
||||||
|
"success": False, "error_code": "file_not_found",
|
||||||
|
"error": f"Datei nicht gefunden: {file_path}",
|
||||||
|
"action": "check_file_path",
|
||||||
|
}
|
||||||
|
|
||||||
|
filename = os.path.basename(file_path)
|
||||||
|
ctype = mime_type or mimetypes.guess_type(filename)[0] \
|
||||||
|
or "application/octet-stream"
|
||||||
|
|
||||||
|
with open(file_path, "rb") as fh:
|
||||||
|
content = fh.read()
|
||||||
|
|
||||||
|
boundary = f"----pmdb-{uuid.uuid4().hex}"
|
||||||
|
body = (
|
||||||
|
f"--{boundary}\r\n"
|
||||||
|
f"Content-Disposition: form-data; name=\"datei\"; "
|
||||||
|
f"filename=\"{filename}\"\r\n"
|
||||||
|
f"Content-Type: {ctype}\r\n\r\n"
|
||||||
|
).encode("utf-8") + content + f"\r\n--{boundary}--\r\n".encode("utf-8")
|
||||||
|
|
||||||
|
url = self.internal_base_url + path
|
||||||
|
req = urllib.request.Request(url, data=body, method="POST")
|
||||||
|
req.add_header("Authorization", f"Bearer {self.token}")
|
||||||
|
req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||||
|
status = resp.status
|
||||||
|
raw = resp.read().decode("utf-8", errors="replace")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
status = e.code
|
||||||
|
raw = e.read().decode("utf-8", errors="replace")
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
return {
|
||||||
|
"success": False, "error_code": "network_error",
|
||||||
|
"error": "PMDB nicht erreichbar",
|
||||||
|
"detail": str(e.reason)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
except Exception as e: # noqa: BLE001 — Timeout etc.
|
||||||
|
return {
|
||||||
|
"success": False, "error_code": "network_error",
|
||||||
|
"error": "PMDB-Upload fehlgeschlagen",
|
||||||
|
"detail": str(e)[:200],
|
||||||
|
"action": "fallback_to_terminal",
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed = self._parse_json(raw)
|
||||||
|
if 200 <= status < 300:
|
||||||
|
return {"success": True, "status": status, "data": parsed}
|
||||||
|
return self._map_error(status, parsed)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# F-621: SSE-Task-Dispatch-Stream (stdlib urllib, kein aiohttp)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def stream_tasks(self, profile: str, last_event_id=None,
|
||||||
|
connect_timeout: Optional[float] = None):
|
||||||
|
"""Generator, der task.dispatched-SSE-Events liefert (F-621).
|
||||||
|
|
||||||
|
@implements: [F-621]
|
||||||
|
|
||||||
|
Blockierender urllib-Read (sync, stdlib-only — konsistent zum Rest des
|
||||||
|
Plugins). Liest das EventSource-Protokoll zeilenweise und liefert
|
||||||
|
parse-te Event-Dicts der Form {event, data}. Der Aufrufer
|
||||||
|
(Listener-Thread) haelt den Generator offen und reconnectet bei
|
||||||
|
Abbruch/Exception.
|
||||||
|
|
||||||
|
Auth (P-191): Token via ``Authorization``-Header (add_header) — bleibt
|
||||||
|
aus der URL fern. Pitfall (F-621): Stream laeuft ueber den INTERNEN
|
||||||
|
``stream_base_url`` (192.168.180.49:8099), nicht ueber den
|
||||||
|
Openresty-Proxy, der Bearer-Stream mit 401 blockt.
|
||||||
|
|
||||||
|
``connect_timeout`` wird nur bei EXPLIZITER Übergabe als Socket-Timeout
|
||||||
|
gesetzt (stdlib urllib kennt keinen getrennten Connect-/Read-Timeout);
|
||||||
|
der generelle ``self.timeout`` (30s) gilt NICHT mehr für den Stream.
|
||||||
|
Default (None) = voll blockierend — kein Idle-Limit am Socket.
|
||||||
|
|
||||||
|
F-727 S1b — normative Marge-Regel (Architektur §2.1, Viola-Mandat M2):
|
||||||
|
Die SSE-Kette ist stabil, wenn gilt:
|
||||||
|
Client-Read-Timeout (am Socket) > 2 × Server-Keepalive-Intervall.
|
||||||
|
Der Stream-Read ist deshalb BLOCKIEREND (``timeout=None``); ein
|
||||||
|
Server-Deploy/Restart meldet den Abbruch sofort via TCP FIN/RST, der
|
||||||
|
Listener reconnectet (Backoff 1s/4s/16s/60s). Wer später den
|
||||||
|
Timeout ändert, MUSS diese Regel gegenprüfen (R7). Server-
|
||||||
|
Gegenstück: SSE_KEEPALIVE_S in backend/broker_routes.py.
|
||||||
|
"""
|
||||||
|
path = f"/mcp/api/stream/tasks?profile={profile}"
|
||||||
|
if last_event_id is not None:
|
||||||
|
path += f"&last_event_id={last_event_id}"
|
||||||
|
url = self.stream_base_url + path
|
||||||
|
req = urllib.request.Request(url, method="GET")
|
||||||
|
req.add_header("Authorization", f"Bearer {self.token}")
|
||||||
|
req.add_header("Accept", "text/event-stream")
|
||||||
|
# F-727 S1b — Read-Timeout vom generellen self.timeout (30s) entkoppelt:
|
||||||
|
# timeout=None = blockierendes Lesen ohne Idle-Limit (docstring-konform,
|
||||||
|
# Marge-Regel oben). connect_timeout wird nur bei EXPLIZITER Übergabe
|
||||||
|
# als Socket-Timeout gesetzt. Default None = voll blockierend.
|
||||||
|
resp = urllib.request.urlopen(req, timeout=connect_timeout)
|
||||||
|
event_type = None
|
||||||
|
data_lines = []
|
||||||
|
try:
|
||||||
|
for raw in resp:
|
||||||
|
line = raw.decode("utf-8", errors="replace").rstrip("\r\n")
|
||||||
|
if line == "":
|
||||||
|
# Leerzeile = Event-Ende.
|
||||||
|
if data_lines:
|
||||||
|
payload = "\n".join(data_lines)
|
||||||
|
data_lines = []
|
||||||
|
try:
|
||||||
|
parsed = json.loads(payload)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
parsed = {"raw": payload}
|
||||||
|
yield {"event": event_type or "message", "data": parsed}
|
||||||
|
event_type = None
|
||||||
|
continue
|
||||||
|
if line.startswith(":"):
|
||||||
|
continue # Kommentar/keepalive.
|
||||||
|
if line.startswith("event:"):
|
||||||
|
event_type = line[len("event:"):].strip()
|
||||||
|
continue
|
||||||
|
if line.startswith("data:"):
|
||||||
|
data_lines.append(line[len("data:"):].strip())
|
||||||
|
continue
|
||||||
|
# 'retry:'/'id:'-Zeilen ignorieren — Reconnect steuert der Listener.
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
resp.close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
"""F454 PMDB Connector Plugin — Profil-Config + Token-Aufloesung.
|
||||||
|
|
||||||
|
@implements: [F454]
|
||||||
|
@implements: [F590]
|
||||||
|
@implements: [F-621]
|
||||||
|
|
||||||
|
V1 (Option A): 1:1-Mapping Hermes-Profil = PMDB-Agent-Name. Das aktive Profil
|
||||||
|
wird via `hermes_cli.profiles.get_active_profile_name()` ermittelt (HERMES_HOME-
|
||||||
|
basiert). Der zugehoerige Bearer-Token liegt in der Profile-Config:
|
||||||
|
|
||||||
|
~/.hermes/profiles/<name>/config.yaml
|
||||||
|
pmdb_connector:
|
||||||
|
base_url: "https://pmdb.myowntools.org/mcp"
|
||||||
|
manager_profiles: [bernd, andreas]
|
||||||
|
auth_keys:
|
||||||
|
default: "mcp_bernd_<geheimnis>"
|
||||||
|
miguel: "mcp_miguel_<geheimnis>"
|
||||||
|
rainer: "mcp_rainer_<geheimnis>"
|
||||||
|
finn: "mcp_finn_<geheimnis>"
|
||||||
|
don: "mcp_don_<geheimnis>"
|
||||||
|
|
||||||
|
V2 Stufe 1 (Plaintext Config) ist der aktuelle Stand. Stufe 2 (Secret-Source)
|
||||||
|
ist als verbindliche Erweiterung eingeplant (Rainers Architektur §2.3).
|
||||||
|
|
||||||
|
F590 (Token-Sync): Die KANONISCHE Token-Quelle ist jetzt ``mcp_tokens.json``
|
||||||
|
(~/.hermes/mcp_tokens.json, F531-Bootstrap-Store). ``resolve_token()`` liest
|
||||||
|
den Bearer-Token ZUERST aus ``mcp_tokens.json`` (agenten[<profil>].token) und
|
||||||
|
faellt nur noch bei Nicht-Fund auf die config.yaml-``auth_keys`` zurueck
|
||||||
|
(backward-compat). Das beseitigt den Token-Drift zwischen zwei Quellen
|
||||||
|
(P-NEW-3 / Daily Note 04.10.).
|
||||||
|
|
||||||
|
Sicherheits-Garantien (P-191/P-219-Schutz):
|
||||||
|
- Token wird NIE geloggt (nur Prefix `mcp_<kuerzel>_***`).
|
||||||
|
- Token erscheint NIE in Tool-Responses oder Fehlermeldungen.
|
||||||
|
- Fehlender Token -> strukturierter Error `token_missing` (kein Crash).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
DEFAULT_BASE_URL = "https://pmdb.myowntools.org/mcp"
|
||||||
|
|
||||||
|
|
||||||
|
def get_active_profile_name() -> str:
|
||||||
|
"""Ermittelt das aktive Hermes-Profil (HERMES_HOME-basiert).
|
||||||
|
|
||||||
|
Fallback-Kette (P-191: nie still scheitern):
|
||||||
|
1. hermes_cli.profiles.get_active_profile_name() (offizielle API)
|
||||||
|
2. HERMES_HOME-Pfad-Analyse (falls hermes_cli nicht importierbar)
|
||||||
|
3. "default"
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from hermes_cli.profiles import get_active_profile_name as _gapn
|
||||||
|
return _gapn()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
home = os.environ.get("HERMES_HOME", "")
|
||||||
|
if home:
|
||||||
|
p = Path(home)
|
||||||
|
# ~/.hermes/profiles/<name> -> <name>
|
||||||
|
if p.parent.name == "profiles":
|
||||||
|
return p.name
|
||||||
|
return "default"
|
||||||
|
|
||||||
|
|
||||||
|
def _profile_config_path(profile: str) -> Optional[Path]:
|
||||||
|
"""Pfad zur Profile-Config (HERMES_HOME-basiert, P-119/P-147-sicher).
|
||||||
|
|
||||||
|
Zwei Faelle (P-119/P-147-Klasse — HERMES_HOME-Dopplung):
|
||||||
|
1. HERMES_HOME zeigt auf ein PROFIL-Verzeichnis
|
||||||
|
(~/.hermes/profiles/<name>) -> die Config liegt DIREKT dort
|
||||||
|
(HERMES_HOME/config.yaml). Es darf NICHT erneut `profiles/<name>`
|
||||||
|
angehaengt werden, sonst entsteht die Dopplung
|
||||||
|
`.../profiles/<name>/profiles/<name>/config.yaml`.
|
||||||
|
2. HERMES_HOME zeigt auf das BASIS-Verzeichnis (~/.hermes) ->
|
||||||
|
default: <base>/config.yaml
|
||||||
|
benannt: <base>/profiles/<name>/config.yaml
|
||||||
|
|
||||||
|
Ohne HERMES_HOME: Fallback auf ~/.hermes (analog Fall 2).
|
||||||
|
"""
|
||||||
|
home = os.environ.get("HERMES_HOME")
|
||||||
|
if home:
|
||||||
|
base = Path(home)
|
||||||
|
# Fall 1: HERMES_HOME ist bereits ein Profil-Verzeichnis.
|
||||||
|
if base.parent.name == "profiles":
|
||||||
|
return base / "config.yaml"
|
||||||
|
# Fall 2: Basis-Verzeichnis.
|
||||||
|
if profile == "default":
|
||||||
|
return base / "config.yaml"
|
||||||
|
return base / "profiles" / profile / "config.yaml"
|
||||||
|
# Kein HERMES_HOME: Fallback auf ~/.hermes.
|
||||||
|
base = Path.home() / ".hermes"
|
||||||
|
if profile == "default":
|
||||||
|
return base / "config.yaml"
|
||||||
|
return base / "profiles" / profile / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_yaml(path: Path) -> dict:
|
||||||
|
try:
|
||||||
|
import yaml
|
||||||
|
with open(path, encoding="utf-8") as f:
|
||||||
|
data = yaml.safe_load(f) or {}
|
||||||
|
return data if isinstance(data, dict) else {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def load_pmdb_config(profile: str) -> dict:
|
||||||
|
"""Liest die `pmdb_connector`-Sektion aus der Profile-Config.
|
||||||
|
|
||||||
|
Liefert {} wenn keine Sektion existiert (Plugin deaktiviert sich dann
|
||||||
|
sauber mit token_missing).
|
||||||
|
"""
|
||||||
|
path = _profile_config_path(profile)
|
||||||
|
if path is None or not path.exists():
|
||||||
|
return {}
|
||||||
|
data = _load_yaml(path)
|
||||||
|
section = data.get("pmdb_connector")
|
||||||
|
return section if isinstance(section, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F590: Kanonische Token-Quelle mcp_tokens.json (F531-Bootstrap-Store)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _mcp_tokens_path() -> Optional[Path]:
|
||||||
|
"""@implements F-590 — Pfad zur kanonischen mcp_tokens.json.
|
||||||
|
|
||||||
|
mcp_tokens.json liegt IMMER auf der Basis-Ebene (~/.hermes/mcp_tokens.json),
|
||||||
|
NICHT pro Profil. Env ``HERMES_MCP_TOKENS`` ueberschreibt den Pfad (fuer
|
||||||
|
Tests + Betrieb).
|
||||||
|
|
||||||
|
HERMES_HOME-Aufloesung (analog _base_config_path):
|
||||||
|
1. HERMES_HOME zeigt auf ein Profil-Verzeichnis
|
||||||
|
(~/.hermes/profiles/<name>) -> Basis ist der Parent-Parent
|
||||||
|
(~/.hermes/mcp_tokens.json).
|
||||||
|
2. HERMES_HOME zeigt auf die Basis (~/.hermes) -> direkt dort.
|
||||||
|
3. Ohne HERMES_HOME -> ~/.hermes/mcp_tokens.json.
|
||||||
|
"""
|
||||||
|
env = os.environ.get("HERMES_MCP_TOKENS")
|
||||||
|
if env:
|
||||||
|
return Path(env)
|
||||||
|
home = os.environ.get("HERMES_HOME")
|
||||||
|
if home:
|
||||||
|
base = Path(home)
|
||||||
|
if base.parent.name == "profiles":
|
||||||
|
return base.parent.parent / "mcp_tokens.json"
|
||||||
|
return base / "mcp_tokens.json"
|
||||||
|
return Path.home() / ".hermes" / "mcp_tokens.json"
|
||||||
|
|
||||||
|
|
||||||
|
def load_mcp_tokens() -> dict:
|
||||||
|
"""@implements F-590 — liest die ``agenten``-Sektion aus mcp_tokens.json.
|
||||||
|
|
||||||
|
Liefert {} wenn die Datei fehlt oder unlesbar/korrupt ist (kein Crash —
|
||||||
|
der Aufrufer faellt dann auf die config.yaml-``auth_keys`` zurueck).
|
||||||
|
"""
|
||||||
|
path = _mcp_tokens_path()
|
||||||
|
if path is None or not path.exists():
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with open(path, encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
except (OSError, ValueError, json.JSONDecodeError):
|
||||||
|
return {}
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return {}
|
||||||
|
agenten = data.get("agenten")
|
||||||
|
return agenten if isinstance(agenten, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_token_from_mcp_tokens(profile: str) -> Optional[str]:
|
||||||
|
"""@implements F-590 — loest den Bearer-Token aus mcp_tokens.json auf.
|
||||||
|
|
||||||
|
Exakter Match ``agenten[<profil>].token``, dann case-insensitiver Match
|
||||||
|
(P-194: Profil-/Agent-Namen sind case-inkonsistent). Liefert None wenn
|
||||||
|
das Profil nicht in mcp_tokens.json steht (der Aufrufer faellt dann auf
|
||||||
|
die config.yaml-``auth_keys`` zurueck).
|
||||||
|
"""
|
||||||
|
tokens = load_mcp_tokens()
|
||||||
|
if not tokens:
|
||||||
|
return None
|
||||||
|
entry = tokens.get(profile)
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
lower = (profile or "").strip().lower()
|
||||||
|
for key, val in tokens.items():
|
||||||
|
if (key or "").strip().lower() == lower and isinstance(val, dict):
|
||||||
|
entry = val
|
||||||
|
break
|
||||||
|
if isinstance(entry, dict):
|
||||||
|
token = entry.get("token")
|
||||||
|
if token:
|
||||||
|
return str(token).strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _base_config_path() -> Optional[Path]:
|
||||||
|
"""Pfad zur Basis-Config (~/.hermes/config.yaml bzw. HERMES_HOME-Basis).
|
||||||
|
|
||||||
|
F526: Wenn HERMES_HOME auf das BASIS-Verzeichnis (~/.hermes) zeigt (CLI-
|
||||||
|
Kontext) und das Profil als 'default' aufgeloest wurde, liegt der
|
||||||
|
profilspezifische Token moeglicherweise in einer ANDEREN Profile-Config
|
||||||
|
(z.B. ~/.hermes/profiles/rainer/config.yaml). Diese Funktion liefert den
|
||||||
|
Basis-Pfad fuer den Fallback in resolve_token().
|
||||||
|
"""
|
||||||
|
home = os.environ.get("HERMES_HOME")
|
||||||
|
if home:
|
||||||
|
base = Path(home)
|
||||||
|
# HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Basis ist der Parent
|
||||||
|
# (~/.hermes/profiles/<name> -> ~/.hermes).
|
||||||
|
if base.parent.name == "profiles":
|
||||||
|
return base.parent / "config.yaml"
|
||||||
|
# HERMES_HOME ist bereits die Basis.
|
||||||
|
return base / "config.yaml"
|
||||||
|
return Path.home() / ".hermes" / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def _profile_auth_keys(profile: str) -> dict:
|
||||||
|
"""Liest auth_keys aus der Profile-Config (fuer den Fallback-Lookup).
|
||||||
|
|
||||||
|
F526 Layer 1: Wenn die AKTUELLE Config kein auth_keys fuer das Profil hat,
|
||||||
|
prueft der Fallback, ob eine Profile-Config (~/.hermes/profiles/<profile>/
|
||||||
|
config.yaml) den Token traegt. Das ist der Fall bei 'HERMES_HOME=Basis +
|
||||||
|
profile!=default' (P-119/P-147-Luecke).
|
||||||
|
"""
|
||||||
|
path = _profile_config_path(profile)
|
||||||
|
if path is None or not path.exists():
|
||||||
|
return {}
|
||||||
|
data = _load_yaml(path)
|
||||||
|
section = data.get("pmdb_connector")
|
||||||
|
if not isinstance(section, dict):
|
||||||
|
return {}
|
||||||
|
auth_keys = section.get("auth_keys")
|
||||||
|
return auth_keys if isinstance(auth_keys, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_token(profile: str, config: dict) -> Optional[str]:
|
||||||
|
"""Waehlt den Bearer-Token fuer das Profil.
|
||||||
|
|
||||||
|
F590 (Token-Sync, Single Source of Truth): Die KANONISCHE Quelle ist
|
||||||
|
``mcp_tokens.json`` (agenten[<profil>].token). Nur bei Nicht-Fund greift
|
||||||
|
der config.yaml-Fallback (F526-Drei-Schichten, backward-compat):
|
||||||
|
|
||||||
|
1. mcp_tokens.json (kanonisch, F590)
|
||||||
|
2. auth_keys[<profile>] (profile-spezifisch in der AKTUELLEN Config)
|
||||||
|
3. auth_keys["default"] (Default der AKTUELLEN Config)
|
||||||
|
4. Basis-Config (~/.hermes/config.yaml) auth_keys[<profile>|default]
|
||||||
|
5. Profile-Config (~/.hermes/profiles/<profile>/config.yaml)
|
||||||
|
auth_keys[<profile>|default] — deckt 'HERMES_HOME=Basis + profile!=
|
||||||
|
default' ab (P-119/P-147-Luecke).
|
||||||
|
|
||||||
|
Liefert None, wenn kein Token gefunden wird (der Aufrufer meldet dann
|
||||||
|
strukturiert token_not_found_for_profile mit probierte_pfade).
|
||||||
|
"""
|
||||||
|
# 0. F590: kanonische Quelle mcp_tokens.json (beseitigt Token-Drift).
|
||||||
|
token = resolve_token_from_mcp_tokens(profile)
|
||||||
|
if token:
|
||||||
|
return token
|
||||||
|
|
||||||
|
auth_keys = config.get("auth_keys")
|
||||||
|
if not isinstance(auth_keys, dict):
|
||||||
|
auth_keys = {}
|
||||||
|
|
||||||
|
# 1. profile-spezifisch in der aktuellen Config.
|
||||||
|
token = auth_keys.get(profile)
|
||||||
|
if token:
|
||||||
|
return str(token).strip()
|
||||||
|
|
||||||
|
# 2. profile-spezifisch in der PROFILE-Config (HERMES_HOME=Basis + profile
|
||||||
|
# != default, P-119/P-147-Luecke). VOR dem 'default'-Fallback, damit bei
|
||||||
|
# profile='rainer' + Basis-Config ohne 'rainer'-Key der richtige Token
|
||||||
|
# aus ~/.hermes/profiles/rainer/config.yaml gewinnt (statt faelschlich
|
||||||
|
# den 'default'-Token eines ANDEREN Agenten zu laden).
|
||||||
|
if profile != "default":
|
||||||
|
prof_keys = _profile_auth_keys(profile)
|
||||||
|
if prof_keys.get(profile):
|
||||||
|
return str(prof_keys[profile]).strip()
|
||||||
|
|
||||||
|
# 3. default der aktuellen Config.
|
||||||
|
token = auth_keys.get("default")
|
||||||
|
if token:
|
||||||
|
return str(token).strip()
|
||||||
|
|
||||||
|
# 4. Basis-Config (auth_keys[<profile>|default]).
|
||||||
|
base_path = _base_config_path()
|
||||||
|
if base_path is not None and base_path.exists():
|
||||||
|
base_cfg = _load_yaml(base_path)
|
||||||
|
base_section = base_cfg.get("pmdb_connector")
|
||||||
|
if isinstance(base_section, dict):
|
||||||
|
base_keys = base_section.get("auth_keys")
|
||||||
|
if isinstance(base_keys, dict):
|
||||||
|
token = base_keys.get(profile) or base_keys.get("default")
|
||||||
|
if token:
|
||||||
|
return str(token).strip()
|
||||||
|
|
||||||
|
# 5. Profile-Config (auth_keys[<profile>|default]).
|
||||||
|
prof_keys = _profile_auth_keys(profile)
|
||||||
|
if prof_keys:
|
||||||
|
token = prof_keys.get(profile) or prof_keys.get("default")
|
||||||
|
if token:
|
||||||
|
return str(token).strip()
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def probierte_pfade(profile: str, config: dict) -> list[str]:
|
||||||
|
"""Liste der probierten Token-Pfade (fuer die strukturierte Diagnose).
|
||||||
|
|
||||||
|
F590: mcp_tokens.json steht an ERSTER Stelle (kanonische Quelle), danach
|
||||||
|
die config.yaml-Pfade (Fallback).
|
||||||
|
"""
|
||||||
|
pfade = []
|
||||||
|
mcp = _mcp_tokens_path()
|
||||||
|
if mcp is not None:
|
||||||
|
pfade.append(str(mcp))
|
||||||
|
path = _profile_config_path(profile)
|
||||||
|
if path is not None:
|
||||||
|
pfade.append(str(path))
|
||||||
|
base = _base_config_path()
|
||||||
|
if base is not None:
|
||||||
|
pfade.append(str(base))
|
||||||
|
return pfade
|
||||||
|
|
||||||
|
|
||||||
|
def token_prefix(token: str) -> str:
|
||||||
|
"""Maskierter Token-Prefix fuer Logs (P-191: nie Klartext loggen)."""
|
||||||
|
if not token:
|
||||||
|
return "<none>"
|
||||||
|
parts = token.split("_")
|
||||||
|
if len(parts) >= 2 and parts[0] == "mcp":
|
||||||
|
return f"mcp_{parts[1]}_***"
|
||||||
|
return token[:8] + "***"
|
||||||
|
|
||||||
|
|
||||||
|
def manager_profiles(config: dict) -> list:
|
||||||
|
"""Liste der Manager-Profile (Defense-in-Depth fuer Manager-only-Tools)."""
|
||||||
|
mp = config.get("manager_profiles")
|
||||||
|
if isinstance(mp, list):
|
||||||
|
return [str(x).strip().lower() for x in mp if x]
|
||||||
|
return ["bernd", "andreas"]
|
||||||
|
|
||||||
|
|
||||||
|
def base_url(config: dict) -> str:
|
||||||
|
url = config.get("base_url")
|
||||||
|
return str(url).rstrip("/") if url else DEFAULT_BASE_URL
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F-621: SSE-Task-Dispatch-Stream-Konfiguration (opt-in, Stufe 1 Default aus)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
DEFAULT_STREAM_BASE_URL = "http://192.168.180.49:8099"
|
||||||
|
|
||||||
|
# F-719: Interne Basis-URL fuer Anlagen-Endpunkte (gleiche IPv4 wie Stream).
|
||||||
|
DEFAULT_INTERNAL_BASE_URL = "http://192.168.180.49:8099"
|
||||||
|
|
||||||
|
|
||||||
|
def stream_enabled(config: dict) -> bool:
|
||||||
|
"""F-621: SSE-Stream-Listener aktivieren (opt-in).
|
||||||
|
|
||||||
|
Stufe 1 Default ist AUS (``False``) — das Polling bleibt das
|
||||||
|
Sicherheitsnetz. Erst Stufe 2 (persistente Verbindung + Cron-Fallback)
|
||||||
|
schaltet auf True als Default um (F-621 Architektur, 3-Stufen-Migration).
|
||||||
|
"""
|
||||||
|
v = config.get("stream_enabled")
|
||||||
|
if isinstance(v, bool):
|
||||||
|
return v
|
||||||
|
if isinstance(v, str):
|
||||||
|
return v.strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def stream_base_url(config: dict) -> str:
|
||||||
|
"""F-621: Stream-Basis-URL (intern 192.168.180.49:8099).
|
||||||
|
|
||||||
|
Pitfall (F-621): Der Openresty-Proxy (pmdb.myowntools.org) blockt
|
||||||
|
Bearer-Stream mit 401 — der Stream MUSS intern via 192.168.180.49:8099
|
||||||
|
laufen. Config kann ``stream_url``/``stream_base_url`` ueberschreiben.
|
||||||
|
"""
|
||||||
|
url = config.get("stream_url") or config.get("stream_base_url")
|
||||||
|
if url:
|
||||||
|
return str(url).rstrip("/")
|
||||||
|
return DEFAULT_STREAM_BASE_URL
|
||||||
|
|
||||||
|
|
||||||
|
def internal_base_url(config: dict) -> str:
|
||||||
|
"""F-719: Interne Basis-URL fuer Anlagen-Endpunkte (192.168.180.49:8099).
|
||||||
|
|
||||||
|
Upload/Liste/Download von Task-Anlagen laufen IMMER ueber die direkte
|
||||||
|
IPv4 — der Openresty-Proxy blockt Bearer-Tokens (401, P-NEW-F563-PMDB-AUTH).
|
||||||
|
Config kann ``internal_base_url`` (oder ``attachment_base_url``) setzen;
|
||||||
|
Default ist die interne IPv4.
|
||||||
|
"""
|
||||||
|
url = config.get("internal_base_url") or config.get("attachment_base_url")
|
||||||
|
if url:
|
||||||
|
return str(url).rstrip("/")
|
||||||
|
return DEFAULT_INTERNAL_BASE_URL
|
||||||
Executable
+342
@@ -0,0 +1,342 @@
|
|||||||
|
#!/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/<agent>/plugins/pmdb_connector/ und richtet die
|
||||||
|
# Token-Konfiguration ein:
|
||||||
|
#
|
||||||
|
# 1. mcp_tokens.json (KANONISCHE Quelle, F590) -> agenten.<agent>.token
|
||||||
|
# 2. config.yaml (Fallback, F526) -> pmdb_connector.auth_keys.<agent>
|
||||||
|
#
|
||||||
|
# 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 <name> Agent-/Profil-Name (sonst interaktiv)
|
||||||
|
--token <token> PMDB-Bearer-Token (sonst interaktiv, verdeckte Eingabe)
|
||||||
|
--api-url <url> PMDB MCP base_url (Default: https://pmdb.myowntools.org/mcp)
|
||||||
|
--source <dir> 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.<agent>.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'."
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
name: pmdb_connector
|
||||||
|
version: 0.1.0
|
||||||
|
description: >
|
||||||
|
PMDB Connector Plugin — profil-aware Anbindung an den PMDB MCP-Server
|
||||||
|
(https://pmdb.myowntools.org/mcp). Liest das aktive Hermes-Profil, waehlt
|
||||||
|
den zugehoerigen Bearer-Token aus der Profile-Config, bietet pmdb_*-Tools
|
||||||
|
fuer Auftragsabwicklung (get_tasks/accept/decline/submit, get_mask, search,
|
||||||
|
get_baustein, set_bit [Manager-only], create_task [Manager-only],
|
||||||
|
manager_dashboard [Manager-only]) sowie F-719 Task-Anlagen
|
||||||
|
(get_anlagen/download_anlage/upload_ergebnis_anlage/upload_anlage).
|
||||||
|
kind: backend
|
||||||
|
author: Miguel (fuer Bernd/Andreas/Rainer/Finn/Don)
|
||||||
|
provides_tools:
|
||||||
|
- pmdb_get_tasks
|
||||||
|
- pmdb_get_submitted_tasks
|
||||||
|
- pmdb_manager_dashboard
|
||||||
|
- pmdb_accept_task
|
||||||
|
- pmdb_decline_task
|
||||||
|
- pmdb_submit_task
|
||||||
|
- pmdb_get_mask
|
||||||
|
- pmdb_search
|
||||||
|
- pmdb_get_baustein
|
||||||
|
- pmdb_set_bit
|
||||||
|
- pmdb_create_task
|
||||||
|
- pmdb_return_for_revision
|
||||||
|
- pmdb_manager_decision
|
||||||
|
- pmdb_get_anlagen
|
||||||
|
- pmdb_download_anlage
|
||||||
|
- pmdb_upload_ergebnis_anlage
|
||||||
|
- pmdb_upload_anlage
|
||||||
|
# requires_env: NICHT — Token kommt aus profile-config, nicht aus Env
|
||||||
|
# (P-191-Schutz: Env-Vars sind in `hermes config` sichtbar, Profile-config
|
||||||
|
# ist im profile-Home-Verzeichnis).
|
||||||
|
optional_env:
|
||||||
|
- name: PMD_MCP_BASE_URL
|
||||||
|
description: "PMDB MCP-Server URL (default: https://pmdb.myowntools.org/mcp)"
|
||||||
|
prompt: "PMDB MCP Base-URL"
|
||||||
|
password: false
|
||||||
@@ -0,0 +1,643 @@
|
|||||||
|
"""F454 PMDB Connector Plugin — Tests (Phase 1 + Phase 2).
|
||||||
|
|
||||||
|
@implements: [F454]
|
||||||
|
|
||||||
|
Zwei Test-Ebenen:
|
||||||
|
1. Unit-Tests (kein Netzwerk): client.py Error-Mapping, config.py
|
||||||
|
Token-Aufloesung, __init__.py Tool-Registrierung (Mock-ctx).
|
||||||
|
2. Integration-Tests (gegen Live-PMDB auf .49, via Env PMDB_TEST_TOKEN
|
||||||
|
aktiviert): echte HTTP-Calls gegen /mcp/api/*.
|
||||||
|
|
||||||
|
Die Unit-Tests laufen ueberall (stdlib-only). Die Integration-Tests sind
|
||||||
|
standardmaessig SKIPPED (kein Token) und werden auf .49 mit einem echten
|
||||||
|
Test-Token aktiviert.
|
||||||
|
|
||||||
|
Test-Daten-Hygiene (P-191): Integration-Tests legen eigene Credentials/Tasks
|
||||||
|
an und raeumen sie auf — kein Seed-Drift in der Produktions-DB.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
|
||||||
|
os.path.dirname(os.path.abspath(__file__)))))) # -> Repo-Root (damit `plugin` importierbar)
|
||||||
|
|
||||||
|
from plugin.pmdb_connector import client as pmdb_client # noqa: E402
|
||||||
|
from plugin.pmdb_connector import config as pmdb_config # noqa: E402
|
||||||
|
import plugin.pmdb_connector as pmdb_plugin # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F590: Isolation der kanonischen Token-Quelle mcp_tokens.json
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _isolate_mcp_tokens(monkeypatch, tmp_path):
|
||||||
|
"""Isoliert mcp_tokens.json von der echten Produktions-Datei.
|
||||||
|
|
||||||
|
F590: ``resolve_token()`` liest jetzt ZUERST mcp_tokens.json. Tests, die
|
||||||
|
den config.yaml-Fallback (F526) testen, muessen die kanonische Quelle
|
||||||
|
isolieren — sonst liefert die echte ``~/.hermes/mcp_tokens.json`` den
|
||||||
|
echten Produktions-Token und die Assertions brechen (Token-Drift in den
|
||||||
|
Tests). Der Pfad zeigt auf eine nicht-existente Temp-Datei -> leerer
|
||||||
|
Lookup -> config.yaml-Fallback greift.
|
||||||
|
"""
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Unit: client.py Error-Mapping (kein Netzwerk)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _FakeResponse:
|
||||||
|
def __init__(self, status, body):
|
||||||
|
self.status = status
|
||||||
|
self._body = body
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._body.encode("utf-8")
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeURLopen:
|
||||||
|
"""Ersetzt urllib.request.urlopen fuer deterministische Tests."""
|
||||||
|
|
||||||
|
def __init__(self, status=200, body=None, raise_http=None):
|
||||||
|
self.status = status
|
||||||
|
self.body = body if body is not None else {}
|
||||||
|
self.raise_http = raise_http
|
||||||
|
|
||||||
|
def __call__(self, req, timeout=None):
|
||||||
|
if self.raise_http is not None:
|
||||||
|
raise self.raise_http
|
||||||
|
return _FakeResponse(self.status, json.dumps(self.body))
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _client(monkeypatch, status=200, body=None, raise_http=None):
|
||||||
|
fake = _FakeURLopen(status=status, body=body, raise_http=raise_http)
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", fake)
|
||||||
|
return pmdb_client.PMDBClient(token="mcp_test_abc123"), fake
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_get_tasks_success(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 200, {"tasks": [], "count": 0,
|
||||||
|
"blocked_count": 0, "blocked": []})
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["success"] is True
|
||||||
|
assert r["data"]["count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_401_maps_auth_invalid(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 401, {"success": False, "error": "Token weg"})
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["success"] is False
|
||||||
|
assert r["error_code"] == "auth_invalid"
|
||||||
|
assert r["action"] == "renew_token"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_403_maps_forbidden(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 403, {"success": False, "error": "kein Manager"})
|
||||||
|
r = c.set_bit(1, 6)
|
||||||
|
assert r["error_code"] == "forbidden"
|
||||||
|
assert r["action"] == "contact_manager"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_404_maps_not_found(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 404, {"success": False, "error": "Task weg"})
|
||||||
|
r = c.accept_task(999)
|
||||||
|
assert r["error_code"] == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_409_maps_state_conflict(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 409, {"success": False, "error": "nicht pitched"})
|
||||||
|
r = c.accept_task(1)
|
||||||
|
assert r["error_code"] == "state_conflict"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_429_maps_rate_limited(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 429, {"success": False, "error": "zu viel"})
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["error_code"] == "rate_limited"
|
||||||
|
assert r["retry_after_seconds"] == 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_500_maps_pmdb_unavailable(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, 500, {"success": False, "error": "kaputt"})
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["error_code"] == "pmdb_unavailable"
|
||||||
|
assert r["action"] == "fallback_to_terminal"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_network_error(monkeypatch):
|
||||||
|
c, _ = _client(monkeypatch, raise_http=urllib.error.URLError("conn refused"))
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["error_code"] == "network_error"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_accept_task_path(monkeypatch):
|
||||||
|
c, fake = _client(monkeypatch, 200, {"success": True, "status": "accepted"})
|
||||||
|
r = c.accept_task(42)
|
||||||
|
assert r["success"] is True
|
||||||
|
# Pfad-Verifikation: der Request ging an /mcp/api/tasks/42/accept
|
||||||
|
req = fake.last_req if hasattr(fake, "last_req") else None
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_submit_task_sends_payload(monkeypatch):
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class _Cap:
|
||||||
|
def __call__(self, req, timeout=None):
|
||||||
|
captured["url"] = req.full_url
|
||||||
|
captured["data"] = req.data
|
||||||
|
return _FakeResponse(200, json.dumps({"success": True}))
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
c.submit_task(7, {"returnvalue": "ok"})
|
||||||
|
assert captured["url"].endswith("/mcp/api/tasks/7/submit")
|
||||||
|
sent = json.loads(captured["data"].decode("utf-8"))
|
||||||
|
assert sent["payload"] == {"returnvalue": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Unit: config.py Token-Aufloesung
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_resolve_token_profile_specific():
|
||||||
|
cfg = {"auth_keys": {"miguel": "mcp_miguel_x", "default": "mcp_bernd_y"}}
|
||||||
|
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_falls_back_to_default():
|
||||||
|
cfg = {"auth_keys": {"default": "mcp_bernd_y"}}
|
||||||
|
assert pmdb_config.resolve_token("rainer", cfg) == "mcp_bernd_y"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_missing_returns_none(monkeypatch):
|
||||||
|
# F526: Fallback-Kette liest Basis-/Profile-Config vom Filesystem.
|
||||||
|
# Für den deterministischen None-Fall die Filesystem-Lookups mocken.
|
||||||
|
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||||
|
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||||
|
assert pmdb_config.resolve_token("rainer", {}) is None
|
||||||
|
assert pmdb_config.resolve_token("rainer", {"auth_keys": {}}) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_prefix_masks_secret():
|
||||||
|
assert pmdb_config.token_prefix("mcp_miguel_geheim123") == "mcp_miguel_***"
|
||||||
|
assert "geheim123" not in pmdb_config.token_prefix("mcp_miguel_geheim123")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F590: Token-Sync aus mcp_tokens.json (kanonische Quelle)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _write_mcp_tokens(tmp_path, agenten):
|
||||||
|
path = tmp_path / "mcp_tokens.json"
|
||||||
|
path.write_text(json.dumps({"agenten": agenten}), encoding="utf-8")
|
||||||
|
return str(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_tokens_path_default(monkeypatch):
|
||||||
|
"""Default-Pfad: ~/.hermes/mcp_tokens.json (ohne HERMES_HOME)."""
|
||||||
|
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||||
|
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||||
|
assert str(pmdb_config._mcp_tokens_path()).endswith("/.hermes/mcp_tokens.json")
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_tokens_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||||
|
"""HERMES_HOME=Profil-Verzeichnis -> Basis-Parent/mcp_tokens.json."""
|
||||||
|
prof = tmp_path / "profiles" / "miguel"
|
||||||
|
prof.mkdir(parents=True)
|
||||||
|
monkeypatch.delenv("HERMES_MCP_TOKENS", raising=False)
|
||||||
|
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||||
|
assert pmdb_config._mcp_tokens_path() == tmp_path / "mcp_tokens.json"
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_tokens_path_env_override(monkeypatch, tmp_path):
|
||||||
|
"""Env HERMES_MCP_TOKENS überschreibt den Default-Pfad."""
|
||||||
|
custom = tmp_path / "custom-tokens.json"
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", str(custom))
|
||||||
|
assert pmdb_config._mcp_tokens_path() == custom
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_mcp_tokens_missing_returns_empty(monkeypatch, tmp_path):
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||||
|
assert pmdb_config.load_mcp_tokens() == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_mcp_tokens_reads_agenten(monkeypatch, tmp_path):
|
||||||
|
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||||
|
assert pmdb_config.load_mcp_tokens() == {"miguel": {"token": "mcp_miguel_x"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_from_mcp_tokens_exact(monkeypatch, tmp_path):
|
||||||
|
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||||
|
assert pmdb_config.resolve_token_from_mcp_tokens("miguel") == "mcp_miguel_x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_from_mcp_tokens_case_insensitive(monkeypatch, tmp_path):
|
||||||
|
"""P-194: Profil 'Miguel' (gross) matcht agenten['miguel'] (klein)."""
|
||||||
|
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||||
|
assert pmdb_config.resolve_token_from_mcp_tokens("Miguel") == "mcp_miguel_x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_from_mcp_tokens_missing_returns_none(monkeypatch, tmp_path):
|
||||||
|
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_x"}})
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||||
|
assert pmdb_config.resolve_token_from_mcp_tokens("rainer") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_prefers_mcp_tokens_over_config(monkeypatch, tmp_path):
|
||||||
|
"""F590: mcp_tokens.json gewinnt gegen config.yaml auth_keys."""
|
||||||
|
path = _write_mcp_tokens(tmp_path, {"miguel": {"token": "mcp_miguel_KANONISCH"}})
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", path)
|
||||||
|
cfg = {"auth_keys": {"miguel": "mcp_miguel_stale"}}
|
||||||
|
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_KANONISCH"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_token_falls_back_to_config_when_mcp_tokens_missing(
|
||||||
|
monkeypatch, tmp_path):
|
||||||
|
"""Ohne mcp_tokens.json-Eintrag greift der config.yaml-Fallback (F526)."""
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "fehlt.json"))
|
||||||
|
cfg = {"auth_keys": {"miguel": "mcp_miguel_x"}}
|
||||||
|
assert pmdb_config.resolve_token("miguel", cfg) == "mcp_miguel_x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_probierte_pfade_includes_mcp_tokens(monkeypatch, tmp_path):
|
||||||
|
"""F590: mcp_tokens.json steht an ERSTER Stelle in probierte_pfade."""
|
||||||
|
monkeypatch.setenv("HERMES_MCP_TOKENS", str(tmp_path / "mcp_tokens.json"))
|
||||||
|
pfade = pmdb_config.probierte_pfade("miguel", {})
|
||||||
|
assert any(p.endswith("mcp_tokens.json") for p in pfade)
|
||||||
|
assert pfade[0].endswith("mcp_tokens.json")
|
||||||
|
|
||||||
|
|
||||||
|
def test_manager_profiles_default():
|
||||||
|
assert "bernd" in pmdb_config.manager_profiles({})
|
||||||
|
assert "andreas" in pmdb_config.manager_profiles({})
|
||||||
|
|
||||||
|
|
||||||
|
def test_manager_profiles_custom():
|
||||||
|
cfg = {"manager_profiles": ["bernd"]}
|
||||||
|
assert pmdb_config.manager_profiles(cfg) == ["bernd"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_base_url_default():
|
||||||
|
assert pmdb_config.base_url({}) == "https://pmdb.myowntools.org/mcp"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Unit: config.py HERMES_HOME-Pfad-Aufloesung (P0-4 / P-119 / P-147)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_profile_config_path_hermes_home_is_profile(monkeypatch, tmp_path):
|
||||||
|
"""HERMES_HOME zeigt auf ein Profil-Verzeichnis -> Config liegt DIREKT dort.
|
||||||
|
|
||||||
|
P0-4: HERMES_HOME=/home/bernd/.hermes/profiles/miguel. Die Config liegt
|
||||||
|
unter HERMES_HOME/config.yaml. Es darf NICHT erneut `profiles/miguel`
|
||||||
|
angehaengt werden (sonst Dopplung -> token_missing).
|
||||||
|
"""
|
||||||
|
prof = tmp_path / "profiles" / "miguel"
|
||||||
|
prof.mkdir(parents=True)
|
||||||
|
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||||
|
path = pmdb_config._profile_config_path("miguel")
|
||||||
|
assert path == prof / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_profile_config_path_hermes_home_is_base(monkeypatch, tmp_path):
|
||||||
|
"""HERMES_HOME zeigt auf das Basis-Verzeichnis -> profiles/<name>/config.yaml."""
|
||||||
|
base = tmp_path / ".hermes"
|
||||||
|
base.mkdir(parents=True)
|
||||||
|
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||||
|
path = pmdb_config._profile_config_path("miguel")
|
||||||
|
assert path == base / "profiles" / "miguel" / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_profile_config_path_default_profile(monkeypatch, tmp_path):
|
||||||
|
"""default-Profil -> <base>/config.yaml (kein profiles/-Praefix)."""
|
||||||
|
base = tmp_path / ".hermes"
|
||||||
|
base.mkdir(parents=True)
|
||||||
|
monkeypatch.setenv("HERMES_HOME", str(base))
|
||||||
|
path = pmdb_config._profile_config_path("default")
|
||||||
|
assert path == base / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_pmdb_config_from_profile_hermes_home(monkeypatch, tmp_path):
|
||||||
|
"""End-to-End: HERMES_HOME=Profil-Verzeichnis -> load_pmdb_config findet
|
||||||
|
die pmdb_connector-Sektion in HERMES_HOME/config.yaml (P0-4-Fix)."""
|
||||||
|
prof = tmp_path / "profiles" / "miguel"
|
||||||
|
prof.mkdir(parents=True)
|
||||||
|
(prof / "config.yaml").write_text(
|
||||||
|
"pmdb_connector:\n auth_keys:\n miguel: mcp_miguel_x\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
monkeypatch.setenv("HERMES_HOME", str(prof))
|
||||||
|
cfg = pmdb_config.load_pmdb_config("miguel")
|
||||||
|
assert cfg.get("auth_keys", {}).get("miguel") == "mcp_miguel_x"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Unit: __init__.py Tool-Registrierung (Mock-ctx)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _MockCtx:
|
||||||
|
def __init__(self):
|
||||||
|
self.registered = {}
|
||||||
|
|
||||||
|
def register_tool(self, name, toolset, schema, handler, **kw):
|
||||||
|
self.registered[name] = {"toolset": toolset, "schema": schema,
|
||||||
|
"handler": handler, **kw}
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_all_tools(monkeypatch):
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "miguel")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||||
|
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"}})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||||
|
for name in pmdb_plugin._TOOLS:
|
||||||
|
assert name in ctx.registered
|
||||||
|
assert ctx.registered[name]["toolset"] == "pmdb"
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_missing_token_deactivates(monkeypatch):
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "miguel")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config", lambda p: {})
|
||||||
|
# F526: Filesystem-Fallback isolieren, damit kein realer Token geladen wird.
|
||||||
|
monkeypatch.setattr(pmdb_config, "_base_config_path", lambda: None)
|
||||||
|
monkeypatch.setattr(pmdb_config, "_profile_auth_keys", lambda p: {})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
# Alle Tools registriert, aber Handler liefern token_not_found_for_profile.
|
||||||
|
assert len(ctx.registered) == len(pmdb_plugin._TOOLS)
|
||||||
|
r = json.loads(ctx.registered["pmdb_get_tasks"]["handler"]({}))
|
||||||
|
assert r["error_code"] == "token_not_found_for_profile"
|
||||||
|
assert "probierte_pfade" in r
|
||||||
|
|
||||||
|
|
||||||
|
def test_manager_only_guard_blocks_non_manager(monkeypatch):
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "miguel")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||||
|
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||||
|
"manager_profiles": ["bernd"]})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||||
|
assert r["error_code"] == "forbidden"
|
||||||
|
assert r["action"] == "contact_manager"
|
||||||
|
|
||||||
|
|
||||||
|
def test_manager_only_guard_blocks_get_submitted_tasks(monkeypatch):
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "miguel")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||||
|
lambda p: {"auth_keys": {"miguel": "mcp_miguel_x"},
|
||||||
|
"manager_profiles": ["bernd"]})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||||
|
assert r["error_code"] == "forbidden"
|
||||||
|
assert r["action"] == "contact_manager"
|
||||||
|
|
||||||
|
def test_manager_guard_case_insensitive(monkeypatch):
|
||||||
|
# P-194: Profil-Name case-inkonsistent -> Vergleich muss case-insensitive sein.
|
||||||
|
# Profil "Bernd" (gross) vs. manager_profiles ["bernd"] (klein) -> darf NICHT
|
||||||
|
# forbidden liefern (Guard muss case-insensitive matchen).
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "Bernd")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||||
|
lambda p: {"auth_keys": {"Bernd": "mcp_bernd_x"},
|
||||||
|
"manager_profiles": ["bernd"]})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
# Manager-Guard passiert (case-insensitive) -> Handler ruft client (Netzwerk).
|
||||||
|
r = json.loads(ctx.registered["pmdb_get_submitted_tasks"]["handler"]({}))
|
||||||
|
assert r["error_code"] != "forbidden"
|
||||||
|
|
||||||
|
def test_manager_only_allows_manager(monkeypatch):
|
||||||
|
monkeypatch.setattr(pmdb_config, "get_active_profile_name",
|
||||||
|
lambda: "bernd")
|
||||||
|
monkeypatch.setattr(pmdb_config, "load_pmdb_config",
|
||||||
|
lambda p: {"auth_keys": {"bernd": "mcp_bernd_x"},
|
||||||
|
"manager_profiles": ["bernd"]})
|
||||||
|
ctx = _MockCtx()
|
||||||
|
pmdb_plugin.register(ctx)
|
||||||
|
# Manager-Guard passiert -> Handler ruft client.set_bit (Netzwerk).
|
||||||
|
# Ohne Netzwerk -> network_error, NICHT forbidden.
|
||||||
|
r = json.loads(ctx.registered["pmdb_set_bit"]["handler"]({"feature_id": 1, "bit_nr": 6}))
|
||||||
|
assert r["error_code"] != "forbidden"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# F-719: Task-Anlagen (client.py — get_anlagen/download/upload)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _FakeBinaryResponse:
|
||||||
|
"""Response mit Binär-Body + Headers (fuer download_anlage)."""
|
||||||
|
|
||||||
|
def __init__(self, data: bytes, headers: dict = None):
|
||||||
|
self._data = data
|
||||||
|
self.headers = headers or {}
|
||||||
|
self.status = 200
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._data
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_get_anlagen_uses_internal_base(monkeypatch):
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class _Cap:
|
||||||
|
def __call__(self, req, timeout=None):
|
||||||
|
captured["url"] = req.full_url
|
||||||
|
return _FakeResponse(200, json.dumps({"task_id": 7, "anlagen": []}))
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
r = c.get_anlagen(7)
|
||||||
|
assert r["success"] is True
|
||||||
|
# Anlagen laufen IMMER ueber die interne IPv4, nicht ueber den Proxy.
|
||||||
|
assert captured["url"].startswith("http://192.168.180.49:8099")
|
||||||
|
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_download_anlage_returns_bytes(monkeypatch):
|
||||||
|
payload = b"\x89PNG\r\n\x1a\nBINAERDATEN"
|
||||||
|
disp = "attachment; filename*=UTF-8''bild.png"
|
||||||
|
|
||||||
|
class _Resp:
|
||||||
|
def __init__(self):
|
||||||
|
self.headers = {"Content-Type": "image/png",
|
||||||
|
"Content-Disposition": disp}
|
||||||
|
self.status = 200
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", lambda req, timeout=None: _Resp())
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
result = c.download_anlage(7, "abc-def")
|
||||||
|
assert isinstance(result, bytes), "Download muss Bytes liefern (kein JSON-Parsing)"
|
||||||
|
assert result == payload
|
||||||
|
assert c._last_download["content_type"] == "image/png"
|
||||||
|
assert c._last_download["filename"] == "bild.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_download_anlage_http_error_maps(monkeypatch):
|
||||||
|
class _Err(urllib.error.HTTPError):
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__("http://x", 404, "nicht gefunden", None, None)
|
||||||
|
self._body = json.dumps({"success": False, "error": "Anlage nicht gefunden"})
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._body.encode("utf-8")
|
||||||
|
|
||||||
|
def _raise(req, timeout=None):
|
||||||
|
raise _Err()
|
||||||
|
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _raise)
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
r = c.download_anlage(7, "fehlt")
|
||||||
|
assert isinstance(r, dict)
|
||||||
|
assert r["error_code"] == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_content_disposition():
|
||||||
|
assert pmdb_client._parse_content_disposition(
|
||||||
|
"attachment; filename*=UTF-8''bericht.pdf") == "bericht.pdf"
|
||||||
|
assert pmdb_client._parse_content_disposition(
|
||||||
|
'attachment; filename="alt.txt"') == "alt.txt"
|
||||||
|
assert pmdb_client._parse_content_disposition("") == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_multipart_upload_builds_body(tmp_path, monkeypatch):
|
||||||
|
f = tmp_path / "notiz.txt"
|
||||||
|
f.write_bytes(b"inhalt der datei\n")
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class _Cap:
|
||||||
|
def __call__(self, req, timeout=None):
|
||||||
|
captured["url"] = req.full_url
|
||||||
|
captured["data"] = req.data
|
||||||
|
captured["content_type"] = req.headers.get("Content-type") \
|
||||||
|
or req.headers.get("Content-Type")
|
||||||
|
return _FakeResponse(201, json.dumps(
|
||||||
|
{"success": True, "anlagen": [{"id": "u1", "name": "notiz.txt"}]}))
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
monkeypatch.setattr(pmdb_client.urllib.request, "urlopen", _Cap())
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
r = c.upload_anlage(7, str(f))
|
||||||
|
assert r["success"] is True
|
||||||
|
# Endpoint + interne IPv4.
|
||||||
|
assert captured["url"].startswith("http://192.168.180.49:8099")
|
||||||
|
assert captured["url"].endswith("/mcp/api/tasks/7/anlagen")
|
||||||
|
# Multipart-Header mit Boundary.
|
||||||
|
assert captured["content_type"].startswith("multipart/form-data; boundary=")
|
||||||
|
body = captured["data"]
|
||||||
|
assert b"name=\"datei\"" in body
|
||||||
|
assert b"filename=\"notiz.txt\"" in body
|
||||||
|
assert b"inhalt der datei" in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_multipart_upload_file_not_found(monkeypatch):
|
||||||
|
c = pmdb_client.PMDBClient(token="mcp_test_abc123")
|
||||||
|
r = c.upload_anlage(7, "/gibt/es/nicht.txt")
|
||||||
|
assert r["success"] is False
|
||||||
|
assert r["error_code"] == "file_not_found"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Integration (gegen Live-PMDB, via Env PMDB_TEST_TOKEN aktiviert)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
PMDB_TEST_TOKEN = os.environ.get("PMDB_TEST_TOKEN", "")
|
||||||
|
PMDB_TEST_BASE = os.environ.get("PMDB_TEST_BASE",
|
||||||
|
"https://pmdb.myowntools.org/mcp")
|
||||||
|
|
||||||
|
requires_live = pytest.mark.skipif(
|
||||||
|
not PMDB_TEST_TOKEN, reason="PMDB_TEST_TOKEN nicht gesetzt (Integration off)")
|
||||||
|
|
||||||
|
|
||||||
|
@requires_live
|
||||||
|
def test_live_get_tasks_authenticated():
|
||||||
|
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||||
|
r = c.get_tasks()
|
||||||
|
# Mit gueltigem Token: success ODER strukturierter Fehler (nie Exception).
|
||||||
|
assert "success" in r
|
||||||
|
if r["success"]:
|
||||||
|
assert "tasks" in r["data"]
|
||||||
|
assert "count" in r["data"]
|
||||||
|
assert "blocked_count" in r["data"]
|
||||||
|
|
||||||
|
|
||||||
|
@requires_live
|
||||||
|
def test_live_get_mask_404_or_ok():
|
||||||
|
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||||
|
r = c.get_mask("F454")
|
||||||
|
assert "success" in r
|
||||||
|
if r["success"]:
|
||||||
|
assert "bit_kette" in r["data"]
|
||||||
|
|
||||||
|
|
||||||
|
@requires_live
|
||||||
|
def test_live_search():
|
||||||
|
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE, token=PMDB_TEST_TOKEN)
|
||||||
|
r = c.search(feature="F454")
|
||||||
|
assert "success" in r
|
||||||
|
if r["success"]:
|
||||||
|
assert "setcard" in r["data"]
|
||||||
|
|
||||||
|
|
||||||
|
@requires_live
|
||||||
|
def test_live_invalid_token_401():
|
||||||
|
c = pmdb_client.PMDBClient(base_url=PMDB_TEST_BASE,
|
||||||
|
token="mcp_fake_invalidtoken123")
|
||||||
|
r = c.get_tasks()
|
||||||
|
assert r["success"] is False
|
||||||
|
assert r["error_code"] == "auth_invalid"
|
||||||
Reference in New Issue
Block a user