config

package
v0.6.7 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 13 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 config reads the lazy-mcp `servers.json` format. The format is a contract with the sets this binary spawns, so it stays byte-compatible with what lazy-mcp already accepts.

Permission gate for tool calls, compatible with lazy-mcp's experimental `permissions` block. Without a block every call is allowed.

Index

Constants

View Source
const (
	SandboxModeNone  = "none"
	SandboxModeBwrap = "bwrap"

	OnUnavailableDeny  = "deny"
	OnUnavailableWarn  = "warn"
	OnUnavailableAllow = "allow"

	SandboxNetworkNone  = "none"
	SandboxNetworkAllow = "allow"

	// DefaultSandboxMemoryMb ограничивает виртуальную память (RLIMIT_AS), а не
	// RSS: под 512 МиБ не поднимается ни node, ни Go (проверено живьём —
	// canary на go-sdk падал «failed to reserve page summary memory»).
	DefaultSandboxMemoryMb = 2048
	DefaultSandboxPids     = 256
	DefaultSandboxTimeout  = 30
	// DefaultSandboxTmpMb — /tmp внутри песочницы: 128 МиБ хватает node и
	// python, а диск хоста не забивается.
	DefaultSandboxTmpMb = 128
)
View Source
const (
	ExposeResources = "resources"
	ExposePrompts   = "prompts"
)

Exposed surfaces a server may contribute to the proxy.

View Source
const DefaultCallbackPort = 8947

DefaultCallbackPort is the loopback port the redirect listener uses unless a config overrides it. Fixed on purpose: some authorization servers only accept a redirect URI registered by hand.

Variables

View Source
var DefaultSandboxRO = []string{"/usr", "/bin", "/lib", "/lib64", "/etc/ssl", "/etc/resolv.conf", "/etc/passwd", "/etc/group"}

DefaultSandboxRO — минимум, без которого не живёт ни один интерпретатор. Несуществующие пути Wrap пропускает: bwrap падает на отсутствующем источнике.

View Source
var ReservedEnvPrefixes = []string{"MCPRIG_", "BAO_", "OPENBAO_"}

ReservedEnvPrefixes — переменные менеджера и хранилища секретов. Их имена не уходят вниз ни через env/envAllow, ни через ${VAR} набора: иначе сервер получает пароль панели или токен OpenBao.

Functions

func DenyReason added in v0.5.0

func DenyReason(global, server *Permissions, serverName, command string) (string, bool)

DenyReason applies lazy-mcp's resolution order and reports whether the call is denied, together with the rule's message.

Order (first non-empty wins, last matching rule within a level wins): server rules, global rules, server default, global default, implicit allow.

func EnvRefs added in v0.6.6

func EnvRefs(text string) []string

EnvRefs возвращает имена ${VAR} в порядке появления, без повторов. Одна грамматика на всех: раскрывает config, а проверяют набор и doctor.

func ExpandEnvRefs added in v0.6.6

func ExpandEnvRefs(text string, lookup func(name string) (string, bool)) string

ExpandEnvRefs заменяет ${VAR} тем, что вернул lookup; неизвестное имя остаётся как было, чтобы отказ был виден в тексте, а не превращался в пусто.

func HasFileRef

func HasFileRef(value string) bool

HasFileRef сообщает, есть ли {file:…} в любом месте строки: раскрыватель матчит шаблон где угодно, поэтому проверка по префиксу пропускает «p{file:/…}» и уносит файл вниз.

func ParseExpose added in v0.5.0

func ParseExpose(data json.RawMessage) ([]string, string)

ParseExpose reads the expose block: absent or null is no surfaces at all. The kinds themselves are checked by validateSandbox, so Load, Check and the registry agree on what a valid list is.

func ParseProfiles added in v0.5.0

func ParseProfiles(raw []byte) (map[string]*Profile, error)

ParseProfiles decodes a profiles block. Unknown fields and empty patterns are errors: "deny": ["*"] typo'd as "denny" would otherwise silently deny nothing.

func ReservedEnvName

func ReservedEnvName(name string) bool

