server

package
v0.22.1-rc.4 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ConnectionSourceTCP  = transport.ConnectionSourceTCP
	ConnectionSourceTray = transport.ConnectionSourceTray
)
View Source
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

This section is empty.

Functions

func FormatDirectToolName added in v0.21.0

func FormatDirectToolName(serverName, toolName string) string

FormatDirectToolName formats a server name and tool name into a direct mode tool name.

func ParseDirectToolName added in v0.21.0

func ParseDirectToolName(directName string) (serverName, toolName string, ok bool)

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 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

func ValidateDataDirectory

func ValidateDataDirectory(dataDir string, logger *zap.Logger) error

ValidateDataDirectory checks that the data directory has secure permissions This is called before creating socket listeners to ensure security

Types

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 IsolationChecker

type IsolationChecker interface {
	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 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,
	truncator *truncate.Truncator,
	logger *zap.Logger,
	mainServer *Server,
	debugSearch bool,
	config *config.Config,
) *MCPProxyServer

NewMCPProxyServer creates a new MCP proxy server

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) 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) 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).

type PermissionError

type PermissionError struct {
	Path string
	Err  error
}

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

type PortInUseError struct {
	Address string
	Err     error
}

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 NewServer

func NewServer(cfg *config.Config, logger *zap.Logger) (*Server, error)

NewServer creates a new server instance

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) AddServer

func (s *Server) AddServer(ctx context.Context, serverConfig *config.ServerConfig) error

AddServer adds a new upstream server to the configuration. New servers are quarantined by default for security.

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

func (s *Server) ApproveAllTools(serverName string, approvedBy string) (int, error)

ApproveAllTools approves all pending/changed tools for a server (Spec 032).

func (*Server) ApproveTools added in v0.21.0

func (s *Server) ApproveTools(serverName string, toolNames []string, approvedBy string) error

ApproveTools approves specific tools for a server (Spec 032).

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) DiscoverServerTools

func (s *Server) DiscoverServerTools(ctx context.Context, serverName string) error

DiscoverServerTools triggers manual tool discovery for a specific server

func (*Server) EnableServer

func (s *Server) EnableServer(serverName string, enabled bool) error

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

func (s *Server) EventsChannel() <-chan runtime.Event

EventsChannel exposes runtime events for tray/UI consumers. Deprecated: Use SubscribeEvents for per-client subscriptions to avoid event competition.

func (*Server) ForceReconnectAllServers

func (s *Server) ForceReconnectAllServers(reason string) error

ForceReconnectAllServers triggers reconnection attempts for all managed servers.

func (*Server) GetActivity

func (s *Server) GetActivity(id string) (*storage.ActivityRecord, error)

GetActivity returns a single activity record by ID.

func (*Server) GetAllServers

func (s *Server) GetAllServers() ([]map[string]interface{}, error)

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) GetConfig

func (s *Server) GetConfig() (*config.Config, error)

GetConfig returns the current configuration

func (*Server) GetConfigPath

func (s *Server) GetConfigPath() string

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) GetDockerRecoveryStatus

func (s *Server) GetDockerRecoveryStatus() *storage.DockerRecoveryState

GetDockerRecoveryStatus returns the current Docker recovery status

func (*Server) GetListenAddress

func (s *Server) GetListenAddress() string

GetListenAddress returns the address the server is listening on

func (*Server) GetLogDir

func (s *Server) GetLogDir() string

GetLogDir returns the log directory path for tray UI

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) GetQuarantinedServers

func (s *Server) GetQuarantinedServers() ([]map[string]interface{}, error)

GetQuarantinedServers returns information about quarantined servers for tray UI

func (*Server) GetRecentSessions

func (s *Server) GetRecentSessions(limit int) ([]*contracts.MCPSession, int, error)

GetRecentSessions retrieves recent MCP sessions

func (*Server) GetSecretResolver

func (s *Server) GetSecretResolver() *secret.Resolver

GetSecretResolver returns the secret resolver instance

func (*Server) GetServerLogs

func (s *Server) GetServerLogs(serverName string, tail int) ([]contracts.LogEntry, error)

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

func (s *Server) GetServerTools(serverName string) ([]map[string]interface{}, error)

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) 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) ([]*contracts.ToolCallRecord, int, error)

GetToolCalls retrieves tool call history with pagination

func (*Server) GetToolCallsBySession

func (s *Server) GetToolCallsBySession(sessionID string, limit, offset int) ([]*contracts.ToolCallRecord, int, error)

