migrate

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 27 Imported by: ? 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 migrate owns the on-disk YAML schema for LeanProxy's user-server configuration. It re-exports the canonical transport enum used throughout the codebase so callers can refer to it without depending on pkg/registry (which already depends on this package for ServerConfig).

Index

Constants

View Source
const (
	// DefaultHTTPMaxBodyBytes caps one POST body: 64 MiB.
	DefaultHTTPMaxBodyBytes = 64 << 20
	// DefaultHTTPMaxSessions caps the Streamable HTTP sessions open at once.
	DefaultHTTPMaxSessions = 256
	// DefaultHTTPSessionIdleTimeout ends a session idle for this long.
	DefaultHTTPSessionIdleTimeout = 30 * time.Minute
)

Defaults of the `server.http:` block.

View Source
const DefaultMaxConcurrentRequests = 64

DefaultMaxConcurrentRequests is the number of client requests the stdio front end processes at once when server.max_concurrent_requests is unset.

View Source
const DefaultMaxConnections = 32

DefaultMaxConnections is how many client connections the `serve` listener accepts at once when server.max_connections is unset.

View Source
const DefaultMaxLineBytes = 64 << 20

DefaultMaxLineBytes is the largest JSON-RPC message (one line) the `serve` listener reads when server.max_line_bytes is unset: 64 MiB.

View Source
const SimilarityLimit = 5

SimilarityLimit bounds the number of "did you mean" suggestions returned by Install when the requested server id is not in the registry cache.

Variables

View Source
var ErrConfigNotFound = errors.New("config file not found")

ErrConfigNotFound is returned by LoadConfig when the config file does not exist on disk. Callers that need to distinguish "operator pointed at a missing file" from "operator pointed at an unreadable / unparseable file" (or a file that exists but is empty) can use errors.Is to detect this sentinel. Callers that want to fall back to defaults should treat this as a non-error and either branch on the sentinel explicitly or rely on the nil-config / nil-error return contract.

Functions

func ExecutableExists

func ExecutableExists(cmd string) bool

func FormatValidationSummary

func FormatValidationSummary(imported int, result *ValidationResult) string

func InferSandboxImage added in v1.1.1

func InferSandboxImage(command string) (string, bool)

