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
- Variables
- func New(c Config) (http.Handler, error)
- func RunProxy(ctx context.Context, rawURL, tokenFile string, stdin io.Reader, ...) error
- type AlertsV
- type ApplyOut
- type AuditEntry
- type AuditV
- type Auth
- type ChecksV
- type Config
- type DoctorV
- type EventsV
- type Fact
- type FleetConnectionsV
- type FleetStatusV
- type GroupsV
- type Ipv6CheckV
- type KlickReportsV
- type NodeConnectionsV
- type NodeGetV
- type NodeJournalV
- type NodeMetricsV
- type NodePortsV
- type Outcome
- type Plan
- type PlanOut
- type Plans
- type Principal
- type Profile
- type ReasonField
- type RelayCandidatesV
- type RelaysV
- type SubsSettingsV
- type SubscriptionPreviewV
- type UpdatesV
- type UserConnectionV
- type UserDevicesV
- type UserGetV
- type UserTrafficV
- type UsersV
- type WarpStatusV
Constants ¶
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.
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 ¶
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 ¶
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 request whose procedure-specific flag guarantees no change.
WithPlanning(ctx context.Context) context.Context
// WithApprovedStepUp lets only procedures listed on planID through, with their step-up checks, while the plan 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"`
UdpLoss *udpLossV `json:"udp_loss,omitempty"`
// TSPUProbe: the newest run of the TSPU probe, while that source is on and has run.
TSPUProbe *tspuRunV `json:"tspu_probe,omitempty"`
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. All times are measured on the panel's server, not on a person's device.
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 FleetConnectionsV ¶ added in v0.1.56
type FleetConnectionsV struct {
SinceUnix int64 `json:"since_unix"`
NowUnix int64 `json:"now_unix"`
Nodes []fleetNodeConnV `json:"nodes"`
Truncated bool `json:"truncated,omitempty"`
}
FleetConnectionsV is the all-node connection-counter summary.
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 Ipv6CheckV ¶ added in v0.1.66
type Ipv6CheckV struct {
NodeID string `json:"node_id"`
Node string `json:"node"`
Passed bool `json:"passed"`
ErrorCode string `json:"error_code,omitempty"`
Sender string `json:"sender,omitempty"`
CheckedUnix int64 `json:"checked_unix,omitempty"`
Ports []ipv6PortV `json:"ports"`
}
Ipv6CheckV is node_ipv6_check: the verdict of every port, never an address.
type KlickReportsV ¶ added in v0.1.52
type KlickReportsV struct {
Enabled bool `json:"enabled"`
Reports uint32 `json:"reports_7d"`
LastUnix int64 `json:"last_unix,omitempty"`
NowUnix int64 `json:"now_unix"`
Nodes []klickNodeV `json:"nodes"`
Truncated bool `json:"truncated,omitempty"`
}
KlickReportsV is the klick_reports result: the switch of the kl!ck reports and, while it is on, what they say per node.
type NodeConnectionsV ¶ added in v0.1.53
type NodeConnectionsV struct {
NodeID string `json:"node_id"`
NodeName string `json:"node_name"`
Supported bool `json:"supported"`
SinceUnix int64 `json:"since_unix"`
NowUnix int64 `json:"now_unix"`
Inbounds []inboundConnV `json:"inbounds"`
Truncated bool `json:"truncated,omitempty"`
}
NodeConnectionsV is the node_connections result: a node's connection counters per inbound over the window.
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"`
// IPv6 is the node's IPv6 entry (an extra "· IPv6" server in the subscriptions): whether it is on, whether the node can take
// one, and the latest check of the address. Never the address.
IPv6 *ipv6EntryV `json:"ipv6,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
NodeGetV is the node_get result.
type NodeJournalV ¶ added in v0.1.55
type NodeJournalV struct {
SinceUnix int64 `json:"since_unix"`
NowUnix int64 `json:"now_unix"`
Entries []nodeJournalEntryV `json:"entries"`
Truncated bool `json:"truncated,omitempty"`
NodesWithoutJournal []string `json:"nodes_without_journal"`
}
NodeJournalV is the node_journal result: saved warning and error records, ordered newest first.
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 NodePortsV ¶ added in v0.1.28
type NodePortsV struct {
NodeID string `json:"node_id"`
NodeName string `json:"node_name"`
ErrorCode string `json:"error_code,omitempty"`
Sender string `json:"sender,omitempty"`
UDPFilteredUnix int64 `json:"udp_filtered_unix"`
Ports []portCheckV `json:"ports"`
TCP []tcpCheckV `json:"tcp"`
}
NodePortsV is the node_ports result.
type Outcome ¶
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 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.
type ReasonField ¶
type ReasonField struct {
Reason string `` /* 131-byte string literal not displayed */
}
ReasonField is embedded in the arguments of every _plan tool.
type RelayCandidatesV ¶ added in v0.1.65
type RelayCandidatesV struct {
EntryNodeID string `json:"entry_node_id"`
EntryNode string `json:"entry_node"`
AgentSupported bool `json:"agent_supported"`
EntryCountry *relayCountryV `json:"entry_country_check,omitempty"`
Candidates []relayCandidateV `json:"candidates"`
Truncated bool `json:"truncated,omitempty"`
}
RelayCandidatesV is the relay_candidates result.
type RelaysV ¶ added in v0.1.65
type RelaysV struct {
Relays []relayV `json:"relays"`
Offset int `json:"offset"`
Limit int `json:"limit"`
Total int `json:"total"`
NextOffset int `json:"next_offset,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
RelaysV is the relays_list result.
type SubsSettingsV ¶ added in v0.1.16
type SubsSettingsV struct {
Title string `json:"title"` // "" = the brand
EffectiveTitle string `json:"effective_title"`
Announcement string `json:"announcement"`
SupportURL string `json:"support_url"`
UpdateIntervalHours uint32 `json:"update_interval_hours"` // 0 = 12
ServerNameTemplate string `json:"server_name_template"`
UserPage struct {
ShowAnnouncement bool `json:"show_announcement"`
ShowSupport bool `json:"show_support"`
ShowQR bool `json:"show_qr"`
DeviceSelfService bool `json:"device_self_service"`
PagePassword bool `json:"page_password"`
DNSChoice bool `json:"dns_choice"` // people pick the DNS of each server on their page (off when absent)
} `json:"user_page"`
Apps map[string][]subsAppV `json:"apps"` // by platform, in display order
}
SubsSettingsV is what subscription_settings_get returns.
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"`
UpdateChannel string `json:"update_channel"`
RunningVersionChannel string `json:"running_version_channel,omitempty"`
OfferedReleaseChannel string `json:"offered_release_channel,omitempty"`
RunningNewerThanChannelOffers bool `json:"running_newer_than_channel_offers"`
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 UserConnectionV ¶ added in v0.1.53
type UserConnectionV struct {
SinceUnix int64 `json:"since_unix"`
NowUnix int64 `json:"now_unix"`
Rows []deviceConnV `json:"rows"`
NodesWithoutCounters []nodeWithoutV `json:"nodes_without_counters"`
Truncated bool `json:"truncated,omitempty"`
}
UserConnectionV is the user_connection result: a person's connection counters per device, node and inbound over the window.
type UserDevicesV ¶
type UserDevicesV struct {
UserID string `json:"user_id"`
Name string `json:"name"`
Limit uint32 `json:"device_limit"`
Devices []deviceV `json:"devices"`
// Blocked: devices the owner revoked and refused; they are not in devices and take no place. Unblocking is in the admin panel.
Blocked []blockedDeviceV `json:"blocked,omitempty"`
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.
type WarpStatusV ¶ added in v0.1.24
type WarpStatusV struct {
NodeID string `json:"node_id"`
NodeName string `json:"node_name"`
HasAccount bool `json:"has_account"`
Enabled bool `json:"enabled"`
Paused bool `json:"paused"`
AgentState string `json:"agent_state"`
Colo string `json:"colo,omitempty"`
LastHandshakeAgeS *uint64 `json:"last_handshake_age_s,omitempty"`
ProbeCloudflare *warpProbeV `json:"probe_cloudflare,omitempty"`
ProbeOther *warpProbeV `json:"probe_other,omitempty"`
RegisteredUnix int64 `json:"registered_unix,omitempty"`
HasToken bool `json:"has_token"`
Profiles []string `json:"profiles"`
}
WarpStatusV is the warp_status result. It intentionally projects only status and probe fields from GetWarp: account addresses, endpoints, keys and registration metadata stay inside the panel.