ReservedEnvName — имя принадлежит менеджеру, а не нижестоящему серверу.

func ScrubSecrets

func ScrubSecrets(text string, secrets []string) string

ScrubSecrets заменяет секреты в свободном тексте: stderr ребёнка и текст ошибки апстрима охотно повторяют ключ, а наружу он уходить не должен.

func UnknownSandboxKeys

func UnknownSandboxKeys(data json.RawMessage) []string

UnknownSandboxKeys возвращает имена полей sandbox, которых нет в схеме.

func ValidatePublicURL added in v0.5.0

func ValidatePublicURL(raw string) error

ValidatePublicURL проверяет админский публичный адрес панели: абсолютный http(s) с хостом, без query/fragment и без хвостового «/». Адрес становится единственным источником OAuth-redirect, поэтому битое значение — отказ конфигурации, а не тихий дефолт.

Types

type Config

type Config struct {
	Servers        []*Server      `json:"servers"`
	Transport      *HTTPTransport `json:"transport,omitempty"`
	HealthMonitor  *HealthMonitor `json:"healthMonitor,omitempty"`
	RequestTimeout int            `json:"requestTimeout,omitempty"` // ms
	Permissions    *Permissions   `json:"permissions,omitempty"`
	OAuth          *OAuth         `json:"oauth,omitempty"`
	// RateLimit — лимит вызовов на клиента; пустое или нулевое поле — без него.
	RateLimit *RateLimit `json:"rateLimit,omitempty"`
	// Profiles — профили инструментов на ключ, см. internal/config/profiles.go.
	Profiles map[string]*Profile `json:"profiles,omitempty"`
}

Config is one set's file: the servers it proxies plus its listener.

func Load

func Load(path string) (*Config, error)

Load reads a config file. A server without a name fails the whole load; a server that does not decode is kept with a ConfigError like every other defect, so one typo never bricks the set.

func (*Config) OAuthFor

func (c *Config) OAuthFor(srv *Server) *OAuth

OAuthFor returns the effective OAuth settings for one server, set-wide block under the server's own, defaults filled in.

func (*Config) Usable

func (c *Config) Usable() []*Server

Usable reports whether the set can be served: at least one healthy server.

type HTTPTransport

type HTTPTransport struct {
	Type      string `json:"type,omitempty"`
	Host      string `json:"host,omitempty"`
	Port      int    `json:"port,omitempty"`
	Path      string `json:"path,omitempty"`
	AuthToken string `json:"authToken,omitempty"`
	// AuthTokens — все действующие ключи набора: принимается любой из них.
	// authToken остаётся ради файлов с одним ключом; пустой список означает
	// «смотреть на authToken».
	AuthTokens []string `json:"authTokens,omitempty"`
	// AllowAnonymous lets the listener start without an authToken and accepts
	// requests carrying no Authorization header; a presented token is still
	// checked. Set only for an open set.
	AllowAnonymous bool     `json:"allowAnonymous,omitempty"`
	AllowedHosts   []string `json:"allowedHosts,omitempty"`
	// ClientNames — имя клиента из подписи ключа: отпечаток ключа (6 hex от
	// sha256 токена) → подпись. Отпечаток, а не токен: ключ набора в конфиг
	// набора не попадает, а метка в статистике становится человеческой.
	ClientNames map[string]string `json:"clientNames,omitempty"`
	// KeyProfiles — профиль ключа по его отпечатку; ключ без профиля не
	// ограничен ничем, кроме permissions. Отпечаток, а не метка: метку клиент
	// называет сам.
	KeyProfiles map[string]string `json:"keyProfiles,omitempty"`
	// ToolOutTTL — сколько живёт выгрузка усечённого ответа, длительностью
	// ("24h"). Маркер обещает файл на этот срок, поэтому набор берёт его из
	// реестра: у набора под панелью MCPRIG_TOOLOUT_TTL не доезжает. Пусто —
	// переменная окружения, затем DefaultTTL.
	ToolOutTTL string `json:"toolOutTtl,omitempty"`
}

HTTPTransport is the listener the set exposes to MCP clients.

