upstream

package
v0.73.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrStaleGeneration = commitview.ErrStaleGeneration

ErrStaleGeneration is returned by the *At methods when the action was bound to a generation, or an instance, that is no longer the server's current one. It is not a failure: the caller logs it at debug level and does nothing.

Functions

func GenericToolCallCause added in v0.73.0

func GenericToolCallCause(err error) (error, bool)

GenericToolCallCause returns the cause only when err itself is the manager's trusted generic wrapper. It deliberately does not search an error chain: doing so could discard meaningful authentication or transport context.

func SetBeforeBindingCheckHookForTest added in v0.71.0

func SetBeforeBindingCheckHookForTest(h func(name string, sg commitview.ServerGen)) (restore func())

SetBeforeBindingCheckHookForTest installs the seam; test-only.

func SetRetireObserverForTest added in v0.71.0

func SetRetireObserverForTest(fn func(server string, d time.Duration)) (restore func())

SetRetireObserverForTest installs the retirement observer and returns a restore func. Test-only.

func StateChangeNotifier

func StateChangeNotifier(nm *NotificationManager, serverName string) func(oldState, newState types.ConnectionState, info *types.ConnectionInfo)

StateChangeNotifier creates state change notifications based on state transitions

Types

type AdvanceResult added in v0.71.0

type AdvanceResult struct {
	// Unregistered are the instances removed from the registry. The caller
	// disconnects them after it released its own locks (they no longer
	// connect: managed.ErrInstanceUnregistered).
	Unregistered []*managed.Client
	// Restamped names the retained instances that took the committed config
	// and generation in place (no reconnect).
	Restamped []string
}

AdvanceResult reports what AdvanceGenerations did.

type ClientFactory

type ClientFactory interface {
	// Create core client for basic operations
	CreateCoreClient(id string, config *config.ServerConfig) (MCPClient, error)

	// Create managed client with state machine
	CreateManagedClient(id string, config *config.ServerConfig) (StatefulClient, error)

	// Create CLI client for debugging
	CreateCLIClient(id string, config *config.ServerConfig) (MCPClient, error)
}

ClientFactory creates different types of clients

type ClientPool

type ClientPool interface {
	// Pool management
	AddClient(id string, client StatefulClient) error
	RemoveClient(id string)
	GetClient(id string) (StatefulClient, bool)
	GetAllClients() map[string]StatefulClient

	// Bulk operations
	ConnectAll(ctx context.Context) error
	DisconnectAll() error

	// Tool operations across all clients
	DiscoverTools(ctx context.Context) ([]*config.ToolMetadata, error)
	CallTool(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)
}

ClientPool manages multiple clients

type GenerationChange added in v0.71.0

type GenerationChange struct {
	Name string
	// Gen is the server's commit generation in the published snapshot (0 when
	// the server was removed).
	Gen int64
	// Present is false when the commit removed the server.
	Present bool
	// Reconnect is true when the commit changed the connection settings,
	// Enabled or Quarantined (configsvc.ServerChange.Reconnect).
	Reconnect bool
	// Replaced is true for a remove and re-create in one commit (review
	// R8.2): the old instance never survives, even for an equal entry.
	Replaced bool
	// Config is the committed entry (nil when removed).
	Config *config.ServerConfig
	// Binding is the server's committed credential binding in the published
	// snapshot (Spec 116 PR2b; zero when removed).
	Binding commitview.CredentialBinding
}

GenerationChange is one server's state after a config commit, as commit step 7 hands it to AdvanceGenerations.

type MCPClient

type MCPClient interface {
	// Connection management
	Connect(ctx context.Context) error
	Disconnect() error
	IsConnected() bool

	// MCP operations
	ListTools(ctx context.Context) ([]*config.ToolMetadata, error)
	CallTool(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)

	// Status and info
	GetConnectionInfo() types.ConnectionInfo
	GetServerInfo() *mcp.InitializeResult
}

MCPClient defines the core interface for MCP client operations

type Manager

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

