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 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) 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) Close() 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) IncludeDisabledCalls() int64
- 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) 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) SetObservability(obs *observability.Manager)
- type MissingRequiredInputError
- type PermissionError
- type PortInUseError
- 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) ApproveTools(serverName string, toolNames []string, approvedBy string) error
- func (s *Server) BlockAllTools(serverName string, blockedBy string) (int, error)
- func (s *Server) BlockTools(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() interface{}
- 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() interface{}
- func (s *Server) GetOnboardingState() (*storage.OnboardingState, error)
- func (s *Server) GetQuarantinedServers() ([]map[string]interface{}, error)
- func (s *Server) GetRecentSessions(limit int, status string) ([]*contracts.MCPSession, int, error)
- func (s *Server) GetSecretResolver() *secret.Resolver
- func (s *Server) GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, 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) NotifySecretsChanged(ctx context.Context, operation, secretName string) error
- func (s *Server) OnUpstreamServerChange()
- func (s *Server) QuarantineServer(serverName string, quarantined bool) error
- func (s *Server) RecordPreflight(rec runtime.PreflightActivity) 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) 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) ServeErr() <-chan error
- func (s *Server) ServedRoutingMode() string
- func (s *Server) SetAllToolsEnabled(serverName string, enabled bool, updatedBy string) (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) 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(filter storage.ActivityFilter) <-chan *storage.ActivityRecord
- func (s *Server) SubscribeEvents() chan runtime.Event
- func (s *Server) SuggestAlternateListen(baseAddr string) (string, error)
- 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) 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 SessionInfo
- type SessionRisk
- type SessionStore
- func (s *SessionStore) AbandonWorkspaceFetch(sessionID 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) RemoveSession(sessionID string)
- func (s *SessionStore) SetActiveProfile(sessionID, profileSlug string)
- func (s *SessionStore) SetSession(sessionID, clientName, clientVersion string, hasRoots, hasSampling bool, ...)
- 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) 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 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
}
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.
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).
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) Close ¶
func (p *MCPProxyServer) Close() error
Close gracefully shuts down the MCP proxy server and releases resources
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) 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) 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) 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) 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.
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 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) (*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.
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
func (*Server) ApproveAllTools ¶ added in v0.21.0
ApproveAllTools approves all pending/changed tools for a server (Spec 032).
func (*Server) ApproveTools ¶ added in v0.21.0
ApproveTools approves specific tools for a server (Spec 032).
func (*Server) BlockAllTools ¶ added in v0.39.0
BlockAllTools atomically blocks (approve+disable) all pending/changed tools for a server (MCP-2198).
func (*Server) BlockTools ¶ added in v0.39.0
BlockTools atomically blocks (approve+disable) specific tools (MCP-2198).
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 ¶
func (s *Server) GetCurrentConfig() interface{}
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() interface{}
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 ¶
GetRecentSessions retrieves recent MCP sessions, optionally filtered by status ("active" / "closed"; empty means no filter).
func (*Server) GetSecretResolver ¶
GetSecretResolver returns the secret resolver instance
func (*Server) GetServerLogs ¶
GetServerLogs returns recent log lines for a specific server
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) 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) QuarantineServer ¶
QuarantineServer quarantines/unquarantines a server
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) 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 via copy-on-write UpdateConfig (see the runtime-config-snapshot-cow rule). 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.
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).
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) 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) 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) 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) 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(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) 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) 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.
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 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
// 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) Count ¶
func (s *SessionStore) Count() int
Count returns the number of active 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) RemoveSession ¶
func (s *SessionStore) RemoveSession(sessionID string)
RemoveSession removes session information.
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 — trading a flood of junk records for a flood of junk warnings.
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) 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) 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
¶
- activity_result_status.go
- add_from_registry.go
- add_registry_source.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
- 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_annotations.go
- mcp_code_execution.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_quarantine_scan.go
- mcp_routing.go
- mcp_server_view.go
- mcp_surface_fingerprint.go
- mcp_tool_policy_result.go
- mcp_trust_mode.go
- mcp_visibility.go
- observability_bridge.go
- observability_edition.go
- output_sanitisation.go
- output_validation.go
- port.go
- port_unix.go
- preflight_glue.go
- preflight_telemetry.go
- profile_resolver.go
- profile_tool.go
- prompt_quarantine.go
- race_enabled.go
- remove_registry_source.go
- scan_informational.go
- server.go
- serveredition_wire_stub.go
- session_store.go
- tool_gate.go
- toon_encode.go
- ui_redirect.go
- update_failure.go
- workspace.go