mcp

package
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp is the panel's MCP server for agents: the tools of the token profiles over Streamable HTTP, and the stdio proxy that `mistgate mcp` runs.

The tools do not reach into stores. They call the admin API the way any client does, in process, with the Bearer header the agent sent, so the role policy, the token allow-list, the handlers' own validation and the audit rows are the panel's own (inproc.go). A change is two tools, <tool>_plan and <tool>_apply (plan.go); a dangerous one also waits for the owner's click in the admin panel. What an agent reads is built from explicit projections (views.go), cut to size and scrubbed (limits.go, scrub.go): names, notes and logs are untrusted text and say so in every tool description.

Index

Constants

View Source
const (
	StatusPlanned   = "planned"
	StatusAwaiting  = "awaiting"
	StatusApproved  = "approved"
	StatusRejected  = "rejected"
	StatusExpired   = "expired"
	StatusApplying  = "applying"
	StatusApplied   = "applied"
	StatusFailed    = "failed"
	StatusCancelled = "cancelled"
)

Plan states, the values of mcp_plan.status.

View Source
const (

	// MaxUnattendedBulk is how many users one user_disable may name before it needs the owner.
	MaxUnattendedBulk = 3
)

The limits of the MCP server. Strings that came from data (names, notes, log lines) are untrusted and cut short; whole results are capped; lists are paged.

Variables

View Source
var (
	// ErrNotFound: no such plan (for this token).
	ErrNotFound = errors.New("not found")
	// ErrTooManyPlans: the token or the panel has too many open plans.
	ErrTooManyPlans = errors.New("too many open plans")
)

