mistgate Docs
EN
327

In the admin: AI

Admin API

The Connect-RPC API behind the admin, how to call it with curl or a generated client, API tokens and their profiles, and what a token may and may not do.

On this page

The admin UI talks to the panel through a Connect-RPC API. Scripts use the same API, with the same role checks, validation and audit log, by sending an API token instead of a session cookie. AI agents use the same tokens through the MCP server.

Where the API lives#

Every procedure is a POST to the admin URL plus api/ and the procedure path:

Text
<admin URL>api/mistgate.admin.v1.<Service>/<Method>
https://panel.example.com/<prefix>/api/mistgate.admin.v1.UserService/ListUsers

The admin URL is the one mistgate setup printed (Settings → Domains shows it to the owner): with a secret prefix, a secret host or a separate listener. The API is only reachable there; on the public side the same path gets the decoy site.

The handlers are connect-go handlers, so the Connect protocol (JSON or binary protobuf), gRPC and gRPC-Web all work. The examples here use Connect with JSON.

Services#

The API is defined in proto/mistgate/admin/v1/. Generated code is in the repository: Go in gen/mistgate/admin/v1 (packages adminv1 and adminv1connect), TypeScript in web/src/gen.

Service File What it covers
AuthService auth.proto Sign-in, passkeys, password, sessions, step-up, the audit log, captcha settings
InstanceService instance.proto Brand settings, the admin and subscription addresses
FleetService fleet.proto The overview and the event feed
NodeService node.proto Nodes: list, details, settings, install commands, restarts, logs, retirement
ProfileService profile.proto Protocols, profiles and profiles on nodes
GroupService group.proto Groups
UserService user.proto Users, their traffic, devices and subscription link
DeviceService device.proto AmneziaWG devices and their keys
SubscriptionService subscription.proto Subscription settings and app rules
DnsService dns.proto DNS presets, the presets each node offers on the user page, and what people picked
HealthService health.proto Alerts, client-eye checks, the doctor and its fixes
UpdateService update.proto Release bundle, node updates, schedules and rollouts, panel updates
ProvisioningService provisioning.proto Installing nodes over SSH and the saved SSH access of nodes
WarpService warp.proto WARP accounts of nodes
AwgService awg.proto Helpers of the AmneziaWG profile editor
BackupService backup.proto Encrypted panel backups
TrustTunnelService trusttunnel.proto A person's TrustTunnel key and tt:// links (package mistgate.trusttunnel.v1; the admin's write level, closed to API tokens and MCP)
TelegramService telegram.proto The Telegram bot and each admin's chat (owner and signed-in admins only; closed to API tokens and MCP)
ApiTokenService, ApprovalService integrations.proto API tokens and the owner's approvals
CheburcheckService, BsbordService cheburcheck.proto, bsbord.proto The cheburcheck and bsbord sources of the country check: settings, status and test, and for bsbord the unit list and the price check (owner only; changing or disconnecting a source, and the price check, need a step-up; closed to API tokens and MCP)

The comments in the proto files are the reference for every field. Conventions (common.proto):

  • Ids are opaque prefixed strings: nod_…, usr_…, prf_…, grp_…, dev_…, inb_… (a profile on a node).
  • Times are Unix seconds in fields ending in _unix; 0 means unset. Byte counters are unsigned 64-bit.
  • In JSON, field names are lowerCamelCase (pageSize), enums are their names (USER_FILTER_ONLINE) and 64-bit integers are strings (numbers are accepted on input).
  • Updates use optional fields: a field that is absent stays unchanged.
  • Errors are Connect codes with short messages: not_found, already_exists, invalid_argument, failed_precondition, aborted (somebody changed it first), permission_denied, unauthenticated, resource_exhausted.

API tokens#

The owner creates tokens in AI → MCP and tokens → New token (a fresh step-up is needed):

Field Rule
Name 1 to 64 characters, unique among the live tokens ignoring case. It is what the audit log shows.
Access The profile: Read only, Operator or Admin.
Lifetime 90 days by default, at most 365. A token always expires; to renew one, make a new token and revoke the old one.
Requests per minute 120 by default, 1 to 600.

The secret looks like tk1_ followed by 43 URL-safe characters. It is shown once; the panel keeps only its SHA-256 and the last four characters (to tell tokens apart in the list). At most 50 live tokens exist at a time. The list shows when and from where each token was last used, and through which channel (the API or MCP).

Revoke stops a token at once: its next request is refused and the changes it planned through MCP and did not apply are cancelled. Revoking needs a step-up.

Authentication#

Send the token in one Authorization header with the Bearer scheme:

Text
Authorization: Bearer tk1_...

