core

package
v0.69.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const AuthStrategyOAuth = "OAuth"

AuthStrategyOAuth is the name of the OAuth auth strategy as recorded by AuthStrategy. The other strategies ("headers", "no-auth") are internal; only OAuth is something a consumer needs to recognise, because it is the one strategy whose credential lives in the oauth_tokens bucket (GH #1172).

Variables

This section is empty.

Functions

func ContainerOwnedByAny added in v0.68.0

func ContainerOwnedByAny(serverNames []string, containerName, ownerLabel, instanceLabel string) bool

ContainerOwnedByAny is the whole-manager predicate: a container (its name, its com.mcpproxy.server label and its com.mcpproxy.instance label as Docker reported them) is canonically owned by one of serverNames — the configured servers, on THIS mcpproxy instance — under the same label-AND-name-AND-instance rule ownsContainer applies per server. The manager's shutdown and emergency sweeps select containers by the shared com.mcpproxy.managed / com.mcpproxy.instance labels, which any foreign container can copy; only the rows this admits may be stopped, removed or named (codex round 3). Requiring the instance label here too (not just in the sweep's own Docker filter) closes the gap where a sweep that filtered broadly, or a caller re-verifying a single tracked id with no filter at all, would otherwise admit another live mcpproxy instance's container for a same-named server.

func GetInstanceID

func GetInstanceID() string

GetInstanceID returns the unique identifier for this mcpproxy instance (exported for use by manager)

func IsOAuthPending

func IsOAuthPending(err error) bool

IsOAuthPending checks if an error is (or wraps) an ErrOAuthPending.

