Documentation
¶
Overview ¶
Spec 085 US3 — pre-dispatch argument validation (FR-013) and the self-healing invalid_params error renderer shared by Path A (pre-dispatch) and Path B (best-effort upstream classification). Contract: specs/085-compact-router/contracts/invalid-params-error.md.
Index ¶
- Constants
- Variables
- func AddRegistrySourceErrorCode(err error) string
- func EditRegistrySourceErrorCode(err error) string
- func FormatDirectPromptName(serverName, promptName string) string
- func FormatDirectToolName(serverName, toolName string) string
- func ParseDirectToolName(directName string) (serverName, toolName string, ok bool)
- func RegistryAddErrorCode(err error) string
- func RemoveRegistrySourceErrorCode(err error) string
- func SetMCPServerVersion(v string)
- func TagConnectionContext(ctx context.Context, source ConnectionSource) context.Context
- func ValidateDataDirectory(dataDir string, logger *zap.Logger) error
- type AccessEvaluator
- type AddFromRegistryRequest
- type AddRegistrySourceRequest
- type BenchProxyToolDef
- type CacheStore
- type ConnectionSource
- type EditRegistrySourceRequest
- type IsolationChecker
- type Listener
- type ListenerConfig
- type ListenerManager
- type MCPProxyOption
- type MCPProxyServer
- func (p *MCPProxyServer) ApproveAllPrompts(serverName, approvedBy string) (int, error)
- func (p *MCPProxyServer) ApprovePrompt(serverName, promptName, approvedBy string) error
- func (p *MCPProxyServer) BindingGuardActiveBindings() []runtime.BindingRef
- func (p *MCPProxyServer) BindingGuardDelta(current, candidate runtime.GuardState) []runtime.BindingRef
- func (p *MCPProxyServer) BindingGuardFixes(candidate runtime.GuardState, delta []runtime.BindingRef) []runtime.GuardFix
- func (p *MCPProxyServer) CallBuiltInTool(ctx context.Context, toolName string, arguments map[string]interface{}) (*mcp.CallToolResult, error)
- func (p *MCPProxyServer) CallToolDirect(ctx context.Context, request mcp.CallToolRequest) (interface{}, error)
- func (p *MCPProxyServer) CallToolDirectResult(ctx context.Context, request mcp.CallToolRequest) (interface{}, error)
- func (p *MCPProxyServer) Close() error
- func (p *MCPProxyServer) EffectiveAnnotations(serverName, toolName string) (annotations *config.ToolAnnotations, found bool)
- func (p *MCPProxyServer) EffectiveTools(_ context.Context, name string, opt runtime.EffectiveToolsOptions) (*runtime.EffectiveToolsResult, error)
- func (p *MCPProxyServer) EvaluateAccess(subject profile.AccessSubject, server, tool string) profile.AccessVerdict
- func (p *MCPProxyServer) Explain(_ context.Context, subject profile.AccessSubject, tool string) (*runtime.AccessExplanation, error)
- func (p *MCPProxyServer) GetCallToolServer() *mcpserver.MCPServer
- func (p *MCPProxyServer) GetCodeExecServer() *mcpserver.MCPServer
- func (p *MCPProxyServer) GetDirectServer() *mcpserver.MCPServer
- func (p *MCPProxyServer) GetMCPServer() *mcpserver.MCPServer
- func (p *MCPProxyServer) GetMCPServerForMode(mode string) *mcpserver.MCPServer
- func (p *MCPProxyServer) HoldProfileNotifications() (release func())
- func (p *MCPProxyServer) IncludeDisabledCalls() int64
- func (p *MCPProxyServer) NewAccessEvaluator(subject profile.AccessSubject) (*AccessEvaluator, error)
- func (p *MCPProxyServer) NotifyBindingChanged(tokenName string)
- func (p *MCPProxyServer) NotifyUpstreamInventoryChanged()
- func (p *MCPProxyServer) ProfileDeleted(name string)
- func (p *MCPProxyServer) ProfileRenamed(from, to string)
- func (p *MCPProxyServer) ProfileTokensMoved(tokenNames []string)
- func (p *MCPProxyServer) RefreshCallToolModeTools()
- func (p *MCPProxyServer) RefreshCodeExecModeTools()
- func (p *MCPProxyServer) RefreshCodeExecutionAvailability()
- func (p *MCPProxyServer) RefreshDirectModeTools()
- func (p *MCPProxyServer) RefreshDirectModeToolsOnSerializationChange()
- func (p *MCPProxyServer) RefreshPrompts()
- func (p *MCPProxyServer) ResolveProfileV3(ctx context.Context, idx *profileIndex) ProfileResolution
- func (p *MCPProxyServer) RunPreflight(ctx context.Context, params preflight.Params) (preflight.Outcome, error)
- func (p *MCPProxyServer) RunPreflightForSession(ctx context.Context, refs []preflight.ToolRef, filters toolannotations.Filters) (preflight.Outcome, error)
- func (p *MCPProxyServer) SetAdminViews(v profilesAdminViews)
- func (p *MCPProxyServer) SetObservability(obs *observability.Manager)
- func (p *MCPProxyServer) ToolCounts(ctx context.Context, name string, viewer runtime.ViewerScope) runtime.ToolCounts
- func (p *MCPProxyServer) TryProfile(ctx context.Context, draft config.ProfileConfig, query string, limit int) (*runtime.TryResult, error)
- type MissingRequiredInputError
- type PermissionError
- type PortInUseError
- type ProfileResolution
- type Server
- func (s *Server) AddRegistrySource(req *AddRegistrySourceRequest) (*config.RegistryEntry, error)
- func (s *Server) AddRegistrySourceRef(rawURL, protocol, id, name string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
- func (s *Server) AddServer(ctx context.Context, serverConfig *config.ServerConfig) error
- func (s *Server) AddServerFromRegistry(ctx context.Context, req *AddFromRegistryRequest) (*config.ServerConfig, error)
- func (s *Server) AddServerFromRegistryRef(ctx context.Context, registryID, serverID, name string, env map[string]string, ...) (*config.ServerConfig, *contracts.RegistryAddError, error)
- func (s *Server) AggregateToolUsage(since time.Time) (map[string]storage.ToolUsageStat, error)
- func (s *Server) ApplyConfig(cfg *config.Config, cfgPath string) (*runtime.ConfigApplyResult, error)
- func (s *Server) ApproveAllTools(serverName string, approvedBy string) (int, error)
- func (s *Server) ApproveAllToolsAt(serverName string, approvedBy string, expectedIncarnation int64) (int, error)
- func (s *Server) ApproveAllToolsReviewed(serverName string, expected map[string]string, approvedBy string) (int, error)
- func (s *Server) ApproveAllToolsReviewedAt(serverName string, expected map[string]string, approvedBy string, ...) (int, error)
- func (s *Server) ApproveTools(serverName string, toolNames []string, approvedBy string) error
- func (s *Server) ApproveToolsAt(serverName string, toolNames []string, approvedBy string, ...) error
- func (s *Server) ApproveToolsReviewed(serverName string, toolNames []string, expected map[string]string, ...) (int, error)
- func (s *Server) ApproveToolsReviewedAt(serverName string, toolNames []string, expected map[string]string, ...) (int, error)
- func (s *Server) Attention() []contracts.AttentionItem
- func (s *Server) BlockAllTools(serverName string, blockedBy string) (int, error)
- func (s *Server) BlockAllToolsAt(serverName string, blockedBy string, expectedIncarnation int64) (int, error)
- func (s *Server) BlockTools(serverName string, toolNames []string, blockedBy string) (int, error)
- func (s *Server) BlockToolsAt(serverName string, toolNames []string, blockedBy string, ...) (int, error)
- func (s *Server) CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (interface{}, error)
- func (s *Server) DefaultInstructions() string
- func (s *Server) DiscoverServerTools(ctx context.Context, serverName string) error
- func (s *Server) EditRegistrySource(req *EditRegistrySourceRequest) (*config.RegistryEntry, error)
- func (s *Server) EditRegistrySourceRef(id, name, rawURL, serversURL string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
- func (s *Server) EmitActiveProfileChanged(profile string)
- func (s *Server) EnableServer(serverName string, enabled bool) error
- func (s *Server) EventsChannel() <-chan runtime.Event
- func (s *Server) ForceReconnectAllServers(reason string) error
- func (s *Server) GetActivationFirstMCPClient() (bool, []string)
- func (s *Server) GetActivity(id string) (*storage.ActivityRecord, error)
- func (s *Server) GetAllServers() ([]map[string]interface{}, error)
- func (s *Server) GetConfig() (*config.Config, error)
- func (s *Server) GetConfigPath() string
- func (s *Server) GetCurrentConfig() *config.Config
- func (s *Server) GetDesiredConfig() (*config.Config, error)
- func (s *Server) GetDockerRecoveryStatus() *storage.DockerRecoveryState
- func (s *Server) GetListenAddress() string
- func (s *Server) GetLogDir() string
- func (s *Server) GetManagementService() management.Service
- func (s *Server) GetOnboardingState() (*storage.OnboardingState, error)
- func (s *Server) GetQuarantinedServers() ([]map[string]interface{}, error)
- func (s *Server) GetRecentSessions(f storage.SessionFilter) ([]*contracts.MCPSession, int, error)
- func (s *Server) GetReviewQueue(ctx context.Context) (*runtime.ReviewQueue, error)
- func (s *Server) GetSecretResolver() *secret.Resolver
- func (s *Server) GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, error)
- func (s *Server) GetServerReview(ctx context.Context, serverName string) (*runtime.ServerReview, error)
- func (s *Server) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
- func (s *Server) GetServerTools(serverName string) ([]map[string]interface{}, error)
- func (s *Server) GetSessionByID(sessionID string) (*contracts.MCPSession, error)
- func (s *Server) GetStatus() interface{}
- func (s *Server) GetTokenSavings() (*contracts.ServerTokenMetrics, error)
- func (s *Server) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
- func (s *Server) GetToolApprovalStatus(serverName, toolName string) (string, error)
- func (s *Server) GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
- func (s *Server) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
- func (s *Server) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
- func (s *Server) GetUpstreamStats() map[string]interface{}
- func (s *Server) GetVersionInfo() *updatecheck.VersionInfo
- func (s *Server) IsDockerAvailable() bool
- func (s *Server) IsReady() bool
- func (s *Server) IsRunning() bool
- func (s *Server) IsToolConfigDenied(serverName, toolName string) bool
- func (s *Server) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
- func (s *Server) ListRegistries() ([]interface{}, error)
- func (s *Server) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
- func (s *Server) MutateConfig(ctx context.Context, actor runtime.Actor, ...) (*runtime.ConfigApplyResult, *runtime.ConfigDiff, error)
- func (s *Server) NotifySecretsChanged(ctx context.Context, operation, secretName string) error
- func (s *Server) OnUpstreamServerChange()
- func (s *Server) PatchServer(ctx context.Context, serverName string, ...) error
- func (s *Server) QuarantineServer(serverName string, quarantined bool) error
- func (s *Server) QuarantineServerAt(serverName string, quarantined bool, expectedIncarnation int64) error
- func (s *Server) RecordPreflight(rec runtime.PreflightActivity) error
- func (s *Server) RecordStartupOutcome(outcome string) error
- func (s *Server) RecordUpdateFailure(stage string) (bool, error)
- func (s *Server) RefreshRegistryCache(registryID string) (int, error)
- func (s *Server) RefreshVersionInfo() *updatecheck.VersionInfo
- func (s *Server) ReloadConfiguration() error
- func (s *Server) RemoveRegistrySource(id string) (*config.RegistryEntry, error)
- func (s *Server) RemoveRegistrySourceRef(id string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
- func (s *Server) RemoveServer(ctx context.Context, serverName string) error
- func (s *Server) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
- func (s *Server) ResolveViewAs(subject profile.AccessSubject) (httpapi.ViewAsEvaluator, error)
- func (s *Server) RestartServer(serverName string) error
- func (s *Server) RunPreflight(ctx context.Context, params preflight.Params) (preflight.Outcome, error)
- func (s *Server) SaveConfiguration() error
- func (s *Server) SaveOnboardingState(state *storage.OnboardingState) error
- func (s *Server) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)
- func (s *Server) SearchTools(query string, limit int) ([]map[string]interface{}, error)
- func (s *Server) SearchToolsForProfile(ctx context.Context, query string, limit int, inScope func(string) bool) (results []map[string]interface{}, handled bool, err error)
- func (s *Server) SearchToolsScoped(query string, limit int, inScope func(serverName string) bool) ([]map[string]interface{}, error)
- func (s *Server) ServeErr() <-chan error
- func (s *Server) ServedRoutingMode() string
- func (s *Server) ServerIncarnation(serverName string) (int64, bool)
- func (s *Server) SetAllToolsEnabled(serverName string, enabled bool, updatedBy string) (int, error)
- func (s *Server) SetAllToolsEnabledAt(serverName string, enabled bool, updatedBy string, expectedIncarnation int64) (int, error)
- func (s *Server) SetListenAddress(addr string, persist bool) error
- func (s *Server) SetShutdownInfo(reason, signal string)
- func (s *Server) SetToolEnabled(serverName, toolName string, enabled bool, updatedBy string) error
- func (s *Server) SetToolEnabledAt(serverName, toolName string, enabled bool, updatedBy string, ...) error
- func (s *Server) Shutdown() error
- func (s *Server) Start(ctx context.Context) error
- func (s *Server) StartServer(ctx context.Context) error
- func (s *Server) StatusChannel() <-chan interface{}
- func (s *Server) StopServer() error
- func (s *Server) StreamActivities(ctx context.Context, filter storage.ActivityFilter) <-chan *storage.ActivityRecord
- func (s *Server) SubscribeEvents() chan runtime.Event
- func (s *Server) SuggestAlternateListen(baseAddr string) (string, error)
- func (s *Server) ToolAllowedByProfile(ctx context.Context, serverName, toolName string) bool
- func (s *Server) TriggerOAuthLogin(serverName string) error
- func (s *Server) UnquarantineServer(serverName string) error
- func (s *Server) UnsubscribeEvents(ch chan runtime.Event)
- func (s *Server) UpdateOnboardingState(fn func(*storage.OnboardingState) error) error
- func (s *Server) UpdatePolicy() updatecheck.Policy
- func (s *Server) UpdateServer(ctx context.Context, serverName string, updates *config.ServerConfig) error
- func (s *Server) UsageSnapshot() *runtime.UsageAggregate
- func (s *Server) ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)
- type ServerExistsError
- type ServerOption
- type SessionInfo
- type SessionRisk
- type SessionStore
- func (s *SessionStore) AbandonWorkspaceFetch(sessionID string)
- func (s *SessionStore) ClearSelection(name string)
- func (s *SessionStore) Count() int
- func (s *SessionStore) EnsurePersisted(sessionID string, resolveWorkSession func(*SessionInfo) string) string
- func (s *SessionStore) GetActiveProfile(sessionID string) string
- func (s *SessionStore) GetSession(sessionID string) *SessionInfo
- func (s *SessionStore) NotifyTargets(tokenName string) []sessionTarget
- func (s *SessionStore) RemoveSession(sessionID string)
- func (s *SessionStore) RenameSelection(from, to string)
- func (s *SessionStore) Reopen(sessionID string)
- func (s *SessionStore) SessionsForToken(tokenName string) []string
- func (s *SessionStore) SessionsMatching(pred func(*SessionInfo) bool) []sessionTarget
- func (s *SessionStore) SetActiveProfile(sessionID, profileSlug string)
- func (s *SessionStore) SetSession(sessionID, clientName, clientVersion string, hasRoots, hasSampling bool, ...)
- func (s *SessionStore) SetSessionAnonymous(sessionID string, anonymous bool)
- func (s *SessionStore) SetSessionIdentity(sessionID, tokenName, clientID string)
- func (s *SessionStore) SetSessionServer(sessionID string, srv *mcpserver.MCPServer)
- func (s *SessionStore) SetSessionTokenPrefix(sessionID, prefix string)
- func (s *SessionStore) SetStorageManager(manager *storage.Manager)
- func (s *SessionStore) SetWorkspace(sessionID, workspaceRoot string)
- func (s *SessionStore) TryClaimWorkspaceFetch(sessionID string) bool
- func (s *SessionStore) UpdateActivity(sessionID string)
- func (s *SessionStore) UpdateSessionProfile(sessionID, profileName, source string)
- func (s *SessionStore) UpdateSessionStats(sessionID string, tokens int)
- func (s *SessionStore) WorkSessionID(sessionID string) string
- func (s *SessionStore) WorkspaceSettled(sessionID string, wait time.Duration)
- type Status
- type Ucred
Constants ¶
const ( ConnectionSourceTCP = transport.ConnectionSourceTCP ConnectionSourceTray = transport.ConnectionSourceTray )
const ( // DirectModeToolSeparator is the separator between server name and tool name in direct mode. // Using double underscore to avoid conflicts with single underscores in tool names. DirectModeToolSeparator = "__" )
Variables ¶
var ( // ErrNoInstallInfo means the registry entry had neither an install command // nor a URL, so there is nothing runnable to persist. ErrNoInstallInfo = errors.New("no_install_info") // ErrDuplicateName means an upstream server with the target name already exists. ErrDuplicateName = errors.New("duplicate_name") )
Stable error codes shared across surfaces. Surfaces translate these to their own envelopes (HTTP 400/404, MCP structured error, CLI message) via RegistryAddErrorCode so the same failure reads the same way everywhere.
var ( // ErrInvalidRegistryURL means the supplied source URL was not a valid https URL. ErrInvalidRegistryURL = errors.New("invalid_registry_url") // ErrRegistriesLocked means RegistriesLocked is set and runtime additions are refused. ErrRegistriesLocked = errors.New("registries_locked") // ErrRegistryShadowsBuiltin means the requested id collides with a shipped default. ErrRegistryShadowsBuiltin = errors.New("registry_shadows_builtin") // ErrDuplicateRegistry means a custom registry with that id already exists. ErrDuplicateRegistry = errors.New("duplicate_registry") // ErrUnsupportedRegistryProtocol means a protocol other than the single one // MCPProxy implements was requested. Reported separately from // invalid_registry_url so the guidance can talk about the protocol rather than // telling the user to "provide an https URL" for a URL that was fine. ErrUnsupportedRegistryProtocol = errors.New("unsupported_registry_protocol") // ErrRegistrySourceUnusable means the URL answered but serves no MCP server // list (GH #783): a 404, an HTML page, or JSON with nothing server-shaped in // it. Refusing the add here is the whole point — the alternative is a // registry that persists fine and then fails every search. ErrRegistrySourceUnusable = errors.New("registry_source_unusable") )
Stable cross-surface error codes for add-source failures.
var ErrRegistryNotFound = errors.New("registry_not_found")
ErrRegistryNotFound means no custom registry with the requested id exists.
Functions ¶
func AddRegistrySourceErrorCode ¶ added in v0.36.0
AddRegistrySourceErrorCode maps an add-source error to its stable cross-surface code.
func EditRegistrySourceErrorCode ¶ added in v0.37.0
EditRegistrySourceErrorCode maps an edit-source error to its stable cross-surface code (shared HTTP status mapping with add/remove-source).
func FormatDirectPromptName ¶ added in v0.59.0
FormatDirectPromptName formats a server name and prompt name using the same "__" separator convention as FormatDirectToolName.
func FormatDirectToolName ¶ added in v0.21.0
FormatDirectToolName formats a server name and tool name into a direct mode tool name.
func ParseDirectToolName ¶ added in v0.21.0
ParseDirectToolName parses a direct mode tool name (serverName__toolName) into server and tool components. Splits on the FIRST occurrence of "__" only, so tool names containing "__" are preserved. Returns server name, tool name, and whether the parse was successful.
func RegistryAddErrorCode ¶ added in v0.35.0
RegistryAddErrorCode maps an error returned by AddServerFromRegistry (or the pure derivation) to its stable cross-surface code, or "" if it is not one of the recognized add-from-registry failures.
func RemoveRegistrySourceErrorCode ¶ added in v0.37.0
RemoveRegistrySourceErrorCode maps a remove-source error to its stable cross-surface code (shared HTTP status mapping with add-source).
func SetMCPServerVersion ¶ added in v0.21.0
func SetMCPServerVersion(v string)
SetMCPServerVersion sets the version reported by MCP server instances.
func TagConnectionContext ¶
func TagConnectionContext(ctx context.Context, source ConnectionSource) context.Context
TagConnectionContext tags a context with the connection source TagConnectionContext wraps transport.TagConnectionContext for backward compatibility
Types ¶
type AccessEvaluator ¶ added in v0.70.0
type AccessEvaluator struct {
// contains filtered or unexported fields
}
AccessEvaluator evaluates the access chain for one subject. It resolves the subject once (its credential, binding and profile index snapshot) and then answers per (server, tool). It is not safe to keep across a config change.
func (*AccessEvaluator) Evaluate ¶ added in v0.70.0
func (ev *AccessEvaluator) Evaluate(server, tool string) profile.AccessVerdict
Evaluate walks the chain for one (server, tool).
type AddFromRegistryRequest ¶ added in v0.35.0
type AddFromRegistryRequest struct {
RegistryID string // required — must resolve via registries.FindRegistry
ServerID string // required — resolved via registries.FindServerByID
Name string // optional override; defaults to the entry's name/id
Env map[string]string // optional; satisfies declared RequiredInputs
Enabled *bool // optional; defaults to true when nil
// SourceRegistryID / SourceProvenance are stamped server-side by
// AddServerFromRegistry from the resolved registry (MCP-866); they are NOT
// client-settable through the REST/MCP/CLI Ref adapter. They are purely
// informational (MCP-1072) — the derived server follows the global
// quarantine default regardless of provenance.
SourceRegistryID string
SourceProvenance string
}
AddFromRegistryRequest is the reference-based input to the keystone op.
type AddRegistrySourceRequest ¶ added in v0.36.0
type AddRegistrySourceRequest struct {
URL string // required https URL of the registry (base or /v0.1/servers endpoint)
Protocol string // optional; defaults to modelcontextprotocol/registry
ID string // optional; derived from the host when empty
Name string // optional; defaults to the id
}
AddRegistrySourceRequest is the input to the add-source op. Provenance is NOT part of the request — it is always "custom".
type BenchProxyToolDef ¶ added in v0.45.0
type BenchProxyToolDef struct {
Name string
Description string
Schema json.RawMessage
}
BenchProxyToolDef is a static built-in proxy/management tool definition (name + description + JSON input schema) exposed for the in-repo benchmark harness (bench/).
The benchmark scores the per-mode context cost an agent pays for mcpproxy's own tools. That cost MUST reflect every tool the live routing-mode servers expose — including the shared management tool set (upstream_servers, quarantine_security, search_servers, list_registries) that both modes append via buildManagementTools — or the benchmark overstates the token savings (MCP-3161 / Codex finding on PR #747).
Schema is the exact JSON input schema the proxy advertises via tools/list, captured from the live builder. The benchmark's exact-token headline counts schemas on BOTH the baseline upstream tools and these proxy tools; omitting the proxy schemas while counting the baseline's would overstate savings (the MCP-3161 error), so Schema makes the headline honest without drift.
func ProxyModeToolDefs ¶ added in v0.45.0
func ProxyModeToolDefs(routingMode string) []BenchProxyToolDef
ProxyModeToolDefs returns the static built-in proxy + management tool definitions an agent sees in its context window for the given routing mode (config.RoutingModeRetrieveTools or config.RoutingModeCodeExecution).
It is built from the SAME builders the live server uses (buildCallToolModeTools / buildCodeExecModeTools in mcp_routing.go) so the benchmark catalog can never drift from production. Code execution is enabled so the real code_execution tool description (not the disabled stub) is scored — the code_execution routing mode only makes sense with the tool enabled.
type CacheStore ¶ added in v0.32.1
type CacheStore interface {
Store(key, toolName string, args map[string]interface{}, content, recordPath string, totalRecords int) error
}
CacheStore is the narrow interface forwardContentResult needs from a cache manager to persist truncated payloads so the read_cache MCP tool can later page through them. It mirrors cache.Manager.Store but is defined here to keep this package free of an internal/cache import.
type ConnectionSource ¶
type ConnectionSource = transport.ConnectionSource
Re-export transport types for backward compatibility
func GetConnectionSource ¶
func GetConnectionSource(ctx context.Context) ConnectionSource
GetConnectionSource wraps transport.GetConnectionSource for backward compatibility
type EditRegistrySourceRequest ¶ added in v0.37.0
type EditRegistrySourceRequest struct {
ID string // required — the id of the custom registry to edit
Name string // optional new display name
URL string // optional new base/servers https URL
ServersURL string // optional explicit servers-collection URL
}
EditRegistrySourceRequest carries partial updates to a custom registry. Empty string fields mean "leave unchanged".
type IsolationChecker ¶
type IsolationChecker interface {
// ResolveIsolation is the single source of truth for "is this server
// isolated" — it accounts for the global mode, the tri-state per-server
// override and the structural gates (GH #1142).
ResolveIsolation(serverConfig *config.ServerConfig) config.ResolvedIsolation
ShouldIsolate(serverConfig *config.ServerConfig) bool
DetectRuntimeType(command string) string
GetDockerImage(serverConfig *config.ServerConfig, runtimeType string) (string, error)
GetDockerIsolationWarning(serverConfig *config.ServerConfig) string
}
IsolationChecker interface for checking isolation settings
type Listener ¶
type Listener struct {
net.Listener
Source ConnectionSource
Address string // Display address for logging
// contains filtered or unexported fields
}
Listener wraps a net.Listener with metadata about its source
type ListenerConfig ¶
type ListenerConfig struct {
// DataDir is the data directory where socket file will be created
DataDir string
// TrayEndpoint is an optional explicit override for the tray endpoint
// Format: "unix:///path/to/socket.sock" or "npipe:////./pipe/name"
TrayEndpoint string
// TCPAddress is the address for the TCP listener (for browsers)
// Format: "127.0.0.1:8080" or ":8080"
TCPAddress string
// Logger for diagnostic output
Logger *zap.Logger
}
ListenerConfig contains configuration for creating listeners
type ListenerManager ¶
type ListenerManager struct {
// contains filtered or unexported fields
}
ListenerManager manages multiple listeners (TCP + Tray socket/pipe)
func NewListenerManager ¶
func NewListenerManager(config *ListenerConfig) *ListenerManager
NewListenerManager creates a new listener manager
func (*ListenerManager) CloseAll ¶
func (m *ListenerManager) CloseAll() error
CloseAll closes all managed listeners
func (*ListenerManager) CreateTCPListener ¶
func (m *ListenerManager) CreateTCPListener() (*Listener, error)
CreateTCPListener creates a TCP listener for browser/remote access
func (*ListenerManager) CreateTrayListener ¶
func (m *ListenerManager) CreateTrayListener() (*Listener, error)
CreateTrayListener creates a Unix socket (macOS/Linux) or named pipe (Windows) listener for tray access
func (*ListenerManager) GetListeners ¶
func (m *ListenerManager) GetListeners() []*Listener
GetListeners returns all active listeners
type MCPProxyOption ¶ added in v0.57.0
type MCPProxyOption func(*MCPProxyServer)
MCPProxyOption customizes an MCPProxyServer at construction time.
func WithConfigFilePath ¶ added in v0.57.0
func WithConfigFilePath(path string) MCPProxyOption
WithConfigFilePath declares the ACTIVE configuration FILE path this server serves (Spec 097). Every surface that stands up an MCPProxyServer passes it: the daemon from the runtime config service, the CLI's in-process server from its own --config resolution. It must be the config FILE, never a directory derived from --data-dir, which may be overridden after the file is chosen.
type MCPProxyServer ¶
type MCPProxyServer struct {
// contains filtered or unexported fields
}
MCPProxyServer implements an MCP server that acts as a proxy
func NewMCPProxyServer ¶
func NewMCPProxyServer( storage *storage.Manager, index *index.Manager, upstreamManager *upstream.Manager, cacheManager *cache.Manager, truncatorFn func() *truncate.Truncator, logger *zap.Logger, mainServer *Server, debugSearch bool, config *config.Config, sigCache *toolsig.Cache, opts ...MCPProxyOption, ) *MCPProxyServer
NewMCPProxyServer creates a new MCP proxy server
func (*MCPProxyServer) ApproveAllPrompts ¶ added in v0.59.0
func (p *MCPProxyServer) ApproveAllPrompts(serverName, approvedBy string) (int, error)
ApproveAllPrompts approves every pending/changed prompt for a server (or all servers when serverName is empty), then refreshes once. Returns the count approved. Each promotion is guarded by enforcePromptInvariant. Each server's records are re-read and written under its approval lock, bound to the incarnation captured when the call started (Spec 116 FR-014/FR-016): a named server that was removed or replaced fails with runtime.ErrServerReplaced; with serverName empty such a server is skipped.
func (*MCPProxyServer) ApprovePrompt ¶ added in v0.59.0
func (p *MCPProxyServer) ApprovePrompt(serverName, promptName, approvedBy string) error
ApprovePrompt approves a single held prompt: it re-baselines ApprovedHash to the current metadata hash and clears the withhold, then a RefreshPrompts re-registers it. Fails closed via enforcePromptInvariant. Reason is user_approve (an operator/agent explicitly approved).
Spec 116 FR-014/FR-016: the approval is bound to the server's incarnation when it starts, and the record is read and written under the server's approval lock after the incarnation check: once the server was removed or replaced it writes nothing and returns runtime.ErrServerReplaced.
func (*MCPProxyServer) BindingGuardActiveBindings ¶ added in v0.70.0
func (p *MCPProxyServer) BindingGuardActiveBindings() []runtime.BindingRef
BindingGuardActiveBindings returns the bindings that are bypassable right now under the live config, token store and published tool snapshot.
func (*MCPProxyServer) BindingGuardDelta ¶ added in v0.70.0
func (p *MCPProxyServer) BindingGuardDelta(current, candidate runtime.GuardState) []runtime.BindingRef
BindingGuardDelta is the FR-008a "one condition function" (plan D2): Delta = {b in bindings(candidate) : bypassable(b, candidate) and not (b in bindings(current) and bypassable(b, current))}, binding identity = token name (unique across client credentials and guard-bound tokens, Spec 115). A candidate with require_mcp_auth on yields an empty delta. Every API path that could create the condition refuses on a non-empty delta; the runtime guard and the warnings reuse the same evaluator.
func (*MCPProxyServer) BindingGuardFixes ¶ added in v0.70.0
func (p *MCPProxyServer) BindingGuardFixes(candidate runtime.GuardState, delta []runtime.BindingRef) []runtime.GuardFix
BindingGuardFixes lists the remediations for a refusal. require_mcp_auth always works; set_anonymous_profile carries a target only when making the first refused binding's own profile the anonymous profile would leave NO binding of the delta bypassable (the same evaluator, on a candidate with that anonymous_profile) — otherwise it has no target and its label reads "a profile not wider than <p>".
func (*MCPProxyServer) CallBuiltInTool ¶
func (p *MCPProxyServer) CallBuiltInTool(ctx context.Context, toolName string, arguments map[string]interface{}) (*mcp.CallToolResult, error)
CallBuiltInTool provides public access to built-in tools for CLI usage
func (*MCPProxyServer) CallToolDirect ¶
func (p *MCPProxyServer) CallToolDirect(ctx context.Context, request mcp.CallToolRequest) (interface{}, error)
CallToolDirect calls a tool directly without going through the MCP server's request handling This is used for REST API calls that bypass the MCP protocol layer
func (*MCPProxyServer) CallToolDirectResult ¶ added in v0.72.0
func (p *MCPProxyServer) CallToolDirectResult(ctx context.Context, request mcp.CallToolRequest) (interface{}, error)
CallToolDirectResult keeps the MCP result envelope for the REST tool-call endpoint. Other direct callers retain the historical content-only return.
func (*MCPProxyServer) Close ¶
func (p *MCPProxyServer) Close() error
Close gracefully shuts down the MCP proxy server and releases resources
func (*MCPProxyServer) EffectiveAnnotations ¶ added in v0.70.0
func (p *MCPProxyServer) EffectiveAnnotations(serverName, toolName string) (annotations *config.ToolAnnotations, found bool)
EffectiveAnnotations returns the (server, tool) pair's effective annotations for Spec 108 profile-policy enforcement (T013): the ONE annotation source for CompiledPolicy.Decide (via profile.IntrinsicTier), SearchToolsAdmitted's predicate, "view as" and the access explainer — the index itself stores no annotation field and gains none (FR-011, no index-schema change, no reindex). It is a thin wrapper over resolveExactToolIdentity, the SAME identity seam every dispatch path already uses (Spec 105 FR-009), so discovery and execution classify a tool from one source and can never disagree; it is also the documented hook for per-server annotation_overrides once open PR #1323 lands (that PR only needs to change what resolveExactToolIdentity resolves, never this call site or any of its callers).
found=false (the current snapshot does not list this exact server:tool name at all) tells the caller to fail closed: profile.IntrinsicTier(nil, false) is TierDestructive regardless of the returned annotations, which are nil in that case. found=true does not by itself certify that the annotations are current for the LIVE connection generation (a disconnected server can retain a previous connection's stamp) — dispatch enforces currency separately via the epoch-pinned certified() check (mcp.go); this seam only answers "what does the snapshot say", the same answer every other dispatch-adjacent reader of toolIdentity gets.
This delegates to lookupExactToolAnnotations (mcp.go) rather than re-resolving: same identity, same seam, one implementation.
func (*MCPProxyServer) EffectiveTools ¶ added in v0.70.0
func (p *MCPProxyServer) EffectiveTools(_ context.Context, name string, opt runtime.EffectiveToolsOptions) (*runtime.EffectiveToolsResult, error)
EffectiveTools implements runtime.ProfileEvaluator: one row per catalog tool with the verdict of the ONE access chain (the same rendering GET /tools?profile= uses), so `callable` equals what a real call would do.
func (*MCPProxyServer) EvaluateAccess ¶ added in v0.70.0
func (p *MCPProxyServer) EvaluateAccess(subject profile.AccessSubject, server, tool string) profile.AccessVerdict
EvaluateAccess is the one-shot form of NewAccessEvaluator(...).Evaluate. A subject that cannot be resolved (unknown profile) yields a not-visible, not-callable verdict whose only failing step is profile.
func (*MCPProxyServer) Explain ¶ added in v0.70.0
func (p *MCPProxyServer) Explain(_ context.Context, subject profile.AccessSubject, tool string) (*runtime.AccessExplanation, error)
Explain implements runtime.ProfileEvaluator.
func (*MCPProxyServer) GetCallToolServer ¶ added in v0.21.0
func (p *MCPProxyServer) GetCallToolServer() *mcpserver.MCPServer
GetCallToolServer returns the call tool mode MCP server instance.
func (*MCPProxyServer) GetCodeExecServer ¶ added in v0.21.0
func (p *MCPProxyServer) GetCodeExecServer() *mcpserver.MCPServer
GetCodeExecServer returns the code execution mode MCP server instance.
func (*MCPProxyServer) GetDirectServer ¶ added in v0.21.0
func (p *MCPProxyServer) GetDirectServer() *mcpserver.MCPServer
GetDirectServer returns the direct mode MCP server instance.
func (*MCPProxyServer) GetMCPServer ¶
func (p *MCPProxyServer) GetMCPServer() *mcpserver.MCPServer
GetMCPServer returns the underlying MCP server for serving
func (*MCPProxyServer) GetMCPServerForMode ¶ added in v0.21.0
func (p *MCPProxyServer) GetMCPServerForMode(mode string) *mcpserver.MCPServer
GetMCPServerForMode returns the MCP server instance for the given routing mode. Falls back to the default retrieve_tools server for unknown modes.
func (*MCPProxyServer) HoldProfileNotifications ¶ added in v0.70.0
func (p *MCPProxyServer) HoldProfileNotifications() (release func())
HoldProfileNotifications implements runtime.ProfileSessionHook: a rename holds the list_changed delivery until its session rewrite has run, so the re-list it triggers follows the rename instead of clearing the old-name selection.
func (*MCPProxyServer) IncludeDisabledCalls ¶ added in v0.32.0
func (p *MCPProxyServer) IncludeDisabledCalls() int64
IncludeDisabledCalls reports how many retrieve_tools calls opted into include_disabled this process lifetime. Test/observability only.
func (*MCPProxyServer) NewAccessEvaluator ¶ added in v0.70.0
func (p *MCPProxyServer) NewAccessEvaluator(subject profile.AccessSubject) (*AccessEvaluator, error)
NewAccessEvaluator resolves the subject.
- profile: the profile's own reach, as a /mcp/p/<slug> request resolves it. The credential and token_permission steps are skipped.
- client, credential state client: the credential record's binding through the real resolver (locked -> source pin, switchable -> source binding).
- client, admin_key: evaluated as administrator (the client holds the admin key; no profile applies).
- client, none: evaluated as the anonymous caller its keyless connection would be: refused outright under require_mcp_auth, otherwise resolved through anonymous_profile and the FR-008a binding guard.
- client, revoked / expired (or an unreadable record): the credential step fails for every row.
func (*MCPProxyServer) NotifyBindingChanged ¶ added in v0.70.0
func (p *MCPProxyServer) NotifyBindingChanged(tokenName string)
NotifyBindingChanged implements runtime.BindingNotifier (Spec 108 FR-026, plan D18): for every live session authenticated by the named token it clears the stored set_profile selection and sends notifications/tools/list_changed on the server instance that serves the session. It runs synchronously, so the clearing is complete before the binding mutation returns — enforcement never depends on delivery (every request re-resolves against the credential's current binding, FR-020), but no stale selection window is left either.
func (*MCPProxyServer) NotifyUpstreamInventoryChanged ¶ added in v0.70.0
func (p *MCPProxyServer) NotifyUpstreamInventoryChanged()
NotifyUpstreamInventoryChanged pushes tools/list_changed to every session on the retrieve_tools-shaped surfaces when the set of reachable servers changed, so clients re-list and pick up the new retrieve_tools description. Guarded on a real change: an unconditional push would make every servers.changed event (tool reindex, health flap) look like a new tool set. The advertise flag is part of the key, so flipping it re-lists too.
func (*MCPProxyServer) ProfileDeleted ¶ added in v0.70.0
func (p *MCPProxyServer) ProfileDeleted(name string)
ProfileDeleted implements runtime.ProfileSessionHook: a selection of a deleted profile is cleared (the session falls back to its base).
func (*MCPProxyServer) ProfileRenamed ¶ added in v0.70.0
func (p *MCPProxyServer) ProfileRenamed(from, to string)
ProfileRenamed implements runtime.ProfileSessionHook: the stored set_profile selection of every session that had selected the old name follows the rename.
func (*MCPProxyServer) ProfileTokensMoved ¶ added in v0.70.0
func (p *MCPProxyServer) ProfileTokensMoved(tokenNames []string)
ProfileTokensMoved implements runtime.ProfileSessionHook: the sessions of a token whose pin a delete-with-reassign moved get the FR-026 treatment (their stored selection is cleared and each is re-listed).
func (*MCPProxyServer) RefreshCallToolModeTools ¶ added in v0.61.0
func (p *MCPProxyServer) RefreshCallToolModeTools()
RefreshCallToolModeTools rebuilds the call-tool mode server's tool set.
UX audit F16: callToolServer is the surface behind /mcp in the DEFAULT routing mode (retrieve_tools), and its tools were registered exactly once in initRoutingModeServers. Its code_execution entry is therefore the one a client sees, and a hot enable_code_execution toggle had no way to replace it. buildCallToolModeTools reads the live config snapshot, so re-running it on config.reloaded swaps the disabled stub for the live tool (and back).
func (*MCPProxyServer) RefreshCodeExecModeTools ¶ added in v0.21.0
func (p *MCPProxyServer) RefreshCodeExecModeTools()
RefreshCodeExecModeTools rebuilds the code execution mode server's tool catalog description. Should be called when upstream servers change to update the available tools listing.
func (*MCPProxyServer) RefreshCodeExecutionAvailability ¶ added in v0.61.0
func (p *MCPProxyServer) RefreshCodeExecutionAvailability()
RefreshCodeExecutionAvailability re-advertises code_execution on every tool surface that carries it, so an enable_code_execution flip applies without a restart (UX audit F16, issue #1236). directServer is deliberately absent — direct mode does not expose code_execution at all.
The routing-mode surfaces are rebuilt through their content-guarded refreshers, so only a real flip re-registers and notifies. The default/stdio surface (p.server) is updated IN PLACE: its tool set is assembled once by registerTools and SetTools would drop everything else. A flip on adds the live tool with AddTools; a flip off withdraws it with DeleteTools. Both push notifications/tools/list_changed, and neither runs when the surface already matches the flag — mcp-go's AddTools notifies even for an empty batch, so an unguarded call would announce a change on every unrelated reload.
func (*MCPProxyServer) RefreshDirectModeTools ¶ added in v0.21.0
func (p *MCPProxyServer) RefreshDirectModeTools()
RefreshDirectModeTools rebuilds the direct mode server's tool set. Should be called when upstream servers change (connect/disconnect/tool updates).
func (*MCPProxyServer) RefreshDirectModeToolsOnSerializationChange ¶ added in v0.63.0
func (p *MCPProxyServer) RefreshDirectModeToolsOnSerializationChange()
RefreshDirectModeToolsOnSerializationChange rebuilds the direct surface iff the operator's serialization choice has actually moved.
Exported for the config.reloaded listener, which must not simply call RefreshDirectModeTools: that would re-register every tool and push a notifications/tools/list_changed to every connected client on any config edit at all — a "no changes for you" reload that looks, to a client, exactly like the tool set having changed.
func (*MCPProxyServer) RefreshPrompts ¶ added in v0.59.0
func (p *MCPProxyServer) RefreshPrompts()
RefreshPrompts rebuilds every routing-mode server's prompt set: the built-in prompts, plus (only when aggregate_upstream_prompts is enabled) every prompt aggregated from connected upstream servers. Should be called when upstream servers change (connect/disconnect) or on config hot-reload. A no-op when prompts are disabled entirely.
func (*MCPProxyServer) ResolveProfileV3 ¶ added in v0.70.0
func (p *MCPProxyServer) ResolveProfileV3(ctx context.Context, idx *profileIndex) ProfileResolution
ResolveProfileV3 is the FR-020 resolution: highest wins — pin > url > session > binding > anonymous > none — against idx's (index, snapshot) pair. Profile v3 discovery and execution use this single result so the effective server scope, policy, and source cannot come from separate snapshots. Legacy surfaces not yet migrated can still use resolveActiveProfileFromIndex.
func (*MCPProxyServer) RunPreflight ¶ added in v0.58.0
func (p *MCPProxyServer) RunPreflight(ctx context.Context, params preflight.Params) (preflight.Outcome, error)
RunPreflight evaluates one preflight request against local state only.
Errors: preflight.ErrRuntimeUnavailable when the process cannot evaluate honestly, preflight.ErrUnknownProfile for a profile the config does not define, and a wrapped infrastructure error for a failed index/storage/config read — the served surface maps those to 503 rather than fabricating a reason code (FR-006).
func (*MCPProxyServer) RunPreflightForSession ¶ added in v0.58.0
func (p *MCPProxyServer) RunPreflightForSession(ctx context.Context, refs []preflight.ToolRef, filters toolannotations.Filters) (preflight.Outcome, error)
RunPreflightForSession evaluates one IN-BAND preflight — describe_tool check mode (spec 099 FR-003/FR-009/FR-009a).
Two things are pinned here rather than passed in, because they are the security contract of the in-band surface:
- The tier is ALWAYS the agent-token tier. /mcp is unauthenticated by default and its middleware hands such requests a full admin context for back-compat, so no auth context in band proves anything about who is calling; a caller-selectable tier would be a caller-selectable disclosure. Operators wanting scope names and hashes use the REST surface over an authenticated channel (FR-009).
- The scope is the SESSION's, never a request parameter: check mode takes no `profile`, so an agent cannot re-point or widen its own view by asking (FR-009a).
func (*MCPProxyServer) SetAdminViews ¶ added in v0.70.0
func (p *MCPProxyServer) SetAdminViews(v profilesAdminViews)
SetAdminViews installs the REST server's admin views behind the `profiles` tool (called next to httpAPIServer.SetClientsService in server.go).
func (*MCPProxyServer) SetObservability ¶ added in v0.45.0
func (p *MCPProxyServer) SetObservability(obs *observability.Manager)
SetObservability wires the observability manager used to record tool-call metrics and OTLP spans (MCP-32). Safe to call with nil to leave disabled.
func (*MCPProxyServer) ToolCounts ¶ added in v0.70.0
func (p *MCPProxyServer) ToolCounts(ctx context.Context, name string, viewer runtime.ViewerScope) runtime.ToolCounts
ToolCounts implements runtime.ProfileEvaluator: the visible tools of the named profile by the tier the profile gives them, plus the unannotated tools it hides. An administrator's counts are memoized per published snapshot; a restricted viewer's are computed per request over the servers it may see.
func (*MCPProxyServer) TryProfile ¶ added in v0.70.0
func (p *MCPProxyServer) TryProfile(ctx context.Context, draft config.ProfileConfig, query string, limit int) (*runtime.TryResult, error)
TryProfile implements runtime.ProfileEvaluator: what retrieve_tools would return under a DRAFT profile, filtered before the limit exactly as the real call filters, plus what the draft hides. Nothing is persisted.
type MissingRequiredInputError ¶ added in v0.35.0
type MissingRequiredInputError struct {
Names []string
}
MissingRequiredInputError is returned when the registry entry declares required inputs that the request did not supply. It carries the missing names so surfaces can tell the user exactly what to provide.
func (*MissingRequiredInputError) Error ¶ added in v0.35.0
func (e *MissingRequiredInputError) Error() string
type PermissionError ¶
PermissionError represents a permission-related error (exit code 5)
func (*PermissionError) Error ¶
func (e *PermissionError) Error() string
func (*PermissionError) Unwrap ¶
func (e *PermissionError) Unwrap() error
type PortInUseError ¶
PortInUseError indicates that the requested listen address is already occupied.
func (*PortInUseError) Error ¶
func (e *PortInUseError) Error() string
func (*PortInUseError) Unwrap ¶
func (e *PortInUseError) Unwrap() error
type ProfileResolution ¶ added in v0.70.0
type ProfileResolution struct {
// Name is the resolved profile's slug, "" for source "none" or a
// switchable binding/anonymous confinement whose base is "All servers"
// (empty pin, legacy any-selectable).
Name string
// Source is one of the profile.Source* constants: pin, binding, url,
// session, anonymous, none.
Source string
// Scope is the resolved profile's server scope; nil for "none" and for
// the empty-pin "All servers" binding/anonymous case.
Scope *profile.ProfileScope
// Policy is the resolved profile's compiled policy; nil whenever Scope
// is nil, and also for a dangling base (a name that no longer resolves).
Policy *profile.CompiledPolicy
// Base is the bound or anonymous base profile used for switchable_to
// admission — "" for sources url/session/none, and for a source
// pin/binding/anonymous whose base is "All servers" (empty pin).
Base string
// BindingGuarded marks the FR-008a anonymous deny-all resolution when the
// anonymous base is empty. Callers that shape management or code-execution
// capabilities use this alongside Base so an empty anonymous_profile cannot
// retain the legacy administrator-shaped view.
BindingGuarded bool
}
ProfileResolution is the per-request Spec 108-c resolution result (data-model.md §4): one call returns the effective profile, WHERE it came from, and the (scope, policy) pair to decide against — never a second, independent lookup for any of the three.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps the MCP proxy server with all its dependencies
func NewServerWithConfigPath ¶
func NewServerWithConfigPath(cfg *config.Config, configPath string, logger *zap.Logger, opts ...ServerOption) (*Server, error)
NewServerWithConfigPath creates a new server instance with explicit config path tracking
func (*Server) AddRegistrySource ¶ added in v0.36.0
func (s *Server) AddRegistrySource(req *AddRegistrySourceRequest) (*config.RegistryEntry, error)
AddRegistrySource validates the request, derives a custom/unverified registry entry, and persists it into cfg.Registries via copy-on-write UpdateConfig (see the runtime-config-snapshot-cow rule). Returns the persisted entry.
func (*Server) AddRegistrySourceRef ¶ added in v0.36.0
func (s *Server) AddRegistrySourceRef(rawURL, protocol, id, name string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
AddRegistrySourceRef is the surface-facing adapter over AddRegistrySource. On failure it projects the typed error onto the stable cross-surface contracts.RegistryAddError so REST/MCP/CLI report the same code.
func (*Server) AddServer ¶
AddServer adds a new upstream server to the configuration. New servers are quarantined by default for security.
Spec 116: the add is one config commit — the live config, storage and the file all hold the server when this returns.
func (*Server) AddServerFromRegistry ¶ added in v0.35.0
func (s *Server) AddServerFromRegistry(ctx context.Context, req *AddFromRegistryRequest) (*config.ServerConfig, error)
AddServerFromRegistry resolves the referenced registry server, re-derives a validated config.ServerConfig server-side, and persists it quarantined.
func (*Server) AddServerFromRegistryRef ¶ added in v0.35.0
func (s *Server) AddServerFromRegistryRef(ctx context.Context, registryID, serverID, name string, env map[string]string, enabled *bool) (*config.ServerConfig, *contracts.RegistryAddError, error)
AddServerFromRegistryRef is the surface-facing adapter over the keystone AddServerFromRegistry. It builds the reference request from primitive args (so callers across the import graph need not depend on the server-internal request type), and on failure projects the typed error into a stable cross-surface contracts.RegistryAddError (CN-001) so REST/MCP/CLI report the same code. On success the second return is nil.
func (*Server) AggregateToolUsage ¶ added in v0.33.0
AggregateToolUsage rolls up tool_call activity per (server,tool) since the given time (spec 050).
func (*Server) ApplyConfig ¶
func (s *Server) ApplyConfig(cfg *config.Config, cfgPath string) (*runtime.ConfigApplyResult, error)
ApplyConfig applies a new configuration. It is the single funnel behind PATCH /config, POST /config/apply and PATCH /config/docker-isolation, so the FR-008a binding guard lives here: a write that would let a client bound to a named profile escape it while require_mcp_auth is off returns *runtime.BindingGuardError and writes nothing. File-watcher reloads (hand edits) are not refused; the runtime guard in ResolveProfileV3 covers them.
func (*Server) ApproveAllTools ¶ added in v0.21.0
ApproveAllTools approves all pending/changed tools for a server (Spec 032).
func (*Server) ApproveAllToolsAt ¶ added in v0.71.0
func (s *Server) ApproveAllToolsAt(serverName string, approvedBy string, expectedIncarnation int64) (int, error)
ApproveAllToolsAt is ApproveAllTools bound to expectedIncarnation.
func (*Server) ApproveAllToolsReviewed ¶ added in v0.71.0
func (s *Server) ApproveAllToolsReviewed(serverName string, expected map[string]string, approvedBy string) (int, error)
ApproveAllToolsReviewed approves every pending/changed tool bound to the reviewed fingerprints (Spec 117 PR-2); expected == nil is ApproveAllTools.
func (*Server) ApproveAllToolsReviewedAt ¶ added in v0.71.0
func (s *Server) ApproveAllToolsReviewedAt(serverName string, expected map[string]string, approvedBy string, expectedIncarnation int64) (int, error)
ApproveAllToolsReviewedAt is ApproveAllToolsReviewed also bound to the reviewed server incarnation.
func (*Server) ApproveTools ¶ added in v0.21.0
ApproveTools approves specific tools for a server (Spec 032).
func (*Server) ApproveToolsAt ¶ added in v0.71.0
func (s *Server) ApproveToolsAt(serverName string, toolNames []string, approvedBy string, expectedIncarnation int64) error
ApproveToolsAt is ApproveTools bound to expectedIncarnation.
func (*Server) ApproveToolsReviewed ¶ added in v0.71.0
func (s *Server) ApproveToolsReviewed(serverName string, toolNames []string, expected map[string]string, approvedBy string) (int, error)
ApproveToolsReviewed approves the named tools bound to the reviewed fingerprints (Spec 117 PR-2); expected == nil is ApproveTools.
func (*Server) ApproveToolsReviewedAt ¶ added in v0.71.0
func (s *Server) ApproveToolsReviewedAt(serverName string, toolNames []string, expected map[string]string, approvedBy string, expectedIncarnation int64) (int, error)
ApproveToolsReviewedAt is ApproveToolsReviewed also bound to the reviewed server incarnation (Spec 116 + Spec 117 PR-2).
func (*Server) Attention ¶ added in v0.70.0
func (s *Server) Attention() []contracts.AttentionItem
Attention returns the current needs-attention list (Spec 109 FR-001), the same snapshot the runtime's debounced subscriber maintains.
func (*Server) BlockAllTools ¶ added in v0.39.0
BlockAllTools atomically blocks (approve+disable) all pending/changed tools for a server (MCP-2198).
func (*Server) BlockAllToolsAt ¶ added in v0.71.0
func (s *Server) BlockAllToolsAt(serverName string, blockedBy string, expectedIncarnation int64) (int, error)
BlockAllToolsAt is BlockAllTools bound to expectedIncarnation.
func (*Server) BlockTools ¶ added in v0.39.0
BlockTools atomically blocks (approve+disable) specific tools (MCP-2198).
func (*Server) BlockToolsAt ¶ added in v0.71.0
func (s *Server) BlockToolsAt(serverName string, toolNames []string, blockedBy string, expectedIncarnation int64) (int, error)
BlockToolsAt is BlockTools bound to expectedIncarnation.
func (*Server) CallTool ¶
func (s *Server) CallTool(ctx context.Context, toolName string, arguments map[string]interface{}) (interface{}, error)
CallTool calls an MCP tool and returns the result
func (*Server) DefaultInstructions ¶ added in v0.39.0
DefaultInstructions returns the built-in default MCP instructions text, independent of any user-configured custom value. It backs the /api/v1/status `default_instructions` field so the Web UI can render the built-in default as the instructions placeholder without hardcoding the text (MCP-2176). This mirrors resolveInstructions("").
func (*Server) DiscoverServerTools ¶
DiscoverServerTools triggers manual tool discovery for a specific server. This backs the explicit REST operator actions (POST .../discover-tools and its .../refresh alias), so it uses the AUTHORITATIVE refresh path (issue #873): a server that now reports zero tools has its stale index entries removed rather than silently retained.
func (*Server) EditRegistrySource ¶ added in v0.37.0
func (s *Server) EditRegistrySource(req *EditRegistrySourceRequest) (*config.RegistryEntry, error)
EditRegistrySource applies the requested updates to a user-added custom registry by id and persists the change via copy-on-write UpdateConfig (see the runtime-config-snapshot-cow rule). Returns the updated entry.
func (*Server) EditRegistrySourceRef ¶ added in v0.37.0
func (s *Server) EditRegistrySourceRef(id, name, rawURL, serversURL string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
EditRegistrySourceRef is the surface-facing adapter over EditRegistrySource. On failure it projects the typed error onto the stable cross-surface contracts.RegistryAddError so REST/CLI report the same code.
func (*Server) EmitActiveProfileChanged ¶ added in v0.46.0
EmitActiveProfileChanged broadcasts an active_profile.changed event so UI surfaces (Web UI, tray) reflect a default-profile switch made by another client (Profiles v2 T2/T5). The REST handler invokes this via an optional capability assertion, so adding it here does not widen the httpapi ServerController interface.
func (*Server) EnableServer ¶
EnableServer enables/disables a server and ensures all state is synchronized. It acts as the entry point for changes originating from the UI or API.
func (*Server) EventsChannel ¶
EventsChannel exposes runtime events for tray/UI consumers. Deprecated: Use SubscribeEvents for per-client subscriptions to avoid event competition.
func (*Server) ForceReconnectAllServers ¶
ForceReconnectAllServers triggers reconnection attempts for all managed servers.
func (*Server) GetActivationFirstMCPClient ¶ added in v0.29.0
GetActivationFirstMCPClient returns Spec 044's FirstMCPClientEver flag and the capped list of recognized client names. Used by the v2 onboarding wizard (Spec 046 v2) to drive the Verify tab. Nil-safe: when telemetry isn't wired (e.g. CI/test) returns (false, nil).
func (*Server) GetActivity ¶
func (s *Server) GetActivity(id string) (*storage.ActivityRecord, error)
GetActivity returns a single activity record by ID.
func (*Server) GetAllServers ¶
GetAllServers returns information about all upstream servers for tray UI. Phase 6: Uses lock-free StateView for instant responses (<1ms) even during tool indexing.
func (*Server) GetConfigPath ¶
GetConfigPath returns the path to the configuration file for file watching
func (*Server) GetCurrentConfig ¶
GetCurrentConfig returns the current configuration
func (*Server) GetDesiredConfig ¶ added in v0.63.0
GetDesiredConfig returns the configuration as persisted on disk — what the next start will use. Read-modify-write callers must merge onto this one; see Runtime.GetDesiredConfig.
func (*Server) GetDockerRecoveryStatus ¶
func (s *Server) GetDockerRecoveryStatus() *storage.DockerRecoveryState
GetDockerRecoveryStatus returns the current Docker recovery status
func (*Server) GetListenAddress ¶
GetListenAddress returns the address the server is listening on
func (*Server) GetManagementService ¶
func (s *Server) GetManagementService() management.Service
GetManagementService returns the management service instance from runtime. Returns nil if service hasn't been set yet.
func (*Server) GetOnboardingState ¶ added in v0.29.0
func (s *Server) GetOnboardingState() (*storage.OnboardingState, error)
GetOnboardingState returns the wizard engagement state (Spec 046).
func (*Server) GetQuarantinedServers ¶
GetQuarantinedServers returns information about quarantined servers for tray UI
func (*Server) GetRecentSessions ¶
func (s *Server) GetRecentSessions(f storage.SessionFilter) ([]*contracts.MCPSession, int, error)
GetRecentSessions retrieves recent MCP sessions, optionally filtered by status ("active" / "closed"; empty means no filter).
func (*Server) GetReviewQueue ¶ added in v0.70.0
GetReviewQueue forwards the REST review read through the production server controller to the runtime implementation. The HTTP API is mounted with *Server as its controller, so handler-level tests alone do not prove this adapter is wired.
func (*Server) GetSecretResolver ¶
GetSecretResolver returns the secret resolver instance
func (*Server) GetServerLogs ¶
GetServerLogs returns recent log lines for a specific server
func (*Server) GetServerReview ¶ added in v0.70.0
func (s *Server) GetServerReview(ctx context.Context, serverName string) (*runtime.ServerReview, error)
GetServerReview forwards the scoped REST review read to the runtime.
func (*Server) GetServerToolCalls ¶
func (s *Server) GetServerToolCalls(serverName string, limit int) ([]*contracts.ToolCallRecord, error)
GetServerToolCalls retrieves tool call history for a specific server
func (*Server) GetServerTools ¶
GetServerTools returns tools for a specific server
func (*Server) GetSessionByID ¶
func (s *Server) GetSessionByID(sessionID string) (*contracts.MCPSession, error)
GetSessionByID retrieves a session by its ID
func (*Server) GetStatus ¶
func (s *Server) GetStatus() interface{}
GetStatus returns the current server status
func (*Server) GetTokenSavings ¶
func (s *Server) GetTokenSavings() (*contracts.ServerTokenMetrics, error)
GetTokenSavings calculates and returns token savings statistics
func (*Server) GetToolApproval ¶ added in v0.21.0
func (s *Server) GetToolApproval(serverName, toolName string) (*storage.ToolApprovalRecord, error)
GetToolApproval returns the approval record for a specific tool (Spec 032).
func (*Server) GetToolApprovalStatus ¶ added in v0.23.0
GetToolApprovalStatus returns the approval status string for a specific tool.
func (*Server) GetToolCallByID ¶
func (s *Server) GetToolCallByID(id string) (*contracts.ToolCallRecord, error)
GetToolCallByID retrieves a single tool call by ID
func (*Server) GetToolCalls ¶
func (s *Server) GetToolCalls(limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
GetToolCalls retrieves tool call history with pagination. scope restricts the result to a set of server names (nil = unrestricted).
func (*Server) GetToolCallsBySession ¶
func (s *Server) GetToolCallsBySession(sessionID string, limit, offset int, scope storage.ToolCallScope) ([]*contracts.ToolCallRecord, int, error)
GetToolCallsBySession retrieves tool calls filtered by session ID. scope restricts the result to a set of server names (nil = unrestricted).
func (*Server) GetUpstreamStats ¶
GetUpstreamStats returns statistics about upstream servers
func (*Server) GetVersionInfo ¶
func (s *Server) GetVersionInfo() *updatecheck.VersionInfo
GetVersionInfo returns the current version information from the update checker.
func (*Server) IsDockerAvailable ¶ added in v0.39.0
IsDockerAvailable reports whether the host has a reachable Docker daemon via a real probe. The /api/v1/docker/status endpoint uses this for genuine availability rather than the synthetic recovery-state value (MCP-2478).
func (*Server) IsReady ¶
IsReady returns whether the server is fully initialized and ready to serve requests
func (*Server) IsToolConfigDenied ¶ added in v0.32.0
IsToolConfigDenied reports whether toolName is denied by the server's static enabled_tools / disabled_tools config.
func (*Server) ListActivities ¶
func (s *Server) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)
ListActivities returns activity records matching the filter.
func (*Server) ListRegistries ¶
ListRegistries returns the list of available MCP server registries (Phase 7)
func (*Server) ListToolApprovals ¶ added in v0.21.0
func (s *Server) ListToolApprovals(serverName string) ([]*storage.ToolApprovalRecord, error)
ListToolApprovals returns tool approval records for a server (Spec 032).
func (*Server) MutateConfig ¶ added in v0.70.0
func (s *Server) MutateConfig( ctx context.Context, actor runtime.Actor, mutate func(desired *config.Config) (runtime.ChangeHint, error), tokens runtime.TokenRewrite, ) (*runtime.ConfigApplyResult, *runtime.ConfigDiff, error)
MutateConfig is the config funnel (Spec 108-f F2): the read of the desired config, the caller's mutation, the FR-008a guard, an optional token re-pin and the write run under one lock, and the write's profile_change records are attributed to actor. PATCH /config, POST /config/apply, PATCH /config/docker-isolation and every profiles-service mutation go through it.
func (*Server) NotifySecretsChanged ¶
NotifySecretsChanged notifies the runtime that secrets have changed
func (*Server) OnUpstreamServerChange ¶
func (s *Server) OnUpstreamServerChange()
OnUpstreamServerChange should be called when upstream servers are modified
func (*Server) PatchServer ¶ added in v0.71.0
func (s *Server) PatchServer(ctx context.Context, serverName string, resolve func(cur *config.ServerConfig) (*config.ServerConfig, error)) error
PatchServer is UpdateServer whose partial update is resolved inside the commit, against a copy of the live entry (Spec 116 FR-006): resolve sees the current server and returns the update to apply. The REST PATCH handler resolves omitted fields, map merges, isolation and forward-header validation this way, so a PATCH parked before the commit cannot revert a newer write. An error from resolve aborts the commit with nothing written.
func (*Server) QuarantineServer ¶
QuarantineServer quarantines/unquarantines a server
func (*Server) QuarantineServerAt ¶ added in v0.71.0
func (s *Server) QuarantineServerAt(serverName string, quarantined bool, expectedIncarnation int64) error
QuarantineServerAt is QuarantineServer bound to expectedIncarnation (the unquarantine endpoint's expected_incarnation).
func (*Server) RecordPreflight ¶ added in v0.58.0
func (s *Server) RecordPreflight(rec runtime.PreflightActivity) error
RecordPreflight writes one preflight's activity record synchronously and returns the write error (Spec 098 FR-014). It is exposed on the controller surface because the served preflight must persist the record BEFORE it answers 200 — a failure here is a 503, not a logged warning.
func (*Server) RecordStartupOutcome ¶ added in v0.71.0
RecordStartupOutcome stores the Spec 042 last startup outcome in the telemetry block through the runtime's config commit (#1592).
func (*Server) RecordUpdateFailure ¶ added in v0.56.0
RecordUpdateFailure records one desktop auto-update failure occurrence (spec 095 FR-011/FR-012/FR-013). Gate evaluation and the durable increment happen inside one call so no window exists where telemetry is disabled between the two — an occurrence during opt-out can never become transmissible later.
recorded=false means the gate was closed at event time and nothing was persisted; that is a deliberate no-op, and the caller still answers 204.
func (*Server) RefreshRegistryCache ¶ added in v0.35.0
RefreshRegistryCache invalidates a registry's cached server lists (spec 070 FR-007).
func (*Server) RefreshVersionInfo ¶
func (s *Server) RefreshVersionInfo() *updatecheck.VersionInfo
RefreshVersionInfo performs an immediate update check and returns the result.
func (*Server) ReloadConfiguration ¶
ReloadConfiguration reloads the configuration from disk
func (*Server) RemoveRegistrySource ¶ added in v0.37.0
func (s *Server) RemoveRegistrySource(id string) (*config.RegistryEntry, error)
RemoveRegistrySource removes a user-added custom registry by id and persists the change through one config commit (Spec 116). Returns the removed entry.
func (*Server) RemoveRegistrySourceRef ¶ added in v0.37.0
func (s *Server) RemoveRegistrySourceRef(id string) (*config.RegistryEntry, *contracts.RegistryAddError, error)
RemoveRegistrySourceRef is the surface-facing adapter over RemoveRegistrySource. On failure it projects the typed error onto the stable cross-surface contracts.RegistryAddError so REST/CLI report the same code.
func (*Server) RemoveServer ¶
RemoveServer removes an upstream server from the configuration. This stops the server if running and removes it from storage.
Spec 116: the removal is one config commit — the live config, the storage row and its whole purge set (PR2: tool and prompt approvals, OAuth state, scan results, baseline, history), the file and the search index lose the server together, the refresh schedule and other in-memory state are dropped, and the manager instance is unregistered before this returns. There is no cleanup after the commit for a crash or a concurrent writer to skip.
func (*Server) ReplayToolCall ¶
func (s *Server) ReplayToolCall(ctx context.Context, id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)
ReplayToolCall replays a tool call with modified arguments. ctx is the caller's request context: it governs the concurrency-limiter queue wait as well as the upstream call (spec 093 FR-005).
Spec 107 FR-012 (round-2 cross-review finding, PR-D): replay reaches a (server, tool) pair like every other upstream dispatch path, so it MUST produce exactly one `authz` line and, unless shed by the limiter, one `tool_call` line — this endpoint previously wrote neither, because runtime.ReplayToolCall calls the managed client directly and has no access to the server's audit sink. The lookup here is best-effort and duplicates runtime.ReplayToolCall's own (a second, cheap read of the same stored record): if it fails, the call is delegated unaudited exactly as before — runtime.ReplayToolCall's own not-found error is authoritative, and no `(server, tool)` pair was ever resolved to audit.
func (*Server) ResolveViewAs ¶ added in v0.70.0
func (s *Server) ResolveViewAs(subject profile.AccessSubject) (httpapi.ViewAsEvaluator, error)
ResolveViewAs implements the optional view-as capability of the REST controller (GET /api/v1/tools?client= / ?profile=, Spec 108 FR-032): it resolves the subject once and hands back the access-chain evaluator.
func (*Server) RestartServer ¶
RestartServer restarts an upstream server
func (*Server) RunPreflight ¶ added in v0.58.0
func (s *Server) RunPreflight(ctx context.Context, params preflight.Params) (preflight.Outcome, error)
RunPreflight exposes the preflight evaluator on the ServerController surface the REST layer talks to (precedent: GetToolApprovalStatus). internal/httpapi never touches index/storage/stateview directly.
func (*Server) SaveConfiguration ¶
SaveConfiguration saves the current configuration to the persistent config file
func (*Server) SaveOnboardingState ¶ added in v0.29.0
func (s *Server) SaveOnboardingState(state *storage.OnboardingState) error
SaveOnboardingState persists the wizard engagement state (Spec 046).
func (*Server) SearchRegistryServers ¶
func (s *Server) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, *contracts.RegistryCacheInfo, error)
SearchRegistryServers searches for servers in a specific registry (Phase 7)
func (*Server) SearchTools ¶
SearchTools searches for tools using the index
func (*Server) SearchToolsForProfile ¶ added in v0.70.0
func (s *Server) SearchToolsForProfile(ctx context.Context, query string, limit int, inScope func(string) bool) (results []map[string]interface{}, handled bool, err error)
SearchToolsForProfile performs REST tool search with the same profile policy and pre-limit admission used by retrieve_tools. handled is false when no v3 profile resolution applies, preserving the existing search path.
func (*Server) SearchToolsScoped ¶ added in v0.68.0
func (s *Server) SearchToolsScoped(query string, limit int, inScope func(serverName string) bool) ([]map[string]interface{}, error)
SearchToolsScoped is SearchTools for a scoped caller (Spec 107 T075a): the same ranked search, filtered to servers inScope admits BEFORE the top-K cut, so a hidden higher-ranking server cannot displace an entitled hit and the caller's window is the top-`limit` of what they may see. Quarantine withholding is applied inside the predicate too, so a quarantined server's hits never occupy a slot either. Unscoped callers keep SearchTools untouched.
func (*Server) ServeErr ¶ added in v0.52.0
ServeErr delivers a fatal serve failure: a startup bind error (e.g. *PortInUseError) or a serve-loop death after start. Graceful shutdown (context cancellation, http.ErrServerClosed) never fires it.
func (*Server) ServedRoutingMode ¶ added in v0.63.0
ServedRoutingMode returns the routing mode /mcp actually bound at startup.
func (*Server) ServerIncarnation ¶ added in v0.71.0
ServerIncarnation returns serverName's committed incarnation (Spec 116 FR-017); the REST tool listings stamp it on their rows.
func (*Server) SetAllToolsEnabled ¶ added in v0.31.0
SetAllToolsEnabled bulk-toggles every known tool for a server to the given state. Returns the count of tools whose state actually changed.
func (*Server) SetAllToolsEnabledAt ¶ added in v0.71.0
func (s *Server) SetAllToolsEnabledAt(serverName string, enabled bool, updatedBy string, expectedIncarnation int64) (int, error)
SetAllToolsEnabledAt is SetAllToolsEnabled bound to expectedIncarnation.
func (*Server) SetListenAddress ¶
SetListenAddress updates the configured listen address and optionally persists it to disk.
func (*Server) SetShutdownInfo ¶
SetShutdownInfo sets the reason and signal for shutdown (Spec 024). Call this before Shutdown() to include shutdown context in activity logs.
func (*Server) SetToolEnabled ¶ added in v0.29.3
SetToolEnabled sets whether a tool is enabled for MCP exposure (Spec 032).
func (*Server) SetToolEnabledAt ¶ added in v0.71.0
func (s *Server) SetToolEnabledAt(serverName, toolName string, enabled bool, updatedBy string, expectedIncarnation int64) error
SetToolEnabledAt is SetToolEnabled bound to expectedIncarnation.
func (*Server) StartServer ¶
StartServer starts the server if it's not already running
func (*Server) StatusChannel ¶
func (s *Server) StatusChannel() <-chan interface{}
StatusChannel returns a channel that receives status updates
func (*Server) StopServer ¶
StopServer stops the server if it's running
func (*Server) StreamActivities ¶
func (s *Server) StreamActivities(ctx context.Context, filter storage.ActivityFilter) <-chan *storage.ActivityRecord
StreamActivities returns a channel that yields activity records matching the filter.
func (*Server) SubscribeEvents ¶
SubscribeEvents creates a new per-client event subscription channel. Each SSE client should get its own channel to avoid competing for events.
func (*Server) SuggestAlternateListen ¶
SuggestAlternateListen attempts to find an available listen address near baseAddr.
func (*Server) ToolAllowedByProfile ¶ added in v0.70.0
ToolAllowedByProfile is the row-level REST discovery check. It fails closed for dangling or policy-excluded profile resolutions and is a no-op when the request has no effective v3 profile.
func (*Server) TriggerOAuthLogin ¶
TriggerOAuthLogin starts an in-process OAuth flow for the given server name. Used by the tray to avoid cross-process DB locking issues during OAuth.
func (*Server) UnquarantineServer ¶
UnquarantineServer removes a server from quarantine via tray UI
func (*Server) UnsubscribeEvents ¶
UnsubscribeEvents closes and removes the subscription channel.
func (*Server) UpdateOnboardingState ¶ added in v0.70.0
func (s *Server) UpdateOnboardingState(fn func(*storage.OnboardingState) error) error
UpdateOnboardingState runs fn against the current onboarding state and persists it atomically (Spec 109-b).
func (*Server) UpdatePolicy ¶ added in v0.54.0
func (s *Server) UpdatePolicy() updatecheck.Policy
UpdatePolicy returns the effective update policy (Spec 092 FR-015).
func (*Server) UpdateServer ¶ added in v0.23.0
func (s *Server) UpdateServer(ctx context.Context, serverName string, updates *config.ServerConfig) error
UpdateServer applies partial updates to an existing upstream server configuration. Spec 116: one config commit, applied to the LIVE entry read inside the commit lock (so config-only fields such as Shared and AuthBroker survive, and a server removed concurrently is "not found").
func (*Server) UsageSnapshot ¶ added in v0.36.0
func (s *Server) UsageSnapshot() *runtime.UsageAggregate
UsageSnapshot returns the actor-owned usage aggregate snapshot (spec 069 A3).
func (*Server) ValidateConfig ¶
ValidateConfig validates a configuration
type ServerExistsError ¶ added in v0.71.0
type ServerExistsError = runtime.ServerExistsError
ServerExistsError is returned when a create-only add names a server that is already configured. Its text is part of the contract: the REST 409 mapping, cliclient, `upstream add --if-not-exists` and the registry add all match on "already exists". Since Spec 116 the runtime's commit raises it.
type ServerOption ¶ added in v0.68.0
type ServerOption func(*Server)
ServerOption customises a Server at construction time (Spec 107 T103). Distinct from MCPProxyOption (mcp.go), which customises the MCP proxy the Server owns. Every existing caller passes none.
func WithAuditSink ¶ added in v0.68.0
func WithAuditSink(sink audit.Sink) ServerOption
WithAuditSink installs the Spec 107 audit sink. nil (the personal-edition default when audit_log is off) keeps every audit funnel a no-op.
type SessionInfo ¶
type SessionInfo struct {
SessionID string
ClientName string
ClientVersion string
// Workspace is the project the client is working in, as disclosed via MCP
// roots. Filled in asynchronously AFTER the handshake completes (see
// Spec 082) — never during initialize, which would deadlock. Empty for
// clients that do not disclose roots (e.g. Codex).
Workspace string
// TokenName and ClientID identify the credential that authenticated this
// session (Spec 108-c, data-model.md §6): the agent-token/client-
// credential name and, for a client credential, its client id. Both
// empty for an admin/anonymous session. Set once at initialize from the
// AuthContext (SetSessionIdentity) — never re-derived per call, because
// the credential does not change mid-connection.
TokenName string
ClientID string
// TokenPrefix is the credential's 12-char display prefix (Spec 108-j J15).
// It is INTERNAL (never persisted or serialized): the activity funnels with
// no request context read it back so an event carries the same ownership
// proof the SSE renderer checks (name AND prefix).
TokenPrefix string
// Anonymous marks a session that presented no credential (Spec 108-f F10):
// its base is the snapshot's anonymous_profile, read at notify time. Memory
// only, stamped once at initialize.
Anonymous bool
// Profile and ProfileSource are the LATEST effective resolution for this
// session (data-model.md §6 "latest effective, updated on each call").
// The session's BASE (pin, bound profile or anonymous_profile) is
// deliberately not stored here — see UpdateSessionProfile.
Profile string
ProfileSource string
// contains filtered or unexported fields
}
SessionInfo holds MCP session metadata
type SessionRisk ¶ added in v0.22.0
type SessionRisk struct {
Level string `json:"level"` // "high", "medium", "low"
HasOpenWorld bool `json:"has_open_world"` // Any tool with openWorldHint=true or nil
HasDestructive bool `json:"has_destructive"` // Any tool with destructiveHint=true or nil
HasWrite bool `json:"has_write"` // Any tool with readOnlyHint=false or nil
LethalTrifecta bool `json:"lethal_trifecta"` // All three categories present
Warning string `json:"warning,omitempty"`
}
SessionRisk holds the result of analyzing all connected servers' tool annotations for the "lethal trifecta" risk combination (Spec 035 F2).
type SessionStore ¶
type SessionStore struct {
// contains filtered or unexported fields
}
SessionStore manages MCP session information
func NewSessionStore ¶
func NewSessionStore(logger *zap.Logger) *SessionStore
NewSessionStore creates a new session store
func (*SessionStore) AbandonWorkspaceFetch ¶ added in v0.49.0
func (s *SessionStore) AbandonWorkspaceFetch(sessionID string)
AbandonWorkspaceFetch marks the roots answer as never coming, unblocking anything waiting on it.
func (*SessionStore) ClearSelection ¶ added in v0.70.0
func (s *SessionStore) ClearSelection(name string)
ClearSelection drops every stored set_profile selection of the named profile (it was deleted): those sessions fall back to their base.
func (*SessionStore) Count ¶
func (s *SessionStore) Count() int
Count returns the number of open (not soft-closed) sessions
func (*SessionStore) EnsurePersisted ¶ added in v0.49.0
func (s *SessionStore) EnsurePersisted(sessionID string, resolveWorkSession func(*SessionInfo) string) string
EnsurePersisted writes the session to storage the first time it does something real, and blocks concurrent callers until that row exists.
The blocking matters. UpdateSessionStats requires the row and errors if it is missing, so if a second concurrent first-call merely saw "someone else is persisting" and raced on, its stats would be dropped with a warning. It waits instead.
Returns the work-session id this connection belongs to. It is resolved ONCE per connection and reused, so every record from this connection agrees.
func (*SessionStore) GetActiveProfile ¶ added in v0.46.0
func (s *SessionStore) GetActiveProfile(sessionID string) string
GetActiveProfile returns the active profile slug for a session, or "" when the session has no active profile selection.
func (*SessionStore) GetSession ¶
func (s *SessionStore) GetSession(sessionID string) *SessionInfo
GetSession returns a COPY of the session info.
It must be a copy: the roots goroutine writes Workspace under the lock while callers (the workspace resolver, the activity path) read it, and handing out the live pointer is a data race.
func (*SessionStore) NotifyTargets ¶ added in v0.70.0
func (s *SessionStore) NotifyTargets(tokenName string) []sessionTarget
NotifyTargets returns every live session authenticated by tokenName with its serving instance — the FR-026 fan-out seam behind SessionsForToken.
func (*SessionStore) RemoveSession ¶
func (s *SessionStore) RemoveSession(sessionID string)
RemoveSession soft-closes a session (#1205).
The entry is KEPT, marked closed: a client that re-registers on the same id (e.g. a GET stream ending and being re-opened) sends no new initialize, so dropping the entry would lose its client name, workspace, persisted flag and work session for good. The next activity or Reopen revives it; otherwise it is evicted after closedSessionTTL.
Only sessions that were actually persisted are closed in storage. A session that never did any work has no stored record (Spec 082), and asking storage to close it would return "session not found" on every idle disconnect.
func (*SessionStore) RenameSelection ¶ added in v0.70.0
func (s *SessionStore) RenameSelection(from, to string)
RenameSelection rewrites every stored set_profile selection of profile `from` to `to` (a profile rename must not strand a session on a name that no longer exists).
func (*SessionStore) Reopen ¶ added in v0.71.0
func (s *SessionStore) Reopen(sessionID string)
Reopen revives a soft-closed session (the transport re-registered the same id without a new initialize). A no-op for unknown or already-open sessions.
func (*SessionStore) SessionsForToken ¶ added in v0.70.0
func (s *SessionStore) SessionsForToken(tokenName string) []string
SessionsForToken returns the ids of every live session currently authenticated by the named token — the FR-026/FR-027 notification fan-out seam ("send notifications/tools/list_changed to every live MCP session authenticated by that credential"). Order is unspecified.
func (*SessionStore) SessionsMatching ¶ added in v0.70.0
func (s *SessionStore) SessionsMatching(pred func(*SessionInfo) bool) []sessionTarget
SessionsMatching returns every live session for which pred is true, with its serving instance (the FR-027 fan-out seam). pred runs under the store's read lock and must not call back into the store.
func (*SessionStore) SetActiveProfile ¶ added in v0.46.0
func (s *SessionStore) SetActiveProfile(sessionID, profileSlug string)
SetActiveProfile records the active profile slug for a session (Profiles v2 T2, set_profile). An empty slug clears the selection (back to all-servers).
func (*SessionStore) SetSession ¶
func (s *SessionStore) SetSession(sessionID, clientName, clientVersion string, hasRoots, hasSampling bool, experimental []string)
SetSession registers a session in memory at initialize time.
Spec 082: it deliberately does NOT write to storage. A connection earns a durable record by doing something (see EnsurePersisted); one that only shakes hands and leaves — which is what background agents do, every ~15 minutes, around the clock — leaves no trace.
The in-memory entry is still created here, immediately: activity records resolve their client name from this map (SetSessionClientResolver), so deferring it would strip the identity from the very first thing a session does.
func (*SessionStore) SetSessionAnonymous ¶ added in v0.70.0
func (s *SessionStore) SetSessionAnonymous(sessionID string, anonymous bool)
SetSessionAnonymous records whether a session presented no credential.
func (*SessionStore) SetSessionIdentity ¶ added in v0.70.0
func (s *SessionStore) SetSessionIdentity(sessionID, tokenName, clientID string)
SetSessionIdentity records the credential that authenticated a session (Spec 108-c, data-model.md §6): the agent-token/client-credential name and its client id (empty for a regular agent token or an admin/anonymous session). Called once at initialize, from the request's AuthContext — the credential never changes mid-connection, so this is never called again for the same sessionID.
func (*SessionStore) SetSessionServer ¶ added in v0.70.0
func (s *SessionStore) SetSessionServer(sessionID string, srv *mcpserver.MCPServer)
SetSessionServer records the MCP server instance serving a session (the session -> server-instance map, data-model.md §6). Called once at initialize.
func (*SessionStore) SetSessionTokenPrefix ¶ added in v0.70.0
func (s *SessionStore) SetSessionTokenPrefix(sessionID, prefix string)
SetSessionTokenPrefix records the display prefix of the credential that authenticated a session (Spec 108-j J15), next to SetSessionIdentity.
func (*SessionStore) SetStorageManager ¶
func (s *SessionStore) SetStorageManager(manager *storage.Manager)
SetStorageManager sets the storage manager for persistence
func (*SessionStore) SetWorkspace ¶ added in v0.49.0
func (s *SessionStore) SetWorkspace(sessionID, workspaceRoot string)
SetWorkspace records the project this session is working in, discovered by asking the client for its MCP roots after the handshake completed.
If the session has already been persisted (it did some work before the roots answer arrived — a real race, the roots round-trip is not instant), the stored record is updated too, so the project is not lost.
func (*SessionStore) TryClaimWorkspaceFetch ¶ added in v0.49.0
func (s *SessionStore) TryClaimWorkspaceFetch(sessionID string) bool
TryClaimWorkspaceFetch returns true exactly once per session, for the caller that should go and ask the client for its roots. Returns false if there is nothing to fetch (no roots capability, already known) or someone already went.
func (*SessionStore) UpdateActivity ¶ added in v0.21.4
func (s *SessionStore) UpdateActivity(sessionID string)
UpdateActivity updates the last activity timestamp for a session without incrementing stats. A never-persisted session has no row to touch — and must not gain one here, since merely exchanging MCP messages is not "work" (Spec 082): that is exactly what the handshake-only agents do.
func (*SessionStore) UpdateSessionProfile ¶ added in v0.70.0
func (s *SessionStore) UpdateSessionProfile(sessionID, profileName, source string)
UpdateSessionProfile records the LATEST effective profile resolution for a session (data-model.md §6), called after resolving a request's ProfileResolution. The session's BASE is deliberately not stored: it changes on reassignment and rename, so every consumer derives it at use time from TokenName -> the token's current profile_pin, or, for a session with no TokenName, from the snapshot's anonymous_profile — never from a value cached here.
Spec 108 FR-033: a CHANGED resolution of a persisted session is written through to its row (one small write per change, never per call), so /sessions?profile= filters on the latest effective profile. A session that is not persisted yet is copied at EnsurePersisted instead.
func (*SessionStore) UpdateSessionStats ¶
func (s *SessionStore) UpdateSessionStats(sessionID string, tokens int)
UpdateSessionStats updates token usage for a session.
Callers MUST have called EnsurePersisted first: storage refuses to update the stats of a row that does not exist, and under Spec 082 the row is not created until the session does its first piece of work. We skip the write for a never-persisted session rather than logging a warning for it.
func (*SessionStore) WorkSessionID ¶ added in v0.49.0
func (s *SessionStore) WorkSessionID(sessionID string) string
WorkSessionID returns the work session this connection belongs to, if it has been resolved yet.
func (*SessionStore) WorkspaceSettled ¶ added in v0.49.0
func (s *SessionStore) WorkspaceSettled(sessionID string, wait time.Duration)
WorkspaceSettled blocks until the client's roots have arrived, or we have given up waiting, or the deadline passes — whichever comes first.
This exists so the FIRST piece of activity on a connection is not attributed before we know the project. Without it, the first tool call resolves a workspace-less work session and the second (roots having landed in between) resolves a workspace-keyed one: a single connection would split across two work sessions, which is exactly the thing this feature exists to prevent.
type Status ¶
type Status struct {
Phase string `json:"phase"` // Starting, Ready, Error
Message string `json:"message"` // Human readable status message
UpstreamStats map[string]interface{} `json:"upstream_stats"` // Upstream server statistics
ToolsIndexed int `json:"tools_indexed"` // Number of tools indexed
LastUpdated time.Time `json:"last_updated"`
}
Status represents the current status of the server
Source Files
¶
- access_chain.go
- access_explain.go
- activity_result_status.go
- add_from_registry.go
- add_registry_source.go
- audit_funnel.go
- bench_export.go
- cache_authz.go
- code_exec_dispatch.go
- concurrency_shed.go
- config_cow.go
- content_forward.go
- diagnostics_fixers.go
- edit_registry_source.go
- forward_headers.go
- host_validation.go
- listener.go
- listener_linux.go
- listener_mux.go
- listener_permissions_unix.go
- listener_unix.go
- mcp.go
- mcp_activity_args.go
- mcp_activity_attribution.go
- mcp_admin_access.go
- mcp_agent_access.go
- mcp_annotations.go
- mcp_code_execution.go
- mcp_credentials_tool.go
- mcp_credentials_tool_schema.go
- mcp_describe_check.go
- mcp_describe_direct.go
- mcp_describe_tool.go
- mcp_direct_callability.go
- mcp_direct_catalog.go
- mcp_direct_scope.go
- mcp_entry_builder.go
- mcp_input_validation.go
- mcp_max_result_size.go
- mcp_output_schema.go
- mcp_profiles_tool.go
- mcp_profiles_tool_schema.go
- mcp_quarantine_scan.go
- mcp_routing.go
- mcp_server_view.go
- mcp_surface_fingerprint.go
- mcp_tool_policy_result.go
- mcp_trust_mode.go
- mcp_upstream_telemetry.go
- mcp_upstream_writer.go
- mcp_visibility.go
- observability_bridge.go
- observability_edition.go
- open_object_schema.go
- output_sanitisation.go
- output_validation.go
- port.go
- port_unix.go
- preflight_glue.go
- preflight_telemetry.go
- profile_binding_guard.go
- profile_change_notify.go
- profile_evaluator.go
- profile_notify.go
- profile_refusals.go
- profile_resolver.go
- profile_resolver_v3.go
- profile_rest_discovery.go
- profile_tool.go
- profile_tool_dispatch.go
- prompt_quarantine.go
- race_enabled.go
- remove_registry_source.go
- review_capture.go
- scan_bundle_reprotect.go
- scan_informational.go
- scanner_isolation.go
- server.go
- serveredition_wire_stub.go
- session_store.go
- tls_listeners.go
- tool_gate.go
- toon_encode.go
- tpa_bundle_telemetry.go
- tpa_bundle_wiring.go
- ui_redirect.go
- update_failure.go
- view_as.go
- web_ui_handler.go
- workspace.go