InferSandboxImage returns a sensible default sandbox image for a well-known interpreter command, and whether one was found. Used when sandbox.image is left unset (#312): npx/npm/node get a current Node Alpine image, uvx/uv/python(3) get a current Python (uv) Alpine image. Any other command must set sandbox.image explicitly.

func IsAlreadyInstalled added in v0.8.0

func IsAlreadyInstalled(err error) bool

IsAlreadyInstalled reports whether err (or any wrapped error) is an ErrAlreadyInstalled.

func IsLeanProxyServer added in v1.1.1

func IsLeanProxyServer(srv DiscoveredServer) bool

IsLeanProxyServer reports whether a discovered entry runs LeanProxy itself (e.g. the entry a client uses to start `leanproxy-mcp server run --stdio`, or the HTTP gateway entry). Importing it would make the proxy start itself as an upstream.

func IsUnknownServer added in v0.8.0

func IsUnknownServer(err error) bool

IsUnknownServer reports whether err (or any wrapped error) is an ErrUnknownServer.

func MarshalConfig added in v0.2.0

func MarshalConfig(cfg *Config) ([]byte, error)

func SaveConfig added in v0.8.0

func SaveConfig(path string, cfg *Config) error

SaveConfig writes cfg to path with 0600 permissions, creating the parent directory if needed. The write is atomic: a temp file in the same directory is created, fsynced, then renamed over the target.

func SuggestSimilar added in v0.8.0

func SuggestSimilar(needle string, entries []CacheEntry, limit int) []string

SuggestSimilar ranks entries by Levenshtein distance to needle and returns the top-n closest names. Identical matches are excluded (Resolve handles the exact case before calling this helper).

func ValidateHTTPOrigin added in v1.1.1

func ValidateHTTPOrigin(origin string) error

ValidateHTTPOrigin checks one allowlisted browser origin: an http or https scheme and a host, with an optional port and nothing else (no path, no wildcard).

Types

type AuthConfig added in v0.7.0

type AuthConfig struct {
	Type         string   `yaml:"type"` // bearer, oauth2
	ClientID     string   `yaml:"client_id"`
	ClientSecret string   `yaml:"client_secret"`
	Scopes       []string `yaml:"scopes"`
	TokenURL     string   `yaml:"token_url"` // optional, for bearer token exchange
}

type CacheConfig added in v0.8.0

type CacheConfig struct {
	VectorStore *VectorStoreConfig `yaml:"vector_store,omitempty"`
}

type CacheEntry added in v0.8.0

type CacheEntry struct {
	Name          string
	Transport     string
	Command       string
	Args          []string
	Env           map[string]string
	URL           string
	TokensPerTurn int64
	// Version is the exact version to pin at install time, when known
	// (issue #313). Empty means the source did not publish one.
	Version string
	// PackageRegistry identifies the package registry Command/Args came
	// from ("npm", "pypi", "oci"), when the entry is registry-sourced.
	// Empty for legacy/custom entries that only ever had a raw command.
	PackageRegistry string
	// PackageIdentifier is the bare package/image name (no version
	// suffix), set alongside PackageRegistry.
	PackageIdentifier string
	// Registry is the source this entry came from ("official", or a
	// configured custom source name). Recorded into InstalledFrom.
	Registry string
}

CacheEntry is the subset of a registry feed record the installer cares about. Defining it here keeps the installer decoupled from the registry package's concrete types.

type CacheSettings

type CacheSettings struct {
	Enabled  bool   `yaml:"enabled"`
	MaxSize  int    `yaml:"max_size"`
	TTL      string `yaml:"ttl"`
	TTLValue time.Duration
}

type CacheSnapshot added in v0.8.0

type CacheSnapshot struct {
	Entries []CacheEntry
}

CacheSnapshot is the materialized view of the registry cache. It is returned by ServerSource.LookupCache.

type ClaudeDesktopScanner added in v1.1.1

type ClaudeDesktopScanner struct {
	// contains filtered or unexported fields
}

ClaudeDesktopScanner reads the "mcpServers" of Claude Desktop's claude_desktop_config.json.

func (*ClaudeDesktopScanner) Name added in v1.1.1

func (s *ClaudeDesktopScanner) Name() string

func (*ClaudeDesktopScanner) Scan added in v1.1.1

type ClaudeScanner

type ClaudeScanner struct{}

ClaudeScanner reads Claude Code's user-scoped servers: the top-level "mcpServers" of ~/.claude.json (and the older ~/.config/claude/mcp_config.json).

func (*ClaudeScanner) Name

func (s *ClaudeScanner) Name() string

func (*ClaudeScanner) Scan

type Config

type Config struct {
	Version       string                `yaml:"version"`
	Servers       []*ServerConfig       `yaml:"servers"`
	Reconnect     *ReconnectConfig      `yaml:"reconnect,omitempty"`
	Cache         *CacheConfig          `yaml:"cache,omitempty"`
	Injection     *injection.Config     `yaml:"injection,omitempty"`
	Bouncer       *bouncer.Config       `yaml:"bouncer,omitempty"`
	ResponseCache *responsecache.Config `yaml:"response_cache,omitempty"`
	// ToolSearch configures the search_tools index (synonyms, optional
	// hybrid embedding ranking). Absent means BM25 with the default
	// synonyms.
	ToolSearch *toolsearch.Config `yaml:"tool_search,omitempty"`
	// Server holds settings for the proxy's own MCP front end (the
	// `server run --stdio` loop the IDE talks to), as opposed to the
	// upstream servers listed under Servers.
	Server *FrontendConfig `yaml:"server,omitempty"`
	// Telemetry configures the optional OpenTelemetry traces/metrics
	// exporter (issue #317). Off by default; also enabled by the standard
	// OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_PROTOCOL env vars,
	// which take precedence over this block (see pkg/telemetry.Resolve).
	Telemetry *telemetry.Config `yaml:"telemetry,omitempty"`
	// Security holds the upstream-trust settings (issue #310: tool
	// pinning). Absent means the defaults (tool pinning in warn mode).
	Security *SecurityConfig `yaml:"security,omitempty"`
	// Registry configures marketplace server sources (issue #313). The
	// official MCP Registry (registry.modelcontextprotocol.io) is always
	// available as the default source and needs no entry here; Sources
	// lists additional opt-in custom NDJSON feeds.
	Registry *RegistrySettings `yaml:"registry,omitempty"`
	// Policy is the per-tool policy layer (issue #314): allow / deny /
	// confirm rules on "server.tool" globs and annotations, and what
	// happens to calls to tools a server does not advertise. Absent means
	// the defaults: every advertised tool allowed, unadvertised ones
	// refused.
	Policy *policy.Config `yaml:"policy,omitempty"`
	// Response is the response token governor (issue #319): per-tool
	// budgets for tool results, smart truncation, and the spill store
	// read_result pages from. Absent or enabled: false means off (the
	// default).
	Response *governor.Config `yaml:"response,omitempty"`
	// Exposure decides how the upstream tools reach each client (issue
	// #322): through LeanProxy's discovery router, or listed directly
	// (passthrough / hybrid) for clients with native tool search. Absent
	// means the defaults: the built-in client table (Claude Code, Claude
	// Desktop, Cursor, VS Code get passthrough), router for any other
	// client.
	Exposure *exposure.Config `yaml:"exposure,omitempty"`
	// CodeMode is the EXPERIMENTAL execute_code tool (issue #325): a
	// sandboxed JavaScript program that calls several tools and returns
	// only its answer. Only a binary built with `-tags codemode` has it;
	// absent or enabled: false means off (the default).
	CodeMode *codemode.Config `yaml:"code_mode,omitempty"`
}

func LoadConfig

func LoadConfig(ctx context.Context, path string) (*Config, error)

func (*Config) EffectiveHTTPFrontend added in v1.1.1

func (c *Config) EffectiveHTTPFrontend() ResolvedHTTPFrontend

EffectiveHTTPFrontend returns the server.http block with its defaults resolved; its SessionIdleTimeout is then a valid duration.

func (*Config) EffectiveMaxConcurrentRequests added in v1.1.1

func (c *Config) EffectiveMaxConcurrentRequests() int

EffectiveMaxConcurrentRequests returns server.max_concurrent_requests, or DefaultMaxConcurrentRequests when it is unset or zero.

func (*Config) EffectiveMaxConnections added in v1.1.1

func (c *Config) EffectiveMaxConnections() int

EffectiveMaxConnections returns server.max_connections, or DefaultMaxConnections when it is unset or zero.

func (*Config) EffectiveMaxLineBytes added in v1.1.1

func (c *Config) EffectiveMaxLineBytes() int

EffectiveMaxLineBytes returns server.max_line_bytes, or DefaultMaxLineBytes when it is unset or zero.

func (*Config) EffectiveReconnect added in v0.9.0

func (c *Config) EffectiveReconnect() ResolvedReconnect

func (*Config) ToolPinningConfig added in v1.1.1

func (c *Config) ToolPinningConfig() *toolpin.Config

ToolPinningConfig returns security.tool_pinning (nil: the defaults).

func (*Config) Validate

func (c *Config) Validate() error

type CursorScanner

type CursorScanner struct{}

CursorScanner reads the "mcpServers" of Cursor's global ~/.cursor/mcp.json.

func (*CursorScanner) Name

func (s *CursorScanner) Name() string

func (*CursorScanner) Scan

type DiscoveredServer

type DiscoveredServer struct {
	Name      string
	Source    string
	Transport TransportType
	Stdio     *StdioConfig
	HTTP      *HTTPConfig
	Enabled   *bool
}

type ErrAlreadyInstalled added in v0.8.0

type ErrAlreadyInstalled struct {
	ServerID string
}

ErrAlreadyInstalled is returned when the server name already exists in the user config and neither Force nor an interactive confirmation has been supplied.

func (*ErrAlreadyInstalled) Error added in v0.8.0

func (e *ErrAlreadyInstalled) Error() string

type ErrUnknownServer added in v0.8.0

type ErrUnknownServer struct {
	ServerID  string
	Suggested []string
}

ErrUnknownServer is returned by Install when the requested server id is not present in the local registry cache. It carries suggested similar names so callers can present a "did you mean" hint without re-running the search.

func (*ErrUnknownServer) Error added in v0.8.0

func (e *ErrUnknownServer) Error() string

type FrontendConfig added in v1.1.1

type FrontendConfig struct {
	// MaxConcurrentRequests caps how many client requests `server run
	// --stdio` handles in parallel (and, for `serve`, how many requests one
	// TCP connection runs in parallel). When the cap is reached the reader
	// waits for a free slot; it never rejects. 0 or absent means
	// DefaultMaxConcurrentRequests.
	MaxConcurrentRequests int `yaml:"max_concurrent_requests,omitempty"`
	// MaxLineBytes caps the size of one newline-delimited JSON-RPC message
	// read by the `serve` TCP listener. A longer line gets an error reply
	// and the connection is closed. 0 or absent means
	// DefaultMaxLineBytes.
	MaxLineBytes int `yaml:"max_line_bytes,omitempty"`
	// MaxConnections caps how many client connections the `serve` TCP
	// listener accepts at once; extra connections are closed right away.
	// 0 or absent means DefaultMaxConnections.
	MaxConnections int `yaml:"max_connections,omitempty"`
	// HTTP configures the Streamable HTTP front end (`server run --http`,
	// issue #309). Absent means the defaults.
	HTTP *HTTPFrontendConfig `yaml:"http,omitempty"`
}

FrontendConfig is the `server:` block. Unknown keys in the block (e.g. the legacy host/port documented for `serve`) are ignored.

func (*FrontendConfig) Validate added in v1.1.1

func (c *FrontendConfig) Validate() error

Validate rejects negative values. A nil receiver is valid (defaults).

type GenericScanner

type GenericScanner struct{}

GenericScanner reads ~/.config/mcp.json, under "mcp_servers" or "mcpServers".

func (*GenericScanner) Name

func (s *GenericScanner) Name() string

func (*GenericScanner) Scan

type HTTPConfig

type HTTPConfig struct {
	URL     string            `yaml:"url"`
	Headers map[string]string `yaml:"headers"`
	Auth    *AuthConfig       `yaml:"auth,omitempty"`
}

type HTTPFrontendConfig added in v1.1.1

type HTTPFrontendConfig struct {
	// AllowedHosts are Host header values accepted beyond the bind host
	// and the loopback names ("gateway.lan" or "gateway.lan:8765").
	AllowedHosts []string `yaml:"allowed_hosts,omitempty"`
	// AllowedOrigins are the browser origins ("https://app.example")
	// allowed to call the endpoint. Requests without an Origin header (every
	// non-browser MCP client) are not affected; any other origin gets 403.
	AllowedOrigins []string `yaml:"allowed_origins,omitempty"`
	// MaxBodyBytes caps one POST body. 0 or absent means
	// DefaultHTTPMaxBodyBytes.
	MaxBodyBytes int64 `yaml:"max_body_bytes,omitempty"`
	// MaxSessions caps the sessions open at once. 0 or absent means
	// DefaultHTTPMaxSessions.
	MaxSessions int `yaml:"max_sessions,omitempty"`
	// SessionIdleTimeout ends a session with no request in flight and no
	// open GET stream for this long (a Go duration, e.g. "30m"). Absent
	// means DefaultHTTPSessionIdleTimeout.
	SessionIdleTimeout string `yaml:"session_idle_timeout,omitempty"`
}

HTTPFrontendConfig is the `server.http:` block: limits and browser allowlists of the Streamable HTTP front end. The listen address and the token come from the command line (`--http`, `--http-token`), like `serve`'s.

func (*HTTPFrontendConfig) Validate added in v1.1.1

func (c *HTTPFrontendConfig) Validate() error

Validate checks the block. A nil receiver is valid (defaults).

type ImportResult

type ImportResult struct {
	Imported   int
	Duplicates int
	Errors     []error
	Validation *ValidationResult
}

type InstallOptions added in v0.8.0

type InstallOptions struct {
	// Force, when true, allows overwriting an existing server definition.
	Force bool

	// StopExisting, when true, asks the stopper to gracefully stop any
	// running instance that shares the target name before the new definition
	// is written.
	StopExisting bool

	// GracefulTimeout is the budget for the graceful stop before the caller
	// proceeds with the install regardless. Zero means use the stop call's
	// default context.
	GracefulTimeout time.Duration

	// Stopper, when set, is invoked to stop existing instances when
	// StopExisting is true. It may be nil for offline (config-only) installs.
	Stopper LifecycleStopper

	// Logger is used for operational logs. Defaults to slog.Default().
	Logger *slog.Logger

	// DryRun, when true, prevents any filesystem writes and any stopper
	// calls. The result still reflects what would have happened.
	DryRun bool

	// Enabled controls the written server's `enabled` field (issue #313).
	// A newly installed server defaults to enabled: false (the caller must
	// have shown the user the exact command, env names, transport/URL and
	// trust signals and gotten confirmation — or passed --yes) before
	// setting this true. Replacing an existing server keeps that server's
	// previous enabled state instead of using this field, since the
	// operator already made that call once.
	Enabled bool

	// Sandbox, when non-nil, is written as the installed stdio server's
	// stdio.sandbox block (issue #312/#313's `--sandbox` flag). Ignored for
	// a non-stdio transport.
	Sandbox *SandboxConfig
}

InstallOptions controls Install behavior. The zero value performs an additive install with no graceful stop and no lifecycle manager.

type InstallResult added in v0.8.0

type InstallResult struct {
	ServerID        string
	ServerName      string
	Transport       string
	Replaced        bool
	Stopped         bool
	ConfigPath      string
	DryRun          bool
	EstimatedTools  int
	SnapshotSummary string
}

InstallResult captures the outcome of a successful Install call. It is always non-nil when err is nil.

type InstalledFromConfig added in v1.1.1

type InstalledFromConfig struct {
	// Registry is the source name: "official" for the MCP Registry API, or
	// the configured name of a custom NDJSON source (registry.sources).
	Registry string `yaml:"registry"`
	// Name is the server's name as known to that registry (may differ
	// from the local server Name after a rename).
	Name string `yaml:"name"`
	// Version is the exact version pinned at install time.
	Version string `yaml:"version,omitempty"`
	// InstalledAt is when the install (or last `marketplace update`) ran,
	// RFC 3339.
	InstalledAt string `yaml:"installed_at"`
}

InstalledFromConfig is servers[].installed_from.

type Installer added in v0.8.0

type Installer struct {
	Source     ServerSource
	ConfigPath string
	Logger     *slog.Logger
}

Installer is the top-level facade used by cmd/add. It composes a cache source and a config path.

func NewInstaller added in v0.8.0

func NewInstaller(source ServerSource, configPath string, logger *slog.Logger) *Installer

NewInstaller wires an Installer with the given cache source and config path. Either may be overridden after construction by setting the fields directly.

func (*Installer) Install added in v0.8.0

func (i *Installer) Install(ctx context.Context, entry CacheEntry, opts InstallOptions) (*InstallResult, error)

Install builds a ServerConfig from the cache entry, merges it into the user config at i.ConfigPath (writing through MarshalConfig), and — if StopExisting is true — gracefully stops any running instance that shares the target name via the provided Stopper.

The returned result is always non-nil when err is nil.

func (*Installer) Resolve added in v0.8.0

func (i *Installer) Resolve(ctx context.Context, serverID string) (CacheEntry, error)

Resolve returns the registry entry for serverID (case-insensitive). If no exact match is found, it returns an *ErrUnknownServer populated with up to SimilarityLimit suggestions ranked by edit distance.

Resolve never triggers a Sync; callers are expected to have a fresh cache.

type LifecycleStopper added in v0.8.0

type LifecycleStopper interface {
	Stop(ctx context.Context, id string) error
}

LifecycleStopper is the narrow surface the installer needs from a server lifecycle manager. The concrete *registry.LifecycleManager satisfies it via its Stop method, but the installer accepts the interface so callers can pass a fake in tests.

type MigrationSummary

type MigrationSummary struct {
	OpenCodeCount int
	ClaudeCount   int
	// ClaudeDesktopCount counts Claude Desktop's servers.
	ClaudeDesktopCount int
	VSCodeCount        int
	CursorCount        int
	GenericCount       int
	TotalServers       int
}

func (*MigrationSummary) Total

func (s *MigrationSummary) Total() int

type Migrator

type Migrator struct {
	// contains filtered or unexported fields
}

func NewMigrator

func NewMigrator() *Migrator

func (*Migrator) Import

func (m *Migrator) Import(ctx context.Context, servers []DiscoveredServer, targetPath string, yes bool) (*ImportResult, error)

func (*Migrator) ImportAll

func (m *Migrator) ImportAll(ctx context.Context, servers []DiscoveredServer, yes bool) (*ImportResult, error)

func (*Migrator) Scan

func (m *Migrator) Scan(ctx context.Context) (*ScanResult, error)

func (*Migrator) Summarize

func (m *Migrator) Summarize(servers []DiscoveredServer) *MigrationSummary

func (*Migrator) Validate

func (m *Migrator) Validate(servers []DiscoveredServer) *ValidationResult

type OpenCodeScanner

type OpenCodeScanner struct{}

OpenCodeScanner reads the "mcp" block of ~/.config/opencode/opencode.json: "local" entries (a command array) and "remote" entries (a url).

func (*OpenCodeScanner) Name

func (s *OpenCodeScanner) Name() string

func (*OpenCodeScanner) Scan

type PineconeVectorConfig added in v0.8.0

type PineconeVectorConfig struct {
	Index     string `yaml:"index"`
	APIKeyEnv string `yaml:"api_key_env"`
}

type QdrantVectorConfig added in v0.8.0

type QdrantVectorConfig struct {
	URL        string `yaml:"url"`
	APIKey     string `yaml:"api_key"`
	APIKeyEnv  string `yaml:"api_key_env"`
	Collection string `yaml:"collection"`
}

type RateLimitConfig added in v1.1.1

type RateLimitConfig struct {
	// RequestsPerSecond is the sustained rate of requests allowed per
	// second. 0 or absent means unlimited.
	RequestsPerSecond float64 `yaml:"requests_per_second"`
	// Burst is the maximum number of requests allowed to proceed
	// immediately before the sustained rate applies. Defaults to
	// RequestsPerSecond (rounded up, minimum 1) when RequestsPerSecond > 0
	// and Burst is not set.
	Burst int `yaml:"burst"`
}

RateLimitConfig is an optional, per-server request rate limit applied to requests forwarded to that server. It is unset by default, meaning no limit: local stdio servers in particular don't need one. When set, RequestsPerSecond of 0 (or an absent block) also means unlimited; a positive value enables waiting-based limiting (see pkg/pool).

func (*RateLimitConfig) Validate added in v1.1.1

func (c *RateLimitConfig) Validate() error

Validate returns an error if the rate limit configuration has negative values. A nil receiver is valid (unlimited).

type ReconnectConfig added in v0.9.0

type ReconnectConfig struct {
	Enabled             *bool         `yaml:"enabled"`
	HealthInterval      string        `yaml:"health_check_interval"`
	HealthIntervalValue time.Duration `yaml:"-"`
	MaxFailures         int           `yaml:"health_check_failures"`
	MaxRestartAttempts  int           `yaml:"max_restart_attempts"`
	RestartBackoff      string        `yaml:"restart_backoff"`
	RestartBackoffValue time.Duration `yaml:"-"`
	StableWindow        string        `yaml:"stable_window"`
	StableWindowValue   time.Duration `yaml:"-"`
}

type RegistrySettings added in v1.1.1

type RegistrySettings struct {
	// Sources are opt-in custom NDJSON feed URLs, synced in addition to
	// the official MCP Registry by `marketplace sync`. Each must have a
	// unique, non-empty Name (used for provenance display and as the
	// InstalledFrom.Registry value for servers installed from it) and a
	// non-empty http(s) URL.
	Sources []RegistrySourceConfig `yaml:"sources,omitempty"`
}

RegistrySettings is the `registry:` block.

func (*RegistrySettings) Validate added in v1.1.1

func (r *RegistrySettings) Validate() error

Validate checks that every source has a name and an http(s) URL, and that names are unique. A nil receiver is valid (no custom sources).

type RegistrySourceConfig added in v1.1.1

type RegistrySourceConfig struct {
	Name string `yaml:"name"`
	URL  string `yaml:"url"`
}

RegistrySourceConfig is one entry of registry.sources.

type ResolvedHTTPFrontend added in v1.1.1

type ResolvedHTTPFrontend struct {
	AllowedHosts       []string
	AllowedOrigins     []string
	MaxBodyBytes       int64
	MaxSessions        int
	SessionIdleTimeout time.Duration
}

ResolvedHTTPFrontend is the server.http block with defaults applied.

type ResolvedReconnect added in v0.9.0

type ResolvedReconnect struct {
	Enabled            bool
	HealthInterval     time.Duration
	MaxFailures        int
	MaxRestartAttempts int
	RestartBackoff     time.Duration
	StableWindow       time.Duration
}

type RootConfig added in v1.1.1

type RootConfig struct {
	URI  string `yaml:"uri" json:"uri"`
	Name string `yaml:"name,omitempty" json:"name,omitempty"`
}

RootConfig is one static root of servers[].roots: a file:// URI and an optional display name.

type SQLiteVectorConfig added in v0.8.0

type SQLiteVectorConfig struct {
	Path string `yaml:"path"`
}

type SandboxConfig added in v1.1.1

type SandboxConfig struct {
	// Runtime selects the container engine: "docker", "podman", or "none"
	// (the default — unsandboxed). An empty value is treated as "none".
	Runtime string `yaml:"runtime"`
	// Image is the container image the command runs in. Required unless it
	// can be inferred from the stdio command (npx/npm/node -> a Node
	// image, uvx/uv/python(3) -> a Python/uv image); see
	// InferSandboxImage.
	Image string `yaml:"image,omitempty"`
	// Network is the container network mode: "none" (default — no network
	// access), "bridge", or "host".
	Network string `yaml:"network,omitempty"`
	// Mounts are explicit host<->container bind mounts. Empty by default:
	// the container gets no access to the host filesystem beyond its own
	// read-only root and the /tmp tmpfs.
	Mounts []SandboxMount `yaml:"mounts,omitempty"`
	// Memory is a Docker/Podman memory limit (e.g. "512m", "1g"). Empty
	// means the runtime's own default (unlimited).
	Memory string `yaml:"memory,omitempty"`
	// CPUs is a Docker/Podman CPU limit (e.g. "1", "0.5"). Empty means the
	// runtime's own default (unlimited).
	CPUs string `yaml:"cpus,omitempty"`
	// CacheVolume, when true, mounts a named volume for the package
	// manager cache of a well-known interpreter command (npm for
	// npx/npm/node, uv for uvx/uv) so repeated starts do not re-download
	// packages. Off by default; unrecognized commands are unaffected.
	CacheVolume bool `yaml:"cache_volume,omitempty"`
}

SandboxConfig is servers[].stdio.sandbox (#312): optional container isolation for a stdio MCP server. Marketplace-installed third-party servers (npx/uvx packages) run arbitrary code with the full filesystem and network access of the proxy's own user by default; this wraps the configured command in `docker run`/`podman run` with network and filesystem restrictions instead.

func (*SandboxConfig) Validate added in v1.1.1

func (s *SandboxConfig) Validate(serverName, command string) error

Validate checks sandbox settings. command is the stdio server's own command, used to check whether an omitted Image can be inferred. A nil receiver (no sandbox configured) is always valid.

type SandboxMount added in v1.1.1

type SandboxMount struct {
	Host      string `yaml:"host"`
	Container string `yaml:"container"`
	ReadOnly  bool   `yaml:"read_only,omitempty"`
}

SandboxMount is one entry of sandbox.mounts: an explicit host directory bound into the container at container, optionally read-only.

type ScanResult

type ScanResult struct {
	Scanners []string
	Servers  []DiscoveredServer
	// Skipped are entries that run LeanProxy itself (see
	// IsLeanProxyServer); they are not imported.
	Skipped []DiscoveredServer
	// Warnings are files or entries that could not be read. They do not
	// stop the scan of the other files.
	Warnings []error
}

type Scanner

type Scanner interface {
	Name() string
	Scan(ctx context.Context) ([]DiscoveredServer, error)
}

type SecurityConfig added in v1.1.1

type SecurityConfig struct {
	// ToolPinning pins upstream tool definitions and reports or blocks
	// drift (off | warn | block; warn by default).
	ToolPinning *toolpin.Config `yaml:"tool_pinning,omitempty"`
}

SecurityConfig is the `security:` block.

type ServerConfig

type ServerConfig struct {
	Name                string             `yaml:"name"`
	Enabled             *bool              `yaml:"enabled"`
	Transport           TransportType      `yaml:"transport"`
	ComplexityTier      string             `yaml:"complexity_tier,omitempty"`
	Stdio               *StdioConfig       `yaml:"stdio,omitempty"`
	HTTP                *HTTPConfig        `yaml:"http,omitempty"`
	Timeout             string             `yaml:"timeout"`
	TimeoutValue        time.Duration      `yaml:"-"`
	ConnectTimeout      string             `yaml:"connect_timeout"`
	ConnectTimeoutValue time.Duration      `yaml:"-"`
	IdleTimeout         string             `yaml:"idle_timeout"`
	IdleTimeoutValue    time.Duration      `yaml:"-"`
	CacheSettings       *CacheSettings     `yaml:"cache_settings,omitempty"`
	SummarizeSettings   *SummarizeSettings `yaml:"summarize_settings,omitempty"`
	RateLimit           *RateLimitConfig   `yaml:"rate_limit,omitempty"`
	// MaxInFlight caps how many requests the proxy multiplexes concurrently
	// over one stdio server's pipe. Callers beyond the cap wait for a free
	// slot (bounded by their own timeout) instead of being rejected. 0 or
	// absent means the default (32). Only used by stdio servers.
	MaxInFlight int `yaml:"max_in_flight,omitempty"`
	// MaxResponseBytes caps the size of one JSON-RPC message (one stdout
	// line) read from a stdio server. A larger response fails only the call
	// it answers; the server keeps working. 0 or absent means the default
	// (64 MiB). Only used by stdio servers.
	MaxResponseBytes int `yaml:"max_response_bytes,omitempty"`
	// AllowSampling lets this server send sampling/createMessage requests,
	// which the proxy relays to the client (issue #308). Sampling makes the
	// client's LLM generate text on the server's behalf, spending the
	// user's tokens, so it is off by default: the request is refused with
	// -32601 and the sampling capability is not declared to the server.
	// Every relayed sampling request is logged.
	AllowSampling bool `yaml:"allow_sampling,omitempty"`
	// Roots, when set, answers this server's roots/list requests from this
	// static list instead of relaying them to the client (issue #308).
	// Each uri must be a file:// URI.
	Roots []RootConfig `yaml:"roots,omitempty"`
	// InstalledFrom records provenance when this server was written by
	// `leanproxy add`/`marketplace update` (issue #313): which registry
	// source it came from, its name there, the exact version pinned, and
	// when. Absent for hand-written or migrated entries.
	InstalledFrom *InstalledFromConfig `yaml:"installed_from,omitempty"`
}

func PreviewServerConfig added in v1.1.1

func PreviewServerConfig(entry CacheEntry) (*ServerConfig, error)

buildServerConfig converts a CacheEntry into a ServerConfig that the rest of the system can persist, validate, and start. Stdio is preferred when a Command is present; otherwise HTTP is used and the URL is promoted into http.url. PreviewServerConfig builds the ServerConfig that Install would write for entry, without writing anything. It is exported so callers (cmd/add) can show the exact command line, env var names, transport and URL to the user for confirmation before any file is touched (issue #313).

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

type ServerSource added in v0.8.0

type ServerSource interface {
	// LookupCache returns the list of (name, transport, command, url,
	// tokens-per-turn) records available locally. The bool reports whether
	// any cache was present; an empty slice with bool == true means "cache
	// exists but is empty".
	LookupCache(ctx context.Context) (CacheSnapshot, error)
}

ServerSource is the minimal interface the installer needs from a registry cache. It is satisfied by *registry.FeedFetcher (which returns a *registry.FeedIndex) but defined here to avoid an import cycle with the registry package, which in turn depends on this package for the ServerConfig schema.

type StdioConfig

type StdioConfig struct {
	Command string   `yaml:"command"`
	Args    []string `yaml:"args"`
	// Env holds explicit "KEY=VALUE" entries added on top of the minimal
	// base environment (#311). A value may reference "${VAR}" to expand a
	// variable from the proxy's own (parent) environment; a reference to a
	// variable that is not set there fails the server's start with an
	// error naming the server and the variable.
	Env []string `yaml:"env"`
	// EnvPassthrough lists parent environment variable names to copy
	// through to the child as-is, in addition to the minimal base
	// environment and Env (#311). Only names — never values — are ever
	// logged for these.
	EnvPassthrough []string `yaml:"env_passthrough"`
	// InheritEnv restores the pre-#311 behavior of passing the proxy's
	// entire environment to the child. It logs one warning per server at
	// start and exists only to ease migration; least-privilege (the
	// default, false) should be preferred.
	InheritEnv bool   `yaml:"inherit_env"`
	CWD        string `yaml:"cwd"`
	// Sandbox, when set, runs this stdio server inside a container runtime
	// (docker/podman) instead of spawning it directly on the host (#312).
	// Absent (or runtime: none, the default) means unsandboxed, unchanged
	// from pre-#312 behavior.
	Sandbox *SandboxConfig `yaml:"sandbox,omitempty"`
}

type SummarizeSettings

type SummarizeSettings struct {
	Enabled   bool   `yaml:"enabled"`
	MaxTokens int    `yaml:"max_tokens"`
	Strategy  string `yaml:"strategy"`
}

type TransportType added in v0.8.0

type TransportType string

TransportType enumerates the wire transports a server may speak. The string values are part of the public YAML schema and must not change without a migration step.

const (
	TransportStdio TransportType = "stdio"
	TransportHTTP  TransportType = "http"
	TransportSSE   TransportType = "sse"
)

type VSCodeScanner

type VSCodeScanner struct {
	// contains filtered or unexported fields
}

VSCodeScanner reads VS Code's MCP servers (VS Code, VS Code Insiders and VSCodium):

  • "servers" of the user profile's mcp.json,
  • "mcp": {"servers": ...} (or "mcp.servers") of the user settings.json,
  • "servers" of the workspace .vscode/mcp.json in the current directory.

func (*VSCodeScanner) Name

func (s *VSCodeScanner) Name() string

func (*VSCodeScanner) Scan

type ValidationError

type ValidationError struct {
	ServerName string
	Message    string
	Field      string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Errors   []ValidationError
	Warnings []ValidationError
}

func (*ValidationResult) ErrorCount

func (r *ValidationResult) ErrorCount() int

func (*ValidationResult) HasErrors

func (r *ValidationResult) HasErrors() bool

func (*ValidationResult) HasWarnings

func (r *ValidationResult) HasWarnings() bool

func (*ValidationResult) WarningCount

func (r *ValidationResult) WarningCount() int

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

func NewValidator

func NewValidator() *Validator

func NewValidatorWithoutExecutableCheck

func NewValidatorWithoutExecutableCheck() *Validator

func (*Validator) ValidateServers

func (v *Validator) ValidateServers(servers []DiscoveredServer) *ValidationResult

type VectorStoreConfig added in v0.8.0

type VectorStoreConfig struct {
	Backend   string                `yaml:"backend"`
	Dimension int                   `yaml:"dimension"`
	SQLite    *SQLiteVectorConfig   `yaml:"sqlite,omitempty"`
	Qdrant    *QdrantVectorConfig   `yaml:"qdrant,omitempty"`
	Pinecone  *PineconeVectorConfig `yaml:"pinecone,omitempty"`
}

Jump to

Keyboard shortcuts

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