package mcp
import (
"context"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/henrygd/beszel"
"github.com/henrygd/beszel/internal/hub/utils"
mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
)
func RegisterRoutes(app core.App, se *core.ServeEvent) error {
if enabled, _ := utils.GetEnv("MCP"); enabled != "true" {
return nil
}
server := newServer(app)
handler := mcpsdk.NewStreamableHTTPHandler(func(_ *http.Request) *mcpsdk.Server { return server }, &mcpsdk.StreamableHTTPOptions{
Stateless: true,
DisableLocalhostProtection: true,
})
mcpHandler := func(e *core.RequestEvent) error {
ctx := context.WithValue(e.Request.Context(), authContextKey{}, e.Auth)
handler.ServeHTTP(e.Response, e.Request.WithContext(ctx))
return nil
}
for _, method := range []string{http.MethodPost, http.MethodGet, http.MethodDelete} {
se.Router.Route(method, "/mcp", mcpHandler).BindFunc(requireAuth)
}
return nil
}
func requireAuth(e *core.RequestEvent) error {
if e.Auth != nil {
return e.Next()
}
settingsPage := "Settings > API Keys"
if appURL := strings.TrimSuffix(e.App.Settings().Meta.AppURL, "/"); appURL != "" {
settingsPage += " (" + appURL + "/settings/api-keys)"
}
const usage = " and send it in the Authorization header as \"Bearer <key>\"."
msg := "Missing API key. Create one in " + settingsPage + usage
challenge := `Bearer realm="beszel"`
if e.Request.Header.Get("Authorization") != "" {
msg = "Invalid, expired or revoked API key. Create a new one in " + settingsPage + usage
challenge += `, error="invalid_token", error_description="` + strings.ReplaceAll(msg, `"`, `'`) + `"`
}
e.Response.Header().Set("WWW-Authenticate", challenge)
return e.UnauthorizedError(msg, nil)
}
func newServer(app core.App) *mcpsdk.Server {
server := mcpsdk.NewServer(&mcpsdk.Implementation{
Name: "beszel",
Version: beszel.Version,
}, &mcpsdk.ServerOptions{
Instructions: "Beszel is a lightweight server monitoring hub. " +
"Use list_systems to see monitored systems and their current usage (including battery and Wi-Fi signal), " +
"get_system for hardware details and current sensors, get_system_stats " +
"for historical metrics, get_container_stats for historical container usage " +
"(e.g. to find which container caused a past spike), list_containers for current container usage, " +
"list_services for systemd services, get_disk_health for SMART and ZFS " +
"health, list_network_monitors for endpoint monitoring, and list_alerts / " +
"list_alert_events for alert configurations and triggered events. Data " +
"access matches the permissions of the authenticated hub user. " +
"list_containers, list_services, get_disk_health and list_network_monitors " +
"search all visible systems when the system argument is omitted, so " +
"questions spanning systems need only one call.",
})
registerTools(app, server)
return server
}
type mcphub struct {
app core.App
}
const notVisibleMsg = "not found or not visible to this user"
type authContextKey struct{}
func (h *mcphub) authRecord(ctx context.Context) (*core.Record, error) {
record, _ := ctx.Value(authContextKey{}).(*core.Record)
if record == nil {
return nil, errors.New("missing authenticated user; create an API key in Settings > API Keys and send it in the Authorization header of your MCP client")
}
return record, nil
}
func shareAllSystems() bool {
value, _ := utils.GetEnv("SHARE_ALL_SYSTEMS")
return value == "true"
}
func (h *mcphub) resolveSystem(auth *core.Record, system string) (*core.Record, error) {
notFound := fmt.Errorf("system %q "+notVisibleMsg, system)
records, err := h.app.FindRecordsByFilter("systems", "name = {:s} || id = {:s}", "", maxListRecords, 0, dbx.Params{"s": system})
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, notFound
}
for _, record := range records {
if record.Id == system {
return h.visibleSystem(auth, record, notFound)
}
}
visible := make([]*core.Record, 0, len(records))
for _, record := range records {
if _, err := h.visibleSystem(auth, record, notFound); err == nil {
visible = append(visible, record)
}
}
switch {
case len(visible) == 0:
return nil, notFound
case len(visible) > 1:
return nil, fmt.Errorf("system name %q is ambiguous (%d visible systems match); use the system id instead", system, len(visible))
}
return visible[0], nil
}
func (h *mcphub) visibleSystem(auth *core.Record, record *core.Record, notFound error) (*core.Record, error) {
if auth.IsSuperuser() || shareAllSystems() || slices.Contains(record.GetStringSlice("users"), auth.Id) {
return record, nil
}
return nil, notFound
}