Manager manages connections to multiple upstream MCP servers

func NewManager

func NewManager(logger *zap.Logger, globalConfig *config.Config, boltStorage *storage.BoltDB, secretResolver *secret.Resolver, storageMgr *storage.Manager) *Manager

NewManager creates a new upstream manager

func (*Manager) AddNotificationHandler

func (m *Manager) AddNotificationHandler(handler NotificationHandler)

AddNotificationHandler adds a notification handler to receive state change notifications

func (*Manager) AddServer

func (m *Manager) AddServer(id string, serverConfig *config.ServerConfig) error

AddServer adds a server and connects it (unbound legacy method).

func (*Manager) AddServerAt added in v0.71.0

func (m *Manager) AddServerAt(id string, serverConfig *config.ServerConfig, gen int64) error

AddServerAt installs (or keeps) the instance serving id at generation gen and, when the server is enabled, connects THAT instance (never whatever the name resolves to later). ErrStaleGeneration when gen is not current.

func (*Manager) AddServerConfig

func (m *Manager) AddServerConfig(id string, serverConfig *config.ServerConfig) error

AddServerConfig adds a server configuration without connecting (unbound).

func (*Manager) AddServerConfigAt added in v0.71.0

func (m *Manager) AddServerConfigAt(id string, serverConfig *config.ServerConfig, gen int64) error

AddServerConfigAt installs (or keeps) the instance serving id at commit generation gen without connecting it. It returns ErrStaleGeneration, and changes nothing, unless gen is id's current committed generation.

func (*Manager) AdvanceGenerations added in v0.71.0

func (m *Manager) AdvanceGenerations(changes []GenerationChange) AdvanceResult

AdvanceGenerations applies one config commit to the registry (commit step 7, plan.md §Commit pipeline). changes must list EVERY server of the published configuration (unchanged ones too, so the desired view is complete after the boot commit) plus every server the commit removed. For each name:

  • removed: the instance is unregistered and the name tombstoned;
  • replaced, or a connection/Enabled/Quarantined change whose generation moved: the instance is unregistered (the commit's worker installs the new one);
  • otherwise a registered instance behind the committed generation is restamped with the committed config (SetConfigAt), or unregistered if it does not run the committed connection settings.

It takes captureMu for writing and then mu (L3 → L4); the caller holds no approval lock (rule 2). Limiter updates run after both are released. It never connects or disconnects.

func (*Manager) CallStats added in v0.71.0

func (m *Manager) CallStats(server string) (calls, failures int, dominantKind string)

CallStats returns the counted calls and failures for server inside the rolling window, plus a short label for the dominant failure kind.

func (*Manager) CallTool

func (m *Manager) CallTool(ctx context.Context, toolName string, args map[string]interface{}) (interface{}, error)

CallTool calls a tool on the appropriate upstream server

func (*Manager) CallToolOnEpoch added in v0.67.0

func (m *Manager) CallToolOnEpoch(ctx context.Context, toolName string, args map[string]interface{}, expectedEpoch int64) (interface{}, error)

CallToolOnEpoch is CallTool pinned to the connection generation the caller certified the tool identity against (Spec 105 FR-009 "stale generation"; codex r3 D2): the dispatch reaches the upstream on exactly that generation of the server's live client (managed.Client.CallToolOnEpoch) or is refused with managed.ErrConnectionGenerationChanged and zero upstream calls. The reconnect_on_use branch is deliberately NOT taken for a pinned call — a reconnect is a new generation by construction, whose tool set the caller never certified — so a client found disconnected is refused the same way. The refusal is returned verbatim, never enriched, so errors.Is holds.

func (*Manager) CaptureReplacementQueued added in v0.70.0

func (m *Manager) CaptureReplacementQueued() bool

CaptureReplacementQueued reports whether a replacement/removal is waiting behind an active capture persistence section. It is primarily useful for observability and deterministic concurrency tests; it never mutates state.

func (*Manager) ClearOAuthToken

func (m *Manager) ClearOAuthToken(serverName string) error

ClearOAuthToken clears the OAuth token for a specific server. This is called by the OAuth logout flow to remove stored credentials. Works for both explicit OAuth config and discovered OAuth (server-announced OAuth).

func (*Manager) ConcurrencyStats added in v0.54.0

func (m *Manager) ConcurrencyStats() (global limiter.Stats, servers map[string]limiter.Stats)

ConcurrencyStats reports the current occupancy of the global aggregate limiter and of every live per-server limiter (FR-013: queue depth).

func (*Manager) ConnectAll

func (m *Manager) ConnectAll(ctx context.Context) error

ConnectAll connects to all configured servers that should retry

func (*Manager) ConnectInstance added in v0.71.0

func (m *Manager) ConnectInstance(name string, inst *managed.Client) error

ConnectInstance connects inst, an instance a bound call (AddServerAt, ReplaceInstanceAt) returned, with the server's resolved init timeout. It never resolves the name again. An instance that has since been unregistered refuses to connect, which is reported as success (nothing failed).

func (*Manager) ConnectServerAt added in v0.71.0

func (m *Manager) ConnectServerAt(ctx context.Context, name string, gen int64) error

ConnectServerAt connects the instance serving name at generation gen. ErrStaleGeneration when gen is not name's committed generation, or the registered instance does not run it yet.

func (*Manager) CurrentCredentialBinding added in v0.71.0

func (m *Manager) CurrentCredentialBinding(name string) (commitview.CredentialBinding, bool)

CurrentCredentialBinding reports the credential binding of the instance registered for name (Spec 116 PR2b). The RefreshManager applies a refresh flight's outcome only when it ran under this binding.

func (*Manager) DesiredBinding added in v0.71.0

func (m *Manager) DesiredBinding(name string) (commitview.CredentialBinding, bool)

DesiredBinding reports the committed credential binding the manager holds for name (zero and false when absent or removed). Test and diagnostics accessor.

func (*Manager) DesiredGeneration added in v0.71.0

func (m *Manager) DesiredGeneration(name string) (gen int64, present bool)

DesiredGeneration reports the committed generation the manager holds for name and whether the name is present (not removed). Test and diagnostics accessor.

func (*Manager) DisconnectAll

func (m *Manager) DisconnectAll() error

DisconnectAll disconnects from all servers

func (*Manager) DisconnectServer

func (m *Manager) DisconnectServer(serverName string) error

DisconnectServer disconnects a specific server without removing its configuration. This is used after OAuth logout to force re-authentication on next connect.

func (*Manager) DisconnectServerAt added in v0.71.0

func (m *Manager) DisconnectServerAt(name string, gen int64, inst managed.InstanceID) error

DisconnectServerAt disconnects the exact instance inst serving name at generation gen, and returns ErrStaleGeneration without acting when the generation moved or another instance (a restart, ForceReconnectAll or Docker recovery at the same generation) now serves the name (review R5.2).

func (*Manager) DiscoverTools

func (m *Manager) DiscoverTools(ctx context.Context) ([]*config.ToolMetadata, error)

DiscoverTools discovers all tools from all connected upstream servers. Security: Tools from quarantined servers are NOT discovered to prevent Tool Poisoning Attacks (TPA) from exposing potentially malicious tool descriptions.

func (*Manager) DiscoverToolsDue added in v0.38.0

func (m *Manager) DiscoverToolsDue(ctx context.Context) ([]*config.ToolMetadata, error)

DiscoverToolsDue is the periodic-sweep variant of DiscoverTools: it lists only servers whose per-server tool_discovery_interval has elapsed and skips those whose resolved interval disables the sweep (<=0). The background indexing loop uses this so a per-server override changes how often that server is re-listed; event-driven callers (connect, reload, manual refresh) use DiscoverTools for a full sweep (spec 074, US3/SC-006/FR-005).

func (*Manager) DiscoverToolsReport added in v0.67.0

func (m *Manager) DiscoverToolsReport(ctx context.Context, dueOnly bool) ([]*config.ToolMetadata, []string, error)

DiscoverToolsReport is DiscoverTools / DiscoverToolsDue with the names of the servers whose tools/list actually SUCCEEDED in this sweep, so a caller can tell a server that listed zero tools (discovery completed, nothing served) from one the sweep skipped or that failed to list (Spec 105 FR-009: the discovery-completed marker must be stamped for the former and left alone for the latter).

func (*Manager) DiscoverToolsReportCaptured added in v0.71.0

func (m *Manager) DiscoverToolsReportCaptured(ctx context.Context, dueOnly bool) ([]*config.ToolMetadata, []string, map[string]managed.InventoryCapture, error)

DiscoverToolsReportCaptured is DiscoverToolsReport that also returns, per listed server, the capture of that server's own tools/list (Spec 117 PR-3, FR-031): the sweep applies each server's inventory in capture order, not under one ticket for the whole sweep.

func (*Manager) ForceCleanupAllContainers

func (m *Manager) ForceCleanupAllContainers()

ForceCleanupAllContainers is a public wrapper for emergency container cleanup This is called when graceful shutdown fails and containers must be force-removed Only removes containers owned by THIS instance (matching instance ID) AND canonically owned by a configured server (listOwnedManagedContainers).

func (*Manager) ForceReconnectAll

func (m *Manager) ForceReconnectAll(reason string) *ReconnectResult

ForceReconnectAll triggers reconnection attempts for all managed clients. For Docker-based servers, this includes container health verification to catch frozen containers. Returns detailed results about which servers were reconnected, skipped, or failed.

func (*Manager) GetAllClients

func (m *Manager) GetAllClients() map[string]*managed.Client

GetAllClients returns all clients

func (*Manager) GetAllServerNames

func (m *Manager) GetAllServerNames() []string

GetAllServerNames returns a slice of all configured server names

func (*Manager) GetClient

func (m *Manager) GetClient(id string) (*managed.Client, bool)

GetClient returns a client by ID

func (*Manager) GetDockerRecoveryStatus

func (m *Manager) GetDockerRecoveryStatus() *storage.DockerRecoveryState

GetDockerRecoveryStatus returns the current Docker recovery status

func (*Manager) GetPrompt added in v0.59.0

func (m *Manager) GetPrompt(ctx context.Context, name string, args map[string]string) (*mcp.GetPromptResult, error)

GetPrompt resolves a colon-qualified "serverName:promptName" and forwards the call to the owning upstream client.

func (*Manager) GetStats

func (m *Manager) GetStats() map[string]interface{}

GetStats returns statistics about upstream connections GetStats returns statistics about all managed clients. Phase 6 Fix: Lock-free implementation to prevent deadlock with async operations.

Issue #1148, round 4: this map is not an internal counter — it is served verbatim as `upstream_stats` on GET /api/v1/status, on the /api/v1/servers response, and on every SSE `status` event, and it is what the tray renders. Its per-server entries therefore sit behind the same trust boundary as the server list on those same payloads, which httpapi.redactServerSecrets and Runtime.redactServerSecrets already mask. Leaving `url` and `last_error` raw here meant one half of a single response was masked and the other half was not. Mask them at the point they are written.

Issue #1167: unconditionally, with no reveal_secret_headers opt-out. This producer takes no ctx and neither does its consumer chain, so there is no caller identity to AND the operator flag with - and the flag alone handed a scoped agent token every server's raw url and last_error on /api/v1/status and on every SSE status event. Same rule, same reason, as the StateView implementation in internal/server.Server.GetUpstreamStats, which is the one that actually runs.

func (*Manager) GetTotalToolCount

func (m *Manager) GetTotalToolCount() int

GetTotalToolCount returns the total number of tools across all servers. Uses cached counts to avoid excessive network calls (2-minute cache per server). Phase 6 Fix: Lock-free implementation to prevent deadlock.

func (*Manager) GlobalConfig added in v0.52.0

func (m *Manager) GlobalConfig() *config.Config

GlobalConfig returns the proxy-wide config the manager currently uses for newly created clients and Docker-recovery decisions (see SetGlobalConfig). May be nil before the first Store.

func (*Manager) HasDockerContainers

func (m *Manager) HasDockerContainers() bool

HasDockerContainers reports whether any RUNNING Docker container this instance manages (com.mcpproxy.managed=true, com.mcpproxy.instance=<this instance>) is also canonically owned by a configured server — core.ContainerOwnedByAny over listOwnedManagedContainers, the same selection the shutdown and emergency sweeps apply. The instance/managed labels alone are shared and copyable (Spec 105 D9): a foreign container that copies them, or one whose owning server was since removed from config, must not be reported as still running — that false positive drove the runtime/server shutdown path into its 15-second cleanup-verification wait, a second force-clean, and a false "still running after force cleanup" report for a container mcpproxy neither started nor can act on (codex round 10, docker finding 1). includeStopped is false: an already-stopped row must not read as still running either.

func (*Manager) InvalidateAllToolCountCaches

func (m *Manager) InvalidateAllToolCountCaches()

InvalidateAllToolCountCaches invalidates tool count caches for all clients This should be called when tools are known to have changed (e.g., after indexing)

func (*Manager) Limiters added in v0.54.0

func (m *Manager) Limiters() *limiter.Registry

Limiters exposes the live limiter registry (metrics surface, tests).

func (*Manager) ListPrompts added in v0.59.0

func (m *Manager) ListPrompts(ctx context.Context) ([]mcp.Prompt, error)

ListPrompts aggregates prompts from every connected, enabled, non-quarantined upstream client. Each returned prompt's Name is rewritten to "serverName:promptName" so a subsequent GetPrompt call can be routed back to the right server. A per-client failure is logged and that client is skipped; the rest of the aggregation proceeds.

func (*Manager) ListServers

func (m *Manager) ListServers() map[string]*config.ServerConfig

ListServers returns information about all registered servers

func (*Manager) RecordCallOutcome added in v0.71.0

func (m *Manager) RecordCallOutcome(server string, result *mcp.CallToolResult, err error)

RecordCallOutcome feeds one dispatched tool call into the named server's rolling failure-rate window (Spec 113-d). callstats.Classify decides whether the outcome counts: isError results, limiter/generation refusals, caller cancellation and auth-required errors are excluded. Dispatch paths should use RecordClientCallOutcome, which also refuses to resurrect the window of a server that was removed while the call was in flight.

func (*Manager) RecordClientCallOutcome added in v0.71.0

func (m *Manager) RecordClientCallOutcome(ctx context.Context, client *managed.Client, result *mcp.CallToolResult, err error)

RecordClientCallOutcome is RecordCallOutcome for a dispatch that went through client. It is the single entry point shared by Manager.callTool and the code_execution dispatch, which calls the managed client directly and bypasses the manager. The outcome is dropped unless client is still the registered client for its server: RemoveServer deletes the client and then drops the window, so a call still in flight at removal (its transport closes and it fails) must not recreate the history a same-named replacement would inherit. The check and the Record happen under the manager read lock, which RemoveServer's delete takes for writing, so either the record lands before the drop (and is wiped by it) or the check fails.

func (*Manager) RefreshOAuthToken

func (m *Manager) RefreshOAuthToken(serverName string) error

RefreshOAuthToken triggers a token refresh for a specific server. This is called by the RefreshManager for proactive token refresh.

OAuth detection checks both: 1. Static config (serverConfig.OAuth) - for servers with pre-configured OAuth 2. Database tokens - for servers using dynamic OAuth discovery (Protected Resource Metadata)

func (*Manager) RemoveServer

func (m *Manager) RemoveServer(id string)

RemoveServer removes an upstream server (unbound legacy method).

func (*Manager) RemoveServerAt added in v0.71.0

func (m *Manager) RemoveServerAt(name string, gen int64) error

RemoveServerAt unregisters and disconnects the instance serving name. With gen > 0 it acts only when gen is name's current committed generation (a disabled server's worker); with gen == 0 it acts only when the committed configuration no longer has the name (the supervisor's removal of a server the commit already tombstoned). ErrStaleGeneration otherwise.

func (*Manager) ReplaceInstanceAt added in v0.71.0

func (m *Manager) ReplaceInstanceAt(name string, gen int64, expected *managed.Client, cfg *config.ServerConfig) (*managed.Client, error)

ReplaceInstanceAt replaces expected, the instance serving name at generation gen, with a fresh instance at the SAME generation (RestartServer, ForceReconnectAll, Docker recovery). It returns ErrStaleGeneration, and changes nothing, when the generation moved or expected is no longer the registered instance (review R4.1, R5.4). cfg defaults to expected's config. The old instance is unregistered (it never connects again) and disconnected before this returns; the new one is not connected.

func (*Manager) ResolveToolDiscoverySweepTick added in v0.38.0

func (m *Manager) ResolveToolDiscoverySweepTick(globalCfg *config.Config) (time.Duration, bool)

ResolveToolDiscoverySweepTick computes how long the periodic indexing loop should wait between sweeps: the smallest positive resolved tool-discovery interval across the global default and every managed server. Per-server configs are read through each client's thread-safe GetConfig() snapshot — deliberately NOT by iterating globalCfg.Servers, which would race in-place mutation of the shared (copy-on-write) config snapshot from the background loop (the original cause of the MCP-1189 -race failure). anyEnabled is false when every resolved interval is disabled (<=0), in which case the loop idles.

func (*Manager) RetryConnection

func (m *Manager) RetryConnection(serverName string) error

RetryConnection triggers a connection retry for a specific server This is typically called after OAuth completion to immediately use new tokens

func (*Manager) SetCallHealthObserver added in v0.71.0

func (m *Manager) SetCallHealthObserver(observer func(server string))

SetCallHealthObserver registers the callback invoked (debounced, off the call path's locks) when a server's failure-rate verdict changes.

func (*Manager) SetCommittedViewChecker added in v0.71.0

func (m *Manager) SetCommittedViewChecker(check func(name string, sg commitview.ServerGen) error)

SetCommittedViewChecker installs the construction-time check of the committed view (Spec 116 PR2b, review R6.1; storage.Manager. CheckCommittedView): before an instance is built for (name, gen), the stored row must still carry exactly the committed {gen, incarnation, OAuth epoch} the manager holds for it. nil (tests, CLI-only managers) skips it.

func (*Manager) SetConnectDeadlineHookForTest added in v0.73.0

func (m *Manager) SetConnectDeadlineHookForTest(fn func(name string, ctx context.Context))

SetConnectDeadlineHookForTest installs the connectDeadlineHook seam. Test-only.

func (*Manager) SetGlobalConfig added in v0.38.0

func (m *Manager) SetGlobalConfig(globalConfig *config.Config)

SetGlobalConfig swaps the proxy-wide config the manager uses for newly created clients and Docker-recovery decisions, and propagates it to every existing managed client so their background health-check loops re-resolve the new global interval on the next cycle (spec 074, FR-012/SC-002). Called from the runtime on a config hot-reload (ApplyConfig). The atomic swap is lock-free; the client fan-out snapshots under mu.RLock to avoid holding the lock while touching each client.

func (*Manager) SetLogConfig

func (m *Manager) SetLogConfig(logConfig *config.LogConfig)

SetLogConfig sets the logging configuration for upstream server loggers

func (*Manager) SetPromptsChangedCallback added in v0.59.0

func (m *Manager) SetPromptsChangedCallback(callback func(serverName string))

SetPromptsChangedCallback sets the callback for triggering aggregated-prompt refresh when an upstream sends notifications/prompts/list_changed (F13). It is applied to existing clients and to all clients created later (see SetToolDiscoveryCallback for why).

func (*Manager) SetRejectionObserver added in v0.54.0

func (m *Manager) SetRejectionObserver(observe limiter.Observer)

SetRejectionObserver installs the origin-independent shed seam (FR-012): the runtime passes a callback that turns a rejection into a "rejected" activity record and a rejection metric, regardless of which surface originated the call. Existing clients are re-wired immediately.

func (*Manager) SetToolDiscoveryCallback

func (m *Manager) SetToolDiscoveryCallback(callback func(ctx context.Context, serverName string) error)

SetToolDiscoveryCallback sets the callback for triggering tool re-indexing when upstream servers send notifications/tools/list_changed notifications. It is applied to every client that already exists and to all clients created later: the supervisor can add (and connect) clients before the runtime registers this callback, and a client without it silently drops list_changed notifications. Applying under m.mu (the same m.mu → mc.mu order AddServerConfig uses) keeps concurrent setters from leaving a stale callback.

func (*Manager) SetUserLoggedOut

func (m *Manager) SetUserLoggedOut(serverName string, loggedOut bool) error

SetUserLoggedOut marks a server as explicitly logged out by the user. This prevents automatic reconnection until the user explicitly logs in again.

func (*Manager) ShutdownAll

func (m *Manager) ShutdownAll(ctx context.Context) error

ShutdownAll disconnects all clients and ensures all Docker containers are stopped This should be called during application shutdown to ensure clean exit

func (*Manager) StartManualOAuth

func (m *Manager) StartManualOAuth(serverName string, force bool) error

StartManualOAuth performs an in-process OAuth flow for the given server. This avoids cross-process DB locking by using the daemon's storage directly.

func (*Manager) StartManualOAuthQuick

func (m *Manager) StartManualOAuthQuick(serverName string) (*core.OAuthStartResult, error)

StartManualOAuthQuick starts OAuth and returns browser status immediately. Unlike StartManualOAuth (fully async, no result) or StartManualOAuthWithInfo (fully sync, blocks), this returns browser status quickly but continues the OAuth callback handling in background.

This is the recommended method for API endpoints that need to return browser_opened status.

func (*Manager) StartManualOAuthWithInfo

func (m *Manager) StartManualOAuthWithInfo(serverName string, force bool) (*core.OAuthStartResult, error)

StartManualOAuthWithInfo performs an in-process OAuth flow and returns the auth URL and browser status. This is used by Phase 3 (Spec 020) to return structured information about the OAuth flow start. Unlike StartManualOAuth, this method waits for the auth URL to be obtained before returning.

func (*Manager) UsesDockerIsolation added in v0.32.0

func (m *Manager) UsesDockerIsolation() bool

UsesDockerIsolation reports whether this manager could have launched Docker containers (a global or per-server isolation mode that resolves to docker, or a server whose own command is docker). When false, no container cleanup verification is needed on shutdown — shelling out to `docker ps` would be pure waste (and, in test processes, adds ~17s/Close via the verification loop). Same predicate the Docker recovery monitor uses, so behavior stays consistent.

func (*Manager) WithCurrentClientOnEpoch added in v0.70.0

func (m *Manager) WithCurrentClientOnEpoch(id string, expected *managed.Client, expectedEpoch int64, fn func() error) (current bool, err error)

WithCurrentClientOnEpoch runs fn only while id still names expected and that exact client remains on expectedEpoch. captureMu makes the pointer check and fn one linearization region with AddServerConfig/RemoveServer (which need its writer lock to replace the entry); the managed-client epoch lock keeps a same-pointer reconnect from changing its connection identity in the middle of fn. fn must be bounded and must not initiate a connection change, because those transitions wait for the locks held here.

type Notification

type Notification struct {
	Level      NotificationLevel `json:"level"`
	Title      string            `json:"title"`
	Message    string            `json:"message"`
	ServerName string            `json:"server_name,omitempty"`
	Timestamp  time.Time         `json:"timestamp"`
}

Notification represents a notification to be sent to the UI

type NotificationHandler

type NotificationHandler interface {
	SendNotification(notification *Notification)
}

NotificationHandler defines the interface for handling notifications

type NotificationLevel

type NotificationLevel int

NotificationLevel represents the level of a notification

const (
	NotificationInfo NotificationLevel = iota
	NotificationWarning
	NotificationError
)

func (NotificationLevel) String

func (l NotificationLevel) String() string

String returns the string representation of the notification level

type NotificationManager

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

NotificationManager manages notification handlers and provides convenience methods

func NewNotificationManager

func NewNotificationManager() *NotificationManager

NewNotificationManager creates a new notification manager

func (*NotificationManager) AddHandler

func (nm *NotificationManager) AddHandler(handler NotificationHandler)

AddHandler adds a notification handler

func (*NotificationManager) NotifyOAuthRequired

func (nm *NotificationManager) NotifyOAuthRequired(serverName string)

NotifyOAuthRequired sends a notification when OAuth authentication is required

func (*NotificationManager) NotifyServerConnected

func (nm *NotificationManager) NotifyServerConnected(serverName string)

NotifyServerConnected sends a notification when a server connects

func (*NotificationManager) NotifyServerConnecting

func (nm *NotificationManager) NotifyServerConnecting(serverName string)

NotifyServerConnecting sends a notification when a server starts connecting

func (*NotificationManager) NotifyServerDisconnected

func (nm *NotificationManager) NotifyServerDisconnected(serverName string, reason error)

NotifyServerDisconnected sends a notification when a server disconnects

func (*NotificationManager) NotifyServerError

func (nm *NotificationManager) NotifyServerError(serverName string, err error)

NotifyServerError sends a notification when a server encounters an error

func (*NotificationManager) SendNotification

func (nm *NotificationManager) SendNotification(notification *Notification)

SendNotification sends a notification to all registered handlers

type ReconnectResult

type ReconnectResult struct {
	TotalServers      int
	AttemptedServers  int
	SuccessfulServers []string
	FailedServers     map[string]error
	SkippedServers    map[string]string // server name -> skip reason
}

ReconnectResult tracks the results of a ForceReconnectAll operation

type StatefulClient

type StatefulClient interface {
	MCPClient

	// State management
	GetState() types.ConnectionState
	IsConnecting() bool

	// Advanced connection management
	ShouldRetry() bool
	SetStateChangeCallback(callback func(oldState, newState types.ConnectionState, info *types.ConnectionInfo))

	// Tool count optimization
	GetCachedToolCount(ctx context.Context) (int, error)
}

StatefulClient extends MCPClient with state management capabilities

type TransportClient

type TransportClient interface {
	// Transport-specific connection
	ConnectWithTransport(ctx context.Context, transportType string) error

	// Access to underlying transport details
	GetTransportType() string
	GetStderr() io.Reader // For stdio transport
}

TransportClient defines transport-specific client creation

Directories

Path Synopsis
Package callstats keeps a rolling, in-memory record of per-server tool-call outcomes so the health calculator can report a server whose calls mostly fail as degraded even though its connection looks fine (Spec 113-d).
Package callstats keeps a rolling, in-memory record of per-server tool-call outcomes so the health calculator can report a server whose calls mostly fail as degraded even though its connection looks fine (Spec 113-d).
Package dialgate is the per-instance retirement barrier of Spec 116 PR4 (#1564, FR-022..FR-026).
Package dialgate is the per-instance retirement barrier of Spec 116 PR4 (#1564, FR-022..FR-026).
Package launcher manages locally-spawned upstream processes that expose their MCP endpoint over HTTP / SSE / streamable-HTTP transports.
Package launcher manages locally-spawned upstream processes that expose their MCP endpoint over HTTP / SSE / streamable-HTTP transports.
Package limiter implements the bounded-concurrency admission control used by the upstream tool-call choke point (spec 093, GH #955).
Package limiter implements the bounded-concurrency admission control used by the upstream tool-call choke point (spec 093, GH #955).

Jump to

Keyboard shortcuts

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