Files
sherlock/cmd/gssh-mcp/main.go
T
amacocian 1c2108dd2b
Release / tag (push) Successful in 2s
CI / build (push) Successful in 3m5s
Fix fmt
2026-06-13 13:40:24 +02:00

162 lines
5.2 KiB
Go

// Command gssh-mcp is sherlock's MCP server for the Gssh SSH gateway
// (https://terminal.alexandru.macocian.me). It authenticates as the
// operator against Authentik (OIDC + PKCE, loopback callback) and
// uses the resulting JWT bearer token to:
//
// - list the operator's host allow-list,
// - force ephemeral SSH cert creation, and
// - run a single shell command on a host over the headless
// WebSocket exec endpoint, returning stdout/stderr/exit_code.
//
// Two modes mirror gitea-mcp:
//
// gssh-mcp start the stdio MCP server (agents spawn this)
// gssh-mcp --probe run auth + one API call, print result, exit
//
// Deployment configuration (the Authentik issuer/client ID and the
// Gssh base URL) comes entirely from the sherlock config file; there
// are no compiled-in defaults. See docs/configuration.md.
package main
import (
"context"
"errors"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/agent"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/authn"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/browser"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/config"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/keyring"
"gitea.alexandru.macocian.me/amacocian/sherlock/internal/xdg"
)
// serviceName is the wallet key under which gssh tokens live, and the
// [services.<serviceName>] section read from the config file. The
// sherlock CLI's `logout gssh` clears the same wallet entry.
const serviceName = "gssh"
// Version is overwritten at build time via -ldflags "-X main.Version=...".
var Version = "0.0.0-dev"
// scopes asked from Authentik. `openid` is required for an ID token;
// `profile`/`email` populate user-info claims; the Authentik provider
// is the one that decides what audience and `groups` claim to stamp
// onto the access token Gssh's JwtBearer scheme will validate.
var scopes = []string{"openid", "profile", "email"}
func main() {
probe := flag.Bool("probe", false, "run auth + one API call, print result, exit")
showVersion := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *showVersion {
fmt.Println(Version)
return
}
svc, err := config.LoadService(serviceName)
if err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp:", err)
if errors.Is(err, config.ErrNotFound) {
fmt.Fprintln(os.Stderr, "Create it (see docs/configuration.md) or run the sherlock install script.")
}
os.Exit(2)
}
store, err := keyring.Open()
if err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp:", err)
os.Exit(3)
}
agent.EnsurePathContainsSiblings()
lockPath, err := xdg.RefreshLockPath()
if err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp:", err)
os.Exit(1)
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
cfg := authn.Config{
Issuer: svc.Issuer,
ClientID: svc.ClientID,
ClientSecret: svc.ClientSecret,
Scopes: scopes,
}
holder := authn.NewTokenHolder()
src := authn.NewTokenSource(store, serviceName, cfg, authn.EnsureOptions{
LockPath: lockPath,
OnAuthURL: func(u string) {
fmt.Fprintln(os.Stderr, "gssh-mcp: opening browser for Gssh OAuth login:")
fmt.Fprintln(os.Stderr, " ", u)
if err := browser.Open(u); err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp: open browser:", err)
fmt.Fprintln(os.Stderr, "(visit the URL above manually)")
}
},
}, holder.Set).Lifetime(ctx)
// Lazy auth: the token getter triggers the (possibly browser-opening)
// OAuth flow on the first tool call and launches the background
// renewer. Auth is deliberately kept off the startup path so the MCP
// handshake completes instantly — otherwise the agent would time out
// the connect while waiting on a first-time browser login.
token := func(reqCtx context.Context) (string, error) {
if err := src.EnsureStarted(reqCtx); err != nil {
return "", fmt.Errorf("gssh auth: %w", err)
}
return holder.AccessToken(), nil
}
dbg("startup: pid=%d (lazy auth; authenticates on first tool call)", os.Getpid())
api := &gsshAPI{
baseURL: strings.TrimRight(svc.BaseURL, "/"),
token: token,
client: &http.Client{Timeout: 30 * time.Second},
}
if *probe {
// --probe authenticates eagerly: that's the whole point of a probe.
if err := src.EnsureStarted(ctx); err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp: auth:", err)
os.Exit(5)
}
var u struct {
Data struct {
Name string `json:"Name"`
Account string `json:"Account"`
Roles []string `json:"Roles"`
} `json:"Data"`
Message string `json:"Message"`
}
if err := api.get(ctx, "/api/v1/users/me", nil, &u); err != nil {
fmt.Fprintln(os.Stderr, "gssh-mcp: users/me:", err)
os.Exit(5)
}
fmt.Printf("OK: logged in to %s as %s (account=%s, roles=%v)\n",
svc.BaseURL, u.Data.Name, u.Data.Account, u.Data.Roles)
return
}
server := mcp.NewServer(&mcp.Implementation{Name: "gssh-mcp", Version: Version}, nil)
registerTools(server, api)
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil && !errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "gssh-mcp:", err)
os.Exit(1)
}
}