A request with a Bearer header is judged by the token alone; a cookie is never looked at. Refusals:

Status Body code Message
401 unauthenticated not signed in (missing, malformed or unknown token), token revoked, token expired
403 permission_denied this call is not available to API tokens, this token's profile cannot do this, this needs the owner's approval; it is not available over the API, this is used only while the MCP server makes a plan; it is not available over the API
429 resource_exhausted too many requests for this token, slow down, with Retry-After

Calling the API#

With curl#

Shell
TOKEN=$(head -n1 ~/.config/mistgate/token)
ADMIN=https://panel.example.com/<prefix>/

curl -sS "${ADMIN}api/mistgate.admin.v1.UserService/ListUsers" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"filter": "USER_FILTER_ONLINE", "pageSize": 20}'

A change looks the same. Extending two users by 30 days (operator profile or higher):

Shell
curl -sS "${ADMIN}api/mistgate.admin.v1.UserService/ExtendUsers" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"userIds": ["usr_...", "usr_..."], "days": 30}'

An error comes back as JSON with an HTTP error status:

JSON
{"code": "permission_denied", "message": "this token's profile cannot do this"}

With a generated client#

The Go packages are importable from the module github.com/mistgate/mistgate; pin a release tag or a commit, since the API may still change before 1.0. The client's base URL is the admin URL plus api:

Go
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"connectrpc.com/connect"

	adminv1 "github.com/mistgate/mistgate/gen/mistgate/admin/v1"
	"github.com/mistgate/mistgate/gen/mistgate/admin/v1/adminv1connect"
)

// bearer adds the API token to every request.
type bearer struct{ token string }

func (b bearer) RoundTrip(r *http.Request) (*http.Response, error) {
	r = r.Clone(r.Context())
	r.Header.Set("Authorization", "Bearer "+b.token)
	return http.DefaultTransport.RoundTrip(r)
}

func main() {
	raw, err := os.ReadFile(os.Getenv("MISTGATE_TOKEN_FILE"))
	if err != nil {
		log.Fatal(err)
	}
	token := strings.TrimSpace(strings.SplitN(string(raw), "\n", 2)[0])
	hc := &http.Client{Transport: bearer{token}}

	// The admin URL that `mistgate setup` printed, plus "api".
	base := "https://panel.example.com/<prefix>/api"
	users := adminv1connect.NewUserServiceClient(hc, base)

	resp, err := users.ListUsers(context.Background(), connect.NewRequest(&adminv1.ListUsersRequest{PageSize: 10}))
	if err != nil {
		log.Fatal(connect.CodeOf(err), err)
	}
	for _, u := range resp.Msg.GetUsers() {
		fmt.Println(u.GetId(), u.GetName(), u.GetStatus())
	}
}

For another language, generate a client from proto/ with buf generate and the Connect or gRPC plugin of that language.

The Telegram proxy#

The MTProto profiles and a person's Telegram key use these parts of ProfileService and UserService:

  • ProtocolInfo.experimental (from ProfileService.ListProtocols): true for a protocol that is new and not proven in the field yet. MTProto sets it.
  • AppToggles.telegram, in CreateUser and UpdateUser, is the person's Telegram switch. Turning it on makes the person's key, and turning it off revokes it. At least one of happ and amnezia must stay on.
  • ListUsers takes the filter USER_FILTER_TELEGRAM: the people whose Telegram switch is on, whatever their key or the MTProto profiles. Each user in the list carries access_telegram (the switch is on and an MTProto server is usable for them) and telegram_issued (a key was made).
  • GetTelegramLinks reads a person's proxy: has_key, key_device_id, key_issued_unix and the tg://proxy links, one per node and profile, with ipv6, relay and via marking the node's IPv6 twin and a relay's twin. It writes nothing. A link carries the person's secret, so treat the answer like a password.
  • IssueTelegramKey makes the key when the person has none (it needs the switch on and a person who is not disabled; the device limit does not apply), RotateTelegramKey gives it a new secret so that every earlier link stops working (not_found "key" without one), and RevokeTelegramKey revokes it and leaves the switch on. Each answers with the person's proxy as GetTelegramLinks does. The key is a device of the person of kind DEVICE_KIND_TELEGRAM_KEY, and RevokeDevice removes it too.

All four calls are for the owner and helpers, and closed to API tokens, like the other calls that return a credential.

A person in several groups#

