Documentation
¶
Overview ¶
Package config provides configuration types and merge utilities for MCPProxy. This file implements smart config patching with deep merge semantics. Related issues: #239, #240
Index ¶
- Constants
- Variables
- func BoolPtr(b bool) *bool
- func CanonicalToolName(serverName, rawName string) string
- func ConnectionEquivalent(a, b *ServerConfig) bool
- func CreateSampleConfig(path string) error
- func DefaultCheckIntervals() []time.Duration
- func DoctorFindings(cfg *Config) []string
- func EffectiveRequireMCPAuth(cfg *Config) bool
- func EnsureConfigFile(path, dataDir string) (created bool, err error)
- func GetConfigPath(dataDir string) string
- func IdPProviderFamily(_ *Config) string
- func IsBuiltInDefaultImage(key, image string) bool
- func IsDeprecatedDefaultRegistry(id string) bool
- func IsDockerCommand(command string) bool
- func IsTrustedProxy(remoteAddr string, trusted []string) bool
- func IsValidProfileSlug(name string) bool
- func IsValidTrustMode(s string) bool
- func LogLoadDiagnostics(cfg *Config, logger *zap.Logger)
- func LoopbackBindHost(hostname string) string
- func MergeMap(dst, src map[string]string) map[string]string
- func MergeMapWithOpts(dst, src map[string]string, mapField string, opts MergeOptions) map[string]string
- func MergeMapWithRemoval(dst, src map[string]string) map[string]string
- func MergeServerConfig(base, patch *ServerConfig, opts MergeOptions) (*ServerConfig, *ConfigDiff, error)
- func MigrateDeepScanConfig(cfg *Config)
- func NeedsGitCapableImage(runtimeType string, args []string) bool
- func NormalizeRegistryProvenance(p string) string
- func OAuthConfigChanged(old, new *OAuthConfig) bool
- func OverrideForProcess[T any](cfg *Config, f Field[T], source OverrideSource, value T)
- func ParseLoopbackRedirectURI(rawURI string) (bindHost string, port int, path string, err error)
- func ProcessOverrideFields() []string
- func PruneDeprecatedRegistries(cfg *Config) int
- func PublicURL(_ *Config) string
- func RawToolName(tool *ToolMetadata) string
- func ReapplyFlagOverrides(cfg, live *Config)
- func RequireMCPAuthOverridden(_ *Config) bool
- func ResetProcessOverrides()
- func ResolveRoutingMode(mode string) string
- func SandboxEnforceable() bool
- func SaveConfig(cfg *Config, path string) error
- func SaveConfigToDataDir(cfg *Config) error
- func SaveConfigWithEdits(cfg, mergeBase *Config, path string) error
- func ServerContributesTools(enabled, quarantined bool) bool
- func ServerDependsOnDocker(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) bool
- func ServerEditionAccessProjection(_ *Config) any
- func ServerEditionAdminEmails(_ *Config) []string
- func ServerEditionEnabled(_ *Config) bool
- func ServerEditionRestartProjection(cfg *Config) any
- func ServerEditionRestartReason(_, _ *Config) string
- func SetRegistriesInitCallback(callback func(*Config))
- func ValidTrustModes() []string
- func ValidateIsolationModeOverride(mode *IsolationMode) error
- func ValidateOAuthExtraParams(params map[string]string) error
- func ValidateProfiles(cfg *Config) (warnings []string, err error)
- func WriteLoadDiagnostics(cfg *Config, w io.Writer)
- type APIKeySource
- type AuditLogConfig
- type AuthBrokerConfig
- type ConcurrencyDefaults
- type Config
- func DecodeConfigFile(configPath string) (*Config, error)
- func DefaultConfig() *Config
- func Load() (*Config, error)
- func LoadFromFile(configPath string) (*Config, error)
- func LoadOrCreateConfig(dataDir string) (*Config, error)
- func LoadWithPath() (*Config, string, error)
- func PersistableConfig(effective *Config, path string) *Config
- func PersistableConfigWithEdits(effective, mergeBase *Config, path string) *Config
- func (c *Config) DefaultQuarantineForNewServer() bool
- func (c *Config) EffectiveActivityMaxRecords() int
- func (c *Config) EffectiveActivityMaxSizeMB() int
- func (c *Config) EffectiveActivityRetentionDays() int
- func (c *Config) EffectiveMaxResultSizeChars() int
- func (c *Config) EnsureAPIKey() (apiKey string, wasGenerated bool, source APIKeySource)
- func (c *Config) GetAnonymousID() string
- func (c *Config) GetTelemetryEndpoint() string
- func (c *Config) IsQuarantineEnabled() bool
- func (c *Config) IsTelemetryEnabled() bool
- func (c *Config) LoadDiagnostics() []LoadDiagnostic
- func (c *Config) MarshalJSON() ([]byte, error)
- func (c *Config) ProfileWarnings() []string
- func (c *Config) QuarantineDefaultForServer(sc *ServerConfig) bool
- func (c *Config) ResolveGlobalConcurrency() ResolvedConcurrency
- func (c *Config) ResolveHTTPIdleTimeout() time.Duration
- func (c *Config) ResolveHTTPReadTimeout() time.Duration
- func (c *Config) ResolveHTTPWriteTimeout() time.Duration
- func (c *Config) ResolveHealthCheckInterval(sc *ServerConfig) time.Duration
- func (c *Config) ResolveInitTimeout(sc *ServerConfig) time.Duration
- func (c *Config) ResolveServerConcurrency(sc *ServerConfig) ResolvedConcurrency
- func (c *Config) ResolveToolDiscoveryInterval(sc *ServerConfig) time.Duration
- func (c *Config) ResolveToonOutput(sc *ServerConfig) string
- func (c *Config) UnmarshalJSON(data []byte) error
- func (c *Config) Validate() error
- func (c *Config) ValidateDetailed() []ValidationError
- type ConfigDiff
- type CursorMCPConfig
- type CursorServerConfig
- type CustomPattern
- type DeepScanConfig
- type DeprecatedField
- type DockerIsolationConfig
- type DockerRecoveryConfig
- func (d *DockerRecoveryConfig) GetCheckIntervals() []time.Duration
- func (d *DockerRecoveryConfig) GetMaxRetries() int
- func (d *DockerRecoveryConfig) IsEnabled() bool
- func (d *DockerRecoveryConfig) ShouldNotifyOnFailure() bool
- func (d *DockerRecoveryConfig) ShouldNotifyOnRetry() bool
- func (d *DockerRecoveryConfig) ShouldNotifyOnStart() bool
- func (d *DockerRecoveryConfig) ShouldNotifyOnSuccess() bool
- func (d *DockerRecoveryConfig) ShouldPersistState() bool
- type Duration
- type FeatureFlags
- type Field
- type FieldChange
- type ForwardedInfo
- type ImmutableFieldError
- type IntentDeclarationConfig
- type IsolationConfig
- type IsolationMode
- type LoadDiagnostic
- type LogConfig
- type MergeOptions
- type MetricsExporterConfig
- type OAuthConfig
- type ObservabilityConfig
- type OutputSanitisationConfig
- func (c *OutputSanitisationConfig) EnabledStripClasses() map[string]bool
- func (c *OutputSanitisationConfig) IsBlock() bool
- func (c *OutputSanitisationConfig) IsEnabled() bool
- func (c *OutputSanitisationConfig) IsRedact() bool
- func (c *OutputSanitisationConfig) IsSpotlightEnabled() bool
- func (c *OutputSanitisationConfig) IsStripEnabled() bool
- func (c *OutputSanitisationConfig) WouldMutate(trust string) bool
- type OutputValidationConfig
- func (c *OutputValidationConfig) BlockOnMissingStructured() bool
- func (c *OutputValidationConfig) EffectiveMaxBytes() int
- func (c *OutputValidationConfig) EffectiveMaxDepth() int
- func (c *OutputValidationConfig) IsEnabled() bool
- func (c *OutputValidationConfig) IsStrict() bool
- func (c *OutputValidationConfig) IsWarn() bool
- type OverrideSource
- type ProfileConfig
- type RegistryEntry
- type ResolvedAuditLog
- type ResolvedConcurrency
- type ResolvedIsolation
- type SearchResult
- type SecurityConfig
- func (sc *SecurityConfig) DeepScanScanners() []string
- func (sc *SecurityConfig) EffectiveFetchPackageSource() *bool
- func (sc *SecurityConfig) EffectiveTPABundlePath() string
- func (sc *SecurityConfig) IsAutoBaselineScanEnabled() bool
- func (sc *SecurityConfig) IsDeepScanEnabled() bool
- func (sc *SecurityConfig) IsDisableNoNewPrivileges() bool
- type SensitiveDataDetectionConfig
- type ServerConfig
- func (sc *ServerConfig) ContributesTools() bool
- func (sc *ServerConfig) EffectiveTrustMode() TrustMode
- func (sc *ServerConfig) HasStaticAuthorizationHeader() bool
- func (sc *ServerConfig) IsAutoApproveToolChanges() bool
- func (sc *ServerConfig) IsQuarantineSkipped() bool
- func (sc *ServerConfig) IsToolAllowedByConfig(toolName string) bool
- func (sc *ServerConfig) MarkQuarantineExplicitlySet(explicit bool)
- func (sc *ServerConfig) MarshalJSON() ([]byte, error)
- func (sc *ServerConfig) QuarantineExplicitlySet() bool
- func (sc *ServerConfig) UnmarshalJSON(data []byte) error
- type ServerEditionConfig
- type StartupError
- type TLSConfig
- type TelemetryConfig
- type TokenizerConfig
- type ToolAnnotations
- type ToolMetadata
- type ToolRegistration
- type ToolStatEntry
- type ToolStats
- type TracingExporterConfig
- type TrustMode
- type TrustModeNormalization
- type TrustedProxiesProvider
- type UpdateCheckConfig
- type ValidationError
Constants ¶
const ( TransportHTTP = "http" TransportStdio = "stdio" )
Transport values EffectiveAuditLog accepts (Spec 107 FR-014): "http" for the HTTP/SSE listener, "stdio" for the native stdio MCP transport (where stdout is the JSON-RPC channel and can never double as a log sink).
const ( DefaultAuditLogMaxSizeMB = 50 DefaultAuditLogMaxBackups = 10 DefaultAuditLogMaxAgeDays = 90 )
Default rotation values (contracts/config-keys.md).
const ( // MsgAuditLogStdoutIgnoredStdio is the WARN line for a stdout sink // silently suppressed under the stdio transport: an absent audit_log // block whose per-edition default would otherwise be stdout:true, or an // explicit block whose `stdout` was left unset (never for an explicit // `stdout: true`, which is refused instead — see // MsgAuditLogStdoutRefusedStdio). MsgAuditLogStdoutIgnoredStdio = "audit_log.stdout is ignored under the stdio transport; set audit_log.path" // MsgAuditLogStdoutRefusedStdio is the StartupError message for an // explicit `enabled: true, stdout: true` with no `path` under the stdio // transport (FR-014: an explicit value always wins - it is refused, // never silently disabled). MsgAuditLogStdoutRefusedStdio = "audit_log.stdout cannot be used under the stdio transport (stdout carries JSON-RPC); set audit_log.path" // MsgAuditLogDisabledNotice is the startup notice for an explicit // audit_log.enabled: false under the server edition. MsgAuditLogDisabledNotice = "audit attribution is off" // MsgAuditLogDefaultActive is the startup notice for the server-edition // default (audit_log absent, non-stdio transport): FR-014 requires one // startup line naming that the default sink (stdout) is active so an // operator relying on a silent config file is not surprised by lines on // stdout (round-1 cross-review finding, PR-D). MsgAuditLogDefaultActive = "audit_log is not configured; the server-edition default is active (enabled, stdout) — set audit_log to override" // MsgAuditLogNoSink is the validation message for enabled:true with // neither stdout nor a path set. MsgAuditLogNoSink = "audit_log is enabled but has no sink (set stdout: true or a path)" )
Boot/doctor/validation message text (contracts/config-keys.md, exact strings — both the log line and the write-door validators use these).
const ( // Routing mode constants (Spec 031) RoutingModeRetrieveTools = "retrieve_tools" // Default: BM25 search via retrieve_tools + call_tool_read/write/destructive RoutingModeDirect = "direct" // All upstream tools exposed directly with serverName__toolName naming RoutingModeCodeExecution = "code_execution" // JS orchestration via code_execution tool with tool catalog // Tool response mode constants (Spec 085) ToolResponseModeFull = "full" // Default: today's schema-bearing retrieve_tools entries ToolResponseModeCompact = "compact" // Compact signatures + first-sentence descriptions // Direct-surface serialization constants (Spec 102). A SEPARATE axis from // ToolResponseMode above: that one governs the retrieve_tools surface, this // one governs the direct enumeration surface (/mcp/all, and /mcp plus the // legacy aliases when routing_mode is "direct"). They are orthogonal, and // compact + deferred is a legal combination in which each governs only its // own surface (plan.md D1). DirectToolResponseModeFull = "full" // Default: today's schema-bearing direct entries DirectToolResponseModeDeferred = "deferred" // Signature-suffixed descriptions, permissive schema )
const ( // RegistryProvenanceOfficial marks a built-in, shipped-by-default registry. RegistryProvenanceOfficial = "official" // RegistryProvenanceCustom marks a user-added registry. RegistryProvenanceCustom = "custom" )
Registry provenance tags (MCP-866). Trust is derived, not user-asserted: a registry is "trusted" only when it is one of the shipped built-in defaults. Anything a user adds at runtime (e.g. via `registry add-source`) is "custom". Provenance is purely informational now (MCP-1072): it no longer forces quarantine — servers added from any registry follow the global quarantine default. It still drives the derived "trusted" flag a few surfaces show.
const ( UpdateChannelStable = "stable" UpdateChannelRC = "rc" )
Update-check release channels (Spec 079 FR-013). "stable" follows GitHub releases/latest and never offers prereleases; "rc" additionally offers prerelease tags (v*-rc.*, v*-next.*) published to the GitHub pre-release channel — the config-file equivalent of MCPPROXY_ALLOW_PRERELEASE_UPDATES.
const ( // GitCapableImageRegistry is the public registry the built-in image lives // on when the operator configured none of their own. GitCapableImageRegistry = "ghcr.io" // DefaultDockerRegistry is the value `docker_isolation.registry` ships // with. It is Docker Hub, i.e. "the public default", so it says nothing // about an operator running a mirror — and the built-in git-capable image // is not published there, so rewriting it onto this host would turn a // working pull into a guaranteed failure. DefaultDockerRegistry = "docker.io" // GitCapableImageRepo is DefaultGitCapableImage without its registry host. GitCapableImageRepo = "astral-sh/uv:python3.13-bookworm" // DefaultGitCapableImage is the fully-qualified built-in image. DefaultGitCapableImage = GitCapableImageRegistry + "/" + GitCapableImageRepo )
DefaultGitCapableImage is mcpproxy's own git-capable image: the non-slim uv image, which ships git (verified: git version 2.39.5).
It is deliberately NOT seeded into `docker_isolation.default_images`. Every key that map ships is written back into the operator's config file verbatim on the next save (SaveConfig marshals the whole merged map), which makes presence meaningless for a seeded key and leaves value equality as the only signal of intent — and value equality cannot express "I explicitly chose the image mcpproxy ships". An operator mirroring `uvx` who deliberately pointed `uvx-git` at this public image had that choice read as "unset" and silently replaced by their git-less mirror. Because the key is never seeded, its presence now means exactly one thing: the operator typed it.
The registry half is split out so a configured `docker_isolation.registry` can qualify it — an air-gapped host that set only `registry` cannot pull ghcr.io at all. See core.IsolationManager.builtInGitCapableImage.
const ( // IsolationSourceGlobal: the effective mode came from the global config — // either because the server sets no override, or because its explicit // enabled:true simply agrees with the global mode. IsolationSourceGlobal = "global" // IsolationSourceServerMode: a per-server `isolation.mode` override won. IsolationSourceServerMode = "server-mode" // IsolationSourceServerOptOut: a per-server `isolation.enabled:false` // downgraded an otherwise-active global mode. IsolationSourceServerOptOut = "server-opt-out" // IsolationSourceServerOptInIgnored: the server sets `isolation.enabled:true` // but global isolation is off, so the opt-in is ignored. IsolationSourceServerOptInIgnored = "server-opt-in-ignored" // IsolationSourceNotStdio: structural gate — the server has no local // command, so there is no child process to isolate. PROCESS-SPAWN ONLY: // it says nothing about whether separate scanner containers may run // (GH #1303), so ResolveScannerIsolationMode never emits it. IsolationSourceNotStdio = "not-stdio" // IsolationSourceAlreadyDocker: structural gate — the server already // invokes docker itself, so wrapping it would break its socket access. // PROCESS-SPAWN ONLY, for the same reason as IsolationSourceNotStdio. IsolationSourceAlreadyDocker = "already-docker" // but this host cannot enforce it (any non-Linux OS, or a Linux kernel // without Landlock), so the child process runs unconfined. IsolationSourceSandboxUnavailable = "sandbox-unavailable" // IsolationSourceUnsupportedMode: the configured mode is not one the spawn // path implements, so nothing wraps the child process. Reachable from a // hand-edited config file; the write surfaces reject unknown modes. IsolationSourceUnsupportedMode = "unsupported-mode" )
Isolation resolution sources. These are a stable vocabulary: they are serialized onto the REST/MCP surfaces so a UI can explain WHY a server is (or is not) isolated instead of rendering a bare toggle. Clients must treat an unrecognized value as "inherited from the global setting".
const ( DefaultDataDir = ".mcpproxy" ConfigFileName = "mcp_config.json" )
const ( LoopbackIPv4Host = "127.0.0.1" LoopbackIPv6Host = "::1" )
LoopbackIPv4Host / LoopbackIPv6Host are the addresses the callback listener binds for the two loopback families a pinned redirect URI can name.
const CodeExecutionDisabledMessage = `Code execution is disabled. Enable it by setting "enable_code_execution": true in your mcpproxy configuration file.`
CodeExecutionDisabledMessage is the single explanation every surface gives when EnableCodeExecution is false. The MCP disabled stub, the handler gate that covers REST and tray dispatch, and the HTTP 403 body all render this string, so a caller who switches transports never has to wonder whether two different refusals mean two different things.
const EnvAutoBaselineScan = "MCPPROXY_AUTO_BASELINE_SCAN"
EnvAutoBaselineScan is the environment kill-switch for the automatic, informational Pass-1 baseline scan (`security.auto_baseline_scan`). Like the bundle path, precedence is enforced in the accessor (SecurityConfig.IsAutoBaselineScanEnabled) rather than only in the loader, so a config posted to /api/v1/config/apply cannot defeat the operator's env setting. Accepts "true"/"1" and "false"/"0"; any other value is ignored.
const EnvTPABundlePath = "MCPPROXY_TPA_BUNDLE_PATH"
EnvTPABundlePath is the environment override for the offline TPA signature-bundle location (spec 086 FR-019). It outranks security.tpa_bundle_path on EVERY path that resolves the corpus — the loader, /api/v1/config/apply, hot-reload, and stdio startup — because the precedence is enforced in SecurityConfig.EffectiveTPABundlePath rather than only in the loader's env pass.
const ExitCodeAuditLogError = 4
ExitCodeAuditLogError is the exit code an unhonourable audit_log configuration returns (Spec 107 FR-014: same band as every other configuration boot failure).
const GitCapableImageKey = "uvx-git"
GitCapableImageKey is the `docker_isolation.default_images` key naming the image used for Python package runners that install from a git URL.
The shipped Python default is Astral's *slim* uv image, which does not contain git:
$ docker run --rm --entrypoint sh ghcr.io/astral-sh/uv:python3.13-bookworm-slim -c 'git --version' sh: 1: git: not found
so `uvx --from …git+https://…` (the only distribution channel for a large share of MCP servers) failed under Docker isolation with "Git executable not found" / "Git operation failed" (#1143). Raising the global Python default to the non-slim image would cost every user a ~1.5GB pull for a case many never hit, so the git-capable image is selected per-server, from its own named key, which operators can retarget to a mirror or a custom build.
const MsgRequireMCPAuthOverridden = "require_mcp_auth: false is overridden to true because server_edition.enabled is true"
MsgRequireMCPAuthOverridden is the boot notice and doctor finding text of contracts/config-keys.md for an explicit require_mcp_auth: false under an enabled server-edition block (Spec 107 FR-029).
const OAuthCallbackPath = "/oauth/callback"
OAuthCallbackPath is the loopback path mcpproxy's OAuth callback server listens on when `oauth.redirect_uri` does not specify its own path (or is unset, in which case mcpproxy allocates a dynamic port entirely).
It lives here rather than in internal/oauth because internal/oauth imports this package (never the other way round) and the config layer has to validate `oauth.redirect_uri` where the operator types it. internal/oauth aliases it as DefaultRedirectPath.
Variables ¶
var ( // ErrImmutableField is returned when attempting to modify an immutable field ErrImmutableField = errors.New("cannot modify immutable field") // ErrInvalidConfig is returned when merged config fails validation ErrInvalidConfig = errors.New("invalid configuration after merge") )
Error types for merge operations
var ( FieldListen = scalar("listen", func(c *Config) *string { return &c.Listen }) FieldDataDir = scalar("data_dir", func(c *Config) *string { return &c.DataDir }) FieldAPIKey = scalar("api_key", func(c *Config) *string { return &c.APIKey }) FieldTrayEndpoint = scalar("tray_endpoint", func(c *Config) *string { return &c.TrayEndpoint }) FieldEnableSocket = scalar("enable_socket", func(c *Config) *bool { return &c.EnableSocket }) FieldToolResponseLimit = scalar("tool_response_limit", func(c *Config) *int { return &c.ToolResponseLimit }) FieldToolResponseMode = scalar("tool_response_mode", func(c *Config) *string { return &c.ToolResponseMode }) FieldDirectToolResponseMode = scalar("direct_tool_response_mode", func(c *Config) *string { return &c.DirectToolResponseMode }) FieldDebugSearch = scalar("debug_search", func(c *Config) *bool { return &c.DebugSearch }) FieldRequireMCPAuth = scalar("require_mcp_auth", func(c *Config) *bool { return &c.RequireMCPAuth }) FieldReadOnlyMode = scalar("read_only_mode", func(c *Config) *bool { return &c.ReadOnlyMode }) FieldDisableManagement = scalar("disable_management", func(c *Config) *bool { return &c.DisableManagement }) FieldAllowServerAdd = scalar("allow_server_add", func(c *Config) *bool { return &c.AllowServerAdd }) FieldAllowServerRemove = scalar("allow_server_remove", func(c *Config) *bool { return &c.AllowServerRemove }) FieldEnablePrompts = scalar("enable_prompts", func(c *Config) *bool { return &c.EnablePrompts }) FieldAggregateUpstreamPrompts = scalar("aggregate_upstream_prompts", func(c *Config) *bool { return &c.AggregateUpstreamPrompts }) FieldTrustedHosts = scalar("trusted_hosts", func(c *Config) *[]string { return &c.TrustedHosts }) FieldMaxConcurrentRequests = scalar("max_concurrent_requests", func(c *Config) **int { return &c.MaxConcurrentRequests }) FieldQueueSize = scalar("queue_size", func(c *Config) **int { return &c.QueueSize }) FieldQueueTimeout = scalar("queue_timeout", func(c *Config) **Duration { return &c.QueueTimeout }) FieldHTTPReadTimeout = scalar("http_read_timeout", func(c *Config) **Duration { return &c.HTTPReadTimeout }) FieldHTTPWriteTimeout = scalar("http_write_timeout", func(c *Config) **Duration { return &c.HTTPWriteTimeout }) FieldHTTPIdleTimeout = scalar("http_idle_timeout", func(c *Config) **Duration { return &c.HTTPIdleTimeout }) FieldLogLevel = Field[string]{ Name: "logging.level", Get: func(c *Config) string { return loggingOf(c).Level }, Set: func(c *Config, v string) { l := cowLogging(c); l.Level = v }, } FieldLogEnableFile = Field[bool]{ Name: "logging.enable_file", Get: func(c *Config) bool { return loggingOf(c).EnableFile }, Set: func(c *Config, v bool) { l := cowLogging(c); l.EnableFile = v }, } FieldLogDir = Field[string]{ Name: "logging.log_dir", Get: func(c *Config) string { return loggingOf(c).LogDir }, Set: func(c *Config, v string) { l := cowLogging(c); l.LogDir = v }, } FieldTLSEnabled = Field[bool]{ Name: "tls.enabled", Get: func(c *Config) bool { return tlsOf(c).Enabled }, Set: func(c *Config, v bool) { t := cowTLS(c); t.Enabled = v }, } FieldTLSRequireClientCert = Field[bool]{ Name: "tls.require_client_cert", Get: func(c *Config) bool { return tlsOf(c).RequireClientCert }, Set: func(c *Config, v bool) { t := cowTLS(c); t.RequireClientCert = v }, } FieldTLSCertsDir = Field[string]{ Name: "tls.certs_dir", Get: func(c *Config) string { return tlsOf(c).CertsDir }, Set: func(c *Config, v string) { t := cowTLS(c); t.CertsDir = v }, } FieldTPABundlePath = Field[string]{ Name: "security.tpa_bundle_path", Get: func(c *Config) string { return securityOf(c).TPABundlePath }, Set: func(c *Config, v string) { s := cowSecurity(c); s.TPABundlePath = v }, } FieldAutoBaselineScan = Field[*bool]{ Name: "security.auto_baseline_scan", Get: func(c *Config) *bool { return securityOf(c).AutoBaselineScan }, Set: func(c *Config, v *bool) { if c.Security == nil && v == nil { return } s := cowSecurity(c) s.AutoBaselineScan = v }, } )
The overridable fields. Keep in lockstep with the overrides applied in cmd/mcpproxy (serve flags), applyTLSEnvOverrides (env) and Validate (env API key): an override applied without going through OverrideForProcess is persisted by every save path, which is the bug this file exists to close.
var ErrCodeExecutionDisabled = errors.New("code execution is disabled")
ErrCodeExecutionDisabled is the TYPED identity of that refusal, matched with errors.Is; what a caller READS is always CodeExecutionDisabledMessage. The MCP contract forces the tool handler to answer with an isError result rather than a transport error, which leaves the REST layer nothing but a string to classify by. Carrying this sentinel out through the dispatch error lets the HTTP surface answer 403 — a refusal retrying cannot fix — instead of the 500 a flattened message would produce.
Functions ¶
func BoolPtr ¶
BoolPtr returns a pointer to the given bool value. Useful for setting *bool fields in struct literals.
func CanonicalToolName ¶ added in v0.67.0
CanonicalToolName returns the canonical "<server>:<rawName>" id for an exact (server, raw name) pair. Unlike index.CanonicalToolName it never guards against a double prefix: the raw name is exact by contract, so a raw "a:erase" on server "a" is correctly rendered as "a:a:erase" — the spelling handleCallToolVariant splits back into the same pair.
func ConnectionEquivalent ¶ added in v0.64.0
func ConnectionEquivalent(a, b *ServerConfig) bool
ConnectionEquivalent reports whether two snapshots of the same server carry identical CONNECTION settings — everything that decides how mcpproxy dials or spawns the upstream.
It is the supervisor's "did the user change something?" predicate. That used to be a five-field comparison (URL, protocol, command, enabled, quarantined), which was harmless only because a server that should be connected but wasn't eventually got an ActionConnect anyway. Since GH #1145 a permanently failed server is parked and that fallback no longer fires, so a missed field is a user who fixes their `args` — or points `isolation.image` at an image that actually has the toolchain — and never sees the server come back.
Deliberately EXCLUDED: Name (identity, keyed elsewhere), Created, and Updated. Updated is rewritten by unrelated config writes (quarantine bookkeeping, tool hashes), so including it would reconnect every server on the next tick. Also excluded are settings that do not affect the connection itself — trust mode, tool allow/deny lists, concurrency limits, output formatting — which are applied in place without a redial.
func CreateSampleConfig ¶
CreateSampleConfig creates a sample configuration file
func DefaultCheckIntervals ¶
DefaultCheckIntervals returns the default Docker recovery check intervals
func DoctorFindings ¶ added in v0.68.0
DoctorFindings returns the configuration findings `mcpproxy doctor` renders as runtime_warnings (Spec 107 T052). It reads the config it is handed — the caller passes the LIVE snapshot — and never mutates it. Edition-neutral findings live here; the server-only ones come from the build-tagged serverEditionDoctorFindings (a no-op on the personal build).
func EffectiveRequireMCPAuth ¶ added in v0.68.0
EffectiveRequireMCPAuth is the configured value on the personal build.
func EnsureConfigFile ¶ added in v0.53.0
EnsureConfigFile seeds a default configuration at an explicitly named path that does not exist yet, and reports whether it created one.
It exists for the first run of an instance whose config path is named on the command line rather than discovered — the relocated tray instance of GH #936 spawns its core with BOTH `--data-dir <root>` and `--config <root>/mcp_config.json`, and on a fresh root that file has never been written. LoadFromFile refuses a missing explicit path, so without this the core exited on the spot with "no such file or directory" and the instance could never come up.
Why here and not inside LoadFromFile: LoadFromFile is also the HOT-RELOAD entry point (internal/runtime/lifecycle.go, internal/runtime/configsvc). A config file that disappears under a running proxy must fail the reload and leave the live config alone; creating a default there would replace every server the user has with nothing. Seeding is a startup decision, so it is made at startup, once.
dataDir is the directory the caller will run out of (the `--data-dir` flag when one was given); the seeded file records it, exactly as the implicit path records its own. An empty dataDir leaves the field unset, so the loader's usual default applies.
func GetConfigPath ¶
GetConfigPath returns the path to the configuration file in the data directory
func IdPProviderFamily ¶ added in v0.68.0
IdPProviderFamily is always "" on the personal build.
func IsBuiltInDefaultImage ¶ added in v0.64.0
IsBuiltInDefaultImage reports whether image is exactly the value mcpproxy ships for that `default_images` key — i.e. whether the entry is still mcpproxy's own choice rather than the operator's.
It answers that question only for the RUNTIME keys mcpproxy actually seeds ("uvx", "npx", …). For those, the merge makes presence meaningless — every built-in key is present in every loaded config, and is written back on the next save — so value equality is the only distinction that survives, and treating a shipped default as a deliberate choice is how an air-gapped install ends up pulling a public image.
It is NOT how GitCapableImageKey is decided: that key is never seeded, so its presence is the operator's intent (see DefaultGitCapableImage).
An operator who deliberately configures the shipped value for a runtime key is not harmed by being read as "unset": every branch that consults this then falls back to their other entries, which point at the same place the shipped value does unless they are mirroring — in which case the mirror is what they wanted.
func IsDeprecatedDefaultRegistry ¶ added in v0.37.0
IsDeprecatedDefaultRegistry reports whether id is a known former-default registry that was removed from the shipped set and must not be resurrected.
func IsDockerCommand ¶ added in v0.64.0
IsDockerCommand reports whether a server's command already invokes Docker. Such servers are typically pre-configured containers; wrapping them (in a container or a Landlock sandbox) would break their access to the Docker socket.
func IsTrustedProxy ¶ added in v0.68.0
IsTrustedProxy reports whether remoteAddr (RemoteAddr form) is inside the trusted list. Unparsable peers and an empty list are never trusted.
func IsValidProfileSlug ¶ added in v0.46.0
IsValidProfileSlug reports whether name is a valid, filesystem-safe profile slug (FR-007): a lowercase-alphanumeric start followed by up to 62 more of [a-z0-9_-] (1-63 chars total). Callers that map a slug onto a directory path (e.g. per-profile Bleve indexes) use this as a defense-in-depth guard against path traversal, in addition to ValidateProfiles' load-time enforcement.
func IsValidTrustMode ¶ added in v0.53.0
IsValidTrustMode reports whether s is an acceptable trust_mode value. The empty string is valid and means "inherit" (resolved by EffectiveTrustMode to manual, or derived from the legacy fields by the load-time migration).
Matching is exact and case-SENSITIVE on purpose: EffectiveTrustMode fails closed to manual on an unrecognized value, so silently accepting "Scan" would leave an operator believing scanning is on while the runtime holds everything for manual review (GH #938 finding 1).
func LogLoadDiagnostics ¶ added in v0.68.0
LogLoadDiagnostics emits one WARN line per recorded diagnostic. It is called once after the logger exists (cmd/mcpproxy/main.go right after logs.SetupLogger) and after each successful hot reload — never by the loader, which has no logger. A nil config or logger, or no diagnostics, is a silent no-op.
func LoopbackBindHost ¶ added in v0.62.0
LoopbackBindHost maps the hostname of a pinned redirect URI onto the address the callback listener must bind.
"localhost" deliberately binds 127.0.0.1 rather than resolving it: the URI string sent to the provider keeps the operator's spelling (providers match it literally), while the listener stays on the family mcpproxy can guarantee. Mainstream browsers fall back from ::1 to 127.0.0.1 via Happy Eyeballs, and docs/configuration.md steers operators to 127.0.0.1 for that reason.
func MergeMap ¶
MergeMap deep merges src into dst, returning a new map. Empty string values in src do NOT remove keys (use explicit removal mechanism). The original maps are not modified.
func MergeMapWithOpts ¶
func MergeMapWithOpts(dst, src map[string]string, mapField string, opts MergeOptions) map[string]string
MergeMapWithOpts deep merges src into dst with RFC 7396 null-means-remove semantics. Keys marked for removal via opts.ShouldRemoveMapKey are deleted from the result. This implements proper JSON Merge Patch behavior where null values remove keys. The original maps are not modified.
func MergeMapWithRemoval ¶
MergeMapWithRemoval deep merges src into dst with support for key removal. Keys with empty string values in src will be removed from the result.
func MergeServerConfig ¶
func MergeServerConfig(base, patch *ServerConfig, opts MergeOptions) (*ServerConfig, *ConfigDiff, error)
MergeServerConfig deep merges patch into base, returning the merged config and diff.
Merge semantics:
- Scalar fields: Replace if patch value is non-zero
- Map fields (env, headers): Deep merge, null values remove keys
- Struct fields (isolation, oauth): Deep merge nested fields
- Array fields (args, extra_args, scopes): Replace entirely
- Nil/omitted fields in patch: Preserve base value
Returns:
- merged: The resulting merged configuration (new copy)
- diff: Changes made during merge (nil if opts.GenerateDiff is false)
- error: Validation or merge error
func MigrateDeepScanConfig ¶ added in v0.47.0
func MigrateDeepScanConfig(cfg *Config)
MigrateDeepScanConfig runs the Spec 077 US3 deep-scan config migration on an already-parsed config. LoadFromFile applies it automatically (via initializeRegistries); the /api/v1/config/apply path bypasses LoadFromFile, so it calls this explicitly to normalize an API-submitted config identically to a file load before diffing/saving (SC-007). Idempotent + nil-safe.
func NeedsGitCapableImage ¶ added in v0.64.0
NeedsGitCapableImage reports whether a server with the given detected runtime type and args needs an isolation image that contains git — i.e. it is a Python package runner asked to install from a git URL (`git+https://`, `pkg@git+ssh://`, …).
It deliberately looks only at the `git+` marker that pip/uv URLs require: a package merely *named* something with "git" in it does not match.
func NormalizeRegistryProvenance ¶ added in v0.37.0
NormalizeRegistryProvenance maps legacy provenance strings persisted by earlier builds (MCP-866's "official/trusted" / "custom/unverified") onto the current two-value vocabulary ("official" / "custom"). Already-current and empty values pass through unchanged, so the mapping is idempotent. This lets an existing config.db converge without breaking on read (MCP-1072).
func OAuthConfigChanged ¶
func OAuthConfigChanged(old, new *OAuthConfig) bool
OAuthConfigChanged checks if OAuth configuration has changed between two configs. Returns true if any OAuth field differs (ClientID, Scopes, ExtraParams, etc.)
func OverrideForProcess ¶ added in v0.68.0
func OverrideForProcess[T any](cfg *Config, f Field[T], source OverrideSource, value T)
OverrideForProcess sets field f on cfg to value for THIS PROCESS ONLY and records it, so PersistableConfig (and therefore SaveConfig) writes the file's value back as long as the effective value still equals the override.
func ParseLoopbackRedirectURI ¶ added in v0.62.0
ParseLoopbackRedirectURI validates an operator-pinned OAuth redirect URI (the per-server `oauth.redirect_uri` config field) and returns the loopback host to bind, the port it pins, and the callback path the listener must serve.
Providers such as GitHub OAuth Apps require the callback URL to match the registered one exactly and reject wildcards, so operators need a way to nail the loopback port down instead of letting mcpproxy allocate a fresh one per login. The URI must therefore be an RFC 8252 loopback redirect with an explicit port, e.g.
http://127.0.0.1:54108/oauth/callback
The path is taken verbatim from the URI rather than pinned to OAuthCallbackPath: some authorization servers publish a single shared OAuth application whose registered redirect path an operator cannot change (issue #1304), and mcpproxy's own callback path is an implementation detail the provider has no reason to agree with. A URI with no path at all (e.g. "http://127.0.0.1:54108") defaults to "/" - what an HTTP client actually requests for a path-less URL - not to OAuthCallbackPath, so the listener matches what the provider will really send. OAuthCallbackPath remains the default only when oauth.redirect_uri is unset entirely (dynamic allocation). Anything else about the URI is rejected with an actionable error rather than silently downgraded to dynamic allocation.
func ProcessOverrideFields ¶ added in v0.68.0
func ProcessOverrideFields() []string
ProcessOverrideFields lists the names of the fields currently overridden for this process, sorted and de-duplicated, for diagnostics and logging.
func PruneDeprecatedRegistries ¶ added in v0.37.0
PruneDeprecatedRegistries removes deprecated former-default registries (IsDeprecatedDefaultRegistry) from cfg.Registries in place and returns the number removed. It is idempotent and matches by the known former-default id set ONLY, so a genuinely user-added custom registry is never dropped.
func RawToolName ¶ added in v0.67.0
func RawToolName(tool *ToolMetadata) string
RawToolName returns the exact upstream-reported name of a tool.
It prefers the RawName stamp written at discovery (internal/upstream/core/client.go ListTools). Metadata built without the stamp — index reads, test fixtures, code paths that only carry the canonical id — falls back to trimming the tool's OWN server prefix once from Name, which is exact for both a raw name ("ns:erase" → "ns:erase") and a canonical id ("a:ns:erase" on server "a" → "ns:erase"). The one shape the fallback cannot disambiguate is a raw name that itself begins with the server's own prefix ("a:erase" on server "a"), which is why producers MUST stamp RawName rather than rely on the fallback.
func ReapplyFlagOverrides ¶ added in v0.68.0
func ReapplyFlagOverrides(cfg, live *Config)
ReapplyFlagOverrides layers every flag-sourced override back onto cfg — a config freshly loaded from the file, on which the loader has already re-applied the env overrides but knows nothing about the serve flags — and refreshes each record's file value. Without it a hot reload after an external edit silently switched `--read-only` (or any other flag) off.
live is the config this process was running before the reload. A flag the live config no longer carries was superseded by an API edit (which is on disk by now) and is not resurrected over that edit.
func RequireMCPAuthOverridden ¶ added in v0.68.0
RequireMCPAuthOverridden is always false on the personal build.
func ResetProcessOverrides ¶ added in v0.68.0
func ResetProcessOverrides()
ResetProcessOverrides forgets every recorded override. For tests.
func ResolveRoutingMode ¶ added in v0.63.0
ResolveRoutingMode resolves a configured routing mode to the one actually served, mirroring MCPProxyServer.GetMCPServerForMode: unset — and anything unrecognised — falls back to retrieve_tools. Callers that report "the routing mode" to an operator must resolve first, or a config holding "" reads as a mode nobody can act on.
func SandboxEnforceable ¶ added in v0.64.0
func SandboxEnforceable() bool
SandboxEnforceable reports whether the "sandbox" isolation mode can actually confine a child process on this host. Exported so surfaces that explain isolation state (and tests that assert the mode matrix) can ask the same question the resolver asks, instead of re-deriving it from GOOS.
func SaveConfig ¶
SaveConfig saves configuration to file
func SaveConfigToDataDir ¶
SaveConfigToDataDir saves configuration to the data directory
func SaveConfigWithEdits ¶ added in v0.68.0
SaveConfigWithEdits is SaveConfig for the save that persists an API edit: the overridden fields that moved between mergeBase (the config the edit was merged onto) and cfg are the caller's edits and are written as they are; every other overridden field is written back from the file as in SaveConfig. See PersistableConfigWithEdits.
Never persists a process-only override (serve flag, MCPPROXY_* env, env API key): the file's value is written back for every field still carrying one (see process_overrides.go). That makes every save a read-modify-write of the file, so in-process savers — the runtime, telemetry, serve's own saves — are serialised: a save always reads the file the previous save wrote, and an API edit can never be reverted by a concurrent save that had read the file before it landed. (A stale config saved whole still overwrites unrelated fields with what it holds — the residual window telemetry.persistConfig documents — but a field it merely carries from an override is restored from the file, never from that stale copy.)
func ServerContributesTools ¶ added in v0.62.0
ServerContributesTools reports whether a server's tools count as AVAILABLE to an agent. A quarantined server's tools are refused by every dispatch path (the SECURITY BLOCK in internal/server/mcp.go) and are withheld from the search index (#1061), so it contributes zero — the same answer the index writer's serverEligibleForIndexing and preflight.ClassifyTool already give. Takes plain bools because most callers hold a stateview server status rather than a *ServerConfig. Issue #1064.
func ServerDependsOnDocker ¶ added in v0.64.0
func ServerDependsOnDocker(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) bool
ServerDependsOnDocker reports whether STARTING this server needs a working Docker daemon — which is a different question from "do we isolate it".
Two disjoint ways a server ends up talking to Docker:
- We containerise it: ResolveIsolation resolves its effective mode to docker, so the spawn path wraps the command in `docker run`.
- It containerises itself: its own command already invokes docker, so ResolveIsolation's already-docker structural gate deliberately forces mode=none (never double-wrap) — yet the process still shells out to the daemon and still pays image-pull latency.
Callers that care about the LAUNCH SHAPE (which wrapper runs, which remediation to offer) must keep asking ResolveIsolation. Callers that care about DOCKER-THE-DEPENDENCY — the connect budget that must survive an image pull, the recovery monitor, shutdown container cleanup — ask this, so the two questions cannot silently collapse into one predicate again (GH #1142).
It is built ON TOP of the resolver plus the already-docker structural fact, so there is still exactly one implementation of the isolation algorithm.
A third, separate question — may the security scanner run its own Docker containers against this server — is answered by ResolveScannerIsolationMode.
func ServerEditionAccessProjection ¶ added in v0.68.0
ServerEditionAccessProjection is always nil on the personal build: the carrier is not interpreted, so there is no live access block to compare (any change inside the carrier is `server_edition`, restart-pinned).
func ServerEditionAdminEmails ¶ added in v0.68.0
ServerEditionAdminEmails is always nil on the personal build: the carrier is not interpreted, so there is no live key to compare.
func ServerEditionEnabled ¶ added in v0.68.0
ServerEditionEnabled is always false on the personal build.
func ServerEditionRestartProjection ¶ added in v0.68.0
ServerEditionRestartProjection returns the opaque carrier itself on the personal build (Spec 107 FR-040): the block is canonical JSON that is never interpreted here, so DetectConfigChanges compares its bytes and reports ANY difference as `server_edition`, restart-pinned. A nil block marshals to `null`, so absent-vs-absent compares equal and absent-vs-present does not.
func ServerEditionRestartReason ¶ added in v0.68.0
ServerEditionRestartReason is the single reason the personal build can give — it cannot tell which key inside the opaque block moved.
func SetRegistriesInitCallback ¶
func SetRegistriesInitCallback(callback func(*Config))
SetRegistriesInitCallback sets the callback function for registries initialization
func ValidTrustModes ¶ added in v0.53.0
func ValidTrustModes() []string
ValidTrustModes returns the accepted trust_mode values in their canonical order. It is the single source of truth for the operator-facing error text produced by config validation and by the REST layer (GH #938).
func ValidateIsolationModeOverride ¶ added in v0.64.0
func ValidateIsolationModeOverride(mode *IsolationMode) error
ValidateIsolationModeOverride reports whether a per-server `isolation.mode` override is a mode the spawn path actually implements.
Both write seams (REST `mode_override`, MCP `isolation_json`) call this so an unknown value is refused where the operator can see it, instead of being persisted to BBolt and the config file and only surfacing as a failed validation on the NEXT daemon start.
nil and the empty string are "unset" (inherit the global mode), not errors.
func ValidateOAuthExtraParams ¶
ValidateOAuthExtraParams validates that extra_params does not attempt to override reserved OAuth 2.0 parameters
func ValidateProfiles ¶ added in v0.39.0
ValidateProfiles enforces the Spec 057 profile rules (data-model.md). Fatal rules (invalid/reserved/duplicate slug) return an error that points at the offending entry; soft rules (unknown server, empty server list) return human-readable warnings without failing the load. A nil/empty Profiles slice is fully valid (returns no warnings, no error) — preserving zero-config behaviour (SC-004).
func WriteLoadDiagnostics ¶ added in v0.68.0
WriteLoadDiagnostics prints one `warning: <message> (key: <path>)` line per recorded diagnostic to w. It is the logger-less twin of LogLoadDiagnostics for the CLI subcommands, which have no zap logger but do load the file and — for `upstream add|remove` in standalone mode, `telemetry enable|disable` and the API-key reset — write it back, so a removed key would otherwise be erased with no operator-visible warning (FR-032). Callers pass stderr so `-o json` consumers of stdout are never disturbed. A nil config, a nil writer or no diagnostics writes nothing.
Types ¶
type APIKeySource ¶
type APIKeySource int
APIKeySource represents where the API key came from
const ( APIKeySourceEnvironment APIKeySource = iota APIKeySourceConfig APIKeySourceGenerated )
func (APIKeySource) String ¶
func (s APIKeySource) String() string
String returns a human-readable representation of the API key source
type AuditLogConfig ¶ added in v0.68.0
type AuditLogConfig struct {
Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"`
Path string `json:"path,omitempty" mapstructure:"path"`
Stdout *bool `json:"stdout,omitempty" mapstructure:"stdout"`
MaxSizeMB *int `json:"max_size_mb,omitempty" mapstructure:"max-size-mb"`
MaxBackups *int `json:"max_backups,omitempty" mapstructure:"max-backups"`
MaxAgeDays *int `json:"max_age_days,omitempty" mapstructure:"max-age-days"`
Compress *bool `json:"compress,omitempty" mapstructure:"compress"`
}
AuditLogConfig is the wire shape of the `audit_log` key. Every field except Path is a pointer so an omitted key is distinguishable from an explicit zero/false value (data-model.md §9): omitted `compress` -> true default, explicit `false` -> false; omitted `max_size_mb` -> 50, explicit `0` -> a validation error. Path's own emptiness already is the "unset" signal, so it stays a plain string.
type AuthBrokerConfig ¶ added in v0.38.0
type AuthBrokerConfig struct {
// contains filtered or unexported fields
}
AuthBrokerConfig is the personal-edition carrier for a server's `auth_broker` block. The connect flow is a server-edition feature (spec 074); the personal edition keeps the field on ServerConfig so configs round trip (Spec 107 FR-040): the block is held as the canonical JSON of what was read (canonicalRawJSON — every key and value kept, key order and whitespace normalised so jsonEqual-based change detection stays quiet), never interpreted, never validated and never warned about.
Omission is the parent pointer's job: ServerConfig.AuthBroker is `*T,omitempty`, so a server without the key leaves the pointer nil and the key stays absent on write. A non-nil carrier with no raw bytes marshals as `{}`.
func (*AuthBrokerConfig) Clone ¶ added in v0.68.0
func (a *AuthBrokerConfig) Clone() *AuthBrokerConfig
Clone returns a deep copy of the carrier (nil-safe). CopyServerConfig uses it so a copied server never aliases the source's backing array.
func (AuthBrokerConfig) MarshalJSON ¶ added in v0.68.0
func (a AuthBrokerConfig) MarshalJSON() ([]byte, error)
MarshalJSON emits the stored document; an empty carrier is `{}`.
func (*AuthBrokerConfig) UnmarshalJSON ¶ added in v0.68.0
func (a *AuthBrokerConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON stores the document in canonical form (every key and value kept; key order and whitespace are not part of the contract).
type ConcurrencyDefaults ¶ added in v0.54.0
type ConcurrencyDefaults struct {
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty" mapstructure:"max_concurrent_requests"`
QueueSize *int `json:"queue_size,omitempty" mapstructure:"queue_size"`
QueueTimeout *Duration `json:"queue_timeout,omitempty" mapstructure:"queue_timeout" swaggertype:"string"`
}
ConcurrencyDefaults is the per-server DEFAULT SET — scope (b) of FR-020. Every setting is tri-state (nil = not configured); the same three settings exist verbatim on ServerConfig as per-server overrides and at the top level as the global aggregate limiter.
type Config ¶
type Config struct {
Listen string `json:"listen" mapstructure:"listen"`
TrayEndpoint string `json:"tray_endpoint,omitempty" mapstructure:"tray-endpoint"` // Tray endpoint override (unix:// or npipe://)
EnableSocket bool `json:"enable_socket" mapstructure:"enable-socket"` // Enable Unix socket/named pipe for local IPC (default: true)
DataDir string `json:"data_dir" mapstructure:"data-dir"`
// Deprecated: EnableTray is unused and has no runtime effect. Kept for backward compatibility.
EnableTray bool `json:"enable_tray,omitempty" mapstructure:"tray"`
DebugSearch bool `json:"debug_search" mapstructure:"debug-search"`
Servers []*ServerConfig `json:"mcpServers" mapstructure:"servers"`
// Profiles are optional named, server-scoped views exposed at /mcp/p/<name>
// (Spec 057). Absent/empty is fully supported — /mcp is unchanged and configs
// without this key serialize byte-identically (SC-004).
Profiles []ProfileConfig `json:"profiles,omitempty" mapstructure:"profiles"`
// Deprecated: TopK is superseded by ToolsLimit and has no runtime effect. Kept for backward compatibility.
TopK int `json:"top_k,omitempty" mapstructure:"top-k"`
ToolsLimit int `json:"tools_limit" mapstructure:"tools-limit"`
ToolResponseLimit int `json:"tool_response_limit" mapstructure:"tool-response-limit"`
CallToolTimeout Duration `json:"call_tool_timeout" mapstructure:"call-tool-timeout" swaggertype:"string"`
// MaxResultSizeChars is advertised on every tool as
// `_meta.anthropic/maxResultSizeChars`; it raises Claude Code's
// inline-response ceiling from 50k to up to 500k chars. Omit the key for
// the 500000 default; set it to 0 to disable the annotation.
MaxResultSizeChars *int `json:"max_result_size_chars,omitempty" mapstructure:"max-result-size-chars"`
// Concurrency limits (spec 093, GH #955). Scope (a) of FR-020: the GLOBAL
// AGGREGATE limiter — one proxy-wide cap on concurrently running upstream
// tool calls, with its own bounded wait queue. Tri-state pointers: absent =
// the limiter does not exist (default, zero behavior change); an explicit 0
// max also disables it; positive = that cap. This scope is NEVER a
// per-server inheritance source — per-server values come from
// ServerConcurrencyDefaults / the per-server overrides — but a server's
// effective concurrency is bounded by BOTH its own limiter and this one.
// Resolved by ResolveGlobalConcurrency; hot-reloadable; overridable via
// MCPPROXY_MAX_CONCURRENT_REQUESTS / _QUEUE_SIZE / _QUEUE_TIMEOUT (FR-022).
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty" mapstructure:"max-concurrent-requests"`
QueueSize *int `json:"queue_size,omitempty" mapstructure:"queue-size"`
QueueTimeout *Duration `json:"queue_timeout,omitempty" mapstructure:"queue-timeout" swaggertype:"string"`
// ServerConcurrencyDefaults is scope (b) of FR-020: the blanket per-server
// default set inherited by every server that does not override a setting.
// Absent (the default) = no per-server limiting unless a server configures
// it explicitly. File/API-configured only — no env scheme (FR-022).
ServerConcurrencyDefaults *ConcurrencyDefaults `json:"server_concurrency_defaults,omitempty" mapstructure:"server-concurrency-defaults"`
// ToonOutput selects the TOON encoding mode for call_tool_* result text
// blocks (spec 084): "off" (default — responses byte-identical to
// pre-feature behavior), "adaptive" (encode only tabular-uniform payloads
// that beat compact JSON by ToonMinSavingsPct), or "always"
// (benchmark/debug only — encodes every JSON-parseable block and can
// INCREASE token cost). Per-server override: ServerConfig.ToonOutput.
// Resolved by ResolveToonOutput; hot-reloadable.
ToonOutput string `json:"toon_output,omitempty" mapstructure:"toon-output"`
// ToonMinSavingsPct is the minimum byte-savings percentage (validated
// 1-90; 0/unset → 15) the complete TOON emission (marker + hint + body)
// must achieve over the exact passthrough emission for adaptive mode to
// encode a block. Byte savings approximate token savings for the tabular
// payload class; the spec-083 profiler reports true token deltas.
// Global-only (no per-server override, FR-001).
ToonMinSavingsPct int `json:"toon_min_savings_pct,omitempty" mapstructure:"toon-min-savings-pct"`
// Discovery & health-check cadence (spec 074, #608). Both are *Duration
// tri-state pointers: nil = inherit the built-in default; a pointer to 0s =
// the loop is disabled; a positive value = that interval. Defaults live only
// in the resolvers (ResolveHealthCheckInterval / ResolveToolDiscoveryInterval)
// so an unset key behaves exactly as before this feature (SC-005). Validated
// in Validate(): health-check ∈ {0} ∪ [5s,1h]; tool-discovery ∈ {0} ∪ [30s,24h].
HealthCheckInterval *Duration `json:"health_check_interval,omitempty" mapstructure:"health-check-interval" swaggertype:"string"`
ToolDiscoveryInterval *Duration `json:"tool_discovery_interval,omitempty" mapstructure:"tool-discovery-interval" swaggertype:"string"`
// InitTimeout is the global default deadline for an upstream's MCP
// `initialize` handshake (MCP-3322 / GH #760). *Duration tri-state: nil =
// inherit the built-in 30s default; a positive value = that deadline. A
// per-server InitTimeout overrides this. Resolved by ResolveInitTimeout;
// validated to {0} ∪ [1s, 30m] in Validate(). Servers doing legitimate
// first-run warmup (cache/index build) before answering `initialize` can
// raise this so they are not killed mid-startup.
InitTimeout *Duration `json:"init_timeout,omitempty" mapstructure:"init-timeout" swaggertype:"string"`
// HTTPReadTimeout caps how long reading a whole request (headers + body)
// may take. Unset = 120s; "0s" disables it. Requires a restart.
HTTPReadTimeout *Duration `json:"http_read_timeout,omitempty" mapstructure:"http-read-timeout" swaggertype:"string"`
// HTTPWriteTimeout caps how long producing a whole response may take on
// non-streaming endpoints (REST, Web UI, health). Unset = 120s; "0s"
// disables it globally. MCP and SSE /events routes are exempt by design.
HTTPWriteTimeout *Duration `json:"http_write_timeout,omitempty" mapstructure:"http-write-timeout" swaggertype:"string"`
// HTTPIdleTimeout caps how long an idle keep-alive connection is kept open.
// Unset = 180s. "0s" removes the dedicated idle deadline, but net/http then
// falls back to ReadTimeout — idle is fully unbounded only when
// http_read_timeout is also "0s". Requires a restart.
HTTPIdleTimeout *Duration `json:"http_idle_timeout,omitempty" mapstructure:"http-idle-timeout" swaggertype:"string"`
// Environment configuration for secure variable filtering
Environment *secureenv.EnvConfig `json:"environment,omitempty" mapstructure:"environment"`
// ForwardProxyEnv opts in to forwarding the ambient HTTP(S)/ALL/NO/FTP proxy
// environment variables to spawned stdio upstream servers (MCP-2769). OFF by
// default: proxy URLs commonly embed credentials (http://user:pass@proxy), so
// forwarding them to every upstream is a credential-leak risk. When enabled,
// values are forwarded with their userinfo (credentials) redacted.
ForwardProxyEnv bool `json:"forward_proxy_env,omitempty" mapstructure:"forward-proxy-env"`
// Logging configuration
Logging *LogConfig `json:"logging,omitempty" mapstructure:"logging"`
// Security settings
APIKey string `json:"api_key,omitempty" mapstructure:"api-key"` // API key for REST API authentication
RequireMCPAuth bool `json:"require_mcp_auth" mapstructure:"require-mcp-auth"` // Require authentication on /mcp endpoint (default: false)
// TrustedHosts lists non-loopback Host header values accepted on loopback
// listeners (GH #898). DNS-rebinding protection rejects requests whose Host
// header is not a loopback address when mcpproxy listens on loopback; a
// reverse proxy (nginx → 127.0.0.1) forwarding the public domain in Host
// trips it. Entries are hostnames, case-insensitive; an entry without a
// port matches any port, with a port it must match exactly; a leading dot
// (".example.com") is a subdomain wildcard. The single entry "*" disables
// Host and Origin validation entirely. The same list also validates the
// Origin header when present (MCP spec DNS-rebinding defense). Empty
// (default) keeps full protection. Env override: MCPPROXY_TRUSTED_HOSTS
// (comma-separated).
TrustedHosts []string `json:"trusted_hosts,omitempty" mapstructure:"trusted-hosts"`
// TrustedProxies lists the CIDRs or IP addresses whose X-Forwarded-For /
// X-Real-IP / X-Forwarded-Proto / X-Forwarded-Host headers are believed
// (Spec 107 FR-027). Empty (default) trusts nobody. Edition-neutral, live
// (hot-reloadable). Env override: MCPPROXY_TRUSTED_PROXIES (comma-separated).
// The one reader is ForwardedHeaders; validation is validateTrustedProxies.
TrustedProxies []string `json:"trusted_proxies,omitempty" mapstructure:"trusted-proxies"`
// AuditLog configures the Spec 107 edition-neutral audit sink
// (internal/audit). nil means "use the per-edition/per-transport
// default" (EffectiveAuditLog); restart-pinned (bound at sink
// construction). See audit_log.go.
AuditLog *AuditLogConfig `json:"audit_log,omitempty" mapstructure:"audit-log"`
ReadOnlyMode bool `json:"read_only_mode" mapstructure:"read-only-mode"`
DisableManagement bool `json:"disable_management" mapstructure:"disable-management"`
AllowServerAdd bool `json:"allow_server_add" mapstructure:"allow-server-add"`
AllowServerRemove bool `json:"allow_server_remove" mapstructure:"allow-server-remove"`
// Prompts settings
EnablePrompts bool `json:"enable_prompts" mapstructure:"enable-prompts"`
// AggregateUpstreamPrompts, when true, aggregates every connected upstream
// server's advertised MCP prompts into mcpproxy's own prompts/list
// (exposed as "<server>__<prompt>"). OFF by default: users are safe by
// default and opt in deliberately. EnablePrompts still governs the built-in
// prompts + the prompts capability; this flag gates ONLY the upstream
// aggregation performed by RefreshPrompts. Hot-reloadable.
AggregateUpstreamPrompts bool `json:"aggregate_upstream_prompts" mapstructure:"aggregate-upstream-prompts"`
// Repository detection settings
CheckServerRepo bool `json:"check_server_repo" mapstructure:"check-server-repo"`
// Docker isolation settings
DockerIsolation *DockerIsolationConfig `json:"docker_isolation,omitempty" mapstructure:"docker-isolation"`
// Docker recovery settings
DockerRecovery *DockerRecoveryConfig `json:"docker_recovery,omitempty" mapstructure:"docker-recovery"`
// Registries configuration for MCP server discovery
Registries []RegistryEntry `json:"registries,omitempty" mapstructure:"registries"`
// RegistriesLocked is an enterprise stub knob (MCP-866): when true, runtime
// additions of custom registries (e.g. `registry add-source`, the REST/MCP
// add-source surface) are rejected so an administrator can pin the discovery
// sources. Built-in defaults are unaffected. Documented but otherwise inert
// beyond the add-source rejection.
RegistriesLocked bool `json:"registries_locked,omitempty" mapstructure:"registries-locked"`
// AllowPrivateRegistryFetch opts out of the registry SSRF guard (MCP-1076,
// CWE-918). By default (false) registry fetches refuse any host that is — or
// resolves to — a non-routable address (loopback, RFC1918/CGNAT private,
// link-local incl. the 169.254.169.254 cloud-metadata endpoint), so a
// malicious or typo'd registry source cannot turn the daemon into a
// request-forgery vector against internal services.
//
// This opt-out is BLANKET (all-or-nothing): setting it true disables the
// guard for EVERY non-routable range at once — loopback, RFC1918/CGNAT
// private, link-local AND the 169.254.169.254 cloud-metadata endpoint. There
// is no way to allow only loopback; enabling it for a localhost dev registry
// also re-opens the cloud-metadata SSRF vector. Set true ONLY when you
// intentionally run a trusted registry mirror on an internal/private address,
// ideally on a host with no cloud-metadata exposure. The change takes effect
// only on daemon (re)start or config reload.
AllowPrivateRegistryFetch bool `json:"allow_private_registry_fetch,omitempty" mapstructure:"allow-private-registry-fetch"`
// Deprecated: Features flags are unused and have no runtime effect. Kept for backward compatibility.
Features *FeatureFlags `json:"features,omitempty" mapstructure:"features"`
// TLS configuration
TLS *TLSConfig `json:"tls,omitempty" mapstructure:"tls"`
// Tokenizer configuration for token counting
Tokenizer *TokenizerConfig `json:"tokenizer,omitempty" mapstructure:"tokenizer"`
// Code execution settings
EnableCodeExecution bool `json:"enable_code_execution" mapstructure:"enable-code-execution"` // Enable JavaScript code execution tool (default: true since v0.66.0)
CodeExecutionTimeoutMs int `json:"code_execution_timeout_ms,omitempty" mapstructure:"code-execution-timeout-ms"` // Timeout in milliseconds (default: 120000, max: 600000)
CodeExecutionMaxToolCalls int `json:"code_execution_max_tool_calls,omitempty" mapstructure:"code-execution-max-tool-calls"` // Max tool calls per execution (0 = unlimited, default: 0)
CodeExecutionPoolSize int `json:"code_execution_pool_size,omitempty" mapstructure:"code-execution-pool-size"` // JavaScript runtime pool size (default: 10)
CodeExecutionMaxParallel int `json:"code_execution_max_parallel,omitempty" mapstructure:"code-execution-max-parallel"` // Default concurrency for call_tools() batches (1-32, default: 8)
// ToolResponseSessionRiskWarning controls whether the prose `warning` field
// is included in the `session_risk` object returned by `retrieve_tools`.
// The structured fields (level, lethal_trifecta, has_open_world_tools, etc.)
// are always included. Default: false (quiet for LLM clients) — see issue #406.
// Most tools lack annotations, so the MCP-spec defaults treat them as fully
// permissive across all three risk axes, which makes the prose warning fire
// on almost every call and wastes tokens.
ToolResponseSessionRiskWarning bool `json:"tool_response_session_risk_warning,omitempty" mapstructure:"tool-response-session-risk-warning"`
// Health status settings
OAuthExpiryWarningHours float64 `json:"oauth_expiry_warning_hours,omitempty" mapstructure:"oauth-expiry-warning-hours"` // Hours before token expiry to show degraded status (default: 1.0)
// Activity logging settings (RFC-003)
ActivityRetentionDays int `json:"activity_retention_days,omitempty" mapstructure:"activity-retention-days"` // Max age before pruning (default: 90)
ActivityMaxRecords int `json:"activity_max_records,omitempty" mapstructure:"activity-max-records"` // Max records before pruning (default: 100000)
// ActivityMaxSizeMB caps the total activity-log size in MB before the
// oldest records are pruned. Omit the key for the 256MB default; set it to
// 0 to disable the size cap.
ActivityMaxSizeMB *int `json:"activity_max_size_mb,omitempty" mapstructure:"activity-max-size-mb"`
ActivityMaxResponseSize int `json:"activity_max_response_size,omitempty" mapstructure:"activity-max-response-size"` // Response truncation limit in bytes (default: 65536)
ActivityCleanupIntervalMin int `json:"activity_cleanup_interval_min,omitempty" mapstructure:"activity-cleanup-interval-min"` // Background cleanup interval in minutes (default: 60)
// Bounds for the per-server tool-call history behind GET /api/v1/tool-calls
// (#1176). It is a recent-debugging window, not an audit log — the activity
// log is the durable record — and it kept every upstream response whole,
// per server, forever. A non-positive value means "use the default", not
// "disable": this store must never be unbounded again, so there is
// deliberately no off switch.
ToolCallMaxResponseSize int `json:"tool_call_max_response_size,omitempty" mapstructure:"tool-call-max-response-size"` // Cap on a stored response, in bytes (default: 65536)
ToolCallMaxRecordsPerServer int `json:"tool_call_max_records_per_server,omitempty" mapstructure:"tool-call-max-records-per-server"` // Calls retained per server (default: 1000)
// Intent declaration settings (Spec 018)
IntentDeclaration *IntentDeclarationConfig `json:"intent_declaration,omitempty" mapstructure:"intent-declaration"`
// Sensitive data detection settings (Spec 026)
SensitiveDataDetection *SensitiveDataDetectionConfig `json:"sensitive_data_detection,omitempty" mapstructure:"sensitive-data-detection"`
// Output-schema validation settings (Spec 056)
OutputValidation *OutputValidationConfig `json:"output_validation,omitempty" mapstructure:"output-validation"`
// Output sanitisation settings (Spec 054 Track B)
OutputSanitisation *OutputSanitisationConfig `json:"output_sanitisation,omitempty" mapstructure:"output-sanitisation"`
// Telemetry settings (Spec 036)
Telemetry *TelemetryConfig `json:"telemetry,omitempty" mapstructure:"telemetry"`
// Observability settings (Spec 069): usage aggregate cache/persistence cadence.
Observability *ObservabilityConfig `json:"observability,omitempty" mapstructure:"observability"`
// Update-check settings (Spec 079 FR-012): config-file control of the
// background upgrade-awareness checker (internal/updatecheck). nil =
// enabled on the stable channel (existing default behavior). The existing
// environment switches keep working and WIN over these keys (FR-014):
// MCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even when
// enabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-selects
// the rc channel even when channel=stable.
UpdateCheck *UpdateCheckConfig `json:"update_check,omitempty" mapstructure:"update-check"`
// Routing mode (Spec 031): how MCP tools are exposed to clients
// Valid values: "retrieve_tools" (default), "direct", "code_execution"
RoutingMode string `json:"routing_mode,omitempty" mapstructure:"routing-mode"`
// Tool response mode (Spec 085): how retrieve_tools serializes results.
// Valid values: "" (= full), "full" (default: today's schema-bearing
// entries), "compact" (signature + first-sentence entries). Orthogonal to
// routing_mode — routing_mode selects the tool SURFACE, this selects the
// SERIALIZATION within the retrieve_tools surface. Serialization-only: it
// never affects the query, ranking, or result set. Hot-reloadable.
ToolResponseMode string `json:"tool_response_mode,omitempty" mapstructure:"tool-response-mode"`
// DirectToolResponseMode selects the serialization of the DIRECT
// enumeration surface (Spec 102). Valid values: "" (= full), "full"
// (default: today's schema-bearing entries), "deferred" (description +
// compact signature, with a minimal permissive input schema; upstream
// inputSchema and outputSchema are stripped and recovered on demand via
// describe_tool).
//
// Deliberately NOT an extension of tool_response_mode: reusing that axis
// would silently change /mcp/all output for every deployment already
// running compact, which FR-015 forbids. Serialization-only — it never
// changes WHICH tools are listed, only how (FR-008). Hot-reloadable.
DirectToolResponseMode string `json:"direct_tool_response_mode,omitempty" mapstructure:"direct-tool-response-mode"`
// Instructions text returned in the MCP initialize response to guide AI agents.
// When empty, a built-in default is used that explains retrieve_tools workflow.
Instructions string `json:"instructions,omitempty" mapstructure:"instructions"`
// QuarantineEnabled controls whether quarantine is active. It gates two
// things together:
// 1. Server-level auto-quarantine for newly added servers (issue #370).
// When true, servers added via the upstream_servers MCP tool or the
// REST API default to quarantined=true; when false, they default to
// quarantined=false. Explicit per-request values always win.
// 2. Tool-level quarantine (Spec 032): per-tool SHA-256 approval of
// tool descriptions/schemas.
// When nil (default), quarantine is enabled (secure by default). Set to
// explicit false to opt out of both. Per-server SkipQuarantine still
// applies for the tool-level check on individual servers.
QuarantineEnabled *bool `json:"quarantine_enabled,omitempty" mapstructure:"quarantine-enabled"`
// Security scanner settings (Spec 039)
Security *SecurityConfig `json:"security,omitempty" mapstructure:"security"`
// RevealSecretHeaders, when true, disables the redaction of the
// secret-bearing server fields — sensitive header values (Authorization,
// X-API-Key, Cookie, …), env-var secrets, and URL query credentials — in
// responses from the `upstream_servers` MCP tool, the `/api/v1/servers`
// REST API, and the SSE event stream. It also lets URL secrets echoed
// into last_error / health.detail through unscrubbed.
//
// Default false — sensitive values are surfaced masked as
// `••••<last2> (<N> chars)` (error strings use `***REDACTED***`) so an
// MCP agent cannot read Bearer tokens / API keys / URL secrets out of
// another upstream's config (PR #425, issue #872). ${env:…}/${keyring:…}
// references are labels, not secrets, and pass through unchanged.
//
// The Web UI / macOS tray edit forms work without seeing the real
// values: PATCH /api/v1/servers/{id} deep-merges (omitted keys are
// preserved, see `headers_remove` / `env_remove` for explicit
// deletes), so clients compute a diff and only send the keys that
// actually changed. Redacted-but-unchanged values never round-trip
// — the backend keeps the real string. Set this to true if a
// downstream tool genuinely needs raw values in the response.
RevealSecretHeaders bool `json:"reveal_secret_headers,omitempty" mapstructure:"reveal-secret-headers"`
// Server edition multi-user configuration (only meaningful with -tags server).
// Renamed from the legacy "teams" key (MCP-1086); an existing config that
// still uses "teams" is normalized onto this field on load (see loader.go).
ServerEdition *ServerEditionConfig `json:"server_edition,omitempty" mapstructure:"server_edition" swaggerignore:"true"`
// contains filtered or unexported fields
}
Config represents the main configuration structure
func DecodeConfigFile ¶ added in v0.68.0
DecodeConfigFile decodes the config file over the defaults and applies only the read-time normalizations (legacy key migration, created stamps). Unlike LoadFromFile it applies no env overrides, runs no validation, creates no directories and touches no process-global state, so it is safe as the base of a read-modify-write save while the server is running. (Not "ReadFile": the oauth door scan keys config-returning functions by bare name and would taint every os.ReadFile call in the tree.)
func LoadFromFile ¶
LoadFromFile loads configuration from a specific file
func LoadOrCreateConfig ¶
LoadOrCreateConfig loads configuration from the data directory or creates a new one
func LoadWithPath ¶ added in v0.68.0
LoadWithPath is Load that also reports which config file it read (or created), so callers that persist later write to the file they loaded rather than to a path re-derived from data_dir.
func PersistableConfig ¶ added in v0.68.0
PersistableConfig returns the config that should go to disk at path for the given effective config: a shallow copy in which every field that still carries its process-only override is replaced by the value the file at path holds now (or held when the override was applied, if the file cannot be read). Fields that were edited since keep the edit. With no overrides recorded the effective config is returned as is.
The copy shares Servers, Registries and every nested block it does not touch with effective; the ones it restores are copied first. Callers must not mutate the shared structures.
A save that carries an API edit uses PersistableConfigWithEdits instead, so the edited fields are persisted whatever they equal.
func PersistableConfigWithEdits ¶ added in v0.68.0
PersistableConfigWithEdits is PersistableConfig for the save that persists an API edit: mergeBase is the config the edit was merged onto (the desired config for PUT/PATCH /api/v1/config), and every overridden field that MOVED between mergeBase and effective is the caller's edit — persisted as is, whatever it moved to. Moving listen from the file's address to the flag's own address is the operator making that address permanent (base != next == override is distinguishable, unlike a plain round trip); moving it back to the file's value is an edit too. A field that merely round-tripped a value mergeBase already held — the file's listen after a disk reload, say — keeps restoring the file value, whatever it equals.
The override records are never removed by an edit. The one save that carries the edit ignores them; every other save — a concurrent telemetry write of the still-live config, the next server enable — keeps restoring the CURRENT file value, which after the edit's save is the edit itself. That is what makes an edit of api_key under MCPPROXY_API_KEY safe: there is no window in which a stale config carrying the env secret is unprotected.
Known limitation: an edit that sets an overridden field to exactly the override's value while mergeBase already holds that value is indistinguishable from a round trip and is not persisted — unreachable from the Web UI, which already shows the override as the current value.
func (*Config) DefaultQuarantineForNewServer ¶ added in v0.24.0
DefaultQuarantineForNewServer returns the default value for the Quarantined field when a new server is added via an API that does not explicitly specify it (MCP upstream_servers tool, REST /api/v1/servers). Secure by default: true unless the operator has disabled quarantine globally via quarantine_enabled=false.
func (*Config) EffectiveActivityMaxRecords ¶ added in v0.65.0
func (*Config) EffectiveActivityMaxSizeMB ¶ added in v0.65.0
EffectiveActivityMaxSizeMB resolves the total activity-log size cap in MB.
nil (key absent) = the built-in default. An explicit 0 = the size cap is disabled, and stays disabled.
func (*Config) EffectiveActivityRetentionDays ¶ added in v0.65.0
EffectiveActivityRetentionDays and EffectiveActivityMaxRecords resolve the two remaining retention counts.
These stay plain ints rather than becoming tri-state pointers because 0 has no documented meaning for them — but 0 and absent used to DIVERGE, which is the #1175 defect in a quieter form: an omitted key took DefaultConfig's 90 days / 100000 records, while an explicit 0 was ignored by ActivityService.SetRetentionConfig and silently fell through to that service's own much smaller constants (7 days / 10000 records). An operator who wrote 0 got a tenth of the retention the documentation promises, and saving the config flipped them back. Resolving here makes the two agree.
func (*Config) EffectiveMaxResultSizeChars ¶ added in v0.65.0
EffectiveMaxResultSizeChars resolves the `_meta.anthropic/maxResultSizeChars` ceiling advertised on every tool.
nil (key absent) = the built-in default. An explicit 0 = the operator disabled the annotation, and stays 0.
func (*Config) EnsureAPIKey ¶
func (c *Config) EnsureAPIKey() (apiKey string, wasGenerated bool, source APIKeySource)
EnsureAPIKey ensures the API key is set, generating one if needed Returns the API key, whether it was auto-generated, and the source SECURITY: Empty API keys are never allowed - always auto-generates if empty or missing
func (*Config) GetAnonymousID ¶ added in v0.22.0
GetAnonymousID returns the anonymous telemetry ID if set.
func (*Config) GetTelemetryEndpoint ¶ added in v0.22.0
GetTelemetryEndpoint returns the telemetry endpoint URL.
func (*Config) IsQuarantineEnabled ¶ added in v0.21.0
IsQuarantineEnabled returns whether quarantine (both server-level auto-quarantine and tool-level approval) is enabled. Defaults to true (secure by default) when not explicitly set.
func (*Config) IsTelemetryEnabled ¶ added in v0.22.0
IsTelemetryEnabled returns whether telemetry is enabled. Respects MCPPROXY_TELEMETRY=false env var override and defaults to true.
func (*Config) LoadDiagnostics ¶ added in v0.68.0
func (c *Config) LoadDiagnostics() []LoadDiagnostic
LoadDiagnostics returns the diagnostics recorded by the load that produced this Config, in file order. A Config built in code, or one decoded with a bare json.Unmarshal, has none.
func (*Config) MarshalJSON ¶
MarshalJSON implements json.Marshaler interface
func (*Config) ProfileWarnings ¶ added in v0.39.0
ProfileWarnings returns the non-fatal profile diagnostics captured by the most recent Validate() call (unknown-server and empty-server warnings). The boot path logs these via its logger; an empty result means no warnings.
func (*Config) QuarantineDefaultForServer ¶ added in v0.53.0
func (c *Config) QuarantineDefaultForServer(sc *ServerConfig) bool
QuarantineDefaultForServer resolves the add-time Quarantined default for a specific new server from its trust_mode (spec 086 stage 3, FR-011). Secure by default: a server is admitted UNQUARANTINED only under trust_mode auto; scan and manual are quarantined on add (scan is later auto-unquarantined once its baseline scan settles green — see the EventTypeSecurityScanSettled handler).
The global quarantine_enabled=false escape hatch (#370) still wins: when quarantine is disabled globally, every new server is admitted unquarantined regardless of its trust_mode, preserving DefaultQuarantineForNewServer's semantics. A nil server config fails closed to quarantine.
CN-002: the mode is read from the server's config/registry-derived trust_mode, never from a request-driven admission override.
func (*Config) ResolveGlobalConcurrency ¶ added in v0.54.0
func (c *Config) ResolveGlobalConcurrency() ResolvedConcurrency
ResolveGlobalConcurrency resolves the global aggregate limiter — scope (a) of FR-020. Absent or 0 max = no global limiter.
func (*Config) ResolveHTTPIdleTimeout ¶ added in v0.54.1
ResolveHTTPIdleTimeout resolves http.Server.IdleTimeout: unset → 180s, 0 → no idle deadline of its own, positive → that value (GH #965). NOTE: net/http falls back to ReadTimeout when IdleTimeout is zero, so an explicit "0s" here fully disables the idle deadline only when http_read_timeout is also 0 — otherwise idle connections are reaped after the read timeout.
func (*Config) ResolveHTTPReadTimeout ¶ added in v0.54.1
ResolveHTTPReadTimeout resolves http.Server.ReadTimeout: unset → 120s, 0 → disabled, positive → that value (GH #965).
func (*Config) ResolveHTTPWriteTimeout ¶ added in v0.54.1
ResolveHTTPWriteTimeout resolves http.Server.WriteTimeout: unset → 120s, 0 → disabled, positive → that value (GH #965). Streaming routes (MCP + SSE /events) clear the resulting deadline per-request, so this value only governs non-streaming endpoints — see defaultHTTPWriteTimeout.
func (*Config) ResolveHealthCheckInterval ¶ added in v0.38.0
func (c *Config) ResolveHealthCheckInterval(sc *ServerConfig) time.Duration
ResolveHealthCheckInterval resolves the effective health-check probe interval for a server: per-server override → global → 30s default. A resolved value <= 0 disables the periodic probe for that server (spec 074, FR-006).
func (*Config) ResolveInitTimeout ¶ added in v0.46.0
func (c *Config) ResolveInitTimeout(sc *ServerConfig) time.Duration
ResolveInitTimeout resolves the effective MCP `initialize` handshake deadline for a server: per-server override → global → 30s default (MCP-3322 / GH #760). Unlike the discovery intervals, a resolved value <= 0 maps to the default rather than "disabled" — a zero/negative connect deadline would let a stuck upstream hang the connect path forever, so we always keep a real ceiling.
func (*Config) ResolveServerConcurrency ¶ added in v0.54.0
func (c *Config) ResolveServerConcurrency(sc *ServerConfig) ResolvedConcurrency
ResolveServerConcurrency resolves a server's per-server limiter — scopes (b) and (c) of FR-020: per-server override → per-server default set → unset. The global aggregate limiter is never an inheritance source here; it applies on top of the resolved value (effective concurrency = min of the two).
func (*Config) ResolveToolDiscoveryInterval ¶ added in v0.38.0
func (c *Config) ResolveToolDiscoveryInterval(sc *ServerConfig) time.Duration
ResolveToolDiscoveryInterval resolves the effective tool-discovery sweep interval: per-server override → global → 5m default. A resolved value <= 0 disables the periodic sweep (connect-time + reactive list_changed discovery still run). The periodic index rebuild is global; pass nil for the sweep.
func (*Config) ResolveToonOutput ¶ added in v0.51.0
func (c *Config) ResolveToonOutput(sc *ServerConfig) string
ResolveToonOutput resolves the effective toon_output mode for a server (spec 084, FR-001): per-server non-empty value > global non-empty value > "off". It deliberately returns a raw string, NOT a toonenc.Mode — internal/config is imported almost everywhere and must not depend on internal/toonenc; callers parse the string via toonenc.ParseMode at the server/bench boundary.
func (*Config) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler interface
func (*Config) ValidateDetailed ¶
func (c *Config) ValidateDetailed() []ValidationError
ValidateDetailed performs detailed validation and returns all errors.
It is the shared gate for every *write* surface: the REST config API (POST /api/v1/config/validate, POST /api/v1/config/apply, PATCH /api/v1/config all funnel through Runtime.ValidateConfig / Runtime.ApplyConfig) and the MCP `upstream_servers` tool. Anything appended here is therefore rejected before it is persisted.
The boot path is deliberately NOT this function — see Validate(), which runs validateDetailedCore() so that a pre-existing bad value on disk cannot brick a load that has nothing to do with the offending server.
type ConfigDiff ¶
type ConfigDiff struct {
// Modified fields with before/after values
Modified map[string]FieldChange `json:"modified,omitempty"`
// Fields that were added (didn't exist in base)
Added []string `json:"added,omitempty"`
// Fields that were removed (via null in patch)
Removed []string `json:"removed,omitempty"`
// Timestamp of the merge operation
Timestamp time.Time `json:"timestamp"`
}
ConfigDiff captures changes made during a merge operation for auditing
func (*ConfigDiff) IsEmpty ¶
func (d *ConfigDiff) IsEmpty() bool
IsEmpty returns true if no changes were made
type CursorMCPConfig ¶
type CursorMCPConfig struct {
MCPServers map[string]CursorServerConfig `json:"mcpServers"`
}
CursorMCPConfig represents the structure for Cursor IDE MCP configuration
type CursorServerConfig ¶
type CursorServerConfig struct {
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
CursorServerConfig represents a single server configuration in Cursor format
type CustomPattern ¶ added in v0.17.0
type CustomPattern struct {
Name string `json:"name" mapstructure:"name"` // Unique identifier for this pattern
Regex string `json:"regex,omitempty" mapstructure:"regex"` // Regex pattern (mutually exclusive with Keywords)
Keywords []string `json:"keywords,omitempty" mapstructure:"keywords"` // Keywords to match (mutually exclusive with Regex)
Severity string `json:"severity" mapstructure:"severity"` // Risk level: critical, high, medium, low
Category string `json:"category,omitempty" mapstructure:"category"` // Category (defaults to "custom")
}
CustomPattern represents a user-defined detection pattern
type DeepScanConfig ¶ added in v0.47.0
type DeepScanConfig struct {
// Enabled is the master opt-in for the heavy layer (FR-006). Default false.
Enabled bool `json:"enabled" mapstructure:"enabled"`
// FetchPackageSource controls whether the scanner fetches the PUBLISHED
// source of package-runner servers (npx/uvx) — without executing it — when
// no local source is available. Absorbs the deprecated top-level
// scanner_fetch_package_source. Default (nil) is ENABLED within deep scan.
FetchPackageSource *bool `json:"fetch_package_source,omitempty" mapstructure:"fetch-package-source" swaggertype:"boolean"`
// DisableNoNewPrivileges, when true, omits the `--security-opt
// no-new-privileges` flag from scanner container runs (snap-docker/AppArmor
// escape hatch). Absorbs the deprecated top-level
// scanner_disable_no_new_privileges. Default false.
DisableNoNewPrivileges bool `json:"disable_no_new_privileges,omitempty" mapstructure:"disable-no-new-privileges"`
// Scanners optionally restricts which deep scanners may run under the
// umbrella (by scanner id). Empty ⇒ all enabled deep scanners are eligible.
Scanners []string `json:"scanners,omitempty" mapstructure:"scanners"`
}
DeepScanConfig configures the opt-in "deep scan" layer (Spec 077 US3): Docker-based scanner plugins plus published-package-source extraction. The whole layer is off by default; when disabled only the deterministic in-process baseline scanner runs and no Docker is invoked. A deep-scan failure is surfaced as an informational note and never degrades the baseline verdict.
type DeprecatedField ¶ added in v0.17.8
type DeprecatedField struct {
JSONKey string `json:"json_key"`
Message string `json:"message"`
Replacement string `json:"replacement,omitempty"`
}
DeprecatedField describes a deprecated configuration field.
func CheckDeprecatedFields ¶ added in v0.17.8
func CheckDeprecatedFields(configPath string) []DeprecatedField
CheckDeprecatedFields reads the raw JSON config file and returns which deprecated keys are present. It does not validate or parse the full config.
func CleanDeprecatedFields ¶ added in v0.24.3
func CleanDeprecatedFields(configPath string) ([]DeprecatedField, error)
CleanDeprecatedFields removes deprecated keys from the config file on disk. It creates a .bak backup before modifying the file. If no deprecated fields are found, the file is not touched and no backup is created. Returns the list of removed fields, or nil if nothing was changed.
type DockerIsolationConfig ¶
type DockerIsolationConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Global enable/disable for Docker isolation (legacy; superseded by Mode)
Mode IsolationMode `json:"mode,omitempty" mapstructure:"mode"` // Isolation mode: "docker" | "sandbox" | "none". Empty falls back to Enabled (MCP-34.2)
EnableCacheVolume bool `json:"enable_cache_volume" mapstructure:"enable_cache_volume"` // Mount shared cache volumes for faster restarts (default: true)
DefaultImages map[string]string `json:"default_images" mapstructure:"default_images"` // Map of runtime type to Docker image
Registry string `json:"registry,omitempty" mapstructure:"registry"` // Custom registry (defaults to docker.io)
NetworkMode string `json:"network_mode,omitempty" mapstructure:"network_mode"` // Docker network mode (default: bridge)
MemoryLimit string `json:"memory_limit,omitempty" mapstructure:"memory_limit"` // Memory limit for containers
CPULimit string `json:"cpu_limit,omitempty" mapstructure:"cpu_limit"` // CPU limit for containers
Timeout Duration `json:"timeout,omitempty" mapstructure:"timeout" swaggertype:"string"` // Container startup timeout
ExtraArgs []string `json:"extra_args,omitempty" mapstructure:"extra_args"` // Additional docker run arguments
LogDriver string `json:"log_driver,omitempty" mapstructure:"log_driver"` // Docker log driver (default: json-file)
LogMaxSize string `json:"log_max_size,omitempty" mapstructure:"log_max_size"` // Maximum size of log files (default: 100m)
LogMaxFiles string `json:"log_max_files,omitempty" mapstructure:"log_max_files"` // Maximum number of log files (default: 3)
}
DockerIsolationConfig represents global Docker isolation settings
func DefaultDockerIsolationConfig ¶
func DefaultDockerIsolationConfig() *DockerIsolationConfig
DefaultDockerIsolationConfig returns default Docker isolation configuration
func (*DockerIsolationConfig) ResolvedMode ¶ added in v0.46.0
func (dic *DockerIsolationConfig) ResolvedMode() IsolationMode
ResolvedMode returns the effective global isolation mode, applying back-compat mapping from the legacy Enabled bool (MCP-34.2):
- an explicit Mode always wins;
- otherwise enabled:true ⇒ docker, enabled:false ⇒ none;
- a nil config resolves to none.
type DockerRecoveryConfig ¶
type DockerRecoveryConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable Docker recovery monitoring (default: true)
CheckIntervals []Duration `json:"check_intervals,omitempty" mapstructure:"intervals" swaggerignore:"true"` // Custom health check intervals (exponential backoff)
MaxRetries int `json:"max_retries,omitempty" mapstructure:"max_retries"` // Maximum retry attempts (0 = unlimited)
NotifyOnStart bool `json:"notify_on_start" mapstructure:"notify_on_start"` // Show notification when recovery starts (default: true)
NotifyOnSuccess bool `json:"notify_on_success" mapstructure:"notify_on_success"` // Show notification on successful recovery (default: true)
NotifyOnFailure bool `json:"notify_on_failure" mapstructure:"notify_on_failure"` // Show notification on recovery failure (default: true)
NotifyOnRetry bool `json:"notify_on_retry" mapstructure:"notify_on_retry"` // Show notification on each retry (default: false)
PersistentState bool `json:"persistent_state" mapstructure:"persistent_state"` // Save recovery state across restarts (default: true)
}
DockerRecoveryConfig represents Docker recovery settings for the tray application
func (*DockerRecoveryConfig) GetCheckIntervals ¶
func (d *DockerRecoveryConfig) GetCheckIntervals() []time.Duration
GetCheckIntervals returns the configured check intervals as time.Duration slice, or defaults if not set
func (*DockerRecoveryConfig) GetMaxRetries ¶
func (d *DockerRecoveryConfig) GetMaxRetries() int
GetMaxRetries returns the maximum number of retries (0 = unlimited)
func (*DockerRecoveryConfig) IsEnabled ¶
func (d *DockerRecoveryConfig) IsEnabled() bool
IsEnabled returns whether Docker recovery is enabled (default: true)
func (*DockerRecoveryConfig) ShouldNotifyOnFailure ¶
func (d *DockerRecoveryConfig) ShouldNotifyOnFailure() bool
ShouldNotifyOnFailure returns whether to notify on recovery failure (default: true)
func (*DockerRecoveryConfig) ShouldNotifyOnRetry ¶
func (d *DockerRecoveryConfig) ShouldNotifyOnRetry() bool
ShouldNotifyOnRetry returns whether to notify on each retry (default: false)
func (*DockerRecoveryConfig) ShouldNotifyOnStart ¶
func (d *DockerRecoveryConfig) ShouldNotifyOnStart() bool
ShouldNotifyOnStart returns whether to notify when recovery starts (default: true)
func (*DockerRecoveryConfig) ShouldNotifyOnSuccess ¶
func (d *DockerRecoveryConfig) ShouldNotifyOnSuccess() bool
ShouldNotifyOnSuccess returns whether to notify on successful recovery (default: true)
func (*DockerRecoveryConfig) ShouldPersistState ¶
func (d *DockerRecoveryConfig) ShouldPersistState() bool
ShouldPersistState returns whether to persist recovery state across restarts (default: true)
type Duration ¶
Duration is a wrapper around time.Duration that can be marshaled to/from JSON. When serialized to JSON, it is represented as a string (e.g., "30s", "5m"). @swaggertype string
func (Duration) MarshalJSON ¶
MarshalJSON implements json.Marshaler interface
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler interface
type FeatureFlags ¶
type FeatureFlags struct {
// Runtime features
EnableRuntime bool `json:"enable_runtime" mapstructure:"enable_runtime"`
EnableEventBus bool `json:"enable_event_bus" mapstructure:"enable_event_bus"`
EnableSSE bool `json:"enable_sse" mapstructure:"enable_sse"`
// Observability features
EnableObservability bool `json:"enable_observability" mapstructure:"enable_observability"`
EnableHealthChecks bool `json:"enable_health_checks" mapstructure:"enable_health_checks"`
EnableMetrics bool `json:"enable_metrics" mapstructure:"enable_metrics"`
EnableTracing bool `json:"enable_tracing" mapstructure:"enable_tracing"`
// Security features
EnableOAuth bool `json:"enable_oauth" mapstructure:"enable_oauth"`
EnableQuarantine bool `json:"enable_quarantine" mapstructure:"enable_quarantine"`
EnableDockerIsolation bool `json:"enable_docker_isolation" mapstructure:"enable_docker_isolation"`
// Storage features
EnableSearch bool `json:"enable_search" mapstructure:"enable_search"`
EnableCaching bool `json:"enable_caching" mapstructure:"enable_caching"`
EnableAsyncStorage bool `json:"enable_async_storage" mapstructure:"enable_async_storage"`
// UI features
EnableWebUI bool `json:"enable_web_ui" mapstructure:"enable_web_ui"`
EnableTray bool `json:"enable_tray" mapstructure:"enable_tray"`
// Development features
EnableDebugLogging bool `json:"enable_debug_logging" mapstructure:"enable_debug_logging"`
EnableContractTests bool `json:"enable_contract_tests" mapstructure:"enable_contract_tests"`
}
FeatureFlags represents feature toggles for mcpproxy functionality
func DefaultFeatureFlags ¶
func DefaultFeatureFlags() FeatureFlags
DefaultFeatureFlags returns the default feature flag configuration
func (*FeatureFlags) IsFeatureEnabled ¶
func (ff *FeatureFlags) IsFeatureEnabled(feature string) bool
IsFeatureEnabled checks if a specific feature is enabled
func (*FeatureFlags) ValidateFeatureFlags ¶
func (ff *FeatureFlags) ValidateFeatureFlags() error
ValidateFeatureFlags validates feature flag dependencies
type Field ¶ added in v0.68.0
Field names a configuration value a process-only override can shadow. Set copies nested structs before writing (copy-on-write) so a PersistableConfig result never writes through a pointer it shares with the effective config.
type FieldChange ¶
type FieldChange struct {
// Path to the field (e.g., "isolation.image")
Path string `json:"path"`
// Value before merge
From interface{} `json:"from"`
// Value after merge
To interface{} `json:"to"`
}
FieldChange represents a single field modification
type ForwardedInfo ¶ added in v0.68.0
type ForwardedInfo struct {
// Scheme is "http" or "https": X-Forwarded-Proto from a trusted peer,
// otherwise the listener's own TLS state.
Scheme string
// Host is X-Forwarded-Host from a trusted peer, otherwise r.Host.
Host string
// ClientIP is the right-most X-Forwarded-For hop that is not itself a
// trusted proxy (then X-Real-IP) from a trusted peer, otherwise the
// RemoteAddr host. An unparsable RemoteAddr (a socket peer) is returned
// raw, as before.
ClientIP string
}
ForwardedInfo is what ForwardedHeaders resolves for one request.
func ForwardedHeaders ¶ added in v0.68.0
func ForwardedHeaders(r *http.Request, trusted []string) ForwardedInfo
ForwardedHeaders resolves the client-facing scheme, host and client IP of r, honouring the X-Forwarded-* / X-Real-IP headers only when the direct peer is a trusted proxy.
type ImmutableFieldError ¶
type ImmutableFieldError struct {
Field string
}
ImmutableFieldError provides details about which immutable field was modified
func (*ImmutableFieldError) Error ¶
func (e *ImmutableFieldError) Error() string
func (*ImmutableFieldError) Unwrap ¶
func (e *ImmutableFieldError) Unwrap() error
type IntentDeclarationConfig ¶
type IntentDeclarationConfig struct {
// StrictServerValidation controls whether server annotation mismatches
// cause rejection (true) or just warnings (false).
// Default: true (reject mismatches)
StrictServerValidation bool `json:"strict_server_validation" mapstructure:"strict-server-validation"`
}
IntentDeclarationConfig controls intent validation behavior for tool calls
func DefaultIntentDeclarationConfig ¶
func DefaultIntentDeclarationConfig() *IntentDeclarationConfig
DefaultIntentDeclarationConfig returns the default intent declaration configuration
func (*IntentDeclarationConfig) IsStrictServerValidation ¶
func (c *IntentDeclarationConfig) IsStrictServerValidation() bool
IsStrictServerValidation returns whether strict server validation is enabled
type IsolationConfig ¶
type IsolationConfig struct {
Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"` // Enable Docker isolation for this server (nil = inherit global; legacy, superseded by Mode)
Mode *IsolationMode `json:"mode,omitempty" mapstructure:"mode"` // Isolation mode: "docker" | "sandbox" | "none" (MCP-34.2). Unset per-server inherits the global mode; unset globally falls back to the legacy "enabled" flag (true ⇒ docker, false ⇒ none)
Image string `json:"image,omitempty" mapstructure:"image"` // Custom Docker image (overrides default)
NetworkMode string `json:"network_mode,omitempty" mapstructure:"network_mode"` // Custom network mode for this server
ExtraArgs []string `json:"extra_args,omitempty" mapstructure:"extra_args"` // Additional docker run arguments for this server
WorkingDir string `json:"working_dir,omitempty" mapstructure:"working_dir"` // Custom working directory in container
LogDriver string `json:"log_driver,omitempty" mapstructure:"log_driver"` // Docker log driver override for this server
LogMaxSize string `json:"log_max_size,omitempty" mapstructure:"log_max_size"` // Maximum size of log files override
LogMaxFiles string `json:"log_max_files,omitempty" mapstructure:"log_max_files"` // Maximum number of log files override
}
IsolationConfig represents per-server isolation settings
func CopyIsolationConfig ¶ added in v0.64.0
func CopyIsolationConfig(src *IsolationConfig) *IsolationConfig
CopyIsolationConfig returns a deep copy of an isolation override set, or nil for a nil input. Exported so the REST PATCH seam can start from the persisted overrides and apply only the fields the request actually carried, instead of dropping the ones it does not expose (GH #1142).
func MergeIsolationConfig ¶
func MergeIsolationConfig(base, patch *IsolationConfig, removeIfNil bool) *IsolationConfig
MergeIsolationConfig deep merges patch into base isolation config. Returns nil if both are nil, or if removeIfNil is true and patch is nil.
func (*IsolationConfig) HasEnabledOverride ¶ added in v0.64.0
func (ic *IsolationConfig) HasEnabledOverride() bool
HasEnabledOverride reports whether this server sets the legacy `enabled` bool at all. False means "inherit the global isolation setting" (GH #1142).
func (*IsolationConfig) HasModeOverride ¶ added in v0.64.0
func (ic *IsolationConfig) HasModeOverride() bool
HasModeOverride reports whether this server sets a per-server `isolation.mode` override. A nil pointer AND a pointer to the empty string both mean "unset" — the empty string is documented as the unset mode, and treating it as an override resolved servers to a mode the spawn path does not implement while reporting them isolated (GH #1142).
func (*IsolationConfig) IsExplicitlyDisabled ¶ added in v0.64.0
func (ic *IsolationConfig) IsExplicitlyDisabled() bool
IsExplicitlyDisabled reports whether this server opts OUT of isolation via the legacy `enabled` bool. A nil Enabled is "inherit", never an opt-out.
func (*IsolationConfig) IsExplicitlyEnabled ¶ added in v0.64.0
func (ic *IsolationConfig) IsExplicitlyEnabled() bool
IsExplicitlyEnabled reports whether this server opts IN to isolation via the legacy `enabled` bool. A nil Enabled is "inherit", never an opt-in.
This is NOT the answer to "is this server isolated" — that question has exactly one answer, upstream/core.IsolationManager.ResolveIsolation, which also accounts for the global mode and the structural gates.
type IsolationMode ¶ added in v0.46.0
type IsolationMode string
IsolationMode selects how an stdio MCP server's process is isolated (MCP-34.2).
- "docker" — run the server inside a Docker container (the original behavior).
- "sandbox" — run under a native OS sandbox (Landlock LSM + rlimits on Linux; see MCP-34). No daemon required.
- "none" — no isolation; the server process runs directly on the host.
The empty string means "unset": back-compat code falls back to the legacy boolean Enabled flag (enabled:true ⇒ docker, enabled:false ⇒ none).
const ( // IsolationModeDocker runs the server inside a Docker container. IsolationModeDocker IsolationMode = "docker" // IsolationModeSandbox runs the server under a native OS sandbox (Landlock/rlimits). IsolationModeSandbox IsolationMode = "sandbox" // IsolationModeNone disables isolation; the process runs directly. IsolationModeNone IsolationMode = "none" )
func ResolveScannerIsolationMode ¶ added in v0.68.0
func ResolveScannerIsolationMode(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) (IsolationMode, string)
ResolveScannerIsolationMode answers a DIFFERENT question from ResolveIsolation: not "do we containerise or confine THIS server's own child process", but "may the security scanner run its own short-lived Docker containers against this server's already-captured tool definitions" (GH #1303).
It shares ResolveIsolation's config precedence verbatim — the per-server `isolation.mode` override still wins outright, a disabled global still ignores per-server bool opt-ins, and an active global still honours a per-server `enabled:false` opt-out — so an operator's explicit security policy keeps deciding whether Docker scanners run. What it deliberately does NOT apply are the two STRUCTURAL gates, which exist purely to protect process spawning:
- not-stdio: an HTTP/SSE server has no child process for us to wrap, so there is nothing to containerise — but a scanner container does not wrap the server, it reads JSON captured over MCP;
- already-docker: wrapping a command that itself invokes docker would break its access to the Docker socket — but a scanner container is a separate, short-lived process that never touches the server's own container.
Routing those gates into the scanner question forced mode=none for every remote server, silently skipped every Docker-based scanner plugin, and made the skip message's own remedy ("set isolation.mode to docker for this server") a dead end because the gate ignored that override too.
It also skips the host-CAPABILITY gate (isolationDelivered), which refines ResolvedIsolation.Isolated and never Mode — matching what ResolveMode returns.
See also: ResolveIsolation (how is this server's process launched) and ServerDependsOnDocker (does STARTING this server need a Docker daemon). The three are distinct questions and must stay distinct (GH #1142, GH #1303).
The returned source is one of the IsolationSource* constants — never IsolationSourceNotStdio or IsolationSourceAlreadyDocker — and is for logging and error text only; it is not serialised onto the isolation-explain surfaces, which keep using ResolveIsolation. A nil serverConfig carries no override and therefore inherits the global mode.
func (IsolationMode) IsValid ¶ added in v0.46.0
func (m IsolationMode) IsValid() bool
IsValid reports whether the mode is a recognized value. The empty string ("unset") is treated as valid because the global config falls back to the legacy Enabled bool; callers that require an explicit mode should check for emptiness separately.
type LoadDiagnostic ¶ added in v0.68.0
type LoadDiagnostic struct {
// Key is the JSON path of the offending key (e.g.
// "server_edition.max_user_servers", "mcpServers[0].auth_broker.mode").
Key string
// Message is the exact operator-facing text from contracts/config-keys.md.
Message string
}
LoadDiagnostic is one non-fatal finding recorded while a configuration file was loaded: a key the server edition no longer supports and dropped, or a deprecated key it still decodes (Spec 107 FR-032/FR-033/FR-035).
The loader has no logger (loadConfigFile returns only an error and main.go builds the logger after the load), and once the typed decode has dropped the keys they cannot be reconstructed later, so the loader records them on the Config and LogLoadDiagnostics emits them once a logger exists. The personal build carries the server-edition blocks as opaque JSON and records nothing.
type LogConfig ¶
type LogConfig struct {
Level string `json:"level" mapstructure:"level"`
EnableFile bool `json:"enable_file" mapstructure:"enable-file"`
EnableConsole bool `json:"enable_console" mapstructure:"enable-console"`
Filename string `json:"filename" mapstructure:"filename"`
LogDir string `json:"log_dir,omitempty" mapstructure:"log-dir"` // Custom log directory
MaxSize int `json:"max_size" mapstructure:"max-size"` // MB
MaxBackups int `json:"max_backups" mapstructure:"max-backups"` // number of backup files
MaxAge int `json:"max_age" mapstructure:"max-age"` // days
Compress bool `json:"compress" mapstructure:"compress"`
JSONFormat bool `json:"json_format" mapstructure:"json-format"`
}
LogConfig represents logging configuration
type MergeOptions ¶
type MergeOptions struct {
// GenerateDiff controls whether to compute changes for audit trail
GenerateDiff bool
// NullRemovesField controls whether nil pointer in patch removes the field
// Default: true (RFC 7396 semantics)
NullRemovesField bool
// ImmutableFields lists fields that cannot be changed via merge
// Default: ["name", "created"]
ImmutableFields []string
// contains filtered or unexported fields
}
MergeOptions controls merge behavior
func DefaultMergeOptions ¶
func DefaultMergeOptions() MergeOptions
DefaultMergeOptions returns standard merge options
func (MergeOptions) GetRemoveMarkersForMap ¶
func (o MergeOptions) GetRemoveMarkersForMap(mapField string) []string
GetRemoveMarkersForMap returns all keys that should be removed from a map field
func (MergeOptions) ShouldRemove ¶
func (o MergeOptions) ShouldRemove(field string) bool
ShouldRemove checks if a field should be removed
func (MergeOptions) ShouldRemoveMapKey ¶
func (o MergeOptions) ShouldRemoveMapKey(mapField, key string) bool
ShouldRemoveMapKey checks if a specific key within a map field should be removed e.g., ShouldRemoveMapKey("env", "API_KEY") checks for "env.API_KEY" marker
func (MergeOptions) WithRemoveMarker ¶
func (o MergeOptions) WithRemoveMarker(field string) MergeOptions
WithRemoveMarker adds a field to the remove markers (used for explicit null handling)
type MetricsExporterConfig ¶ added in v0.45.0
type MetricsExporterConfig struct {
// Enabled exposes /metrics on the existing HTTP listener when true.
// The endpoint is admin-authenticated (SEC-07): scrapers must present the
// global API key, via X-API-Key or an Authorization: Bearer header.
Enabled bool `json:"enabled" mapstructure:"enabled"`
}
MetricsExporterConfig controls the Prometheus /metrics endpoint (MCP-32).
func DefaultMetricsExporterConfig ¶ added in v0.45.0
func DefaultMetricsExporterConfig() *MetricsExporterConfig
DefaultMetricsExporterConfig returns the default (disabled) metrics exporter.
type OAuthConfig ¶
type OAuthConfig struct {
ClientID string `json:"client_id,omitempty" mapstructure:"client_id"`
ClientSecret string `json:"client_secret,omitempty" mapstructure:"client_secret"`
RedirectURI string `json:"redirect_uri,omitempty" mapstructure:"redirect_uri"`
Scopes []string `json:"scopes,omitempty" mapstructure:"scopes"`
PKCEEnabled bool `json:"pkce_enabled,omitempty" mapstructure:"pkce_enabled"`
ExtraParams map[string]string `json:"extra_params,omitempty" mapstructure:"extra_params"` // Additional OAuth parameters (e.g., RFC 8707 resource)
}
OAuthConfig represents OAuth configuration for a server
func MergeOAuthConfig ¶
func MergeOAuthConfig(base, patch *OAuthConfig, removeIfNil bool) *OAuthConfig
MergeOAuthConfig deep merges patch into base OAuth config. Returns nil if both are nil, or if removeIfNil is true and patch is nil.
func (*OAuthConfig) Validate ¶
func (o *OAuthConfig) Validate() error
Validate performs validation on OAuthConfig
type ObservabilityConfig ¶ added in v0.35.0
type ObservabilityConfig struct {
// UsageCacheTTL bounds the freshness of the usage endpoint's read cache for
// wide windows (FR-005). Default 5s.
UsageCacheTTL Duration `json:"usage_cache_ttl,omitempty" mapstructure:"usage-cache-ttl" swaggertype:"string"`
// UsagePersistInterval is how often the actor-owned usage aggregate snapshot
// is flushed to storage. Default 30s.
UsagePersistInterval Duration `json:"usage_persist_interval,omitempty" mapstructure:"usage-persist-interval" swaggertype:"string"`
// Metrics gates the Prometheus /metrics scrape endpoint (MCP-32). Disabled
// by default — operators opt in for k8s/enterprise deployments.
Metrics *MetricsExporterConfig `json:"metrics,omitempty" mapstructure:"metrics"`
// Tracing gates the OpenTelemetry OTLP trace exporter (MCP-32). Disabled by
// default.
Tracing *TracingExporterConfig `json:"tracing,omitempty" mapstructure:"tracing"`
}
ObservabilityConfig controls the Spec 069 usage aggregate cadence plus the MCP-32 metrics/tracing exporters.
func DefaultObservabilityConfig ¶ added in v0.35.0
func DefaultObservabilityConfig() *ObservabilityConfig
DefaultObservabilityConfig returns the default observability configuration.
type OutputSanitisationConfig ¶ added in v0.34.0
type OutputSanitisationConfig struct {
SpotlightUntrusted bool `json:"spotlight_untrusted,omitempty" mapstructure:"spotlight-untrusted"` // wrap untrusted output in spotlight markers; default true
ResponseAction string `json:"response_action,omitempty" mapstructure:"response-action"` // "spotlight" | "redact" | "block"; default "spotlight"
StripControlChars bool `json:"strip_control_chars,omitempty" mapstructure:"strip-control-chars"` // strip control-character classes; default false
StripClasses []string `json:"strip_classes,omitempty" mapstructure:"strip-classes"` // classes to strip: ansi/c0c1/bidi/zero_width
MaxRedactions int `json:"max_redactions,omitempty" mapstructure:"max-redactions"` // cap on redactions per response; default 100
}
OutputSanitisationConfig controls output sanitisation behaviour for proxied tool responses (Spec 054 Track B).
func DefaultOutputSanitisationConfig ¶ added in v0.34.0
func DefaultOutputSanitisationConfig() *OutputSanitisationConfig
DefaultOutputSanitisationConfig returns the default configuration for output sanitisation.
func (*OutputSanitisationConfig) EnabledStripClasses ¶ added in v0.34.0
func (c *OutputSanitisationConfig) EnabledStripClasses() map[string]bool
EnabledStripClasses returns the set of strip classes that are active. When stripping is disabled the returned map is empty. Only the valid keys (ansi/c0c1/zero_width/bidi) are included, lowercased.
func (*OutputSanitisationConfig) IsBlock ¶ added in v0.34.0
func (c *OutputSanitisationConfig) IsBlock() bool
IsBlock returns true when ResponseAction is "block". A nil receiver returns false.
func (*OutputSanitisationConfig) IsEnabled ¶ added in v0.34.0
func (c *OutputSanitisationConfig) IsEnabled() bool
IsEnabled returns true unless the whole config is explicitly disabled. A nil receiver defaults to true.
func (*OutputSanitisationConfig) IsRedact ¶ added in v0.34.0
func (c *OutputSanitisationConfig) IsRedact() bool
IsRedact returns true when ResponseAction is "redact". A nil receiver returns false.
func (*OutputSanitisationConfig) IsSpotlightEnabled ¶ added in v0.34.0
func (c *OutputSanitisationConfig) IsSpotlightEnabled() bool
IsSpotlightEnabled returns SpotlightUntrusted. Track B is fully opt-in: a nil receiver (no output_sanitisation block configured) means spotlighting is off.
func (*OutputSanitisationConfig) IsStripEnabled ¶ added in v0.34.0
func (c *OutputSanitisationConfig) IsStripEnabled() bool
IsStripEnabled returns StripControlChars. A nil receiver returns false.
func (*OutputSanitisationConfig) WouldMutate ¶ added in v0.34.0
func (c *OutputSanitisationConfig) WouldMutate(trust string) bool
WouldMutate reports whether sanitisation would alter the response for the given trust level. Redact and block always mutate; spotlight/strip only mutate untrusted output.
type OutputValidationConfig ¶ added in v0.34.0
type OutputValidationConfig struct {
Mode string `json:"mode,omitempty" mapstructure:"mode"` // "off" | "warn" | "strict"; default "warn"
MaxBytes int `json:"max_bytes,omitempty" mapstructure:"max-bytes"` // structured payload byte cap; default 5<<20
MaxDepth int `json:"max_depth,omitempty" mapstructure:"max-depth"` // nesting depth cap; default 64
MissingStructuredContent string `json:"missing_structured_content,omitempty" mapstructure:"missing-structured-content"` // "allow" | "block"; default "allow"
}
OutputValidationConfig controls output-schema validation behaviour (Spec 056).
func DefaultOutputValidationConfig ¶ added in v0.34.0
func DefaultOutputValidationConfig() *OutputValidationConfig
DefaultOutputValidationConfig returns the default configuration for output-schema validation.
func (*OutputValidationConfig) BlockOnMissingStructured ¶ added in v0.34.0
func (c *OutputValidationConfig) BlockOnMissingStructured() bool
BlockOnMissingStructured returns true when MissingStructuredContent is "block". A nil receiver returns false (default is "allow").
func (*OutputValidationConfig) EffectiveMaxBytes ¶ added in v0.34.0
func (c *OutputValidationConfig) EffectiveMaxBytes() int
EffectiveMaxBytes returns MaxBytes, falling back to 5<<20 when zero or nil.
func (*OutputValidationConfig) EffectiveMaxDepth ¶ added in v0.34.0
func (c *OutputValidationConfig) EffectiveMaxDepth() int
EffectiveMaxDepth returns MaxDepth, falling back to 64 when zero or nil.
func (*OutputValidationConfig) IsEnabled ¶ added in v0.34.0
func (c *OutputValidationConfig) IsEnabled() bool
IsEnabled returns true unless Mode is "off". A nil receiver defaults to true (warn).
func (*OutputValidationConfig) IsStrict ¶ added in v0.34.0
func (c *OutputValidationConfig) IsStrict() bool
IsStrict returns true when Mode is "strict". A nil receiver returns false.
func (*OutputValidationConfig) IsWarn ¶ added in v0.34.0
func (c *OutputValidationConfig) IsWarn() bool
IsWarn returns true when validation is enabled but not strict (i.e. warn mode). A nil receiver returns true (default is warn).
type OverrideSource ¶ added in v0.68.0
type OverrideSource string
OverrideSource says where a process-only override came from.
const ( // OverrideSourceFlag is a `serve` command-line flag. OverrideSourceFlag OverrideSource = "flag" // OverrideSourceEnv is a MCPPROXY_* environment variable, including the // MCPPROXY_API_KEY that Validate folds into api_key. OverrideSourceEnv OverrideSource = "env" )
type ProfileConfig ¶ added in v0.39.0
type ProfileConfig struct {
Name string `json:"name"` // URL slug, validated
Servers []string `json:"servers"` // references to mcpServers[].name
}
ProfileConfig is a named, stateless view over a subset of the configured upstream servers, addressable at /mcp/p/<name> (Spec 057). The Name is used verbatim as the URL slug. Servers references mcpServers[].name; unknown names warn-and-skip rather than fail (FR-015).
func (ProfileConfig) EffectiveServers ¶ added in v0.39.0
func (p ProfileConfig) EffectiveServers(cfg *Config) []string
EffectiveServers returns the profile's server list filtered to those that actually exist in cfg (the warn-skip result). Order is preserved and unknown names are dropped. Used by the profile middleware to build the request scope.
type RegistryEntry ¶
type RegistryEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
ServersURL string `json:"servers_url,omitempty"`
Tags []string `json:"tags,omitempty"`
Protocol string `json:"protocol,omitempty"`
Count interface{} `json:"count,omitempty" swaggertype:"primitive,string"` // number or string
// RequiresKey marks a registry that needs an API key to be queried. When
// true and no key is configured, the registry is skipped/marked unavailable
// rather than failing the whole search (FR-008).
RequiresKey bool `json:"requires_key,omitempty"`
// Provenance is the trust tag for this registry (MCP-866):
// RegistryProvenanceOfficial for built-in defaults, RegistryProvenanceCustom
// for user-added registries. It is authoritatively (re)computed by the
// registries merge from whether the ID is a shipped default — a user cannot
// claim "official" by writing it into their config.
Provenance string `json:"provenance,omitempty" mapstructure:"provenance"`
}
RegistryEntry represents a registry in the configuration
func DefaultRegistries ¶ added in v0.35.0
func DefaultRegistries() []RegistryEntry
DefaultRegistries returns the built-in MCP server discovery registries. It is the single source of truth for the shipped defaults: DefaultConfig() seeds them into a fresh config, and the registries package merges them with any user-defined entries so a custom registry never drops the defaults (FR-006).
func (*RegistryEntry) IsTrusted ¶ added in v0.36.0
func (r *RegistryEntry) IsTrusted() bool
IsTrusted reports whether the registry is an official, shipped-by-default source. Trust is never granted by omission — an absent provenance tag is untrusted.
type ResolvedAuditLog ¶ added in v0.68.0
type ResolvedAuditLog struct {
Enabled bool
Path string
Stdout bool
MaxSizeMB int
MaxBackups int
MaxAgeDays int
Compress bool
}
ResolvedAuditLog is the plain, fully-defaulted form EffectiveAuditLog returns: every field carries a concrete value, ready for the sink constructors (internal/audit.NewFileSink / NewStdoutSink).
func EffectiveAuditLog ¶ added in v0.68.0
func EffectiveAuditLog(cfg *Config, transport string) (resolved ResolvedAuditLog, warning string, err error)
EffectiveAuditLog resolves cfg.AuditLog into a plain ResolvedAuditLog for the given transport. It never mutates cfg.
Return contract:
- (resolved, "", nil): use resolved as-is.
- (resolved, warning, nil): a default was silently adjusted for the transport; the caller logs warning at WARN and still uses resolved (which has Enabled=false in that case - FR-014 "only the default is suppressed").
- (ResolvedAuditLog{}, "", err): an explicit configuration cannot be honoured on this transport; err is always a *StartupError. The caller must not construct a sink.
Only the per-edition DEFAULT differs (FR-014: "Defaults differ by edition, the code does not"): with no `audit_log` block, the personal edition resolves to {Enabled:false} (isServerEditionBuild, keyed on the build tag, not on the server_edition.enabled feature flag — the audit funnels compile into every server-edition binary regardless of whether SSO is turned on) and the server edition to its own stdout/stdio default below. An EXPLICIT block is resolved identically on both editions from this point on — "an explicit value always wins" is not a server-edition- only promise (round-2 cross-review finding, PR-D: this used to return {Enabled:false} unconditionally for every personal build, silently dropping an explicit `audit_log: {enabled: true, ...}`).
type ResolvedConcurrency ¶ added in v0.54.0
type ResolvedConcurrency struct {
MaxConcurrentRequests int
QueueSize int
QueueTimeout time.Duration
}
ResolvedConcurrency is one scope's settings after tri-state resolution. It is the shape the limiter registry consumes.
func (ResolvedConcurrency) Enabled ¶ added in v0.54.0
func (r ResolvedConcurrency) Enabled() bool
Enabled reports whether this scope actually caps concurrency.
type ResolvedIsolation ¶ added in v0.64.0
type ResolvedIsolation struct {
// Mode is the effective isolation mode: docker | sandbox | none. This is
// exactly what the spawn path branches on, so it must never be adjusted for
// host capability — on a Linux kernel without Landlock the sandbox wrapper
// still runs and still applies its rlimits.
Mode IsolationMode
// Isolated reports whether the child process is actually CONFINED — i.e.
// whether Mode is one the spawn path implements AND this host can enforce
// it. It is not simply `Mode != none`: "sandbox" on macOS/Windows, on a
// kernel without Landlock, or a mode the launcher does not implement, all
// run the server unconfined, and the read path must never claim isolation
// the spawn path will not deliver (GH #1142). Source says which.
Isolated bool
// GlobalMode is what "inherit" resolves to right now.
GlobalMode IsolationMode
// Inherited is true when the server carries no per-server enabled/mode
// override, so its state tracks the global setting.
Inherited bool
// Source explains which rule produced Mode; one of the IsolationSource*
// constants above.
Source string
}
ResolvedIsolation is the fully-resolved isolation state of a server: what actually happens at spawn time, plus enough context for a UI to explain it.
This is the ONLY correct answer to "is this server isolated". The raw per-server override (IsolationConfig.Enabled) is tri-state and means nothing on its own — nil is "inherit", not "off" (GH #1142).
func ResolveIsolation ¶ added in v0.64.0
func ResolveIsolation(globalConfig *DockerIsolationConfig, serverConfig *ServerConfig) ResolvedIsolation
ResolveIsolation resolves the effective isolation state for a server, combining the global config (with legacy Enabled⇒docker back-compat), the optional per-server override, and the structural gates — and reports which rule decided the outcome.
It lives in `config` rather than `upstream/core` so that every surface which has to answer "is this server isolated" — the spawn path, the REST/MCP projections, and the contracts converter (which cannot import core without a cycle) — provably runs one algorithm. `core.IsolationManager.ResolveIsolation` wraps this to add the deduplicated ignored-opt-in warning.
Precedence:
- A per-server explicit Mode wins outright (even over a disabled global) — mirroring how other per-server overrides (image, network) take priority.
- Otherwise, when the global mode resolves to none, per-server bool opt-ins are ignored, preserving the pre-mode behavior.
- When the global mode is active, a per-server bool opt-out (enabled:false) downgrades the server to none. A nil Enabled is "inherit", NOT an opt-out.
Structural gates then apply to ALL non-none modes: servers with no command (HTTP transports) and servers that already invoke docker are never isolated.
A final CAPABILITY gate decides Isolated (not Mode): a mode the launcher does not implement, and "sandbox" on a host that cannot enforce Landlock, both run the server unconfined, so they must not be reported as isolated. Mode is left alone there because the spawn path branches on it and still applies the sandbox wrapper's rlimits on Linux — see isolationDelivered.
This answers ONLY the process-spawn question. Two neighbouring questions have their own entry points and must not be answered from this one: ResolveScannerIsolationMode (may Docker-based SCANNER containers run against this server) and ServerDependsOnDocker (does starting it need a daemon).
type SearchResult ¶
type SearchResult struct {
Tool *ToolMetadata `json:"tool"`
Score float64 `json:"score"`
}
SearchResult represents a search result with score
type SecurityConfig ¶ added in v0.24.0
type SecurityConfig struct {
ScanTimeoutDefault Duration `json:"scan_timeout_default,omitempty" mapstructure:"scan-timeout-default" swaggertype:"string"`
IntegrityCheckInterval Duration `json:"integrity_check_interval,omitempty" mapstructure:"integrity-check-interval" swaggertype:"string"`
IntegrityCheckOnRestart bool `json:"integrity_check_on_restart" mapstructure:"integrity-check-on-restart"`
ScannerRegistryURL string `json:"scanner_registry_url,omitempty" mapstructure:"scanner-registry-url"`
RuntimeReadOnly bool `json:"runtime_read_only" mapstructure:"runtime-read-only"`
RuntimeTmpfsSize string `json:"runtime_tmpfs_size,omitempty" mapstructure:"runtime-tmpfs-size"`
// Deprecated (Spec 077 US3): migrated on load into DeepScan.DisableNoNewPrivileges
// (see migrateDeepScanConfig). Retained only so existing configs that still carry
// the top-level key parse; consumers MUST read the effective value via
// SecurityConfig.IsDisableNoNewPrivileges. Cleared after migration.
//
// ScannerDisableNoNewPrivileges, when true, omits the
// `--security-opt no-new-privileges` flag from scanner container runs.
//
// Background: snap-installed Docker on Ubuntu confines dockerd under the
// `snap.docker.dockerd` AppArmor profile. When runc tries to transition
// the container into the inner `docker-default` profile to exec the
// entrypoint, AppArmor refuses the transition because NO_NEW_PRIVS
// forbids privilege/profile changes on exec — the result is EPERM
// ("operation not permitted") and every scanner fails immediately.
//
// Set this to true ONLY on hosts hitting that incompatibility. Scanner
// containers still run with read-only rootfs, tmpfs /tmp, no-network by
// default, and read-only source mounts, so the marginal isolation loss
// is small. The preferred fix remains replacing snap docker with a
// distro-packaged docker.
ScannerDisableNoNewPrivileges bool `json:"scanner_disable_no_new_privileges,omitempty" mapstructure:"scanner-disable-no-new-privileges"`
// Deprecated (Spec 077 US3): migrated on load into DeepScan.FetchPackageSource
// (see migrateDeepScanConfig). Retained only so existing configs that still carry
// the top-level key parse; consumers MUST read the effective value via
// SecurityConfig.EffectiveFetchPackageSource. Cleared after migration.
//
// ScannerFetchPackageSource controls whether the scanner fetches the
// PUBLISHED source of package-runner servers (npx/uvx) — without executing
// it — when no local source is available (no Docker container, no local
// package cache, no working_dir). This is the primary quarantine/scan
// target: a quarantined-on-add server is never run locally, so without this
// the scan degrades to tool-definitions-only (no real source-level
// analysis). See MCP-2206.
//
// Fetching uses `npm pack --ignore-scripts` (npm) and `uv pip download` /
// `pip download` with `--only-binary=:all:` (Python), which only download +
// unpack archives and NEVER run install, build, or setup.py — a scanner must
// not execute the untrusted code it is scanning. The Python
// `--only-binary=:all:` flag is required because downloading an sdist would
// invoke its build backend (setup.py); packages with no wheel fall back to
// tool-definitions-only instead. Extraction is hardened against path
// traversal and decompression bombs.
//
// Default (nil) is ENABLED. Set to false on air-gapped deployments to
// forbid the scanner's network egress; such servers then fall back to the
// tool-definitions-only scan with no regression.
ScannerFetchPackageSource *bool `json:"scanner_fetch_package_source,omitempty" mapstructure:"scanner-fetch-package-source"`
// TPABundlePath is the filesystem path to the tpa-db scanner-bundle.json
// the offline TPA scanner runs (spec 086 FR-019: the signature-DB location
// MUST be configuration-driven, not hardcoded). Empty (the default) runs the
// corpus embedded in this build.
//
// Env override: MCPPROXY_TPA_BUNDLE_PATH. Hot-reloadable — the path is
// re-read on every config.reloaded event via
// scanner.Service.ApplySecurityConfig, so a corpus refresh needs no restart.
// A configured bundle that fails to read/parse/version-check/compile is
// REFUSED and the previously active corpus stays live (fail-closed, never
// fail-empty); the reason is logged and surfaced in the security overview's
// signature_bundle.load_error.
TPABundlePath string `json:"tpa_bundle_path,omitempty" mapstructure:"tpa-bundle-path"`
// DeepScan is the opt-in "deep scan" layer (Spec 077 US3). It subsumes the
// deprecated top-level scanner_fetch_package_source / scanner_disable_no_new_privileges
// keys (migrated on load) and gates the heavy Docker-based scanners + source
// extraction. Disabled by default (FR-006): only the deterministic in-process
// baseline scanner runs. A deep-scan failure NEVER changes the baseline verdict
// (FR-007/FR-008).
DeepScan *DeepScanConfig `json:"deep_scan,omitempty" mapstructure:"deep-scan"`
// AutoBaselineScan is the kill-switch for the AUTOMATIC, informational
// Pass-1 baseline scan: the free in-process TPA scan mcpproxy runs for every
// newly admitted server (any trust mode) and, once per installation, over
// pre-existing servers that have never been scanned.
//
// Informational ONLY: the resulting verdict populates the security badge and
// the scan summary, and NEVER gates quarantine or approval. The
// trust_mode:"scan" admission gate is a separate path and is unaffected by
// this flag.
//
// Default (nil) is ENABLED. Set to false to suppress every automatic scan
// (manual scans keep working). Env override: MCPPROXY_AUTO_BASELINE_SCAN,
// which wins over this field on every path.
AutoBaselineScan *bool `json:"auto_baseline_scan,omitempty" mapstructure:"auto-baseline-scan" swaggertype:"boolean"`
}
SecurityConfig represents security scanner configuration (Spec 039)
func (*SecurityConfig) DeepScanScanners ¶ added in v0.47.0
func (sc *SecurityConfig) DeepScanScanners() []string
DeepScanScanners returns the optional per-scanner allow-list for the deep-scan layer, or nil when unset (all enabled deep scanners are eligible).
func (*SecurityConfig) EffectiveFetchPackageSource ¶ added in v0.47.0
func (sc *SecurityConfig) EffectiveFetchPackageSource() *bool
EffectiveFetchPackageSource resolves the package-source-fetch setting from the deep_scan block first, falling back to the deprecated top-level key for configs loaded before migration. Nil ⇒ default (enabled).
func (*SecurityConfig) EffectiveTPABundlePath ¶ added in v0.53.0
func (sc *SecurityConfig) EffectiveTPABundlePath() string
EffectiveTPABundlePath returns the TPA signature-bundle path the scanner must run, or "" to mean "use the corpus embedded in this build" (spec 086 FR-019).
Precedence: MCPPROXY_TPA_BUNDLE_PATH wins over the file value. The env check lives HERE, not only in the loader's env-override pass, because config objects reach the scanner without ever passing through config.Load — most visibly POST /api/v1/config/apply, which would otherwise let a posted security.tpa_bundle_path silently defeat the operator's env override on the next scanner reconfigure. Nil-safe: a config with no security block still honours the env var, and runs the embedded corpus without one.
func (*SecurityConfig) IsAutoBaselineScanEnabled ¶ added in v0.61.0
func (sc *SecurityConfig) IsAutoBaselineScanEnabled() bool
IsAutoBaselineScanEnabled reports whether mcpproxy may run the automatic, informational Pass-1 baseline scan (new-server admission scan + the one-shot baseline sweep). Default is ENABLED: a nil SecurityConfig, or an unset auto_baseline_scan, means on — the scan is free, in-process, and drives no gating, so an install that never touched the security block still gets its badges populated.
MCPPROXY_AUTO_BASELINE_SCAN outranks the file value on every path (loader, hot-reload, /api/v1/config/apply) because the precedence is resolved here rather than only in the loader's env pass.
func (*SecurityConfig) IsDeepScanEnabled ¶ added in v0.47.0
func (sc *SecurityConfig) IsDeepScanEnabled() bool
IsDeepScanEnabled reports whether the opt-in deep-scan layer is turned on. Nil-safe: a nil SecurityConfig or nil DeepScan means disabled (the default).
func (*SecurityConfig) IsDisableNoNewPrivileges ¶ added in v0.47.0
func (sc *SecurityConfig) IsDisableNoNewPrivileges() bool
IsDisableNoNewPrivileges resolves the no-new-privileges escape hatch from the deep_scan block first, falling back to the deprecated top-level key.
type SensitiveDataDetectionConfig ¶ added in v0.17.0
type SensitiveDataDetectionConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable sensitive data detection (default: true)
ScanRequests bool `json:"scan_requests" mapstructure:"scan-requests"` // Scan tool call arguments (default: true)
ScanResponses bool `json:"scan_responses" mapstructure:"scan-responses"` // Scan tool responses (default: true)
MaxPayloadSizeKB int `json:"max_payload_size_kb" mapstructure:"max-payload-size-kb"` // Max size to scan before truncating (default: 1024)
EntropyThreshold float64 `json:"entropy_threshold" mapstructure:"entropy-threshold"` // Shannon entropy threshold for high-entropy detection (default: 4.5)
Categories map[string]bool `json:"categories,omitempty" mapstructure:"categories"` // Enable/disable specific detection categories
CustomPatterns []CustomPattern `json:"custom_patterns,omitempty" mapstructure:"custom-patterns"` // User-defined detection patterns
SensitiveKeywords []string `json:"sensitive_keywords,omitempty" mapstructure:"sensitive-keywords"` // Keywords to flag
}
SensitiveDataDetectionConfig represents sensitive data detection settings (Spec 026)
func DefaultSensitiveDataDetectionConfig ¶ added in v0.17.0
func DefaultSensitiveDataDetectionConfig() *SensitiveDataDetectionConfig
DefaultSensitiveDataDetectionConfig returns the default configuration for sensitive data detection
func (*SensitiveDataDetectionConfig) GetEntropyThreshold ¶ added in v0.17.0
func (c *SensitiveDataDetectionConfig) GetEntropyThreshold() float64
GetEntropyThreshold returns the entropy threshold (default: 4.5)
func (*SensitiveDataDetectionConfig) GetMaxPayloadSize ¶ added in v0.17.0
func (c *SensitiveDataDetectionConfig) GetMaxPayloadSize() int
GetMaxPayloadSize returns the max payload size in bytes
func (*SensitiveDataDetectionConfig) IsCategoryEnabled ¶ added in v0.17.0
func (c *SensitiveDataDetectionConfig) IsCategoryEnabled(category string) bool
IsCategoryEnabled returns true if the specified category is enabled
func (*SensitiveDataDetectionConfig) IsEnabled ¶ added in v0.17.0
func (c *SensitiveDataDetectionConfig) IsEnabled() bool
IsEnabled returns true if sensitive data detection is enabled (default: true)
type ServerConfig ¶
type ServerConfig struct {
Name string `json:"name,omitempty" mapstructure:"name"`
URL string `json:"url,omitempty" mapstructure:"url"`
Protocol string `json:"protocol,omitempty" mapstructure:"protocol"` // stdio, http, sse, streamable-http, auto
Command string `json:"command,omitempty" mapstructure:"command"`
Args []string `json:"args,omitempty" mapstructure:"args"`
WorkingDir string `json:"working_dir,omitempty" mapstructure:"working_dir"` // Working directory for stdio servers
Env map[string]string `json:"env,omitempty" mapstructure:"env"`
Headers map[string]string `json:"headers,omitempty" mapstructure:"headers"` // For HTTP servers
OAuth *OAuthConfig `json:"oauth" mapstructure:"oauth"` // OAuth configuration (keep even when empty to signal OAuth requirement)
Enabled bool `json:"enabled" mapstructure:"enabled"`
Quarantined bool `json:"quarantined" mapstructure:"quarantined"` // Security quarantine status
// SkipQuarantine is DEPRECATED (MCP-2930): use AutoApproveToolChanges instead.
// Kept for back-compat parsing; on config load a legacy skip_quarantine:true is
// migrated to auto_approve_tool_changes:true only when the new field is unset
// (see normalizeServerQuarantineFlags).
SkipQuarantine bool `json:"skip_quarantine,omitempty" mapstructure:"skip-quarantine"` // Deprecated: use auto_approve_tool_changes
// AutoApproveToolChanges is the per-server intent to auto-approve tool
// changes/additions (disabling per-server rug-pull protection). Supersedes
// skip_quarantine. MCP-2930 only ACCEPTS, persists, and migrates this flag — it
// is NOT yet consulted at runtime; auto-approval is still governed by
// SkipQuarantine until the trust-baseline behavior change (MCP-2931) migrates the
// runtime consumers onto it.
// Tri-state pointer (mirrors QuarantineEnabled): nil = unset (inherit/migrate
// from legacy skip_quarantine), explicit true/false = honored as-is so an
// explicit auto_approve_tool_changes:false overrides a legacy skip_quarantine:true.
// Read via IsAutoApproveToolChanges().
AutoApproveToolChanges *bool `json:"auto_approve_tool_changes,omitempty" mapstructure:"auto-approve-tool-changes"` // Per-server intent to auto-approve tool changes/additions. Accepted/persisted by MCP-2930; runtime enforcement lands in MCP-2931 (until then SkipQuarantine governs behavior)
// TrustMode is the per-server trust tier: auto|scan|manual. Supersedes
// auto_approve_tool_changes (spec 086). An empty value is derived from the
// legacy fields at load via normalizeServerQuarantineFlags; the single
// resolution point is EffectiveTrustMode(), which treats an empty or
// unrecognized value as manual (secure by default). Read via
// EffectiveTrustMode(), never the raw string.
TrustMode string `json:"trust_mode,omitempty" mapstructure:"trust-mode"` // Per-server trust tier: auto|scan|manual. Supersedes auto_approve_tool_changes (086)
Created time.Time `json:"created" mapstructure:"created"`
Updated time.Time `json:"updated,omitempty" mapstructure:"updated"`
Isolation *IsolationConfig `json:"isolation,omitempty" mapstructure:"isolation"` // Per-server isolation settings
ReconnectOnUse bool `json:"reconnect_on_use,omitempty" mapstructure:"reconnect-on-use"` // Attempt reconnection when a tool call targets a disconnected server
// ExposePrompts overrides whether this server's advertised MCP prompts are
// aggregated into mcpproxy's prompts/list. nil (default) inherits the
// default-aggregate behavior (included if the server advertises
// Capabilities.Prompts); false excludes it regardless of capability.
ExposePrompts *bool `json:"expose_prompts,omitempty" mapstructure:"expose-prompts"`
// LauncherWaitTimeout caps how long mcpproxy will wait for a locally-launched
// HTTP/SSE upstream's URL to become reachable after Spawn(). Only consulted
// when the server is configured with both Command and an HTTP/SSE URL — i.e.,
// mcpproxy starts the process AND connects via network. Stdio servers ignore
// this field. Zero or unset → 30s default.
LauncherWaitTimeout Duration `json:"launcher_wait_timeout,omitempty" mapstructure:"launcher_wait_timeout" swaggertype:"string"`
// Per-server discovery & health-check overrides (spec 074). Same *Duration
// tri-state as the global keys: nil = inherit the global value (or default),
// pointer to 0s = disabled for this server, positive = that interval.
// HealthCheckInterval is fully wired into the per-server health loop;
// ToolDiscoveryInterval is accepted/validated and round-trips for
// forward-compat, but the periodic index sweep is governed by the global
// cadence in this iteration (see spec 074 plan §C).
HealthCheckInterval *Duration `json:"health_check_interval,omitempty" mapstructure:"health_check_interval" swaggertype:"string"`
ToolDiscoveryInterval *Duration `json:"tool_discovery_interval,omitempty" mapstructure:"tool_discovery_interval" swaggertype:"string"`
// InitTimeout overrides the global init_timeout for this server's MCP
// `initialize` handshake deadline (MCP-3322 / GH #760). *Duration tri-state:
// nil = inherit the global value (or 30s default), positive = that deadline.
// Resolved by Config.ResolveInitTimeout; validated to {0} ∪ [1s, 30m]. Raise
// this for upstreams that do legitimate first-run warmup (e.g. caching many
// channels/users) before responding to `initialize`.
InitTimeout *Duration `json:"init_timeout,omitempty" mapstructure:"init_timeout" swaggertype:"string"`
// Per-server concurrency overrides — scope (c) of FR-020 (spec 093, #955).
// Tri-state per setting, exactly like HealthCheckInterval: absent = inherit
// the per-server default set (server_concurrency_defaults), explicit 0 =
// disable that setting for this server (0 max = no per-server limiter at
// all; 0 queue_size = no pending capacity, shed immediately at the cap),
// positive = override. The global aggregate limiter is never inherited from
// here — it applies on top, so effective concurrency is min(per-server,
// global). Resolved by Config.ResolveServerConcurrency.
MaxConcurrentRequests *int `json:"max_concurrent_requests,omitempty" mapstructure:"max_concurrent_requests"`
QueueSize *int `json:"queue_size,omitempty" mapstructure:"queue_size"`
QueueTimeout *Duration `json:"queue_timeout,omitempty" mapstructure:"queue_timeout" swaggertype:"string"`
// ToonOutput overrides the global toon_output mode for this server's
// tools (spec 084, FR-001). Plain string, not a pointer: ""/absent =
// inherit the global value; "off"|"adaptive"|"always" = override ("off"
// is the explicit force-off). Resolved by Config.ResolveToonOutput.
ToonOutput string `json:"toon_output,omitempty" mapstructure:"toon_output"`
EnabledTools []string `json:"enabled_tools,omitempty" mapstructure:"enabled_tools"` // Allowlist: only these tools are exposed; mutually exclusive with disabled_tools
DisabledTools []string `json:"disabled_tools,omitempty" mapstructure:"disabled_tools"` // Denylist: these tools are hidden; mutually exclusive with enabled_tools
// SourceRegistryID records which registry this server was added from (empty
// for manually-configured servers). MCP-866: surfaced in the approval /
// quarantine view so a reviewer can see a server's origin.
SourceRegistryID string `json:"source_registry_id,omitempty" mapstructure:"source_registry_id"`
// SourceRegistryProvenance records the source registry's provenance at add
// time (RegistryProvenanceOfficial / RegistryProvenanceCustom). It is purely
// informational (MCP-1072) — surfaced so a reviewer can see a server's origin
// — and no longer gates quarantine or skip_quarantine.
SourceRegistryProvenance string `json:"source_registry_provenance,omitempty" mapstructure:"source_registry_provenance"`
// AuthBroker holds the per-upstream `oauth_connect` credential-connect
// block (spec 074, server edition only). When set, a user can complete a
// per-user consent flow and have their credential STORED encrypted for this
// upstream — nothing injects it into the outbound request (Spec 107
// FR-034); the call path keeps using the server's own headers/oauth
// settings. The concrete type is build-tagged: a validated struct in the
// server edition, an opaque json.RawMessage carrier in the personal
// edition (preserved verbatim through load → save → PATCH, FR-040), so
// personal-edition behavior is unaffected. swaggerignore mirrors ServerEdition.
AuthBroker *AuthBrokerConfig `json:"auth_broker,omitempty" mapstructure:"auth_broker" swaggerignore:"true"`
// contains filtered or unexported fields
}
ServerConfig represents upstream MCP server configuration
func ConvertFromCursorFormat ¶
func ConvertFromCursorFormat(cursorConfig *CursorMCPConfig) []*ServerConfig
ConvertFromCursorFormat converts Cursor IDE format to our internal format
func CopyServerConfig ¶ added in v0.21.2
func CopyServerConfig(src *ServerConfig) *ServerConfig
func (*ServerConfig) ContributesTools ¶ added in v0.62.0
func (sc *ServerConfig) ContributesTools() bool
ContributesTools is the *ServerConfig form of ServerContributesTools. A nil receiver contributes nothing.
func (*ServerConfig) EffectiveTrustMode ¶ added in v0.53.0
func (sc *ServerConfig) EffectiveTrustMode() TrustMode
EffectiveTrustMode is the single resolution point for a server's trust tier (spec 086). It returns one of TrustModeAuto/Scan/Manual, defaulting to manual (secure by default) for empty OR unrecognized trust_mode values (FR-009 — fail closed on a typo like "Scan" or "off").
Because normalizeServerQuarantineFlags populates TrustMode at config load, the legacy-field fallback here only matters for in-memory structs that bypassed the loader (tests, REST-constructed configs): an explicit auto_approve_tool_changes maps true->auto / false->manual, else a legacy skip_quarantine:true maps to auto, else manual. This keeps the accessor correct even when the migration has not run.
func (*ServerConfig) HasStaticAuthorizationHeader ¶ added in v0.66.0
func (sc *ServerConfig) HasStaticAuthorizationHeader() bool
HasStaticAuthorizationHeader reports whether the server is configured to authenticate with a static credential in the `Authorization` header (name matched case-insensitively, value non-blank).
OAuth and a static Authorization header are mutually exclusive on the wire: the OAuth transport populates that very header, and the headers-auth strategy runs before OAuth is ever attempted. A config that declares one has therefore stopped using the other, which lets the server projection ignore an OAuth token record left behind by a previous OAuth login (GH #1172) without a heuristic on other header names. A nil receiver has no headers.
func (*ServerConfig) IsAutoApproveToolChanges ¶ added in v0.42.0
func (sc *ServerConfig) IsAutoApproveToolChanges() bool
IsAutoApproveToolChanges reports the configured per-server intent to auto-approve tool changes/additions (disabling per-server rug-pull protection). It is provided for the runtime consumers that adopt it in MCP-2931 and is NOT yet consulted at runtime — SkipQuarantine / IsQuarantineSkipped still governs behavior until then. Mirrors IsQuarantineEnabled's *bool handling: an unset field (nil) is false; the legacy skip_quarantine is migrated into this field at config load (see normalizeServerQuarantineFlags) only when it is unset, so an explicit value always wins. MCP-2930.
func (*ServerConfig) IsQuarantineSkipped ¶ added in v0.21.0
func (sc *ServerConfig) IsQuarantineSkipped() bool
IsQuarantineSkipped returns whether this server should skip tool-level quarantine. Thin wrapper over EffectiveTrustMode(): only trust_mode auto skips quarantine; scan and manual do not (spec 086).
func (*ServerConfig) IsToolAllowedByConfig ¶ added in v0.32.0
func (sc *ServerConfig) IsToolAllowedByConfig(toolName string) bool
IsToolAllowedByConfig reports whether toolName passes the server's static enabled_tools / disabled_tools filter. Returns true when neither list is set.
func (*ServerConfig) MarkQuarantineExplicitlySet ¶ added in v0.53.0
func (sc *ServerConfig) MarkQuarantineExplicitlySet(explicit bool)
MarkQuarantineExplicitlySet stamps the presence bit on a struct that did not come from JSON. Used by copy helpers so the bit survives a config round-trip.
func (*ServerConfig) MarshalJSON ¶ added in v0.53.0
func (sc *ServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON writes a ServerConfig, omitting "quarantined" when the value is false AND no configuration document ever stated it (issue #937, review P1).
Without this, mcpproxy's own SaveConfig fabricated an operator statement: `Quarantined` is a plain bool with no omitempty, so every save stamped `"quarantined": false` onto servers that had never mentioned the key. Reading that back set the presence bit, and the config-load admission gate then skipped the server permanently — including servers the gate had itself just quarantined, whose config.db record the next start would overwrite with false. One API-triggered save disarmed the gate for good.
A true value is ALWAYS written: a gate decision persisted to disk must be readable back, and quarantine is never expressed by absence.
func (*ServerConfig) QuarantineExplicitlySet ¶ added in v0.53.0
func (sc *ServerConfig) QuarantineExplicitlySet() bool
QuarantineExplicitlySet reports whether the parsed configuration document stated a "quarantined" value for this server. False means the key was absent (or the struct was built in Go rather than decoded), which the config-load admission gate treats as "never been through admission".
func (*ServerConfig) UnmarshalJSON ¶ added in v0.53.0
func (sc *ServerConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a ServerConfig and additionally records whether the "quarantined" key was present at all (issue #937).
The presence bit is what distinguishes "the operator opted out" from "the operator never said anything", and it is the only thing the config-load admission gate keys off. It is deliberately unexported: it describes the DOCUMENT that was parsed, not the server. MarshalJSON below round-trips it by OMITTING the key rather than by writing the bit out.
A JSON `null` does NOT count as a statement. Everywhere else in mcpproxy null means "unset" (RFC 7396 merge-patch semantics — see the env_json handling in internal/server/mcp.go), and a templating tool or serializer that emits null for an unset field must not be able to silently admit a first-seen server.
Note this only fires for JSON decoding. Structs built in Go (REST handlers, the add paths, tests) leave the bit false — i.e. "unstated" — which is the safe default: the gate can only ever ADD quarantine, never remove it.
WARNING — do not EMBED ServerConfig (by pointer or value) in another struct that adds JSON fields of its own. Go promotes these methods to the outer type, so encoding/json treats the wrapper as a Marshaler/Unmarshaler and delegates the whole value here: the wrapper's own fields are silently dropped on encode, and decode fails with "json: Unmarshal(nil *config.Alias)" while the embedded pointer is still nil. A wrapper that needs to embed this must declare its own MarshalJSON/UnmarshalJSON — see internal/serveredition/api.ServerResponse.
type ServerEditionConfig ¶ added in v0.39.0
type ServerEditionConfig struct {
// contains filtered or unexported fields
}
ServerEditionConfig is the personal-edition carrier for the `server_edition` block. Server edition features are not available here, but the block must survive load → save → PATCH → save intact in meaning (Spec 107 FR-040): it is held as the canonical JSON of what was read (canonicalRawJSON), never interpreted, never validated, never normalised and never warned about.
Omission is the parent pointer's job: Config.ServerEdition is `*T,omitempty`, so a document without the key leaves the pointer nil and the key stays absent on write, and a JSON `null` also decodes to a nil pointer. A non-nil carrier with no raw bytes (only constructible from Go code) marshals as `{}`.
func MergeServerEditionRestartGated ¶ added in v0.68.0
func MergeServerEditionRestartGated(live, _ *ServerEditionConfig) *ServerEditionConfig
MergeServerEditionRestartGated pins the WHOLE opaque carrier to `live` on the personal build (cross-review round 1, chunk 3 P1): nothing inside it is interpreted, so every key is restart-pinned by the same rule ServerEditionRestartProjection uses — there is no hot admin_emails exception here (that is server-build-only, #1169).
func (*ServerEditionConfig) Clone ¶ added in v0.68.0
func (c *ServerEditionConfig) Clone() *ServerEditionConfig
Clone returns a deep copy of the carrier (nil-safe). It is provided for symmetry with the server build and pinned by a unit test; nothing copies the top-level block today (the config snapshot shares the pointer and nothing mutates it in the personal build).
func (ServerEditionConfig) MarshalJSON ¶ added in v0.68.0
func (c ServerEditionConfig) MarshalJSON() ([]byte, error)
MarshalJSON emits the stored document; an empty carrier is `{}`.
func (*ServerEditionConfig) UnmarshalJSON ¶ added in v0.68.0
func (c *ServerEditionConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON stores the document in canonical form (every key and value kept; key order and whitespace are not part of the contract).
type StartupError ¶ added in v0.68.0
StartupError is a typed, exit-code-carrying boot failure (Spec 107 FR-014). cmd/mcpproxy's classifyError matches it with errors.As BEFORE its string heuristics, so a wrapped "permission denied" underneath never misclassifies this as ExitCodePermissionError.
func NewStartupError ¶ added in v0.68.0
func NewStartupError(exitCode int, message string) *StartupError
NewStartupError builds a StartupError with the given exit code and message.
func (*StartupError) Error ¶ added in v0.68.0
func (e *StartupError) Error() string
type TLSConfig ¶
type TLSConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable HTTPS
RequireClientCert bool `json:"require_client_cert" mapstructure:"require_client_cert"` // Enable mTLS
CertsDir string `json:"certs_dir,omitempty" mapstructure:"certs_dir"` // Directory for certificates
HSTS bool `json:"hsts" mapstructure:"hsts"` // Enable HTTP Strict Transport Security
}
TLSConfig represents TLS configuration
type TelemetryConfig ¶ added in v0.22.0
type TelemetryConfig struct {
Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"` // Default: true (opt-out)
AnonymousID string `json:"anonymous_id,omitempty" mapstructure:"anonymous-id"` // Auto-generated UUIDv4
Endpoint string `json:"endpoint,omitempty" mapstructure:"endpoint"` // Override for testing
// Spec 042 (Tier 2) additions — all default-zero, all backwards-compatible.
AnonymousIDCreatedAt string `json:"anonymous_id_created_at,omitempty" mapstructure:"anonymous-id-created-at"` // RFC3339; for annual rotation
LastReportedVersion string `json:"last_reported_version,omitempty" mapstructure:"last-reported-version"` // Upgrade funnel
LastStartupOutcome string `json:"last_startup_outcome,omitempty" mapstructure:"last-startup-outcome"` // success|port_conflict|db_locked|...
NoticeShown bool `json:"notice_shown,omitempty" mapstructure:"notice-shown"` // First-run notice flag
}
TelemetryConfig controls anonymous usage telemetry (Spec 036, extended in Spec 042).
type TokenizerConfig ¶
type TokenizerConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"` // Enable token counting
DefaultModel string `json:"default_model" mapstructure:"default_model"` // Default model for tokenization (e.g., "gpt-4")
Encoding string `json:"encoding" mapstructure:"encoding"` // Default encoding (e.g., "cl100k_base")
}
TokenizerConfig represents tokenizer configuration for token counting
type ToolAnnotations ¶
type ToolAnnotations struct {
Title string `json:"title,omitempty"`
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
DestructiveHint *bool `json:"destructiveHint,omitempty"`
IdempotentHint *bool `json:"idempotentHint,omitempty"`
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
ToolAnnotations represents MCP tool behavior hints
type ToolMetadata ¶
type ToolMetadata struct {
// Name is the tool's display/lookup name. Discovery stores the RAW upstream
// name here (no server prefix); index reads return the canonical
// "<server>:<raw>" id (#871). Consumers that need the exact upstream name
// must go through RawToolName, never strip a prefix by hand (Spec 105 FR-009).
Name string `json:"name"`
ServerName string `json:"server_name"`
// RawName is the exact upstream-reported tool name, stamped at discovery
// (Spec 105 FR-009). It is the identity every producer keys on — approval
// records, index docIDs — so "ns:erase" never collapses to "erase". Empty
// on metadata built outside discovery; RawToolName derives it from Name.
RawName string `json:"raw_name,omitempty"`
Description string `json:"description"`
ParamsJSON string `json:"params_json"`
OutputSchemaJSON string `json:"output_schema_json,omitempty"` // declared output schema, raw JSON bytes (Spec 056)
Hash string `json:"hash"`
Created time.Time `json:"created"`
Updated time.Time `json:"updated"`
Annotations *ToolAnnotations `json:"annotations,omitempty"`
}
ToolMetadata represents tool information stored in the index
type ToolRegistration ¶
type ToolRegistration struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]interface{} `json:"input_schema"`
ServerName string `json:"server_name"`
OriginalName string `json:"original_name"`
}
ToolRegistration represents a tool registration
type ToolStatEntry ¶
ToolStatEntry represents a single tool stat entry
type ToolStats ¶
type ToolStats struct {
TotalTools int `json:"total_tools"`
TopTools []ToolStatEntry `json:"top_tools"`
}
ToolStats represents tool statistics
type TracingExporterConfig ¶ added in v0.45.0
type TracingExporterConfig struct {
// Enabled turns on OTLP trace export for tool calls and upstream hops.
Enabled bool `json:"enabled" mapstructure:"enabled"`
// Protocol selects the OTLP transport: "http" or "grpc".
Protocol string `json:"protocol,omitempty" mapstructure:"protocol"`
// Endpoint is the collector address as host:port (no scheme), e.g.
// "localhost:4318" for http or "localhost:4317" for grpc.
Endpoint string `json:"endpoint,omitempty" mapstructure:"endpoint"`
// SampleRate is the head-based trace sampling ratio in [0,1]. Default 0.1.
// Omit the key for the 0.1 default; set it to 0 to sample nothing.
SampleRate *float64 `json:"sample_rate,omitempty" mapstructure:"sample-rate"`
}
TracingExporterConfig controls the OpenTelemetry OTLP trace exporter (MCP-32).
func DefaultTracingExporterConfig ¶ added in v0.45.0
func DefaultTracingExporterConfig() *TracingExporterConfig
DefaultTracingExporterConfig returns the default (disabled) tracing exporter with sane transport defaults pre-filled.
func (*TracingExporterConfig) EffectiveSampleRate ¶ added in v0.65.0
func (t *TracingExporterConfig) EffectiveSampleRate() float64
EffectiveSampleRate resolves the head-based trace sampling ratio.
nil (key absent) = the built-in 0.1. An explicit 0 = sample nothing, and stays nothing. Nil-safe on the receiver: an absent tracing block is the common case.
type TrustMode ¶ added in v0.53.0
type TrustMode string
TrustMode is a per-server trust tier that governs how tool changes and additions are approved (spec 086). It supersedes the legacy skip_quarantine and auto_approve_tool_changes flags:
- TrustModeAuto — auto-approve all changes/additions (today's skip_quarantine / auto_approve_tool_changes:true behavior).
- TrustModeScan — auto-approve a change ONLY when a synchronous, offline TPA scan of the changed tool returns a green (clean) verdict; otherwise the record is held for human review (fail closed).
- TrustModeManual — never auto-approve; every change/addition is held (secure by default).
type TrustModeNormalization ¶ added in v0.53.0
type TrustModeNormalization struct {
// Server is the upstream server whose trust_mode was rewritten.
Server string
// Original is the unrecognized value that was found in the config.
Original string
}
TrustModeNormalization records one per-server trust_mode value that the load path rewrote because it was not in the accepted vocabulary.
func NormalizeTrustModes ¶ added in v0.53.0
func NormalizeTrustModes(c *Config) []TrustModeNormalization
NormalizeTrustModes rewrites every unrecognized per-server trust_mode to the fail-closed tier (manual) and reports what it changed.
Rejecting a bogus trust_mode is right at the WRITE seams — REST POST/PATCH /api/v1/servers, the upstream_servers tool, `--trust-mode` — where an operator is handed the error immediately and nothing has been persisted. It is WRONG on the LOAD path: a config carrying the bogus value that a previous release persisted through the supported REST API would make LoadFromFile fail, so `mcpproxy serve` refused to start and every subsequent hot-reload was blocked until someone hand-edited the file. GH #938 asked for "reject with 400, OR normalize and warn"; the load path normalizes.
The rewrite is to manual, which is exactly the behavior EffectiveTrustMode() already produced for the bad value — so nothing about the RUNTIME decision changes, only the lie the read surfaces used to echo back. Nil-safe and idempotent.
type TrustedProxiesProvider ¶ added in v0.68.0
type TrustedProxiesProvider func() []string
TrustedProxiesProvider yields the LIVE trusted_proxies list; consumers evaluate it per request so a hot reload takes effect without a restart.
type UpdateCheckConfig ¶ added in v0.47.0
type UpdateCheckConfig struct {
// Enabled gates all update checking. Tri-state: nil/absent = enabled
// (default true, matching pre-079 behavior). When false, no network
// check is performed and no upgrade nudge appears on any surface
// (FR-015) — /api/v1/info omits the update object entirely.
Enabled *bool `json:"enabled,omitempty" mapstructure:"enabled"`
// Channel selects which releases are offered as updates: "stable"
// (default; prereleases never offered) or "rc" (prereleases included).
// Empty resolves to stable. Validated in ValidateDetailed.
//
// NOTE: for a RELEASED build the running binary's own version is
// authoritative and overrides this field — a stable build is never
// offered an RC (even with channel=rc), and an RC build always tracks the
// rc channel. This field only takes effect on dev/unstamped builds. See
// internal/updatecheck.Checker.IncludePrereleases.
Channel string `json:"channel,omitempty" mapstructure:"channel"`
}
UpdateCheckConfig is the `update_check` config block (Spec 079 FR-012). It gates the background update poll and the manual re-check (/api/v1/info?refresh=true) and selects the release channel. Hot-reloadable: the runtime re-applies it to the running checker on config reload.
func (*UpdateCheckConfig) IncludePrereleases ¶ added in v0.47.0
func (u *UpdateCheckConfig) IncludePrereleases() bool
IncludePrereleases reports whether the configured channel offers prereleases (channel=rc). Nil-safe.
func (*UpdateCheckConfig) IsEnabled ¶ added in v0.47.0
func (u *UpdateCheckConfig) IsEnabled() bool
IsEnabled reports whether update checking is enabled by config. Nil-safe: a missing block or missing key defaults to enabled (Spec 079 FR-012).
func (*UpdateCheckConfig) ResolvedChannel ¶ added in v0.47.0
func (u *UpdateCheckConfig) ResolvedChannel() string
ResolvedChannel returns the effective release channel, defaulting empty to stable. Nil-safe.
type ValidationError ¶
ValidationError represents a configuration validation error
func ValidateRemovedKeys ¶ added in v0.68.0
func ValidateRemovedKeys(_ map[string]any) []ValidationError
ValidateRemovedKeys is a no-op in the personal edition: the server-edition blocks are opaque JSON carriers there (Spec 107 FR-040) and nothing is normalised, validated or refused.
func (ValidationError) Error ¶
func (v ValidationError) Error() string
Error implements the error interface
Source Files
¶
- audit_log.go
- auth_broker_stub.go
- build_edition_stub.go
- code_execution.go
- concurrency.go
- config.go
- config_validate_serveredition_stub.go
- connection_equivalent.go
- deprecated.go
- doctor_findings.go
- doctor_findings_stub.go
- effective_bounds.go
- env_serveredition_stub.go
- features.go
- isolation_git.go
- isolation_resolve.go
- load_diagnostics.go
- loader.go
- merge.go
- oauth_validation.go
- process_overrides.go
- profiles.go
- removed_keys_stub.go
- server_edition_config_stub.go
- serveredition_accessors_stub.go
- tool_identity.go
- trusted_proxies.go