GetToolCallsBySession retrieves tool calls filtered by session ID

func (*Server) GetUpstreamStats

func (s *Server) GetUpstreamStats() map[string]interface{}

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) IsReady

func (s *Server) IsReady() bool

IsReady returns whether the server is fully initialized and ready to serve requests

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns whether the server is currently running

func (*Server) ListActivities

func (s *Server) ListActivities(filter storage.ActivityFilter) ([]*storage.ActivityRecord, int, error)

ListActivities returns activity records matching the filter.

func (*Server) ListRegistries

func (s *Server) ListRegistries() ([]interface{}, error)

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

func (s *Server) NotifySecretsChanged(ctx context.Context, operation, secretName string) error

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

func (s *Server) QuarantineServer(serverName string, quarantined bool) error

QuarantineServer quarantines/unquarantines a server

func (*Server) RefreshVersionInfo

func (s *Server) RefreshVersionInfo() *updatecheck.VersionInfo

RefreshVersionInfo performs an immediate update check and returns the result.

func (*Server) ReloadConfiguration

func (s *Server) ReloadConfiguration() error

ReloadConfiguration reloads the configuration from disk

func (*Server) RemoveServer

func (s *Server) RemoveServer(ctx context.Context, serverName string) error

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(id string, arguments map[string]interface{}) (*contracts.ToolCallRecord, error)

ReplayToolCall replays a tool call with modified arguments

func (*Server) RestartServer

func (s *Server) RestartServer(serverName string) error

RestartServer restarts an upstream server

func (*Server) SaveConfiguration

func (s *Server) SaveConfiguration() error

SaveConfiguration saves the current configuration to the persistent config file

func (*Server) SearchRegistryServers

func (s *Server) SearchRegistryServers(registryID, tag, query string, limit int) ([]interface{}, error)

SearchRegistryServers searches for servers in a specific registry (Phase 7)

func (*Server) SearchTools

func (s *Server) SearchTools(query string, limit int) ([]map[string]interface{}, error)

SearchTools searches for tools using the index

func (*Server) SetListenAddress

func (s *Server) SetListenAddress(addr string, persist bool) error

SetListenAddress updates the configured listen address and optionally persists it to disk.

func (*Server) SetShutdownInfo

func (s *Server) SetShutdownInfo(reason, signal string)

SetShutdownInfo sets the reason and signal for shutdown (Spec 024). Call this before Shutdown() to include shutdown context in activity logs.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the server

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start starts the MCP proxy server

func (*Server) StartServer

func (s *Server) StartServer(ctx context.Context) error

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

func (s *Server) StopServer() error

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

func (s *Server) SubscribeEvents() chan runtime.Event

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

func (s *Server) SuggestAlternateListen(baseAddr string) (string, error)

SuggestAlternateListen attempts to find an available listen address near baseAddr.

func (*Server) TriggerOAuthLogin

func (s *Server) TriggerOAuthLogin(serverName string) error

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

func (s *Server) UnquarantineServer(serverName string) error

UnquarantineServer removes a server from quarantine via tray UI

func (*Server) UnsubscribeEvents

func (s *Server) UnsubscribeEvents(ch chan runtime.Event)

UnsubscribeEvents closes and removes the subscription channel.

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) ValidateConfig

func (s *Server) ValidateConfig(cfg *config.Config) ([]config.ValidationError, error)

ValidateConfig validates a configuration

type SessionInfo

type SessionInfo struct {
	SessionID     string
	ClientName    string
	ClientVersion string
}

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) Count

func (s *SessionStore) Count() int

Count returns the number of active sessions

func (*SessionStore) GetSession

func (s *SessionStore) GetSession(sessionID string) *SessionInfo

GetSession retrieves session information

func (*SessionStore) RemoveSession

func (s *SessionStore) RemoveSession(sessionID string)

RemoveSession removes session information

func (*SessionStore) SetSession

func (s *SessionStore) SetSession(sessionID, clientName, clientVersion string, hasRoots, hasSampling bool, experimental []string)

SetSession stores or updates session information

func (*SessionStore) SetStorageManager

func (s *SessionStore) SetStorageManager(manager *storage.Manager)

SetStorageManager sets the storage manager for persistence

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.

func (*SessionStore) UpdateSessionStats

func (s *SessionStore) UpdateSessionStats(sessionID string, tokens int)

UpdateSessionStats updates token usage for a session

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

type Ucred

type Ucred struct {
	Pid int32
	Uid uint32
	Gid uint32
}

Ucred holds Unix credentials

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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