A person has one main group (User.group_id, with group_name and group_color) and any number of extra groups: User.extra_group_ids, with extra_group_names and extra_group_colors in step with them (ordered by name). The main group alone decides the DNS preset, the Mihomo template, the response headers and the colour; an extra group only adds access, by the rule of A person in several groups.

  • UpdateUserRequest.add_group_ids and remove_group_ids change the extra groups by deltas, so two changes made at once do not undo each other and a repeat does nothing. group_id is still the main group; with group_id = B and add_group_ids = [A] the person gets B as the main group and keeps A as an extra one, and without A the old main group is left. The refusals are INVALID_ARGUMENT with group_in_both, main_group (the main group cannot be removed) and too_many_groups (16 groups at most, the main one counted), and NOT_FOUND for a group that does not exist.
  • UpdateUserResponse.impact (with dry_run too) says what the new set of groups does: the profiles gained and lost, and AccessImpact.gained_node_ids and lost_node_ids, the nodes where the person starts to get something and where they stop getting anything. A change counts as one change of the person against a token's limit.
  • ListUsersRequest.group_id finds the people who have the group as the main or as an extra group, each once.
  • Group.user_count counts the people whose main group it is and Group.extra_user_count the people who have it as an extra group. DeleteGroup is refused (group_not_empty) only while people have the group as their main one; the extra members just leave it. The audit row user_update carries groups_added and groups_removed, group_delete the number of extra members who left (extra_left).
  • Old clients keep working: a client that only knows group_id changes the main group, as before. A script that walks ListUsers(group_id=X) and sets group_id=Y on everybody now moves the extra members as well and makes Y their main group: filter on User.group_id in such a script.

TrustTunnel#

The TrustTunnel profiles and a person's key use ProfileService, UserService and a service of their own, mistgate.trusttunnel.v1.TrustTunnelService:

  • ProtocolInfo.experimental is true for TrustTunnel, as for MTProto.
  • AppToggles.trust_tunnel, in CreateUser and UpdateUser, is the person's TrustTunnel switch. Turning it on makes the person's key when the person is active, and turning it off revokes it. At least one of happ and amnezia must stay on.
  • GetTrustTunnelLinks reads a person's links: has_key, key_device_id, key_issued_unix and the tt:// links, one per node and profile, with ipv6, relay and via marking twins. A link that cannot be made (a self-signed server) has an empty url and a note. It writes nothing.
  • IssueTrustTunnelKey makes the key when the person has none (the switch must be on and the person active; the key takes a place in the device limit, and at the limit the call fails with device_limit), and RevokeTrustTunnelKey revokes it and leaves the switch on. Each answers as GetTrustTunnelLinks does.

A tt:// link carries the person's secret, so all three calls are the admin's write level and closed to API tokens and MCP, like the other calls that return a credential. In the Cloudflare edition they answer unavailable_in_edition.

Token profiles#

A profile acts as an admin role: Read only as read-only, Operator as helper, Admin as owner. On top of the role, a token may call only the procedures on a fixed allow-list (internal/panel/auth/policy_tokens.go); everything else is refused whatever the profile. Nothing on the list returns a credential.