type HealthMonitor

type HealthMonitor struct {
	Interval int `json:"interval,omitempty"` // ms
	Timeout  int `json:"timeout,omitempty"`  // ms
}

type OAuth

type OAuth struct {
	Disabled     bool     `json:"disabled,omitempty"`
	CallbackPort int      `json:"callbackPort,omitempty"` // loopback, default 8947
	RedirectURL  string   `json:"redirectUrl,omitempty"`
	ClientID     string   `json:"clientId,omitempty"`
	ClientSecret string   `json:"clientSecret,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
}

OAuth tunes the client-side authorization code flow for one server. An empty block is fine: the flow starts only when the server answers 401 or 403.

type PermissionAction

type PermissionAction string

PermissionAction is allow or deny; lazy-mcp's "ask" is not implemented.

const (
	PermissionAllow PermissionAction = "allow"
	PermissionDeny  PermissionAction = "deny"
)

type Permissions

type Permissions struct {
	Default PermissionAction `json:"default,omitempty"`
	Rules   []Rule           `json:"rules,omitempty"`
}

Permissions is the experimental allow/deny block, on the top level or one server. Without it everything is allowed.

func ParsePermissions added in v0.5.0

func ParsePermissions(raw json.RawMessage) (*Permissions, string)

ParsePermissions reads an allow/deny block. The second result describes a defect and is empty when the block is usable; an absent or null block gives (nil, ""). The loader soft-fails a defect, the registry API rejects it — both go through here so the rules cannot drift apart.

type Profile added in v0.5.0

type Profile struct {
	Deny  []string `json:"deny,omitempty"`
	Allow []string `json:"allow,omitempty"`
}

Profile — именованный набор глоб-правил, который сужает права ключа набора. Профиль применяется после permissions и только запрещает: deny побеждает allow, поэтому профиль не может разрешить то, что запретили permissions.

func (*Profile) Allows added in v0.5.0

func (p *Profile) Allows(server, command string) bool

Allows reports whether the profile lets one server/command through. A pattern with "/" matches "server/command" (rateLimit's form); one without it matches the command name alone, like permissions rules.

func (*Profile) Check added in v0.5.0

func (p *Profile) Check(name string) string

Check returns a defect description, empty when the profile is usable.

func (*Profile) Empty added in v0.5.0

func (p *Profile) Empty() bool

Empty reports whether the profile cannot deny anything: no deny rules, and no allow list that would act as a whitelist of nothing.

type RateLimit added in v0.5.0

type RateLimit struct {
	// PerMinute — общий лимит вызовов в минуту на пару (клиент, инструмент).
	PerMinute int `json:"perMinute,omitempty"`
	// Burst — сколько вызовов проходят одной пачкой; по умолчанию PerMinute.
	Burst int `json:"burst,omitempty"`
	// PerTool переопределяет лимит для пары "server/tool".
	PerTool map[string]RateLimit `json:"perTool,omitempty"`
}

RateLimit bounds how often one caller may call a set's tools. It lives in the registry entry of the set and is copied into the set's own servers.json, so the proxy process enforces it where the calls happen.

Нет поля или ноль — лимита нет: так набор ведёт себя и без блока.

func (*RateLimit) Check added in v0.5.0

func (r *RateLimit) Check() string

Check возвращает описание дефекта; пустая строка — блок годен.

func (*RateLimit) Decode added in v0.5.0

func (r *RateLimit) Decode(raw []byte) error

Decode разбирает блок из записи набора или из servers.json. Неизвестное поле — ошибка, а не молчаливый ноль: "perMunute" иначе снял бы лимит, о котором владелец думал, что он есть.

func (*RateLimit) Empty added in v0.5.0

func (r *RateLimit) Empty() bool

Empty reports whether the block sets no limit at all: ноль в общем поле и ни одного ненулевого переопределения.

type Rule

type Rule struct {
	Server  string           `json:"server,omitempty"`
	Pattern string           `json:"pattern"`
	Action  PermissionAction `json:"action"`
	Message string           `json:"message,omitempty"`
}

Rule matches the command name by glob; Server is only allowed on global rules and matches the server name (default "*").

type Sandbox

type Sandbox struct {
	Mode          string   `json:"mode,omitempty"`          // none | bwrap
	OnUnavailable string   `json:"onUnavailable,omitempty"` // deny | warn | allow
	RO            []string `json:"ro,omitempty"`
	RW            []string `json:"rw,omitempty"`
	Network       string   `json:"network,omitempty"` // none | allow
	MemoryMb      int      `json:"memoryMb,omitempty"`
	Pids          int      `json:"pids,omitempty"`
	TimeoutSec    int      `json:"timeoutSec,omitempty"`
	// TmpMb — размер tmpfs /tmp и заодно RLIMIT_FSIZE: иначе сервер набивает
	// tmpfs до лимита хоста.
	TmpMb int `json:"tmpMb,omitempty"`
}

Sandbox — изоляция stdio-сервера. Пустой блок означает умолчания: bwrap, сеть выключена, при недоступной песочнице сервер не стартует.

type Server

type Server struct {
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Transport   TransportKind     `json:"transport,omitempty"`
	Command     []string          `json:"command,omitempty"`
	Cwd         string            `json:"cwd,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
	// EnvAllow — имена переменных окружения владельца, которые сервер получает
	// вдобавок к whitelist. Больше ничего из os.Environ() вниз не уходит.
	EnvAllow []string          `json:"envAllow,omitempty"`
	URL      string            `json:"url,omitempty"`
	Headers  map[string]string `json:"headers,omitempty"`
	Tags     []string          `json:"tags,omitempty"`
	Enabled  bool              `json:"enabled"`
	// Expose — какие поверхности сервера прокси отдаёт клиенту: "resources"
	// и/или "prompts". Пусто — ни одной: без явного разрешения клиент видит
	// только инструменты.
	Expose []string `json:"expose,omitempty"`
	// Hint — одна строка «для чего сервер и с чего начать»: list_servers
	// показывает её агенту вместо встроенной подсказки по имени сервера.
	Hint        string       `json:"hint,omitempty"`
	Permissions *Permissions `json:"permissions,omitempty"`
	OAuth       *OAuth       `json:"oauth,omitempty"`
	Sandbox     *Sandbox     `json:"sandbox,omitempty"`
	ConfigError string       `json:"-"`
}

