mirror of
https://github.com/db9979/sshtermy.git
synced 2026-12-06 04:34:08 +01:00
sshTermy als MCP-Server für KI-Clients (#88)
* Debug-Protokoll für Fehlerberichte, Barrierearm-Modus und Farbenblind-Themes - internal/debuglog: Ereignisse (SSH-Aufbau, Abbrüche, Updates, KI-Anfragen, Sync), Rotation 4 MiB - Schalter in Einstellungen, --debug, bereinigte Kopie (crash.Clean) nach Downloads - Barrierearm: keine Animationen, × für nicht erreichbar, Startanimation aus; geht mit dem Sync - Themes Farbenblind dunkel/hell (Okabe-Ito) - README, README.de, Webseite, Kurzreferenz Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Release-Signatur: Schlüssel tolerant lesen, klare Fehlermeldung, Abgleich mit UPDATE_PUBKEY Der Release-Lauf nach #81 brach mit „UPDATE_SIGNING_KEY fehlt oder ist ungültig“ ab. sshtermy-sign ignoriert jetzt Zeilenumbrüche, Leerzeichen, Anführungszeichen und die keygen-Überschrift, nennt bei Fehlern die gefundene Länge (nie den Schlüssel) und prüft, dass der private Schlüssel zu UPDATE_PUBKEY passt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Gesamtsicherung/Umzug und KI-Datenschutz - Gesamtsicherung: ganzer Datenordner als eine mit dem Master-Passwort verschlüsselte Datei (.sshtbak, Argon2id + AES-256-GCM in Blöcken); Einstellungen › Import / Export oder sshtermy backup / restore. Einspielen nach Rückfrage beim Neustart, der alte Ordner bleibt als <ordner>.vorher-<zeit> - KI-Datenschutz (Einstellungen › KI): alle Anbieter / nur lokale KI / KI aus, pro Verbindung per Tag ki-lokal / ki-aus (no-ai, ai-local); strengere Stufe gilt - „Letzte KI-Anfrage ansehen“: was zuletzt an welchen Host/welches Modell ging - Doku: README DE/EN, Webseite, Handout Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Audit-Protokoll und Herstellerprofile Juniper, MikroTik, Fortinet - internal/audit: fälschungssicheres Protokoll (HMAC-Kette mit Schlüssel aus dem Store, signierter Kopf gegen abgeschnittene Enden), Monatsdateien im Datenordner - Einstellungen › Sicherheit: Audit-Protokoll an/aus (nur dieser Rechner), prüfen und speichern; erfasst Verbindungen, Befehle (Agent/Broadcast markiert, private nur als „(privat)“), Übertragungen, Config-Sicherungen, Verbindungen, Master-Passwort, Gesamtsicherungen, KI-Anfragen (Host/Modell) - Host-Übersicht und Config-Sicherung für Juniper Junos, MikroTik RouterOS, FortiGate: eigene Befehle und Parser, Prompts „[admin@MikroTik] >“ / „FGT #“, Blättern „---(more)---“ / „-- [Q quit|D dump|down]“; geplante Sicherung nimmt den passenden Befehl - Schnellbefehle Juniper und FortiGate; „nur lesen“ kennt get …, /… print, /export - Doku: README DE/EN, Webseite, Handout Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * Verbindungen überstehen Ruhezustand und Netzwechsel - internal/netwatch: Ruhezustand (Wanduhr läuft der monotonen Uhr davon oder der Takt kommt viel zu spät) und Netzwechsel (andere eigene Adressen) erkennen - danach prüft sshTermy jede SSH-Leitung sofort (sshx.Client.Check, 4 s) statt bis zu 30 s auf den Keepalive zu warten; wartende Neuverbindungen starten gleich neu - ohne Netz zählen Neuverbindungsversuche nicht, die Sitzung wartet auf eine Adresse - Doku: README DE/EN, Webseite Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz * sshTermy als MCP-Server für KI-Clients - sshtermy mcp: MCP-Server (JSON-RPC über stdin/stdout) als Brücke zur laufenden, entsperrten App (internal/mcp, lokaler Socket mit Token, internal/localsock auch für das eigene Fenster) - Werkzeuge list_connections, list_tabs, read_tab, run_command (eigene unsichtbare Sitzung über broadcast; Netzwerkgeräte per Shell) - Einstellungen › Sicherheit › MCP-Zugriff: aus / nur lesen / mit Rückfrage; nicht lesende oder gefährliche Befehle nur nach j im Fenster - KI-Datenschutz gilt: Tags ki-aus/ki-lokal und „KI aus“ sperren; Geheimnisse in Ausgaben entfernt; jeder Aufruf im Audit-Protokoll - Doku: README DE/EN (Einrichtung Claude Code/Desktop), Webseite, Handout Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUifSEzjZLFvqVjcUxz --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
0407b1f0bc
commit
cf170a1392
23 files changed
+1032
-7
No files matched your search
@@ -127,6 +127,7 @@ sshTermy ist eine schlanke Terminal-Anwendung (TUI, eine einzige Datei, ~9 MB, k
|
||||
die Wahl wird gespeichert und mit dem Sync übernommen. Beim ersten Start richtet sich sshTermy nach der Systemsprache
|
||||
- **Barrierearm** (Einstellungen › Aussehen): keine Animationen, Formen statt nur Farben (× für „nicht erreichbar“);
|
||||
dazu die **Farbenblind-Themes** (Blau/Gelb/Orange statt Grün/Rot, Okabe-Ito-Farben)
|
||||
- **MCP-Server** (`sshtermy mcp`): Claude und andere KI-Clients können Verbindungen auflisten und lesende Befehle ausführen, alles andere erst nach deiner Bestätigung in sshTermy
|
||||
- **Audit-Protokoll** (Einstellungen › Sicherheit): wer hat wann auf welchem Host was getan: Verbindungen, Befehle
|
||||
(auch aus Agent-Modus und Broadcast), Dateiübertragungen, Config-Sicherungen, geänderte Verbindungen,
|
||||
Master-Passwort, Gesamtsicherungen und KI-Anfragen (nur Host/Modell). Jede Zeile ist verkettet und mit einem
|
||||
@@ -199,6 +200,7 @@ sshtermy --no-intro # ohne Startanimation (dauerhaft: Palette „Startanimatio
|
||||
sshtermy --debug # Debug-Protokoll für diesen Start (debug.log im Konfigurationsordner)
|
||||
sshtermy backup [datei] # Gesamtsicherung aller Daten (fragt das Master-Passwort)
|
||||
sshtermy restore <datei> # Gesamtsicherung einspielen (ersetzt alles, alter Ordner bleibt)
|
||||
sshtermy mcp # MCP-Server für KI-Clients (stdin/stdout), siehe „sshTermy als MCP-Server“
|
||||
```
|
||||
|
||||
## Bedienung
|
||||
@@ -460,6 +462,22 @@ Windows-Anmeldung ──DPAPI CryptProtectData───────────
|
||||
welches Modell ging.
|
||||
- Ratenlimit im Ziel-Modus (Standard 6 Schritte/min, max. 40 Schritte pro Ziel).
|
||||
|
||||
### sshTermy als MCP-Server
|
||||
|
||||
KI-Clients wie Claude Desktop oder Claude Code können deine gespeicherten Verbindungen über das Model Context
|
||||
Protocol nutzen. Einschalten unter Einstellungen › Sicherheit › „MCP-Zugriff für KI-Clients“: **nur lesen**
|
||||
(Verbindungen und offene Tabs auflisten, einen Tab lesen, lesende Befehle wie `df -h` oder `show interfaces`) oder
|
||||
**mit Rückfrage** (jeder andere Befehl läuft erst, wenn du in sshTermy `j` drückst; gefährliche sind rot markiert).
|
||||
sshTermy muss laufen und entsperrt sein; `sshtermy mcp` ist nur die Brücke und hält keine Daten. Verbindungen mit Tag
|
||||
`ki-aus`/`ki-lokal` oder KI-Datenschutz „KI aus“ tauchen nie auf. Geheimnisse in Ausgaben werden entfernt, jeder
|
||||
Aufruf steht im Audit-Protokoll.
|
||||
|
||||
```
|
||||
claude mcp add sshtermy -- sshtermy mcp
|
||||
```
|
||||
|
||||
Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"command": "sshtermy", "args": ["mcp"]}}}`
|
||||
|
||||
### KI-Anbieter und Ersatz
|
||||
|
||||
- **Anbieter** in den KI-Einstellungen (`s`): Spark bzw. jeder OpenAI-kompatible Server (vLLM, SGLang, LiteLLM,
|
||||
|
||||
@@ -126,6 +126,7 @@ sshTermy is a lean terminal application (TUI, a single file, ~9 MB, no installer
|
||||
the choice is saved and synced. On first start sshTermy follows the system language
|
||||
- **Accessible mode** (Settings › Appearance): no animations, shapes instead of color only (× for “unreachable”);
|
||||
together with the **color-blind themes** (blue/yellow/orange instead of green/red, Okabe-Ito colors)
|
||||
- **MCP server** (`sshtermy mcp`): Claude and other AI clients can list your connections and run read-only commands, anything else only after you confirm in sshTermy
|
||||
- **Audit log** (Settings › Security): who did what and when, on which host: connections, commands (also from the
|
||||
agent mode and broadcast), file transfers, config backups, changed connections, master password, full backups and
|
||||
AI requests (host/model only). Each line is chained and signed with a key from the store, so changes, deleted or
|
||||
@@ -197,6 +198,7 @@ sshtermy --no-intro # without the start animation (permanently: palette “Sta
|
||||
sshtermy --debug # write a debug log for this run (debug.log in the config folder)
|
||||
sshtermy backup [file] # full backup of all data (asks for the master password)
|
||||
sshtermy restore <file> # restore a full backup (replaces all data, keeps the old folder)
|
||||
sshtermy mcp # MCP server for AI clients (stdin/stdout), see “sshTermy as MCP server”
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -459,6 +461,21 @@ Windows login ──DPAPI CryptProtectData────────────
|
||||
“Show last AI request” shows exactly what was last sent, to which host and model.
|
||||
- Rate limit in goal mode (default 6 steps/min, at most 40 steps per goal).
|
||||
|
||||
### sshTermy as MCP server
|
||||
|
||||
AI clients such as Claude Desktop or Claude Code can use your saved connections through the Model Context Protocol.
|
||||
Turn it on in Settings › Security › “MCP access for AI clients”: **read only** (list connections and open tabs,
|
||||
read a tab, run read-only commands like `df -h` or `show interfaces`) or **with confirmation** (any other command
|
||||
runs only after you press `y` in sshTermy; dangerous commands are marked red). sshTermy must be running and unlocked;
|
||||
`sshtermy mcp` is only a bridge and holds no data. Connections tagged `no-ai`/`ai-local`, or AI privacy “AI off”, are
|
||||
never shown. Secrets in output are redacted, every call lands in the audit log.
|
||||
|
||||
```
|
||||
claude mcp add sshtermy -- sshtermy mcp
|
||||
```
|
||||
|
||||
Claude Desktop (`claude_desktop_config.json`): `{"mcpServers": {"sshtermy": {"command": "sshtermy", "args": ["mcp"]}}}`
|
||||
|
||||
### AI providers and fallback
|
||||
|
||||
- **Provider** in the AI settings (`s`): Spark / any OpenAI-compatible server (vLLM, SGLang, LiteLLM, LM Studio),
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/db9979/sshtermy/internal/crash"
|
||||
"github.com/db9979/sshtermy/internal/fullbackup"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/mcp"
|
||||
"github.com/db9979/sshtermy/internal/sshx"
|
||||
"github.com/db9979/sshtermy/internal/store"
|
||||
"github.com/db9979/sshtermy/internal/ui"
|
||||
@@ -37,7 +38,7 @@ func main() {
|
||||
// Gesamtsicherung aus dem letzten Lauf einspielen, bevor irgendetwas
|
||||
// den Datenordner öffnet (internal/fullbackup).
|
||||
restoredFrom, restoreErr := "", error(nil)
|
||||
if dir != "" {
|
||||
if dir != "" && (len(os.Args) < 2 || os.Args[1] != "mcp") { // die MCP-Brücke läuft neben der App
|
||||
restoredFrom, restoreErr = fullbackup.ApplyPending(dir)
|
||||
}
|
||||
i18n.Load(dir)
|
||||
@@ -53,6 +54,12 @@ func main() {
|
||||
os.Exit(runBackup(os.Args[2:]))
|
||||
case "restore", "einspielen":
|
||||
os.Exit(runRestore(os.Args[2:]))
|
||||
case "mcp":
|
||||
// MCP-Server für KI-Clients über stdin/stdout (internal/mcp)
|
||||
if err := mcp.Serve(os.Stdin, os.Stdout, &mcp.Remote{DataDir: dir}); err != nil {
|
||||
fail(err)
|
||||
}
|
||||
return
|
||||
case "attach":
|
||||
// neues Fenster eines abgetrennten Tabs (⇧F10), siehe internal/detach
|
||||
if len(os.Args) != 3 {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package detach
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/localsock"
|
||||
)
|
||||
|
||||
func listen(dir string) (net.Listener, string, error) { return localsock.Listen(dir) }
|
||||
|
||||
func dial(network, addr string) (net.Conn, error) { return localsock.Dial(network + ":" + addr) }
|
||||
@@ -547,6 +547,11 @@ type Settings struct {
|
||||
// Nur dieser Rechner: ein Sync soll es nirgends still abschalten.
|
||||
Audit bool `json:"audit,omitempty"`
|
||||
|
||||
// MCP: sshTermy als MCP-Server für KI-Clients (internal/mcp):
|
||||
// "" aus, "lesen" nur lesende Befehle, "rueckfrage" andere nach
|
||||
// Rückfrage. Nur dieser Rechner.
|
||||
MCP string `json:"mcp,omitempty"`
|
||||
|
||||
// Keys: eigene Tastenkürzel, Aktion → Taste (bubbletea-Schreibweise,
|
||||
// z. B. "goal": "ctrl+g"). Fehlt eine Aktion, gilt der Standard.
|
||||
Keys map[string]string `json:"keys,omitempty"`
|
||||
|
||||
@@ -10,3 +10,19 @@ func init() {
|
||||
en[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// MCP-Server (internal/mcp, ui/mcp.go).
|
||||
func init() {
|
||||
for k, v := range map[string]string{
|
||||
"\n\nj = ausführen · n = ablehnen": "\n\ny = run · n = decline",
|
||||
"Ein KI-Client möchte auf %s ausführen:\n\n %s\n": "An AI client wants to run on %s:\n\n %s\n",
|
||||
"MCP-Zugriff für KI-Clients (Claude, …)": "MCP access for AI clients (Claude, …)",
|
||||
"MCP-Zugriff: ": "MCP access: ",
|
||||
"MCP: %s auf %s": "MCP: %s on %s",
|
||||
"MCP: Befehl erlauben?": "MCP: allow command?",
|
||||
"mit Rückfrage": "with confirmation",
|
||||
"nur lesen": "read only",
|
||||
} {
|
||||
en[k] = v
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build !windows
|
||||
|
||||
package detach
|
||||
package localsock
|
||||
|
||||
import (
|
||||
"net"
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package detach
|
||||
package localsock
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package localsock: lokale Verbindung zwischen zwei sshTermy-Prozessen
|
||||
// desselben Benutzers (Unix-Socket bzw. Named Pipe unter Windows). Genutzt
|
||||
// vom eigenen Fenster (internal/detach) und vom MCP-Server (internal/mcp).
|
||||
package localsock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Listen öffnet einen Socket in dir (Unix) bzw. eine Named Pipe (Windows).
|
||||
// addr hat die Form "unix:/pfad" oder "pipe:\\.\pipe\…" und geht an Dial.
|
||||
func Listen(dir string) (ln net.Listener, addr string, err error) { return listen(dir) }
|
||||
|
||||
// Dial verbindet mit einer Adresse aus Listen.
|
||||
func Dial(addr string) (net.Conn, error) {
|
||||
n, a, ok := strings.Cut(strings.TrimSpace(addr), ":")
|
||||
if !ok {
|
||||
return nil, errors.New("localsock: Adresse unlesbar")
|
||||
}
|
||||
return dial(n, a)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/localsock"
|
||||
)
|
||||
|
||||
// Verbindung Brücke ↔ App: erste Zeile das Token aus mcp.json, danach je
|
||||
// Zeile eine Anfrage {id, tool, args} bzw. Antwort {id, text, error}.
|
||||
|
||||
const infoFile = "mcp.json"
|
||||
|
||||
type info struct {
|
||||
Addr string `json:"addr"`
|
||||
Token string `json:"token"`
|
||||
PID int `json:"pid"`
|
||||
}
|
||||
|
||||
type wireReq struct {
|
||||
ID int64 `json:"id"`
|
||||
Tool string `json:"tool"`
|
||||
Args json.RawMessage `json:"args"`
|
||||
}
|
||||
|
||||
type wireResp struct {
|
||||
ID int64 `json:"id"`
|
||||
Text string `json:"text"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Handler: führt ein Werkzeug in der App aus.
|
||||
type Handler func(tool string, args json.RawMessage) (string, error)
|
||||
|
||||
// Host: Socket der laufenden App.
|
||||
type Host struct {
|
||||
ln net.Listener
|
||||
sockDir string
|
||||
info string
|
||||
token []byte
|
||||
handle Handler
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// Listen öffnet den Socket und schreibt Adresse + Token nach dataDir/mcp.json
|
||||
// (nur für den eigenen Benutzer lesbar).
|
||||
func Listen(dataDir string, h Handler) (*Host, error) {
|
||||
sockDir, err := os.MkdirTemp("", "sshtermy-mcp-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ln, addr, err := localsock.Listen(sockDir)
|
||||
if err != nil {
|
||||
os.RemoveAll(sockDir)
|
||||
return nil, err
|
||||
}
|
||||
tok := make([]byte, 32)
|
||||
_, _ = rand.Read(tok)
|
||||
x := &Host{ln: ln, sockDir: sockDir, info: filepath.Join(dataDir, infoFile), token: []byte(hex.EncodeToString(tok)), handle: h}
|
||||
b, _ := json.Marshal(info{Addr: addr, Token: string(x.token), PID: os.Getpid()})
|
||||
if err := os.WriteFile(x.info, b, 0o600); err != nil {
|
||||
x.Close()
|
||||
return nil, err
|
||||
}
|
||||
go x.accept()
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// Close beendet den Socket und löscht mcp.json.
|
||||
func (x *Host) Close() {
|
||||
x.ln.Close()
|
||||
os.Remove(x.info)
|
||||
os.RemoveAll(x.sockDir)
|
||||
}
|
||||
|
||||
func (x *Host) accept() {
|
||||
for {
|
||||
nc, err := x.ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go x.serve(nc)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Host) serve(nc net.Conn) {
|
||||
defer nc.Close()
|
||||
r := bufio.NewReader(nc)
|
||||
_ = nc.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
line, err := r.ReadBytes('\n')
|
||||
if err != nil || subtle.ConstantTimeCompare(trimNL(line), x.token) != 1 {
|
||||
return
|
||||
}
|
||||
_ = nc.SetReadDeadline(time.Time{})
|
||||
var mu sync.Mutex
|
||||
sc := bufio.NewScanner(r)
|
||||
sc.Buffer(make([]byte, 64<<10), 8<<20)
|
||||
for sc.Scan() {
|
||||
var q wireReq
|
||||
if json.Unmarshal(sc.Bytes(), &q) != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
text, err := x.handle(q.Tool, q.Args)
|
||||
resp := wireResp{ID: q.ID, Text: text}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
b, _ := json.Marshal(resp)
|
||||
mu.Lock()
|
||||
nc.Write(append(b, '\n'))
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func trimNL(b []byte) []byte {
|
||||
for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r') {
|
||||
b = b[:len(b)-1]
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// ErrNotRunning: kein laufendes sshTermy mit MCP-Zugriff.
|
||||
var ErrNotRunning = errors.New("sshTermy is not running or MCP access is off (sshTermy: Settings › Security › MCP access)")
|
||||
|
||||
// Remote: Backend der Brücke, verbindet bei Bedarf (auch wenn sshTermy erst
|
||||
// später gestartet wird).
|
||||
type Remote struct {
|
||||
DataDir string
|
||||
mu sync.Mutex
|
||||
nc net.Conn
|
||||
enc *json.Encoder
|
||||
next int64
|
||||
wait map[int64]chan wireResp
|
||||
}
|
||||
|
||||
func (r *Remote) connect() error {
|
||||
b, err := os.ReadFile(filepath.Join(r.DataDir, infoFile))
|
||||
if err != nil {
|
||||
return ErrNotRunning
|
||||
}
|
||||
var in info
|
||||
if json.Unmarshal(b, &in) != nil {
|
||||
return ErrNotRunning
|
||||
}
|
||||
nc, err := localsock.Dial(in.Addr)
|
||||
if err != nil {
|
||||
return ErrNotRunning
|
||||
}
|
||||
if _, err := nc.Write([]byte(in.Token + "\n")); err != nil {
|
||||
nc.Close()
|
||||
return ErrNotRunning
|
||||
}
|
||||
r.nc, r.enc, r.wait = nc, json.NewEncoder(nc), map[int64]chan wireResp{}
|
||||
go r.read(nc)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Remote) read(nc net.Conn) {
|
||||
sc := bufio.NewScanner(nc)
|
||||
sc.Buffer(make([]byte, 64<<10), 16<<20)
|
||||
for sc.Scan() {
|
||||
var resp wireResp
|
||||
if json.Unmarshal(sc.Bytes(), &resp) != nil {
|
||||
continue
|
||||
}
|
||||
r.mu.Lock()
|
||||
ch := r.wait[resp.ID]
|
||||
delete(r.wait, resp.ID)
|
||||
r.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- resp
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.nc == nc {
|
||||
for id, ch := range r.wait {
|
||||
ch <- wireResp{ID: id, Error: "sshTermy was closed"}
|
||||
}
|
||||
r.nc, r.wait = nil, nil
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// Call: Werkzeug in der App ausführen (wartet auch auf Rückfragen beim Nutzer).
|
||||
func (r *Remote) Call(tool string, args json.RawMessage) (string, error) {
|
||||
r.mu.Lock()
|
||||
if r.nc == nil {
|
||||
if err := r.connect(); err != nil {
|
||||
r.mu.Unlock()
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
r.next++
|
||||
id := r.next
|
||||
ch := make(chan wireResp, 1)
|
||||
r.wait[id] = ch
|
||||
err := r.enc.Encode(wireReq{ID: id, Tool: tool, Args: args})
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return "", ErrNotRunning
|
||||
}
|
||||
resp := <-ch
|
||||
if resp.Error != "" {
|
||||
return "", errors.New(resp.Error)
|
||||
}
|
||||
return resp.Text, nil
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Package mcp macht sshTermy zum MCP-Server (Model Context Protocol): ein
|
||||
// KI-Client wie Claude Desktop oder Claude Code startet „sshtermy mcp“ und
|
||||
// spricht über stdin/stdout JSON-RPC 2.0. Dieser Prozess hält selbst keine
|
||||
// Daten: er reicht jeden Werkzeugaufruf über einen lokalen Socket an das
|
||||
// laufende, entsperrte sshTermy weiter (Host/Listen), das entscheidet, ob es
|
||||
// den Aufruf erlaubt (Einstellung „MCP-Zugriff“, Rückfrage, KI-Datenschutz).
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/version"
|
||||
)
|
||||
|
||||
// ProtocolVersion: neueste Fassung, die dieser Server spricht.
|
||||
const ProtocolVersion = "2025-06-18"
|
||||
|
||||
// Tool: Beschreibung für tools/list.
|
||||
type Tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"inputSchema"`
|
||||
}
|
||||
|
||||
func obj(props map[string]any, required ...string) map[string]any {
|
||||
s := map[string]any{"type": "object", "properties": props}
|
||||
if len(required) > 0 {
|
||||
s["required"] = required
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
|
||||
func num(desc string) map[string]any { return map[string]any{"type": "integer", "description": desc} }
|
||||
|
||||
// Tools: was sshTermy anbietet.
|
||||
var Tools = []Tool{
|
||||
{"list_connections", "List the SSH connections saved in sshTermy (alias, host, user, folder, tags, device type, OS). Never includes passwords or keys.",
|
||||
obj(map[string]any{"query": str("optional filter on alias, host, folder or tag")})},
|
||||
{"list_tabs", "List the terminal tabs currently open in sshTermy with their connection and state.", obj(map[string]any{})},
|
||||
{"read_tab", "Read the visible text and recent scrollback of an open tab (secrets are redacted).",
|
||||
obj(map[string]any{"tab": num("tab number from list_tabs"), "lines": num("how many lines from the end, default 100, max 1000")}, "tab")},
|
||||
{"run_command", "Run a shell command on a saved connection in a separate, invisible session and return its output. Read-only commands run directly; anything that could change the system needs the user's confirmation in sshTermy (or is refused, depending on the user's setting). Network devices (switches/routers) accept their CLI show commands.",
|
||||
obj(map[string]any{
|
||||
"connection": str("alias or ID of the connection (see list_connections)"),
|
||||
"command": str("the command line"),
|
||||
"timeout_seconds": num("default 60, max 600"),
|
||||
}, "connection", "command")},
|
||||
}
|
||||
|
||||
// Backend führt Werkzeuge aus (im Brückenprozess: Weiterleitung an die App).
|
||||
type Backend interface {
|
||||
Call(tool string, args json.RawMessage) (string, error)
|
||||
}
|
||||
|
||||
type rpcReq struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type rpcErr struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type rpcResp struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *rpcErr `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type textContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// Serve beantwortet JSON-RPC-Nachrichten (eine pro Zeile) bis EOF.
|
||||
// Werkzeugaufrufe laufen nebenläufig, Antworten werden einzeln geschrieben.
|
||||
func Serve(in io.Reader, out io.Writer, b Backend) error {
|
||||
sc := bufio.NewScanner(in)
|
||||
sc.Buffer(make([]byte, 64<<10), 8<<20)
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
send := func(r rpcResp) {
|
||||
r.JSONRPC = "2.0"
|
||||
data, _ := json.Marshal(r)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
out.Write(append(data, '\n'))
|
||||
}
|
||||
for sc.Scan() {
|
||||
var q rpcReq
|
||||
if err := json.Unmarshal(sc.Bytes(), &q); err != nil {
|
||||
send(rpcResp{ID: json.RawMessage("null"), Error: &rpcErr{-32700, "parse error"}})
|
||||
continue
|
||||
}
|
||||
if len(q.ID) == 0 {
|
||||
continue // Benachrichtigung (notifications/initialized, cancelled …)
|
||||
}
|
||||
switch q.Method {
|
||||
case "initialize":
|
||||
var p struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
}
|
||||
_ = json.Unmarshal(q.Params, &p)
|
||||
pv := ProtocolVersion
|
||||
if p.ProtocolVersion != "" && p.ProtocolVersion < pv {
|
||||
pv = p.ProtocolVersion // ältere Fassung des Clients übernehmen
|
||||
}
|
||||
send(rpcResp{ID: q.ID, Result: map[string]any{
|
||||
"protocolVersion": pv,
|
||||
"capabilities": map[string]any{"tools": map[string]any{}},
|
||||
"serverInfo": map[string]any{"name": "sshtermy", "version": version.Version},
|
||||
"instructions": "sshTermy gives access to the user's saved SSH connections. Prefer read-only commands; changes need the user's approval in sshTermy.",
|
||||
}})
|
||||
case "ping":
|
||||
send(rpcResp{ID: q.ID, Result: map[string]any{}})
|
||||
case "tools/list":
|
||||
send(rpcResp{ID: q.ID, Result: map[string]any{"tools": Tools}})
|
||||
case "tools/call":
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(q.Params, &p); err != nil || !known(p.Name) {
|
||||
send(rpcResp{ID: q.ID, Error: &rpcErr{-32602, "unknown tool"}})
|
||||
continue
|
||||
}
|
||||
if len(p.Arguments) == 0 {
|
||||
p.Arguments = json.RawMessage("{}")
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(id json.RawMessage) {
|
||||
defer wg.Done()
|
||||
text, err := b.Call(p.Name, p.Arguments)
|
||||
res := map[string]any{"content": []textContent{{"text", text}}}
|
||||
if err != nil {
|
||||
res = map[string]any{"content": []textContent{{"text", err.Error()}}, "isError": true}
|
||||
}
|
||||
send(rpcResp{ID: id, Result: res})
|
||||
}(q.ID)
|
||||
default:
|
||||
send(rpcResp{ID: q.ID, Error: &rpcErr{-32601, fmt.Sprintf("method not found: %s", q.Method)}})
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
if err := sc.Err(); err != nil && !errors.Is(err, io.EOF) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func known(name string) bool {
|
||||
for _, t := range Tools {
|
||||
if t.Name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/localsock"
|
||||
)
|
||||
|
||||
type fake struct{}
|
||||
|
||||
func (fake) Call(tool string, args json.RawMessage) (string, error) {
|
||||
if tool == "run_command" {
|
||||
return "", errors.New("vom Nutzer abgelehnt")
|
||||
}
|
||||
return tool + " " + string(args), nil
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
in := strings.Join([]string{
|
||||
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}`,
|
||||
`{"jsonrpc":"2.0","method":"notifications/initialized"}`,
|
||||
`{"jsonrpc":"2.0","id":2,"method":"tools/list"}`,
|
||||
`{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_tabs","arguments":{}}}`,
|
||||
`{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"run_command","arguments":{"connection":"a","command":"rm -rf /"}}}`,
|
||||
`{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nope"}}`,
|
||||
`{"jsonrpc":"2.0","id":6,"method":"foo"}`,
|
||||
`kaputt`,
|
||||
}, "\n") + "\n"
|
||||
var out bytes.Buffer
|
||||
if err := Serve(strings.NewReader(in), &out, fake{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]map[string]any{}
|
||||
for _, l := range strings.Split(strings.TrimSpace(out.String()), "\n") {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(l), &m); err != nil {
|
||||
t.Fatal(l)
|
||||
}
|
||||
id, _ := json.Marshal(m["id"])
|
||||
byID[string(id)] = m
|
||||
}
|
||||
if len(byID) != 7 {
|
||||
t.Fatalf("Antworten: %d\n%s", len(byID), out.String())
|
||||
}
|
||||
init := byID["1"]["result"].(map[string]any)
|
||||
if init["protocolVersion"] != "2025-03-26" {
|
||||
t.Errorf("Version: %v", init["protocolVersion"])
|
||||
}
|
||||
if n := len(byID["2"]["result"].(map[string]any)["tools"].([]any)); n != len(Tools) {
|
||||
t.Errorf("tools/list: %d", n)
|
||||
}
|
||||
if !strings.Contains(out.String(), `"text":"list_tabs {}"`) {
|
||||
t.Error("tools/call ohne Ergebnis")
|
||||
}
|
||||
if r := byID["4"]["result"].(map[string]any); r["isError"] != true {
|
||||
t.Errorf("Fehler nicht als isError: %v", r)
|
||||
}
|
||||
for _, id := range []string{"5", "6", "null"} {
|
||||
if byID[id]["error"] == nil {
|
||||
t.Errorf("id %s: kein Fehler", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostRemote(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
r := &Remote{DataDir: dir}
|
||||
if _, err := r.Call("list_tabs", json.RawMessage(`{}`)); !errors.Is(err, ErrNotRunning) {
|
||||
t.Fatalf("ohne App: %v", err)
|
||||
}
|
||||
h, err := Listen(dir, func(tool string, args json.RawMessage) (string, error) {
|
||||
if tool == "fail" {
|
||||
return "", errors.New("nein")
|
||||
}
|
||||
return "ok:" + tool, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, err := os.Stat(filepath.Join(dir, infoFile)); err != nil || (st.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/') {
|
||||
t.Fatalf("mcp.json: %v", err)
|
||||
}
|
||||
got, err := r.Call("list_tabs", json.RawMessage(`{}`))
|
||||
if err != nil || got != "ok:list_tabs" {
|
||||
t.Fatalf("%q %v", got, err)
|
||||
}
|
||||
if _, err := r.Call("fail", nil); err == nil || err.Error() != "nein" {
|
||||
t.Fatalf("Fehler: %v", err)
|
||||
}
|
||||
// falsches Token: keine Antwort, Verbindung zu
|
||||
b, _ := os.ReadFile(filepath.Join(dir, infoFile))
|
||||
var in info
|
||||
json.Unmarshal(b, &in)
|
||||
nc, err := localsock.Dial(in.Addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nc.Write([]byte("falsch\n{\"id\":1,\"tool\":\"x\"}\n"))
|
||||
buf := make([]byte, 10)
|
||||
if n, _ := nc.Read(buf); n != 0 {
|
||||
t.Fatalf("Antwort trotz falschem Token: %q", buf[:n])
|
||||
}
|
||||
nc.Close()
|
||||
h.Close()
|
||||
if _, err := os.Stat(filepath.Join(dir, infoFile)); err == nil {
|
||||
t.Fatal("mcp.json bleibt nach Close")
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -33,6 +33,7 @@ import (
|
||||
"github.com/db9979/sshtermy/internal/audit"
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/mcp"
|
||||
"github.com/db9979/sshtermy/internal/netwatch"
|
||||
"github.com/db9979/sshtermy/internal/sessionlog"
|
||||
"github.com/db9979/sshtermy/internal/sshx"
|
||||
@@ -78,8 +79,9 @@ type App struct {
|
||||
audit *audit.Log // audit.go
|
||||
nw *netwatch.Watcher // Ruhezustand/Netzwechsel (netwatch.go)
|
||||
nwAt time.Time
|
||||
debugForced bool // --debug: Debug-Protokoll für diesen Start (debugreport.go)
|
||||
startNotice string // Meldung nach dem Entsperren (fullbackup.go)
|
||||
mcpHost *mcp.Host // mcp.go
|
||||
debugForced bool // --debug: Debug-Protokoll für diesen Start (debugreport.go)
|
||||
startNotice string // Meldung nach dem Entsperren (fullbackup.go)
|
||||
startNoticeOK bool
|
||||
st *store.Store
|
||||
hostKeys *sshx.HostKeyStore
|
||||
@@ -295,6 +297,8 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
a.blurred = true
|
||||
return a, nil
|
||||
|
||||
case mcpCallMsg:
|
||||
return a, tea.Batch(a.onMCP(m), a.listen())
|
||||
case hostKeyAskMsg:
|
||||
a.modal = hostKeyModal(m)
|
||||
return a, a.listen()
|
||||
@@ -566,6 +570,7 @@ func (a *App) quit() tea.Cmd {
|
||||
s.close()
|
||||
}
|
||||
a.closeBook()
|
||||
a.stopMCP()
|
||||
a.st.Lock()
|
||||
return tea.Quit
|
||||
}
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/agent"
|
||||
"github.com/db9979/sshtermy/internal/audit"
|
||||
"github.com/db9979/sshtermy/internal/broadcast"
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/i18n"
|
||||
"github.com/db9979/sshtermy/internal/llm"
|
||||
"github.com/db9979/sshtermy/internal/mcp"
|
||||
"github.com/db9979/sshtermy/internal/safety"
|
||||
)
|
||||
|
||||
// sshTermy als MCP-Server (internal/mcp): Einstellungen › Sicherheit ›
|
||||
// „MCP-Zugriff“ = aus / nur lesen / mit Rückfrage. Ein KI-Client startet
|
||||
// „sshtermy mcp“; der reicht jeden Aufruf hierher. Gelesen wird nur, was
|
||||
// der KI-Datenschutz erlaubt; Befehle, die etwas ändern könnten, laufen nur
|
||||
// nach Rückfrage hier im Fenster.
|
||||
|
||||
const (
|
||||
mcpOff = ""
|
||||
mcpRead = "lesen"
|
||||
mcpAsk = "rueckfrage"
|
||||
mcpMaxOut = 100_000
|
||||
)
|
||||
|
||||
func mcpLabel(level string) string {
|
||||
switch level {
|
||||
case mcpRead:
|
||||
return i18n.T("nur lesen")
|
||||
case mcpAsk:
|
||||
return i18n.T("mit Rückfrage")
|
||||
}
|
||||
return i18n.T("aus")
|
||||
}
|
||||
|
||||
func (a *App) mcpLevel() string { return a.st.Settings().MCP }
|
||||
|
||||
// mcpCallMsg: Aufruf aus dem Socket-Goroutine.
|
||||
type mcpCallMsg struct {
|
||||
tool string
|
||||
args json.RawMessage
|
||||
reply func(string, error)
|
||||
}
|
||||
|
||||
func (a *App) startMCP() {
|
||||
if a.mcpLevel() == mcpOff || a.mcpHost != nil {
|
||||
return
|
||||
}
|
||||
ev := a.events
|
||||
h, err := mcp.Listen(a.st.Dir, func(tool string, args json.RawMessage) (string, error) {
|
||||
type res struct {
|
||||
text string
|
||||
err error
|
||||
}
|
||||
ch := make(chan res, 1)
|
||||
var once sync.Once
|
||||
ev <- mcpCallMsg{tool, args, func(t string, e error) { once.Do(func() { ch <- res{t, e} }) }}
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.text, r.err
|
||||
case <-time.After(10 * time.Minute):
|
||||
return "", errors.New("no answer from sshTermy (confirmation timed out)")
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
a.flashErr("MCP: " + err.Error())
|
||||
return
|
||||
}
|
||||
a.mcpHost = h
|
||||
}
|
||||
|
||||
func (a *App) stopMCP() {
|
||||
if a.mcpHost != nil {
|
||||
a.mcpHost.Close()
|
||||
a.mcpHost = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) cycleMCP(dir int) tea.Cmd {
|
||||
levels := []string{mcpOff, mcpRead, mcpAsk}
|
||||
cur := 0
|
||||
for i, l := range levels {
|
||||
if l == a.mcpLevel() {
|
||||
cur = i
|
||||
}
|
||||
}
|
||||
next := levels[cycleIndex(cur, len(levels), dir)]
|
||||
if err := a.st.UpdateSettings(func(s *domain.Settings) { s.MCP = next }); err != nil {
|
||||
a.flashErr(err.Error())
|
||||
return nil
|
||||
}
|
||||
a.auditAdd(audit.EvSettings, "", "MCP-Zugriff: "+next)
|
||||
if next == mcpOff {
|
||||
a.stopMCP()
|
||||
} else {
|
||||
a.startMCP()
|
||||
}
|
||||
a.flash(i18n.T("MCP-Zugriff: ") + mcpLabel(next))
|
||||
return nil
|
||||
}
|
||||
|
||||
// onMCP läuft im Update-Goroutine.
|
||||
func (a *App) onMCP(m mcpCallMsg) tea.Cmd {
|
||||
fail := func(f string, x ...any) tea.Cmd { m.reply("", fmt.Errorf(f, x...)); return nil }
|
||||
switch {
|
||||
case a.mcpLevel() == mcpOff:
|
||||
return fail("MCP access is off in sshTermy")
|
||||
case a.scr == scrUnlock || a.lock != nil:
|
||||
return fail("sshTermy is locked; unlock it first")
|
||||
case a.st.LLM().Privacy == llm.PrivacyOff:
|
||||
return fail("AI is turned off in sshTermy (Settings › AI › AI privacy)")
|
||||
}
|
||||
a.auditAdd("mcp", "", m.tool)
|
||||
switch m.tool {
|
||||
case "list_connections":
|
||||
var p struct{ Query string }
|
||||
_ = json.Unmarshal(m.args, &p)
|
||||
m.reply(a.mcpConnections(p.Query), nil)
|
||||
case "list_tabs":
|
||||
m.reply(a.mcpTabs(), nil)
|
||||
case "read_tab":
|
||||
var p struct{ Tab, Lines int }
|
||||
_ = json.Unmarshal(m.args, &p)
|
||||
s := a.byID(p.Tab)
|
||||
if s == nil || s.term == nil {
|
||||
return fail("no open tab %d (see list_tabs)", p.Tab)
|
||||
}
|
||||
if !mcpAllowed(a, s.conn) {
|
||||
return fail("AI access is off for this connection (privacy tag)")
|
||||
}
|
||||
n := p.Lines
|
||||
if n <= 0 {
|
||||
n = 100
|
||||
}
|
||||
m.reply(agent.Redact(s.term.PlainLines(min(n, 1000))), nil)
|
||||
case "run_command":
|
||||
return a.mcpRun(m)
|
||||
default:
|
||||
return fail("unknown tool %s", m.tool)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mcpAllowed(a *App, c domain.Connection) bool { return a.aiLevel(c) == llm.PrivacyAll }
|
||||
|
||||
type mcpConn struct {
|
||||
ID string `json:"id"`
|
||||
Alias string `json:"alias"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Port int `json:"port,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
Protocol string `json:"protocol,omitempty"`
|
||||
Folder string `json:"folder,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) mcpConnections(q string) string {
|
||||
q = strings.ToLower(strings.TrimSpace(q))
|
||||
out := []mcpConn{}
|
||||
for _, c := range a.st.Connections() {
|
||||
if !mcpAllowed(a, c) {
|
||||
continue
|
||||
}
|
||||
mc := mcpConn{ID: c.ID, Alias: c.Alias, Host: c.Host, Port: c.Port, User: c.Username, Protocol: string(c.Protocol),
|
||||
Folder: c.Group, Tags: c.Tags, Device: string(c.Device)}
|
||||
if c.Profile != nil {
|
||||
mc.OS = c.Profile.OS
|
||||
}
|
||||
if q != "" && !strings.Contains(strings.ToLower(mc.Alias+" "+mc.Host+" "+mc.Folder+" "+strings.Join(mc.Tags, " ")), q) {
|
||||
continue
|
||||
}
|
||||
out = append(out, mc)
|
||||
}
|
||||
b, _ := json.MarshalIndent(out, "", " ")
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (a *App) mcpTabs() string {
|
||||
type tab struct {
|
||||
Tab int `json:"tab"`
|
||||
Alias string `json:"alias"`
|
||||
Host string `json:"host,omitempty"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
out := []tab{}
|
||||
for _, s := range a.sessions {
|
||||
if !mcpAllowed(a, s.conn) {
|
||||
continue
|
||||
}
|
||||
st := "connected"
|
||||
switch s.state {
|
||||
case stReconnect:
|
||||
st = "reconnecting"
|
||||
case stConnected:
|
||||
default:
|
||||
st = "not connected"
|
||||
}
|
||||
out = append(out, tab{s.id, s.conn.Alias, s.conn.Host, st})
|
||||
}
|
||||
b, _ := json.MarshalIndent(out, "", " ")
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (a *App) mcpFind(ref string) (domain.Connection, bool) {
|
||||
if c, ok := a.st.Connection(ref); ok {
|
||||
return c, true
|
||||
}
|
||||
for _, c := range a.st.Connections() {
|
||||
if strings.EqualFold(c.Alias, ref) {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
return domain.Connection{}, false
|
||||
}
|
||||
|
||||
func mcpKind(c domain.Connection) string {
|
||||
net := c.Device == domain.DeviceNetwork
|
||||
os := ""
|
||||
if c.Profile != nil {
|
||||
net = net || c.Profile.Family == domain.FamilyNetwork
|
||||
os = c.Profile.OS
|
||||
}
|
||||
return safety.KindFor(os, net)
|
||||
}
|
||||
|
||||
func (a *App) mcpRun(m mcpCallMsg) tea.Cmd {
|
||||
var p struct {
|
||||
Connection, Command string
|
||||
Timeout int `json:"timeout_seconds"`
|
||||
}
|
||||
_ = json.Unmarshal(m.args, &p)
|
||||
cmd := strings.TrimSpace(p.Command)
|
||||
c, ok := a.mcpFind(strings.TrimSpace(p.Connection))
|
||||
switch {
|
||||
case cmd == "":
|
||||
m.reply("", errors.New("command is empty"))
|
||||
return nil
|
||||
case !ok:
|
||||
m.reply("", fmt.Errorf("no connection %q (see list_connections)", p.Connection))
|
||||
return nil
|
||||
case c.Protocol != "" && c.Protocol != domain.ProtoSSH:
|
||||
m.reply("", errors.New("only SSH connections can run commands via MCP"))
|
||||
return nil
|
||||
case !mcpAllowed(a, c):
|
||||
m.reply("", errors.New("AI access is off for this connection (privacy tag)"))
|
||||
return nil
|
||||
}
|
||||
kind := mcpKind(c)
|
||||
dangers := safety.Check(cmd, kind)
|
||||
if safety.ReadOnly(cmd, kind) && len(dangers) == 0 {
|
||||
return a.mcpExec(c, cmd, p.Timeout, m.reply)
|
||||
}
|
||||
if a.mcpLevel() != mcpAsk {
|
||||
m.reply("", errors.New("only read-only commands are allowed (sshTermy setting “MCP access: read only”); ask the user to run it or to allow confirmations"))
|
||||
return nil
|
||||
}
|
||||
body := fmt.Sprintf(i18n.T("Ein KI-Client möchte auf %s ausführen:\n\n %s\n"), auditConn(c), cmd)
|
||||
for _, d := range dangers {
|
||||
body += "\n▲ " + d.Reason
|
||||
}
|
||||
body += i18n.T("\n\nj = ausführen · n = ablehnen")
|
||||
md := confirmModal(i18n.T("MCP: Befehl erlauben?"), body, func() tea.Cmd { return a.mcpExec(c, cmd, p.Timeout, m.reply) })
|
||||
md.onCancel = func() tea.Cmd {
|
||||
a.auditAdd("mcp", auditConn(c), "abgelehnt: "+cmd)
|
||||
m.reply("", errors.New("the user declined the command"))
|
||||
return nil
|
||||
}
|
||||
if a.modal != nil {
|
||||
m.reply("", errors.New("sshTermy is busy with another dialog; try again in a moment"))
|
||||
return nil
|
||||
}
|
||||
a.modal = md
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) mcpExec(c domain.Connection, cmd string, timeout int, reply func(string, error)) tea.Cmd {
|
||||
if timeout <= 0 {
|
||||
timeout = 60
|
||||
}
|
||||
timeout = min(timeout, 600)
|
||||
a.auditAdd(audit.EvAgent, auditConn(c), "MCP: "+cmd)
|
||||
a.flash(fmt.Sprintf(i18n.T("MCP: %s auf %s"), cmd, c.Alias))
|
||||
dial := a.bcDialer()
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
||||
defer cancel()
|
||||
rs := broadcast.Run(ctx, broadcast.Job{Conns: []domain.Connection{c}, Steps: []string{cmd}}, dial, func(int, broadcast.Result) {})
|
||||
r := rs[0]
|
||||
out := agent.Redact(r.Output)
|
||||
if len(out) > mcpMaxOut {
|
||||
out = out[len(out)-mcpMaxOut:]
|
||||
}
|
||||
switch {
|
||||
case r.Err != "":
|
||||
reply(out, errors.New(r.Err+"\n"+out))
|
||||
default:
|
||||
reply(fmt.Sprintf("%s\n[exit %d]", strings.TrimRight(out, "\n"), r.Exit), nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"github.com/db9979/sshtermy/internal/domain"
|
||||
"github.com/db9979/sshtermy/internal/mcp"
|
||||
)
|
||||
|
||||
func mcpCall(a *App, tool, args string) (string, error, tea.Cmd) {
|
||||
var text string
|
||||
var err error
|
||||
got := false
|
||||
cmd := a.onMCP(mcpCallMsg{tool: tool, args: json.RawMessage(args), reply: func(t string, e error) { text, err, got = t, e, true }})
|
||||
if !got && cmd == nil && a.modal == nil {
|
||||
return "", nil, nil
|
||||
}
|
||||
return text, err, cmd
|
||||
}
|
||||
|
||||
func TestMCPAccess(t *testing.T) {
|
||||
a := newPaletteTestApp(t)
|
||||
a.pal, a.scr = nil, scrManager
|
||||
for _, c := range []domain.Connection{
|
||||
{Alias: "web1", Host: "10.0.0.5", Username: "root"},
|
||||
{Alias: "kunde", Host: "10.9.9.9", Username: "root", Tags: []string{"ki-aus"}},
|
||||
} {
|
||||
if _, err := a.st.UpsertConnection(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err, _ := mcpCall(a, "list_connections", `{}`); err == nil {
|
||||
t.Fatal("MCP aus muss ablehnen")
|
||||
}
|
||||
a.st.UpdateSettings(func(s *domain.Settings) { s.MCP = mcpRead })
|
||||
out, err, _ := mcpCall(a, "list_connections", `{}`)
|
||||
if err != nil || !strings.Contains(out, "web1") || strings.Contains(out, "kunde") || strings.Contains(strings.ToLower(out), "password") {
|
||||
t.Fatalf("Liste: %v\n%s", err, out)
|
||||
}
|
||||
if _, err, _ := mcpCall(a, "run_command", `{"connection":"kunde","command":"uptime"}`); err == nil {
|
||||
t.Fatal("ki-aus muss ablehnen")
|
||||
}
|
||||
if _, err, _ := mcpCall(a, "run_command", `{"connection":"web1","command":"systemctl restart nginx"}`); err == nil || !strings.Contains(err.Error(), "read-only") {
|
||||
t.Fatalf("nur lesen: %v", err)
|
||||
}
|
||||
a.st.UpdateSettings(func(s *domain.Settings) { s.MCP = mcpAsk })
|
||||
var declined error
|
||||
a.onMCP(mcpCallMsg{tool: "run_command", args: json.RawMessage(`{"connection":"web1","command":"rm -rf /var/www"}`),
|
||||
reply: func(_ string, e error) { declined = e }})
|
||||
if a.modal == nil || !strings.Contains(a.modal.body, "rm -rf /var/www") || !strings.Contains(a.modal.body, "▲") {
|
||||
t.Fatalf("Rückfrage fehlt oder ohne Gefahrenhinweis: %+v", a.modal)
|
||||
}
|
||||
a.modalKey(tea.KeyPressMsg{Code: 'n', Text: "n"})
|
||||
if declined == nil || a.modal != nil {
|
||||
t.Fatal("Ablehnen nicht gemeldet")
|
||||
}
|
||||
if _, err, _ := mcpCall(a, "read_tab", `{"tab":99}`); err == nil {
|
||||
t.Fatal("unbekannter Tab")
|
||||
}
|
||||
a.lock = &lockState{}
|
||||
if _, err, _ := mcpCall(a, "list_tabs", `{}`); err == nil || !strings.Contains(err.Error(), "locked") {
|
||||
t.Fatalf("gesperrt: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Ende zu Ende: Brücke (mcp.Remote) → Socket → App.
|
||||
func TestMCPBridge(t *testing.T) {
|
||||
a := newPaletteTestApp(t)
|
||||
a.pal, a.scr = nil, scrManager
|
||||
a.st.UpsertConnection(domain.Connection{Alias: "nas", Host: "192.168.1.20", Username: "admin"})
|
||||
a.st.UpdateSettings(func(s *domain.Settings) { s.MCP = mcpRead })
|
||||
a.startMCP()
|
||||
if a.mcpHost == nil {
|
||||
t.Fatal("kein Socket")
|
||||
}
|
||||
defer a.stopMCP()
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case m := <-a.events:
|
||||
if c, ok := m.(mcpCallMsg); ok {
|
||||
a.onMCP(c)
|
||||
}
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
r := &mcp.Remote{DataDir: a.st.Dir}
|
||||
out, err := r.Call("list_connections", json.RawMessage(`{"query":"nas"}`))
|
||||
if err != nil || !strings.Contains(out, "192.168.1.20") {
|
||||
t.Fatalf("%v %s", err, out)
|
||||
}
|
||||
}
|
||||
@@ -179,6 +179,9 @@ func (a *App) modalKey(k tea.KeyPressMsg) tea.Cmd {
|
||||
}
|
||||
case -1:
|
||||
a.modal = nil
|
||||
if m.onCancel != nil {
|
||||
return m.onCancel()
|
||||
}
|
||||
}
|
||||
case mAbout:
|
||||
switch key {
|
||||
|
||||
@@ -560,6 +560,8 @@ func (a *App) palMenuItems() []palItem {
|
||||
safe(palToggle(ic("sesslog"), i18n.T("Audit-Protokoll (wer, wann, was; fälschungssicher)"), a.auditOn(), "audit protokoll revision compliance nachweis log", func() tea.Cmd { return a.toggleAudit() })),
|
||||
{group: pgSetSafe, menu: "settings", icon: ic("export"), label: i18n.T("Audit-Protokoll prüfen und speichern"), hint: ".txt",
|
||||
keys: "audit protokoll prüfen verify export revision", run: func() tea.Cmd { return a.exportAudit() }},
|
||||
palCycle(pgSetSafe, ic("ai"), i18n.T("MCP-Zugriff für KI-Clients (Claude, …)"), mcpLabel(a.mcpLevel()),
|
||||
"mcp claude model context protocol ki ai client server zugriff", func(dir int) tea.Cmd { return a.cycleMCP(dir) }),
|
||||
}
|
||||
|
||||
// Aussehen & Sprache: je ein Durchschalt-Eintrag, die Einzelwerte nur
|
||||
|
||||
@@ -71,6 +71,7 @@ func (a *App) updateUnlock(msg tea.Msg) tea.Cmd {
|
||||
a.applyLook()
|
||||
a.startDebugLog()
|
||||
a.startAudit()
|
||||
a.startMCP()
|
||||
a.mgr = newManager()
|
||||
a.showWhatsNew(u.setup)
|
||||
a.maybeTour(u.setup)
|
||||
|
||||
@@ -147,6 +147,7 @@ sudo apt update && sudo apt install sshtermy</pre></div>
|
||||
<div class="card"><h3>Aussehen & Tasten</h3><p>Neun Themes, darunter Matrix, Bernstein, Neon und zwei für Farbenblinde, eigene Farben, vier Symbol-Stile, jede Taste frei belegbar.</p></div>
|
||||
<div class="card"><h3>Barrierearm & Support</h3><p>Barrierearmer Modus ohne Animationen, mit Formen statt nur Farben. Debug-Protokoll für Fehlerberichte (<code>--debug</code>), bereinigt von Hosts, IPs und Passwörtern.</p></div>
|
||||
<div class="card"><h3>Bildschirmsperre</h3><p>Sofort sperren oder nach 5 bis 60 Minuten Leerlauf; Sitzungen laufen hinter der Sperre weiter. Master-Passwort und Windows-Anmeldung jederzeit änderbar.</p></div>
|
||||
<div class="card"><h3>MCP-Server</h3><p>Claude und andere KI-Clients nutzen deine Verbindungen über <code>sshtermy mcp</code>: standardmäßig nur lesend, alles andere erst nach deiner Bestätigung.</p></div>
|
||||
<div class="card"><h3>Audit-Protokoll</h3><p>Wer hat wann wo was getan: Verbindungen, Befehle, Übertragungen, Config-Sicherungen. Signiert und verkettet, geänderte oder gelöschte Zeilen fallen auf.</p></div>
|
||||
<div class="card"><h3>Umzug auf neuen Rechner</h3><p>Eine verschlüsselte Datei enthält alles: Verbindungen, Schlüssel, Protokolle, Switch-Sicherungen und Einstellungen. Auf dem neuen Rechner einspielen, der alte Stand bleibt als Kopie.</p></div>
|
||||
<div class="card"><h3>KI-Datenschutz</h3><p>Alle Anbieter, nur lokale KI im eigenen Netz oder gar keine KI, global oder pro Verbindung per Tag. Genau sehen, was zuletzt hinausging.</p></div>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -147,6 +147,7 @@ sudo apt update && sudo apt install sshtermy</pre></div>
|
||||
<div class="card"><h3>Look & keys</h3><p>Nine themes including Matrix, Amber, Neon and two for color blindness, your own colors, four icon styles, every shortcut can be changed.</p></div>
|
||||
<div class="card"><h3>Accessible & supportable</h3><p>Accessible mode without animations and with shapes instead of color only. Debug log for bug reports (<code>--debug</code>), saved cleaned of hosts, IPs and passwords.</p></div>
|
||||
<div class="card"><h3>Screen lock</h3><p>Lock now or after 5 to 60 minutes idle; sessions keep running behind the lock. Change the master password or the Windows sign-in any time.</p></div>
|
||||
<div class="card"><h3>MCP server</h3><p>Claude and other AI clients use your saved connections via <code>sshtermy mcp</code>: read-only by default, anything else only after you confirm.</p></div>
|
||||
<div class="card"><h3>Audit log</h3><p>Who did what, when and where: connections, commands, transfers, config backups. Signed and chained, so edited or deleted lines are detected.</p></div>
|
||||
<div class="card"><h3>Move to a new computer</h3><p>One encrypted file holds everything: connections, keys, logs, switch backups and settings. Restore it on the new machine, the old state stays as a copy.</p></div>
|
||||
<div class="card"><h3>AI privacy</h3><p>Allow all providers, only local AI on your own network, or no AI at all, globally or per connection by tag. See exactly what was last sent.</p></div>
|
||||
|
||||
@@ -182,7 +182,7 @@ export const de = {
|
||||
['_Palette_', '„Jetzt sperren“ · „Master-Passwort“ · „Audit“ · „Gefahren-Check“'],
|
||||
]},
|
||||
{ t: 'Start & Tipps', ic: '$', rows: [
|
||||
['--update · backup', 'Update · alles sichern'],
|
||||
['backup · mcp', 'alles sichern · KI-Clients'],
|
||||
['--no-intro · --debug', 'ohne Startanimation · Debug-Protokoll'],
|
||||
['tsz / trz', 'Datei vom / zum Server (trzsz)'],
|
||||
['_Palette_', '„teilen“: Tab live zeigen'],
|
||||
@@ -368,7 +368,7 @@ export const en = {
|
||||
['_palette_', '“Lock now” · “Master password” · “Audit” · “Danger check”'],
|
||||
]},
|
||||
{ t: 'Start & tips', ic: '$', rows: [
|
||||
['--update · backup', 'newest version · full backup'],
|
||||
['backup · mcp', 'full backup · AI clients'],
|
||||
['--no-intro · --debug', 'no start animation · debug log'],
|
||||
['tsz / trz', 'file from / to the server (trzsz)'],
|
||||
['_palette_', '“share”: show a tab live'],
|
||||
|
||||
Reference in new issue
Block a user