managed

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: 28 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrConnectAborted = errors.New("connect superseded by a concurrent disconnect or a newer attempt")

ErrConnectAborted is returned by Connect when a Disconnect, or a newer connect attempt, ran while the transport was being established. The dial's result (success or failure) is discarded; the client keeps the state the superseding operation left.

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.

View Source
var ErrDispatchRecheckRefused = core.ErrDispatchRecheckRefused

ErrDispatchRecheckRefused marks a call that a WithDispatchRecheck check refused immediately before the transport. Nothing was sent upstream. It is core.ErrDispatchRecheckRefused, so a refusal raised by either layer matches.

View Source
var ErrInstanceRetired = errors.New("server unavailable: it was removed, replaced or quarantined while the request was in flight")

ErrInstanceRetired is returned by a tool call, tools/list or probe on an instance the upstream manager retired (Spec 116 PR4, FR-026): the server was removed, replaced or quarantined while the request was on its way. It is the "server unavailable" answer; the internal dialgate.ErrRetired never reaches a surface (FR-027). It is not a connection failure: it marks nothing unhealthy and is not charged to the replacement instance.

View Source
var ErrInstanceUnregistered = errors.New("instance unregistered: superseded by a newer config commit or replacement")

ErrInstanceUnregistered is returned by Connect on an instance the upstream manager has unregistered (Spec 116 PR3): a newer config commit, a removal or a same-generation replacement superseded it, so it must not connect.

View Source
var ErrSessionReestablished = errors.New("upstream session was lost and re-established; the call was not repeated")

ErrSessionReestablished is returned for a tools/call that hit a terminated session when the call was NOT repeated (write/destructive tool, unknown or changed tool identity). The session itself was re-established, so the next call works. It is not a connection failure and never marks the server Error.

Functions

func WithDispatchRecheck added in v0.71.0

func WithDispatchRecheck(ctx context.Context, check func() error) context.Context

WithDispatchRecheck attaches check to ctx (see core.WithDispatchRecheck). callTool runs the attached checks AFTER the admission-control queue wait, and the core client runs them again once it holds the SSE request lock, immediately before every send (including a session re-init's retry).

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. The instance holds no commit generation (0); the daemon builds instances with NewClientAt.

func NewClientAt added in v0.71.0

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

NewClientAt creates a managed client stamped, from construction, with the Spec 116 commit generation gen of serverConfig (Generation).

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) CaptureIsCurrent added in v0.71.0

func (mc *Client) CaptureIsCurrent(c InventoryCapture) bool

CaptureIsCurrent reports whether c was taken by this client, the client is not retired and its connection epoch has not moved since the list started (no reconnect). Lock-free: it reads two atomics, so it can be called under any lock (the runtime calls it under a server's tool-approval lock).

func (*Client) ConfigAt added in v0.71.0

func (mc *Client) ConfigAt() (*config.ServerConfig, int64)

ConfigAt returns the config this instance holds together with the commit generation it was stamped with, read from ONE atomic load. A caller that binds an action to (config, generation) must use it instead of separate GetConfig and Generation calls: a restamp (SetConfigAt) between those two reads would pair the OLD config with the NEW generation (Spec 116 PR3 Sol round 1).

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) CredentialBinding added in v0.71.0

func (mc *Client) CredentialBinding() commitview.CredentialBinding

CredentialBinding returns the instance's credential binding (zero when unbound).

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) Gate added in v0.71.0

func (mc *Client) Gate() *dialgate.Gate

Gate returns the instance's retirement barrier (Spec 116 PR4). The upstream manager shares it with the transient clients of a manual OAuth flow.

func (*Client) Generation added in v0.71.0

func (mc *Client) Generation() int64

Generation returns the commit generation of the config this instance holds (Spec 116): the generation of the commit that created or last restamped it, or 0 when the instance was built without one. Discovery captures it and drops a result whose generation no longer matches the stored row (D15).

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) InstanceID added in v0.71.0

func (mc *Client) InstanceID() InstanceID

InstanceID returns this instance's process-unique id (0 for a client that was not built by NewClient).

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) ListToolsCaptured added in v0.71.0

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