It MUST unwrap: the pending error is raised inside an auth strategy and then wrapped twice on its way out — connectHTTP/connectSSE add "all authentication strategies failed, last error: %w" and Connect adds "failed to connect: %w". With a bare type assertion the check therefore never fired in production, and every login-blocked server fell through to the generic error path and was re-dialed instead of parked (#1013).

func SetInstanceDataDir added in v0.68.0

func SetInstanceDataDir(dir string)

SetInstanceDataDir records the data directory this process's instance ID should be persisted under (normally cfg.DataDir). Call it once at startup, before the first GetInstanceID() call — e.g. from upstream.NewManager, which every entry point constructs early with the loaded config.

Concurrent mcpproxy processes on the same host must already use distinct data directories (BBolt takes an exclusive lock on config.db), so keying the instance ID off the data dir rather than a single shared file under os.TempDir() gives each process a genuinely distinct ID. A call after the ID has already been resolved, or no call at all, has no effect beyond that first read: GetInstanceID() then falls back to a fresh id for the process's lifetime instead of reusing a host-wide file.

Types

type Client

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

Client implements basic MCP client functionality without state management

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 core MCP client

func NewClientWithOptions

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

NewClientWithOptions creates a new core MCP client with additional options

func (*Client) AuthStrategy added in v0.66.0

func (c *Client) AuthStrategy() string

AuthStrategy reports the name of the auth strategy the CURRENT connection was established with ("headers", "no-auth" or AuthStrategyOAuth), or "" when the client is not connected over HTTP/SSE. It is a fact about the live connection, not the config: a server with a stored OAuth token that connected through its static headers did not use that token.

func (*Client) CallTool

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

CallTool executes a tool on the upstream server

func (*Client) CheckConnectionHealth

func (c *Client) CheckConnectionHealth(ctx context.Context) error

CheckConnectionHealth performs a health check on the connection

func (*Client) ClearOAuthState

func (c *Client) ClearOAuthState()

ClearOAuthState clears OAuth state (public API for manual OAuth flows)

func (*Client) ClearRetryAfter added in v0.61.0

func (c *Client) ClearRetryAfter()

ClearRetryAfter drops any recorded rate-limit hint. Called once a connection succeeds so a hint observed by an auth strategy that was superseded by a working one cannot hold back a later, unrelated reconnect.

func (*Client) Connect

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

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect closes the connection

func (*Client) DisconnectWithContext

func (c *Client) DisconnectWithContext(_ context.Context) error

DisconnectWithContext closes the connection with context timeout

func (*Client) ForceOAuthFlow

func (c *Client) ForceOAuthFlow(ctx context.Context) error

ForceOAuthFlow forces an OAuth authentication flow, bypassing rate limiting (for manual auth)

func (*Client) ForceOAuthFlowWithResult

func (c *Client) ForceOAuthFlowWithResult(ctx context.Context) (*OAuthStartResult, error)

ForceOAuthFlowWithResult forces an OAuth authentication flow and returns the auth URL and browser status. This is used by Phase 3 (Spec 020) to provide the auth URL to clients even when browser opens successfully.

func (*Client) ForceRemoveTrackedContainerIfOwned added in v0.68.0

func (c *Client) ForceRemoveTrackedContainerIfOwned(ctx context.Context, containerID string) (owner string, owned bool, err error)

ForceRemoveTrackedContainerIfOwned is the manager's emergency path for a client whose Disconnect hung: `docker rm -f` the container tracked as containerID, but only after re-establishing canonical ownership NOW — the same ContainerMutator every mutation goes through — so a container renamed, relabelled or reused under that id since it was tracked is left alone (codex round 3). owned reports whether the predicate admitted the container (removal was attempted) and owner is then the com.mcpproxy.server label read back at that moment — the evidence the caller's own records must carry when they name the container (D8, codex round 5); err is the docker error when removal ran and failed, or the lookup error. Records carry container_owner from the label read back; an unowned container is never named in the per-server log.

func (*Client) GetConfig added in v0.17.3

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

GetConfig returns the server configuration

func (*Client) GetConnectionDiagnostics

func (c *Client) GetConnectionDiagnostics() map[string]interface{}

GetConnectionDiagnostics returns detailed diagnostic information about the connection

func (*Client) GetConnectionInfo

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

GetConnectionInfo returns basic connection information

func (*Client) GetContainerID

func (c *Client) GetContainerID() string

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

func (*Client) GetEnvManager

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

GetEnvManager returns the environment manager for testing purposes

func (*Client) GetOAuthHandler added in v0.17.3

func (c *Client) GetOAuthHandler() *transport.OAuthHandler

GetOAuthHandler returns the OAuth handler if the transport supports OAuth. Returns nil if no OAuth handler is configured or transport doesn't support OAuth.

func (*Client) GetPrompt added in v0.59.0

func (c *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 (c *Client) GetServerInfo() *mcp.InitializeResult

GetServerInfo returns server information from initialization

func (*Client) GetStderr

func (c *Client) GetStderr() io.Reader

GetStderr returns stderr reader for stdio transport

func (*Client) GetTransportType

func (c *Client) GetTransportType() string

GetTransportType returns the transport type being used

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected

func (*Client) ListPrompts added in v0.59.0

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

ListPrompts returns the prompts advertised by the upstream server. It returns (nil, nil) — not an error — when the server doesn't advertise Capabilities.Prompts, or when this server's config has explicitly opted out via ExposePrompts: false.

func (*Client) ListTools

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

ListTools retrieves available tools from the upstream server

func (*Client) Ping added in v0.38.0

func (c *Client) Ping(ctx context.Context) error

Ping issues the MCP-standard lightweight liveness check (`ping`) to the upstream server. It is used by the managed client's health loop as a cheap replacement for re-listing every tool just to confirm the connection is alive (spec 074, FR-001). Returns an error if the client is not connected or the request fails so the caller can classify and drive reconnection.

func (*Client) RecentStderrSnapshot added in v0.24.8

func (c *Client) RecentStderrSnapshot() []string

RecentStderrSnapshot returns a copy of the recent stderr lines captured from the child process. Returns nil if nothing has been captured yet.

func (*Client) RefreshOAuthTokenDirect added in v0.17.3

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

RefreshOAuthTokenDirect forces an OAuth token refresh without reconnecting. This is used by the RefreshManager for proactive token refresh. Unlike ForceReconnect (which returns early when already connected), this directly calls the OAuth handler's RefreshToken method, bypassing the IsExpired() check that would prevent refresh of still-valid tokens.

For servers using Dynamic Client Registration (DCR), the handler may not have client credentials populated. In that case, we fall back to manual refresh using stored credentials from the OAuthTokenRecord.

func (*Client) RetryAfterDeadline added in v0.61.0

func (c *Client) RetryAfterDeadline() time.Time

RetryAfterDeadline reports the instant before which this upstream asked us not to come back (from a `Retry-After` on a 429/503), or the zero time when it gave no such hint. The managed client stamps it onto the state machine so both reconnect gates honour it (#1040).

func (*Client) SetExposePrompts added in v0.59.0

func (c *Client) SetExposePrompts(exposePrompts *bool)

SetExposePrompts updates the ExposePrompts override without requiring a reconnect (PR #973 review, P2). Call this whenever the owning managed.Client's config is refreshed so a hot-reloaded expose_prompts value takes effect immediately instead of only after the connection is torn down and recreated.

func (*Client) SetOnPromptsChangedCallback added in v0.59.0

func (c *Client) SetOnPromptsChangedCallback(callback func(serverName string))

SetOnPromptsChangedCallback sets the callback invoked when a notifications/prompts/list_changed notification is received from the upstream MCP server (F13). Enables reactive re-aggregation of upstream prompts.

func (*Client) SetOnToolsChangedCallback

func (c *Client) SetOnToolsChangedCallback(callback func(serverName string))

SetOnToolsChangedCallback sets the callback invoked when a notifications/tools/list_changed notification is received from the upstream MCP server. This enables reactive tool re-indexing.

func (*Client) StartOAuthFlowQuick

func (c *Client) StartOAuthFlowQuick(ctx context.Context) (*OAuthStartResult, error)

StartOAuthFlowQuick starts the OAuth flow and returns browser status immediately. Unlike ForceOAuthFlowWithResult which blocks until OAuth completes, this function: 1. Gets authorization URL synchronously (quick operation) 2. Checks HEADLESS environment variable 3. Attempts browser open and captures result 4. Returns OAuthStartResult immediately 5. Continues OAuth callback handling in a goroutine

This is used by the login API endpoint to return accurate browser_opened status without blocking the HTTP response for the full OAuth flow.

func (*Client) StartProcessMonitoring

func (c *Client) StartProcessMonitoring()

StartProcessMonitoring starts monitoring the underlying process

func (*Client) StartStderrMonitoring

func (c *Client) StartStderrMonitoring()

StartStderrMonitoring starts monitoring stderr output and logging it

func (*Client) StopProcessMonitoring

func (c *Client) StopProcessMonitoring()

StopProcessMonitoring stops process monitoring

func (*Client) StopStderrMonitoring

func (c *Client) StopStderrMonitoring()

StopStderrMonitoring stops stderr monitoring

type ContainerLock

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

ContainerLock provides per-server locking for container creation This prevents race conditions where multiple goroutines try to create containers for the same server simultaneously (e.g., during ForceReconnectAll)

func (*ContainerLock) Lock

func (cl *ContainerLock) Lock(serverName string) *sync.Mutex

Lock acquires a lock for the specified server name Returns a mutex that the caller MUST unlock when done

type ContainerMutation added in v0.68.0

type ContainerMutation string

ContainerMutation is one of the docker commands that change a container's state.

const (
	ContainerStop   ContainerMutation = "stop"
	ContainerKill   ContainerMutation = "kill"
	ContainerRemove ContainerMutation = "rm" // run as `docker rm -f`
)

type ContainerMutator added in v0.68.0

type ContainerMutator struct {
	Docker DockerCommand
	Owns   func(containerName, ownerLabel, instanceLabel string) bool
}

ContainerMutator is the one verify-then-mutate implementation every Docker mutation goes through — the core client's cleanup paths and the manager's sweeps alike (Spec 105 FR-007 / D9, codex round 6). Docker runs the CLI; Owns is the ownership predicate over the name and label read back (ownsContainer for one server, ContainerOwnedByAny for the manager).

func (ContainerMutator) Mutate added in v0.68.0

Mutate re-reads container id immediately before running op on it and runs it only if the row read back has exactly that full id and satisfies Owns. intent, when set, is called with that row right before the command so the caller can record what is about to happen with mutation-time evidence.

func (ContainerMutator) Verify added in v0.68.0

func (cm ContainerMutator) Verify(ctx context.Context, id string) (ContainerRow, bool, error)

Verify re-reads container id and reports whether it still satisfies Owns right now — the same read+predicate Mutate applies before running a command, exposed for a caller that only needs to confirm ownership without mutating anything (e.g. a health check re-establishing ownership before trusting `docker inspect`, codex round 8). ok is true only when the read succeeded and the row's label and name pass Owns; row is the meaningful evidence — id, name and owner label as Docker reported them — only when ok is true.

type ContainerRow added in v0.68.0

type ContainerRow struct {
	ID       string
	Name     string
	Owner    string
	Instance string
	Status   string
}

ContainerRow is a container's identity AND running state as Docker reported them in one read: full id, name, com.mcpproxy.server label value and `docker ps`'s own human status text (e.g. "Up 5 minutes", "Exited (0) 2 minutes ago", "Up 5 minutes (Paused)"). Status, not just identity, comes from this same read (codex round 16 finding 1): a caller that re-read state with a SEPARATE `docker inspect <id>` after Verify trusted whatever container held that id at the LATER moment, which another Docker client can have relabelled or renamed in between.

func (ContainerRow) Running added in v0.68.0

func (r ContainerRow) Running() bool

Running reports whether the container was up — running or paused, exactly `docker inspect`'s State.Running — at the read that produced this row. `docker ps --format` has no `.Running` boolean field (verified against a live daemon: only `.State`, the short State.Status word, and `.Status`, the human text `docker ps` prints in its STATUS column); `.State` is State.Status, not State.Running, so a paused container (State.Status "paused", State.Running true) would misreport as not running through it. Docker's own convention for that STATUS text prefixes "Up" precisely when State.Running is true — including while paused ("Up 5 minutes (Paused)") — so Status carries the same information State.Running would, without a second command.

type DockerCommand added in v0.68.0

type DockerCommand func(ctx context.Context, args ...string) *exec.Cmd

DockerCommand builds one docker invocation: the core client resolves the binary through newDockerCmd, the manager execs the bare name.

type ErrOAuthPending

type ErrOAuthPending struct {
	ServerName string
	ServerURL  string
	Message    string
}

ErrOAuthPending represents a deferred OAuth authentication requirement. This error indicates that OAuth is required but has been intentionally deferred (e.g., for user action via tray UI or CLI) rather than being a connection failure.

func (*ErrOAuthPending) Code added in v0.39.0

func (e *ErrOAuthPending) Code() diagnostics.Code

Code attributes a stable diagnostic code so diagnostics.Classify's typed fast-path resolves this to an actionable OAuth user-state instead of MCPX_UNKNOWN_UNCLASSIFIED. A first-time sign-in maps to OAuthLoginRequired; the "stored token broke" variant (connection_oauth.go server-5xx path) maps to OAuthReauthRequired. The distinction is carried in the message text so the stringified error classifies the same way downstream (e.g. health). MCP-1820.

func (*ErrOAuthPending) Error

func (e *ErrOAuthPending) Error() string

type IsolationManager

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

IsolationManager handles Docker isolation logic for MCP servers

func NewIsolationManager

func NewIsolationManager(globalConfig *config.DockerIsolationConfig) *IsolationManager

NewIsolationManager creates a new isolation manager.

func NewIsolationManagerWithLogger added in v0.24.7

func NewIsolationManagerWithLogger(globalConfig *config.DockerIsolationConfig, logger *zap.Logger) *IsolationManager

NewIsolationManagerWithLogger creates a new isolation manager with a structured logger. The logger is optional — when nil, warnings about ignored per-server isolation opt-ins are silently dropped (callers that care about those warnings should pass a logger).

func (*IsolationManager) BuildDockerArgs

func (im *IsolationManager) BuildDockerArgs(serverConfig *config.ServerConfig, runtimeType string) ([]string, error)

BuildDockerArgs constructs Docker run arguments for isolation

func (*IsolationManager) DetectRuntimeType

func (im *IsolationManager) DetectRuntimeType(command string) string

DetectRuntimeType detects the runtime type based on the command

func (*IsolationManager) GetDockerImage

func (im *IsolationManager) GetDockerImage(serverConfig *config.ServerConfig, runtimeType string) (string, error)

GetDockerImage returns the appropriate Docker image for a server.

Resolution order:

  1. the per-server `isolation.image` override — an explicit user choice always wins;
  2. the git-capable image, when the server is a Python package runner installing from a git URL AND nothing in `default_images` has been retargeted at the operator's own registry (#1143 — see resolveDefaultImage, which explains why a mirrored install keeps its own image instead);
  3. the runtime type's entry in `default_images`;
  4. alpine, for unknown runtime types.

func (*IsolationManager) GetDockerIsolationWarning

func (im *IsolationManager) GetDockerIsolationWarning(serverConfig *config.ServerConfig) string

GetDockerIsolationWarning returns a warning message if Docker isolation is enabled with local files

func (*IsolationManager) HasLocalFilePath

func (im *IsolationManager) HasLocalFilePath(serverConfig *config.ServerConfig) bool

HasLocalFilePath checks if server arguments contain local file paths

func (*IsolationManager) ResolveDefaults added in v0.26.0

func (im *IsolationManager) ResolveDefaults(serverConfig *config.ServerConfig) *ResolvedIsolationDefaults

ResolveDefaults returns the resolved default isolation values for the given server, computed from the detected runtime type and global DockerIsolationConfig — without applying any per-server overrides.

This intentionally does NOT short-circuit when isolation is disabled for the server: the result describes what would be used if isolation were active, which is what UI placeholders need to surface.

Returns nil if the global config is missing (degenerate state).

func (*IsolationManager) ResolveIsolation added in v0.64.0

func (im *IsolationManager) ResolveIsolation(serverConfig *config.ServerConfig) ResolvedIsolation

ResolveIsolation resolves the effective isolation state for a server — the single source of truth for "is this server isolated" (GH #1142). The algorithm lives in config.ResolveIsolation so every reporting surface runs the same code; this wrapper adds the deduplicated warning for a per-server opt-in that the global setting is ignoring.

func (*IsolationManager) ResolveMode added in v0.46.0

func (im *IsolationManager) ResolveMode(serverConfig *config.ServerConfig) config.IsolationMode

ResolveMode resolves the effective isolation mode for a server (MCP-34.2) — the mode-only view of ResolveIsolation. See config.ResolveIsolation for the precedence rules and the structural gates.

func (*IsolationManager) ResolveScannerMode added in v0.68.0

func (im *IsolationManager) ResolveScannerMode(serverConfig *config.ServerConfig) (config.IsolationMode, string)

ResolveScannerMode resolves the isolation mode governing whether DOCKER-BASED security scanner plugins may run against this server, and why (GH #1303).

It is NOT the process-isolation mode: ResolveMode/ShouldIsolate remain the only answer to "how is this server's child process launched". Scanner plugins run in their own short-lived containers over tool definitions already captured over MCP, so the process-spawn structural gates (no local command to wrap; the command already invokes docker) do not apply — see config.ResolveScannerIsolationMode.

Unlike ResolveIsolation this emits no ignored-opt-in warning: that warning is about the spawn decision and is deduped per server name, so firing it here would suppress the one the spawn path owes the operator.

func (*IsolationManager) SetLogger added in v0.24.7

func (im *IsolationManager) SetLogger(logger *zap.Logger)

SetLogger sets the logger on an existing IsolationManager. Intended for call sites that build the manager before a logger is available (e.g. in config-time code) but want per-server warnings at runtime.

func (*IsolationManager) ShouldIsolate

func (im *IsolationManager) ShouldIsolate(serverConfig *config.ServerConfig) bool

ShouldIsolate determines if a server should be isolated via Docker, based on global and server config. It is the legacy boolean view of ResolveMode and stays in lockstep with it: it returns true iff the resolved mode is "docker". Callers that need to distinguish sandbox/none should call ResolveMode.

func (*IsolationManager) TransformCommandForContainer

func (im *IsolationManager) TransformCommandForContainer(command string, args []string, runtimeType string) (containerCommand string, containerArgs []string)

TransformCommandForContainer transforms the original command to run inside the container

type MutationResult added in v0.68.0

type MutationResult struct {
	Container ContainerRow
	Verified  bool
	Err       error
}

MutationResult is what ContainerMutator.Mutate reports. Verified is true when ownership held at the re-read and the command ran, in which case Container is the row read then and Err the docker error if the command failed. Verified false with a nil Err means the container no longer satisfies the predicate (or is gone); with a non-nil Err the re-read itself failed. Nothing was run in either case.

type OAuthParameterError

type OAuthParameterError struct {
	Parameter   string
	Location    string // "authorization_url" or "token_request"
	Message     string
	OriginalErr error
}

OAuthParameterError represents a missing or invalid OAuth parameter

func (*OAuthParameterError) Error

func (e *OAuthParameterError) Error() string

func (*OAuthParameterError) Unwrap

func (e *OAuthParameterError) Unwrap() error

type OAuthStartResult

type OAuthStartResult struct {
	AuthURL       string // The authorization URL for manual use
	BrowserOpened bool   // Whether the browser was successfully opened
	BrowserError  string // Error message if browser opening failed
	CorrelationID string // Unique ID for tracking this OAuth flow
}

OAuthStartResult contains the result of initiating an OAuth flow. Used by Phase 3 (Spec 020) to return auth URL and browser status synchronously.

type ProcessGroup

type ProcessGroup struct {
	PGID int
}

ProcessGroup represents a Unix process group for proper child process management

type ResolvedIsolation added in v0.64.0

type ResolvedIsolation = config.ResolvedIsolation

ResolvedIsolation is re-exported from the config package so callers in this package can keep referring to it without importing config explicitly.

type ResolvedIsolationDefaults added in v0.26.0

type ResolvedIsolationDefaults struct {
	// RuntimeType is the runtime detected from the server command (e.g.
	// "uvx", "npx", "python"). Useful for diagnostic display.
	RuntimeType string

	// Image is the fully-qualified Docker image that would be used,
	// already including registry prefixes via buildFullImageName.
	Image string

	// NetworkMode is the network mode that would be used (typically
	// inherited from the global DockerIsolationConfig).
	NetworkMode string

	// ExtraArgs is the global extra args list that the server would
	// inherit. Per-server extra_args are appended on top, so this
	// communicates the baseline.
	ExtraArgs []string

	// ContainerWorkingDir is the working directory that would be used
	// inside the container. Empty when the global config does not
	// specify one (Docker default applies).
	ContainerWorkingDir string
}

ResolvedIsolationDefaults captures the per-runtime default values that would be used for a server when no per-server overrides are set. It is used by the REST API to expose contextual placeholders to UI clients (notably the macOS tray) so users can see exactly what an "empty" override field will resolve to before deciding whether to override it.

Jump to

Keyboard shortcuts

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