Errors the Plans implementation returns (the wiring maps the store's own to these).

Functions

func New

func New(c Config) (http.Handler, error)

New builds the Streamable HTTP handler of the MCP endpoint. It must sit behind the bearer middleware of the auth package (auth.Service.RequireBearer), which authenticates the request against the token store, applies the token's rate limit and puts the principal in the request context; New never sees a secret. Without a principal the request is refused.

The server is stateless on purpose: every POST is verified again, so a revoked or expired token stops at its very next request, there is no session id to hijack and nothing is pushed to the client. One server per profile, so tools/list shows only what the token may call.

func RunProxy

func RunProxy(ctx context.Context, rawURL, tokenFile string, stdin io.Reader, stdout, stderr io.Writer) error

RunProxy is `mistgate mcp`: a local stdio MCP server for clients that cannot speak HTTP, which forwards every message to the panel's Streamable HTTP endpoint with the token as a Bearer header. It decides nothing, caches nothing and knows no tool: the panel's own server, with its profile and its limits, answers.

rawURL is the admin URL `mistgate setup` prints (https://host/<prefix>/); the endpoint is that URL plus "mcp". The token is the first line of tokenFile. It is never printed, never taken from the command line or the environment. A plain http URL is refused unless the host is a loopback address: a token must not cross a network in the clear.

Types

type AlertsV

type AlertsV struct {
	NowUnix   int64    `json:"now_unix"`
	Active    []alertV `json:"active"`
	History   []alertV `json:"history,omitempty"`
	Truncated bool     `json:"truncated,omitempty"`
}

AlertsV is the alerts_list result.

type ApplyOut

type ApplyOut struct {
	PlanID string `json:"plan_id"`
	Status string `json:"status"`
	Result string `json:"result"`
}

ApplyOut is the result of an _apply tool.

type AuditEntry

type AuditEntry struct {
	Actor  string // "mcp:<token id>"
	Action string // "mcp_plan", "mcp_apply"
	Params map[string]any
	Result string // "ok" | "fail"
}

AuditEntry is a row for the audit log; the source is always "mcp".

type AuditV

type AuditV struct {
	Entries      []auditV `json:"entries"`
	NextBeforeID int64    `json:"next_before_id,omitempty"`
	Truncated    bool     `json:"truncated,omitempty"`
}

AuditV is the audit_search result.

type Auth

type Auth interface {
	// Principal is the token of the request (the handler's request context, as the bearer middleware left it).
	Principal(ctx context.Context) (Principal, bool)
	// WithChannel marks an in-process call as the MCP layer's own: audited as mcp:<id>, not rate limited a second time.
	WithChannel(ctx context.Context) context.Context
	// WithPlanning lets a token-approved procedure through for a call that changes nothing (the dry run of node_fix).
	WithPlanning(ctx context.Context) context.Context
	// WithApprovedStepUp lets one token-approved procedure through, and its step-up check, while plan planID is
	// applying, belongs to the calling token and has the owner's recorded approval. Checked in the database on every use.
	WithApprovedStepUp(ctx context.Context, planID string) context.Context
}

Auth is what the MCP layer needs from the panel's auth (internal/panel/auth, wired in cmd/mistgate). The bearer middleware in front of the MCP handler has already authenticated the request and put the principal in its context.

type ChecksV

type ChecksV struct {
	NowUnix   int64       `json:"now_unix"`
	IntervalS uint32      `json:"interval_s"`
	Columns   []checkColV `json:"columns"`
	Rows      []checkRowV `json:"rows"`
	Truncated bool        `json:"truncated,omitempty"`
}

ChecksV is the checks_results result: the node x profile matrix, one cell per column in the order of columns.

type Config

type Config struct {
	Plans Plans
	Auth  Auth
	// API is the in-process admin API: auth.RequireSession over the services, request paths without the "/api" prefix
	// ("/mistgate.admin.v1.UserService/GetUser").
	API http.Handler
	// Audit writes a row; nil drops them (tests).
	Audit func(ctx context.Context, e AuditEntry)
	Now   func() time.Time // default time.Now
	Log   *slog.Logger
}

Config wires the MCP layer.

type DoctorV

type DoctorV struct {
	Fresh     bool          `json:"fresh"`
	Nodes     []nodeDoctorV `json:"nodes"`
	Truncated bool          `json:"truncated,omitempty"`
}

DoctorV is the node_doctor result.

type EventsV

type EventsV struct {
	Events       []eventV `json:"events"`
	HasMore      bool     `json:"has_more"`
	NextBeforeID int64    `json:"next_before_id,omitempty"`
	Truncated    bool     `json:"truncated,omitempty"`
}

EventsV is the events_search result.

type Fact

type Fact struct {
	Key             string            `json:"key"`
	Value           string            `json:"value"`
	Untrusted       bool              `json:"untrusted,omitempty"`
	Code            string            `json:"code,omitempty"`
	Params          map[string]string `json:"params,omitempty"`
	UntrustedParams []string          `json:"untrusted_params,omitempty"`
}

Fact is one line of "what this will do", built by the panel from structured parameters and what it read. A value that came from data somebody could have written (a user or node name, a note, a node's own text) is untrusted. Code and Params say the same as Value for the owner's UI, which words them itself (integrations.proto ApprovalFact); the params named in UntrustedParams come from data and are shown quoted, apart from the panel's wording.

type FleetStatusV

type FleetStatusV struct {
	NodesTotal     uint32         `json:"nodes_total"`
	NodesProblem   uint32         `json:"nodes_problem"`
	UsersOnline    uint32         `json:"users_online"`
	AlertsActive   uint32         `json:"alerts_active"`
	AlertsCritical uint32         `json:"alerts_critical"`
	Nodes          []nodeBriefV   `json:"nodes"`
	TopConsumers   []topConsumerV `json:"top_consumers,omitempty"`
	Truncated      bool           `json:"truncated,omitempty"`
}

FleetStatusV is the fleet_status result.

type GroupsV

type GroupsV struct {
	Groups    []groupV `json:"groups"`
	Truncated bool     `json:"truncated,omitempty"`
}

GroupsV is the groups_list result.

type NodeGetV

type NodeGetV struct {
	ID            string            `json:"id"`
	Name          string            `json:"name"`
	Country       string            `json:"country,omitempty"`
	Location      string            `json:"location,omitempty"`
	Provider      string            `json:"provider,omitempty"`
	Status        string            `json:"status"`
	Reason        string            `json:"reason,omitempty"`
	Protocols     []string          `json:"protocols,omitempty"`
	AgentVersion  string            `json:"agent_version,omitempty"`
	UptimeS       uint64            `json:"uptime_s"`
	LastSeenUnix  int64             `json:"last_seen_unix"`
	CreatedUnix   int64             `json:"created_unix"`
	Warp          string            `json:"warp,omitempty"`
	Facts         *factsV           `json:"facts,omitempty"`
	Inbounds      []inboundV        `json:"inbounds"`
	OnlineByProto map[string]uint32 `json:"online_by_protocol,omitempty"`
	OnlineUsers   []onlineUserV     `json:"online_users,omitempty"`
	OnlineTotal   uint32            `json:"online_total"`
	Notes         string            `json:"notes,omitempty"`
	Truncated     bool              `json:"truncated,omitempty"`
}

NodeGetV is the node_get result.

type NodeMetricsV

type NodeMetricsV struct {
	ID           string            `json:"id"`
	Name         string            `json:"name"`
	Status       string            `json:"status"`
	HasMetrics   bool              `json:"has_metrics"`
	AtUnix       int64             `json:"at_unix,omitempty"`
	CPUPct       float32           `json:"cpu_pct"`
	SoftIRQPct   float32           `json:"softirq_pct"`
	Load1        float32           `json:"load1"`
	RAMUsed      uint64            `json:"ram_used_bytes"`
	RAMTotal     uint64            `json:"ram_total_bytes"`
	DiskUsed     uint64            `json:"disk_used_bytes"`
	DiskTotal    uint64            `json:"disk_total_bytes"`
	NetRxBps     uint64            `json:"net_rx_bps"`
	NetTxBps     uint64            `json:"net_tx_bps"`
	TrafficToday uint64            `json:"traffic_today_bytes"`
	OnlineByProt map[string]uint32 `json:"online_by_protocol,omitempty"`
	TopToday     []topUserV        `json:"top_today,omitempty"`
}

NodeMetricsV is the node_metrics result. The API has no history per node: these are the current gauges and today's totals.

type Outcome

type Outcome struct {
	Code   string
	Params map[string]string
}

Outcome is what came of a change, as a code the owner's UI words itself ("users_disabled" {n}), next to the English line the agent reads. A failure's code is the panel's own refusal where there is one ("no_trusted_bundle").

type Plan

type Plan struct {
	ID, TokenID, TokenName, TokenProfile, Tool               string
	ParamsJSON, FactsJSON, Summary, Danger, Reason, InnerRef string
	ParamsHash, ConfirmHash                                  []byte
	NeedsApproval                                            bool
	Status                                                   string
	CreatedAt, ExpiresAt, DecidedAt, AppliedAt               time.Time
	DecidedBy, DecidedByName, Result, Error                  string
	OutcomeCode, OutcomeParams                               string // what came of it, for the owner's UI (Outcome)
}

Plan is one change an agent asked for. The fields (names, types, order) are those of store.MCPPlan, so the wiring in cmd/mistgate converts one to the other with a plain conversion.

type PlanOut

type PlanOut struct {
	PlanID        string   `json:"plan_id"`
	Summary       string   `json:"summary"`
	Facts         []Fact   `json:"facts"`
	NeedsApproval bool     `json:"needs_approval"`
	Danger        []string `json:"danger,omitempty"`
	ExpiresInS    int      `json:"expires_in_s"`
	ConfirmToken  string   `json:"confirm_token"`
	Next          string   `json:"next"`
}

PlanOut is the result of a _plan tool.

type Plans

type Plans interface {
	CreateMCPPlan(ctx context.Context, p Plan, maxOpenPerToken, maxAwaiting int) error
	// MCPPlanByConfirm finds the plan of this token with this confirm-token hash; ErrNotFound otherwise.
	MCPPlanByConfirm(ctx context.Context, tokenID string, confirmHash []byte) (Plan, error)
	GetMCPPlan(ctx context.Context, id string) (Plan, error)
	// BeginApply is the compare-and-swap planned|approved -> applying (same token, tool, hashes, not expired). Any error
	// means "not started"; the caller reads the plan again to say why.
	BeginApply(ctx context.Context, id, tokenID, tool string, paramsHash, confirmHash []byte, now time.Time) (Plan, error)
	// FinishApply ends the apply with the agent's English result or error and the outcome (code and JSON params).
	FinishApply(ctx context.Context, id string, ok bool, result, errText, outcomeCode, outcomeParams string, now time.Time) error
}

Plans is the storage of plans: *store.Store through the wiring in cmd/mistgate.

type Principal

type Principal struct {
	TokenID string
	Profile Profile
}

Principal is the token behind a request, as the bearer layer resolved it.

type Profile

type Profile string

Profile is what a token may do: readonly (reads), operator (+ day-to-day changes), admin (+ the dangerous ones, through the owner's approval). The roles they map to (readonly, helper, owner) are the auth package's business.

const (
	ProfileReadonly Profile = "readonly"
	ProfileOperator Profile = "operator"
	ProfileAdmin    Profile = "admin"
)

type ReasonField

type ReasonField struct {
	Reason string `` /* 131-byte string literal not displayed */
}

ReasonField is embedded in the arguments of every _plan tool.

type SubscriptionPreviewV

type SubscriptionPreviewV struct {
	User      userV         `json:"user"`
	Clients   []clientV     `json:"clients,omitempty"`
	Client    *clientV      `json:"client,omitempty"`
	UserAgent string        `json:"user_agent,omitempty"`
	Serve     *serveV       `json:"serve,omitempty"`
	Profiles  []profileRefV `json:"profiles,omitempty"`
	Nodes     []nodeAccessV `json:"nodes,omitempty"`
	Note      string        `json:"note"`
	Truncated bool          `json:"truncated,omitempty"`
}

SubscriptionPreviewV is the subscription_preview result. It says which format a client would get and what the user's access gives; it is not the rendered subscription and carries no link (a link is a credential).

type UpdatesV

type UpdatesV struct {
	NowUnix      int64         `json:"now_unix"`
	PanelVersion string        `json:"panel_version"`
	PanelBuilt   int64         `json:"panel_built,omitempty"`
	Bundle       *bundleV      `json:"bundle,omitempty"`
	Nodes        []nodeUpdateV `json:"nodes"`
	Rollout      *rolloutV     `json:"rollout,omitempty"`
	Truncated    bool          `json:"truncated,omitempty"`
}

UpdatesV is the updates_status result.

type UserDevicesV

type UserDevicesV struct {
	UserID    string    `json:"user_id"`
	Name      string    `json:"name"`
	Limit     uint32    `json:"device_limit"`
	Devices   []deviceV `json:"devices"`
	Truncated bool      `json:"truncated,omitempty"`
}

UserDevicesV is the user_devices result.

type UserGetV

type UserGetV struct {
	User       userV         `json:"user"`
	Devices    []deviceV     `json:"devices"`
	Profiles   []profileRefV `json:"profiles,omitempty"`
	NodeAccess []nodeAccessV `json:"node_access,omitempty"`
	Truncated  bool          `json:"truncated,omitempty"`
}

UserGetV is the user_get result: no subscription link, no keys.

type UserTrafficV

type UserTrafficV struct {
	UserID     string         `json:"user_id"`
	Name       string         `json:"name"`
	UsedBytes  uint64         `json:"used_bytes"`
	QuotaBytes uint64         `json:"quota_bytes"`
	QuotaReset string         `json:"quota_reset,omitempty"`
	NextReset  int64          `json:"next_reset_unix,omitempty"`
	Daily      []dayV         `json:"daily"`
	PerNode    []nodeTrafficV `json:"per_node,omitempty"`
	Truncated  bool           `json:"truncated,omitempty"`
}

UserTrafficV is the user_traffic result.

type UsersV

type UsersV struct {
	Users         []userV `json:"users"`
	NextPageToken string  `json:"next_page_token,omitempty"`
	Total         uint32  `json:"total"`
	Online        uint32  `json:"online"`
	Expiring      uint32  `json:"expiring"`
	OverQuota     uint32  `json:"over_quota"`
	Truncated     bool    `json:"truncated,omitempty"`
}

UsersV is the users_search result.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL