managed

package
v0.70.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrConnectAlreadyActive = errors.New("connection already in progress or established")

ErrConnectAlreadyActive is returned by Connect when another caller's connect is in flight or the client is already Ready. It is a guard, not a failure.

View Source
var ErrConnectionGenerationChanged = errors.New("connection generation changed since the tool identity was resolved")

ErrConnectionGenerationChanged is CallToolOnEpoch's refusal: the client's connection generation is no longer the one the caller certified the tool identity against, so the call was NOT sent. It is returned verbatim (never wrapped with server context) so the dispatch paths can map it onto their own unresolved-identity refusal with errors.Is.

Functions

This section is empty.

Types

type Client

type Client struct {
	StateManager *types.StateManager // Public field for callback access
	// contains filtered or unexported fields
}

Client wraps a core client with state management, concurrency control, and background recovery

func NewClient

func NewClient(id string, serverConfig *config.ServerConfig, logger *zap.Logger, logConfig *config.LogConfig, globalConfig *config.Config, storage *storage.BoltDB, secretResolver *secret.Resolver) (*Client, error)

NewClient creates a new managed client with state management

func (*Client) CallTool

func (mc *Client) CallTool(ctx context.Context, toolName string, args map[string]interface{}) (*mcp.CallToolResult, error)

CallTool executes a tool with error handling

func (*Client) CallToolOnEpoch added in v0.67.0

func (mc *Client) CallToolOnEpoch(ctx context.Context, toolName string, args map[string]interface{}, expectedEpoch int64) (*mcp.CallToolResult, 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 server-side identity check (resolveExactToolIdentity / liveIdentityRefusal) validates a name, its tier and its approval hash on ONE generation (ConnectionEpoch); this entry point makes the dispatch reach the transport on that same generation, or not at all. The generation is re-checked twice: cheaply on entry, and again AFTER the admission-control queue wait — where a call can sit for seconds while a disconnect and a reconnect complete — immediately before the transport, under epochMu, the mutex Connect's and Disconnect's bumps take. A mismatch is refused with ErrConnectionGenerationChanged and zero transport calls. A disconnected client is refused the same way (Disconnect closes the generation), so a reconnect can never happen inside a pinned dispatch.

epochMu is never held across the transport (Client.epochMu's invariant), so check→invoke is not atomic; the residual gap is the scheduling instant between the unlock and the transport's own send, which no lock-free design can close without holding the mutex across foreign code.

func (*Client) Connect

func (mc *Client) Connect(ctx context.Context) error

Connect establishes connection with state management. IMPORTANT: mc.mu is only held briefly for state checks/transitions, NOT during the potentially slow coreClient.Connect() call (which may involve OAuth flows taking minutes). This prevents blocking Disconnect, SetConfig, GetConfig, and other callers.

func (*Client) ConnectedWithOAuth added in v0.66.0

func (mc *Client) ConnectedWithOAuth() bool

ConnectedWithOAuth reports whether the live connection was established by the OAuth auth strategy — i.e. the stored OAuth token is what authenticated it. False when disconnected, when another strategy (static headers, anonymous) won, or for a hand-constructed client with no core. The runtime uses it to decide whether a stored token record is evidence about this server at all (GH #1172).

func (*Client) ConnectionEpoch added in v0.67.0

func (mc *Client) ConnectionEpoch() int64

ConnectionEpoch returns the client's connection-instance token: a monotonically increasing counter bumped on every successful Connect and on every Disconnect (see connectionEpoch), so two observations that read the same value were made on the SAME live connection. The runtime captures it before listing a server's tools and the supervisor stamps it on the discovery snapshot with ToolsDiscovered (stateview.ServerStatus. DiscoveryEpoch); every tool-identity read compares the stamp with the live value, so a discovery result that belongs to a previous connection can never certify a name on the current one when the connection events were dropped or lag (Spec 105 FR-009 "stale generation"; astra r2 C3).

func (*Client) DependsOnDocker added in v0.64.0

func (mc *Client) DependsOnDocker() bool

DependsOnDocker reports whether starting this server needs a working Docker daemon, and therefore whether its connect budget has to absorb an image pull. It is the ONLY input to the 3-minute connect-timeout floor (Manager.resolveConnectTimeout).

It delegates to config.ServerDependsOnDocker, which is built on the SAME resolver the spawn path branches on, so the budget can never be chosen for a launch shape the server will not have — while still covering the server whose OWN command is `docker`, which the resolver deliberately reports as mode=none (we must not double-wrap it) but which pays image-pull latency all the same.

It replaced a hand-rolled mirror of the two LEGACY booleans, which pre-date isolation modes: a per-server `mode: "docker"` override is honoured at spawn even over a legacy `enabled: false`, yet got the SHORT stdio timeout and could be killed mid-pull; while `mode: "sandbox"` servers were handed the long Docker budget they have no use for (GH #1142).

func (*Client) Disconnect

func (mc *Client) Disconnect() error

Disconnect closes the connection and stops monitoring

func (*Client) ForceReconnect

func (mc *Client) ForceReconnect(reason string)

ForceReconnect triggers an immediate reconnection attempt regardless of backoff state.

func (*Client) ForceRemoveTrackedContainerIfOwned added in v0.68.0

func (mc *Client) ForceRemoveTrackedContainerIfOwned(ctx context.Context, containerID string) (string, bool, error)

ForceRemoveTrackedContainerIfOwned is the manager's disconnect-timeout path: it removes the container tracked as containerID only after the core client re-establishes canonical ownership (Spec 105 FR-007 / D9, codex round 3) and hands back the owner label it read at that moment (codex round 5). See core.Client.ForceRemoveTrackedContainerIfOwned.

func (*Client) GetCachedToolCount

func (mc *Client) GetCachedToolCount(ctx context.Context) (int, error)

GetCachedToolCount returns the cached tool count or fetches fresh count if cache is expired Uses a 2-minute cache TTL to reduce frequent ListTools calls

func (*Client) GetCachedToolCountNonBlocking

func (mc *Client) GetCachedToolCountNonBlocking() int

GetCachedToolCountNonBlocking returns the cached tool count without any blocking calls Returns 0 if cache is not populated yet. Safe to call from SSE/API handlers.

func (*Client) GetConfig

func (mc *Client) GetConfig() *config.ServerConfig

GetConfig returns the current server configuration pointer in a thread-safe, lock-free manner. Safe to call whether or not mc.mu is held.

func (*Client) GetConnectionInfo

func (mc *Client) GetConnectionInfo() types.ConnectionInfo

GetConnectionInfo returns detailed connection information

func (*Client) GetConnectionStatus

func (mc *Client) GetConnectionStatus() map[string]interface{}

GetConnectionStatus returns detailed connection status information for compatibility

func (*Client) GetContainerID

func (mc *Client) GetContainerID() string

GetContainerID returns the Docker container ID if this is a Docker-based server

func (*Client) GetEnvManager

func (mc *Client) GetEnvManager() interface{}

GetEnvManager returns the environment manager for testing purposes

func (*Client) GetGlobalConfig added in v0.38.0

func (mc *Client) GetGlobalConfig() *config.Config

GetGlobalConfig returns the current proxy-wide config snapshot (may be nil for hand-constructed test clients). Lock-free; safe to call whether or not mc.mu is held.

func (*Client) GetLastError

func (mc *Client) GetLastError() error

GetLastError returns the last error from the state manager

func (*Client) GetPrompt added in v0.59.0

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

GetPrompt resolves a single prompt by its unqualified name on the upstream server.

func (*Client) GetServerInfo

func (mc *Client) GetServerInfo() *mcp.InitializeResult

GetServerInfo returns server information

func (*Client) GetState

func (mc *Client) GetState() types.ConnectionState

GetState returns the current connection state

func (*Client) GuardReconnectAgainstInFlightCall added in v0.68.0

func (mc *Client) GuardReconnectAgainstInFlightCall() bool

GuardReconnectAgainstInFlightCall exposes guardReconnectAgainstInFlightCall to reconnect orchestration OUTSIDE this package (#1317 round 6): Manager.RetryConnection in internal/upstream/manager.go disconnects and reconnects a client directly (OAuth completion, config-change and token-monitor triggers), bypassing tryReconnect/Connect/TryReconnectSync entirely, so it needs the same guard before its own Disconnect() call.

func (*Client) InvalidateToolCountCache

func (mc *Client) InvalidateToolCountCache()

InvalidateToolCountCache clears the tool count cache Should be called when tools are known to have changed

func (*Client) IsConnected

func (mc *Client) IsConnected() bool

IsConnected returns whether the client is ready for operations

func (*Client) IsConnecting

func (mc *Client) IsConnecting() bool

IsConnecting returns whether the client is in a connecting state

func (*Client) IsDockerCommand

func (mc *Client) IsDockerCommand() bool

IsDockerCommand returns whether this client is running a Docker command

func (*Client) IsOAuthCallRequired added in v0.39.0

func (mc *Client) IsOAuthCallRequired() bool

IsOAuthCallRequired reports whether a tools/call against this otherwise- connected server returned "authorization required" / 401, indicating the endpoint enforces OAuth only at call time. The runtime feeds this into the health calculator to surface a proactive Sign-in CTA. Cleared by a successful call or a fresh Connect. MCP-2084.

func (*Client) IsUserLoggedOut

func (mc *Client) IsUserLoggedOut() bool

IsUserLoggedOut returns true if the user has explicitly logged out

func (*Client) ListPrompts added in v0.59.0

func (mc *Client) ListPrompts(ctx context.Context) ([]mcp.Prompt, error)

ListPrompts returns the prompts advertised by the upstream server.

func (*Client) ListTools

func (mc *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error)

ListTools retrieves tools with concurrency control and coalesces concurrent callers onto a single in-flight upstream call.

func (*Client) RefreshOAuthTokenDirect added in v0.17.3

func (mc *Client) RefreshOAuthTokenDirect(ctx context.Context) error

RefreshOAuthTokenDirect forces an OAuth token refresh without reconnecting. This delegates to the core client's direct refresh implementation. Used by the RefreshManager for proactive token refresh before expiration.

func (*Client) SetAdmissionControl added in v0.54.0

func (mc *Client) SetAdmissionControl(registry *limiter.Registry, observe limiter.Observer)

SetAdmissionControl installs the limiter registry and the rejection observer on this client. The managed client is the single choke point every in-process upstream tool call passes through (spec 093, Option A), so admission here covers the MCP tool-call variants, the REST tool-call endpoint, sandboxed code execution and activity replay alike (FR-003).

Passing a nil registry disables admission for this client (the zero-config default, FR-006).

func (*Client) SetConfig

func (mc *Client) SetConfig(config *config.ServerConfig)

SetConfig atomically swaps the server configuration. Lock-free; callers must not hold mc.mu (they don't need to — the swap is atomic).

Also pushes ExposePrompts down to the coreClient (PR #973 review, P2): coreClient.config is set once at connect time and never reassigned, so without this a hot-reloaded expose_prompts value would stay frozen at whatever was in effect when the connection was created, until the next reconnect-forcing change or restart.

func (*Client) SetGlobalConfig added in v0.38.0

func (mc *Client) SetGlobalConfig(cfg *config.Config)

SetGlobalConfig swaps the proxy-wide config the background loops re-resolve against. Called on a config hot-reload (via Manager.SetGlobalConfig) so the resettable health-check timer picks up a new global interval without a restart (spec 074, FR-012). Lock-free atomic swap.

func (*Client) SetPromptsChangedCallback added in v0.59.0

func (mc *Client) SetPromptsChangedCallback(callback func(serverName string))

SetPromptsChangedCallback sets the callback invoked when a notifications/prompts/list_changed notification is received from the upstream server (F13).

func (*Client) SetStateChangeCallback

func (mc *Client) SetStateChangeCallback(callback func(oldState, newState types.ConnectionState, info *types.ConnectionInfo))

SetStateChangeCallback sets a callback for state changes

func (*Client) SetToolDiscoveryCallback

func (mc *Client) SetToolDiscoveryCallback(callback func(ctx context.Context, serverName string) error)

SetToolDiscoveryCallback sets the callback for triggering tool re-indexing when a notifications/tools/list_changed notification is received from the upstream server.

func (*Client) SetUserLoggedOut

func (mc *Client) SetUserLoggedOut(loggedOut bool)

SetUserLoggedOut marks that the user has explicitly logged out This prevents automatic reconnection until cleared (e.g., by explicit login)

func (*Client) ShouldRetry

func (mc *Client) ShouldRetry() bool

ShouldRetry returns whether connection should be retried

func (*Client) TryReconnectSync added in v0.23.1

func (mc *Client) TryReconnectSync(ctx context.Context) error

TryReconnectSync attempts a synchronous reconnection within the given context. Unlike ForceReconnect which spawns a goroutine, this blocks until the reconnect attempt completes or the context is cancelled. It uses the existing reconnectInProgress flag to prevent concurrent reconnection storms.

Shares the #1317 in-flight-call guard with tryReconnect (see guardReconnectAgainstInFlightCall): IsConnected()==false above proves this client isn't Ready right now, but NOT that every call on it is doomed — an unrelated concurrent failure can flip state to Error while a genuinely healthy CallTool is still in flight on the same connection (review round 3 caught this: an earlier version of this comment assumed otherwise).

Returns nil if reconnection succeeds, error otherwise.

func (*Client) WithConnectionEpoch added in v0.70.0

func (mc *Client) WithConnectionEpoch(expectedEpoch int64, fn func() error) (current bool, err error)

WithConnectionEpoch runs fn while this client remains on expectedEpoch. Connect and Disconnect serialize their epoch transitions through epochMu, so callers that have already established the managed-client identity can make a short, non-transport state update linearizable with that identity.

fn must not call back into Connect, Disconnect, or a path that waits for a connection transition; those operations intentionally wait for this bounded section to finish.

Jump to

Keyboard shortcuts

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