ListToolsCaptured is ListTools that also returns the capture of the flight whose result it returns (the caller's own flight, or the one it joined).

func (*Client) ListToolsFresh added in v0.71.0

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

ListToolsFresh is ListTools for a caller that must see the tools as they are AFTER the call was made — a contract verification triggered by notifications/tools/list_changed (RT-05, Sol r5 P2). It never joins an upstream tools/list that was already in flight when it was called (that request may have been answered before the change the notification announces): it waits for such a request to finish and then lists again, joining only a request that started after the call.

func (*Client) ListToolsFreshCaptured added in v0.71.0

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

ListToolsFreshCaptured is ListToolsFresh that also returns the capture.

func (*Client) MarkUnregistered added in v0.71.0

func (mc *Client) MarkUnregistered()

MarkUnregistered records that the upstream manager removed this instance from its registry. Called only by upstream.Manager, under its registry locks; from then on Connect refuses with ErrInstanceUnregistered.

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) Retire added in v0.71.0

func (mc *Client) Retire()

Retire marks the client as replaced or removed by the upstream manager (Spec 117 FR-036). A retired client is never current again: its captures are discarded and WithConnectionEpoch reports it as not current.

Spec 116 PR4 (FR-022): Retire also closes the instance's dial gate, so from its return the instance launches no process, dials nothing, writes nothing on its connections and runs no OAuth request or browser flow; its tracked connections are closed and its stdio process group killed. The flag is set first, so the capture and call paths see retirement before the gate's barrier runs. Neither step takes a client lock, so the manager can call Retire under its own locks (L3 W + L4 W → L5 is the documented order). Only the manager retires; Disconnect does not.

func (*Client) Retired added in v0.71.0

func (mc *Client) Retired() bool

Retired reports whether the manager retired the client.

func (*Client) SessionReinitCount added in v0.71.0

func (mc *Client) SessionReinitCount() int64

SessionReinitCount reports how many in-place session re-initializations this client has performed (FR-085).

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.

The instance keeps the commit generation it holds (Spec 116): SetConfig is the legacy path that does not know one.

func (*Client) SetConfigAt added in v0.71.0

func (mc *Client) SetConfigAt(cfg *config.ServerConfig, gen int64) bool

SetConfigAt stores cfg together with its commit generation gen as one atomic pair, but only when gen is newer than the generation the instance holds, so a late legacy worker can never roll the config back (Spec 116 review R9.1). It reports whether it applied. Lock-free, like SetConfig.

func (*Client) SetCredentialBinding added in v0.71.0

func (mc *Client) SetCredentialBinding(b commitview.CredentialBinding)

SetCredentialBinding binds the instance's OAuth state to the committed credential binding b of the view it was built for (Spec 116 PR2b). The upstream manager calls it before the instance becomes reachable.

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) SetListToolsObserver added in v0.71.0

func (mc *Client) SetListToolsObserver(fn func(ListToolsEvent))

SetListToolsObserver installs a test observer for ListTools coalescing (nil removes it). It lets cross-package tests acknowledge that a caller has attached to an in-flight tools/list before releasing it. Tests only.

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) Unregistered added in v0.71.0

func (mc *Client) Unregistered() bool

Unregistered reports whether the upstream manager removed this instance from its registry.

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.

type InstanceID added in v0.71.0

type InstanceID uint64

InstanceID identifies one managed client instance (Spec 116 PR3). Zero is never assigned by NewClient.

type InventoryCapture added in v0.71.0

type InventoryCapture struct {
	Seq    uint64  // process-global, strictly increasing; 0 = unordered
	Epoch  int64   // the client's connection epoch when the list started
	Client *Client // the client that ran the list
}

InventoryCapture identifies one upstream tools/list (Spec 117 PR-3, #1565, FR-030). The leader of a list flight takes it when it owns the list and before the upstream request, and every coalesced waiter of that flight gets the same value. The runtime applies tool inventories in capture order: a capture older than one already applied for the server writes nothing.

Seq comes from one process-global counter, so it also orders captures across a client replacement (remove + re-add, endpoint change). Seq 0 means "unordered": a caller with no managed client (fixtures, tests).

type ListToolsEvent added in v0.71.0

type ListToolsEvent struct {
	Seq    uint64
	Leader bool
	Fresh  bool
}

ListToolsEvent reports one step of ListTools coalescing to a test observer: Leader is true when the caller became the leader of call Seq, false when it attached to call Seq as a waiter. Fresh marks a ListToolsFresh caller.

Jump to

Keyboard shortcuts

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