Server is one downstream MCP server. Validation never fails the load: an unusable entry keeps its ConfigError and shows up unhealthy, the rest works.

func (*Server) CallTimeout

func (s *Server) CallTimeout() time.Duration

CallTimeout — свой предел одного вызова инструмента; 0 — действует requestTimeout набора.

func (*Server) Check

func (s *Server) Check() string

Check прогоняет те же правила, что Load, над сервером, собранным снаружи файла: реестр и кнопки probe/browse запускают ровно то, что набор отверг бы. Работает на копии: стор отдаёт общий объект, а setDefaults и ConfigError — запись в него. Пустая строка — сервер годен.

func (*Server) Secrets

func (s *Server) Secrets() []string

Secrets собирает значения, которые нельзя выпускать наружу: все env и заголовки сервера длиной от 8 символов. Фильтра по имени поля нет намеренно: токен под «не секретным» именем утекал, а ${VAR} к этому моменту уже развёрнут (expandSecrets в config.go:966), то есть в значении лежит сам секрет. Перемаскирование безвредного значения дешевле утёкшего ключа. Значение короче 8 символов не маскируется — иначе случайное совпадение испортит обычный текст.

func (*Server) UnmarshalJSON

func (s *Server) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both command forms: the array form and the legacy `"command": "npx"` plus `"args": […]`.

func (*Server) Warnings

func (s *Server) Warnings() []string

Warnings — некритичные замечания: npx/uvx без пина версии ставят «сегодняшний latest», а не тот код, который проверяли.

type TransportKind

type TransportKind string
const (
	TransportStdio TransportKind = "stdio"
	TransportHTTP  TransportKind = "http"
)

Jump to

Keyboard shortcuts

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