Procedure Read only Operator Admin
FleetService.Overview, FleetService.ListEvents yes yes yes
NodeService.ListNodes, NodeService.GetNode yes yes yes
NodeService.CheckPorts no yes yes
HealthService.ListAlerts, GetChecks, GetDoctor yes yes yes
UserService.ListUsers, UserService.GetUser yes yes yes
GroupService.ListGroups yes yes yes
ProfileService.ListProfiles, ProfileService.GetProfile (secrets masked) yes yes yes
ProfileService.ListProtocols, ProfileService.PreviewProfile yes yes yes
SubscriptionService.GetSubscriptionSettings, ListClients, TestUserAgent yes yes yes
UpdateService.GetUpdates, GetOsUpdates yes yes yes
UserService.CreateUser, UpdateUser, SetUsersEnabled, ExtendUsers, ResetUserTraffic, RevokeDevice no yes yes
HealthService.MuteAlert, DismissAlert, RunChecksNow, RunDoctor no yes yes
AuthService.ListAudit no no yes
HealthService.ApplyFix no no only through an approved MCP plan
UpdateService.StartRollout, PauseRollout, ResumeRollout, CancelRollout, RollbackNode no no only through an approved MCP plan
UpdateService.StartOsRollout, CancelOsRollout no no only through an approved MCP plan
UpdateService.RefreshOsUpdates no no no (the owner's click in the admin)
UpdateService.ScheduleNodeUpdate, CancelNodeUpdateSchedule, SetUpdateTimezone, SetUpdateDownloadTimeout no no only through an approved MCP plan
ProvisioningService.ListNodeServerAccess (connection metadata, never a password) no no yes
ProvisioningService.GetSSHFingerprint no no only while the MCP server makes a node_install plan
ProvisioningService.StartNodeProvision, RotateNodeServerPassword no no only through an approved MCP plan
SubscriptionService.UpdateSubscriptionSettings (the shared settings: an app of the user page, texts, own response headers, own Mihomo templates, own routing profiles for Happ and INCY; a save that changes a template or a routing profile is the owner's: a helper gets PERMISSION_DENIED mihomo_templates_owner_only or routing_profiles_owner_only, a token only through the owner's approval of a subscription_mihomo_template_set or subscription_routing_set plan) no only through an approved MCP plan only through an approved MCP plan
SubscriptionService.PreviewRoutingProfile no no no (the admin's reading of a pasted profile; an agent sees the profiles in subscription_settings_get and which one a person gets in subscription_preview)
SubscriptionService.PreviewMihomoTemplate no no no (the admin's preview; an agent reads a template with subscription_mihomo_template_get and sees which one a person gets in subscription_preview)
ProfileService.CreateProfile, UpdateProfile, DeleteProfile, CreateInbound, DeleteInbound; GroupService.UpdateGroup no no only through an approved MCP plan

Closed to every token: deleting users, the subscription link, the Telegram proxy and TrustTunnel keys and links, devices and their keys, unblocking a device (UserService.UnblockDevice; a token can block one with RevokeDevice and block, but only an admin lifts the block), node enrollment, settings, restarts, logs and retirement, preparing the AmneziaWG kernel module, taking a profile off several nodes at once with or without deleting it (ProfileService.RemoveProfileFromNodes), the admin's own SSH install steps (checking a server, retrying a job, revealing or forgetting saved access), creating groups, DNS presets and subscription settings (except the user page's app list through an approved plan), WARP, backups, panel updates and bundle rescans, brand settings, tokens, approvals, the admins' own account (passkeys, password, sessions, step-up) and the captcha settings.

Changes that need the owner#

A token never passes step-up. Procedures that need a step-up, or that change what runs on the nodes, are never callable with a token directly; over the plain API they answer 403 "this needs the owner's approval; it is not available over the API".

They are reachable only through the MCP server with an Admin token (the user page's app list from the Operator profile up): the agent plans the change, the owner reads the plan in AI → Waiting for you and approves it (with a step-up of their own), and only then does the agent's apply carry out the approved plan. The approval is checked in the database on every call, and the grant allows only the procedures listed on that plan. A plan expires 10 minutes after it was made.

Limits#

  • Requests per minute per token: as set on the token (1 to 600, default 120), with a burst of up to 30. Over the limit: 429 with Retry-After.
  • User changes per token: in one hour, counted from the token's first such change, a token may take access away from, or rewrite, at most 10 people: disable them, reset their traffic, revoke or block a device, edit a person, move a group's people, or change a group so that what its people get changes. Every person in every call counts; a call that changes nothing is free, and creating, extending and enabling people are not counted. A call over the limit is refused whole: 429 with the code token_user_change_limit and limit, used, asked and retry_after_seconds (when one call asks for more than the whole limit it is 0 and the message also carries reason=over_hourly_limit: split the call or ask the owner). The owner can lift the limit for one token in AI → MCP and tokens (Limit in the token's row, or the switch when creating it); it needs a fresh step-up. Through MCP a plan over the limit waits for the owner's approval instead of being refused. Existing tokens are limited after the update.
  • Per client network on the admin surface: 30 requests per second with a burst of 200, for cookies and tokens alike.
  • Request size: 64 KiB to 1 MiB depending on the service.
  • Lifetime: every token expires (at most 365 days).

Audit#

Every token call writes a row to the audit log: "called <procedure>", the HTTP status, the client address, and the actor "API token <name>" (or "MCP token <name>" through MCP). Successful reads are written at most once a minute per procedure; changes and refusals every time. The rows of the procedure itself (for example "created the user …") are written as for an admin.

What responses never contain#

  • CreateUser called with a token returns the user without the subscription link and the page password. GetSubscriptionLink is closed to tokens. UpdateUser takes page_password_action (CHANGE, REMOVE or RESTORE) for the person's page password: a new password for the same link, the page open on the link alone, the password asked again with a new one. It counts as one change of the person for a token's hourly limit, a repeat that changes nothing is free, and no response carries the password (the owner reads it with GetSubscriptionLink). User.page_open says that the password was removed.
  • Profile secrets come back masked (••••), for every caller.
  • Device keys and configurations (DeviceService) and WARP accounts are closed to tokens.
  • A device's ID (HWID) is never stored or returned: Device.fingerprint is the first six characters of its hash, enough to tell two identical phones apart.
  • Token secrets are never returned after creation, not even to the owner.
  • Audit parameters never contain secrets.

Edit this page on GitHub