Documentation
¶
Overview ¶
Package pool provides stdio MCP server subprocess pooling and management. It handles concurrent request processing, health monitoring, and lifecycle management for multiple stdio-based MCP servers.
Index ¶
- Constants
- func CheckSandboxRuntime(runtime string) error
- func ChildEnvReport(parentEnv []string, cfg StdioServerConfig) (passed, dropped []string, err error)
- func RequestIDKey(raw json.RawMessage) (string, bool)
- func ScrubURLs(s string) string
- func UpstreamClientCapabilities(cfg *migrate.ServerConfig, acceptsRequests bool) mcp.ClientCapabilities
- type HTTPClientPool
- func (p *HTTPClientPool) Close() error
- func (p *HTTPClientPool) GetServerState(name string) (ServerState, error)
- func (p *HTTPClientPool) GetServerTransport(name string) (string, error)
- func (p *HTTPClientPool) HasServer(name string) bool
- func (p *HTTPClientPool) ListServers() []string
- func (p *HTTPClientPool) RemoveServer(name string) error
- func (p *HTTPClientPool) RestartServer(ctx context.Context, name string) error
- func (p *HTTPClientPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, ...) (*proxy.JSONRPCResponse, error)
- func (p *HTTPClientPool) SendRequestToServer(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *HTTPClientPool) SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *HTTPClientPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
- func (p *HTTPClientPool) ServerCount() int
- func (p *HTTPClientPool) ServerInitializeResult(name string) (*InitializeResult, bool)
- func (p *HTTPClientPool) SetServerEventHandler(fn ServerEventHandler)
- func (p *HTTPClientPool) SetServerMessageHandler(h ServerMessageHandler)
- func (p *HTTPClientPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
- type HTTPClientServer
- func (s *HTTPClientServer) CallTool(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error)
- func (s *HTTPClientServer) Close() error
- func (s *HTTPClientServer) Initialize(ctx context.Context) error
- func (s *HTTPClientServer) ListTools(ctx context.Context) ([]mcp.Tool, error)
- type HealthCheckResult
- type HealthChecker
- func (hc *HealthChecker) CheckServer(ctx context.Context, name string) HealthCheckResult
- func (hc *HealthChecker) GetAllHealth() map[string]HealthCheckResult
- func (hc *HealthChecker) GetServerHealth(name string) (HealthStatus, error)
- func (hc *HealthChecker) RegisterServer(name string)
- func (hc *HealthChecker) SetMaxFailures(n int)
- func (hc *HealthChecker) Start(ctx context.Context, interval time.Duration)
- func (hc *HealthChecker) Stop()
- func (hc *HealthChecker) UnregisterServer(name string)
- type HealthStatus
- type InitializeResult
- type PingRequest
- type PingResponse
- type ReconnectSettings
- type Request
- type Response
- type SSEPool
- func (p *SSEPool) Close() error
- func (p *SSEPool) GetServerState(name string) (ServerState, error)
- func (p *SSEPool) GetServerTransport(name string) (string, error)
- func (p *SSEPool) HasServer(name string) bool
- func (p *SSEPool) ListServers() []string
- func (p *SSEPool) RemoveServer(name string) error
- func (p *SSEPool) RestartServer(ctx context.Context, name string) error
- func (p *SSEPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, ...) (*proxy.JSONRPCResponse, error)
- func (p *SSEPool) SendRequestToServer(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *SSEPool) SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *SSEPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
- func (p *SSEPool) ServerCount() int
- func (p *SSEPool) ServerInitializeResult(name string) (*InitializeResult, bool)
- func (p *SSEPool) SetServerEventHandler(fn ServerEventHandler)
- func (p *SSEPool) SetServerMessageHandler(h ServerMessageHandler)
- func (p *SSEPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
- type SSEServer
- type ServerEvent
- type ServerEventHandler
- type ServerEventKind
- type ServerEventSource
- type ServerHandle
- type ServerInfo
- type ServerMessageHandler
- type ServerMessageSource
- type ServerSnapshot
- type ServerSource
- type ServerState
- type ServerStats
- type SessionInfoProvider
- type StdioPool
- func (p *StdioPool) Close() error
- func (p *StdioPool) GetOrStartServer(ctx context.Context, name string) (*StdioServerV2, error)
- func (p *StdioPool) GetServer(name string) (*StdioServerV2, error)
- func (p *StdioPool) GetServerState(name string) (ServerState, error)
- func (p *StdioPool) GetServerStats(name string) (ServerStats, error)
- func (p *StdioPool) GetServerTransport(name string) (string, error)
- func (p *StdioPool) HasServer(name string) bool
- func (p *StdioPool) IsServerMCPInitialized(name string) bool
- func (p *StdioPool) ListServers() []string
- func (p *StdioPool) MarkServerMCPInitialized(name string)
- func (p *StdioPool) PutRequest(name string, req Request) error
- func (p *StdioPool) RemoveServer(name string) error
- func (p *StdioPool) RestartServer(ctx context.Context, name string) error
- func (p *StdioPool) SendNotificationToServer(ctx context.Context, name string, method string, params json.RawMessage) error
- func (p *StdioPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, ...) (*proxy.JSONRPCResponse, error)
- func (p *StdioPool) SendRequestToServer(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *StdioPool) SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *StdioPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
- func (p *StdioPool) ServerCount() int
- func (p *StdioPool) ServerInitializeResult(name string) (*InitializeResult, bool)
- func (p *StdioPool) ServerRecentStderr(name string) string
- func (p *StdioPool) SetReconnect(settings ReconnectSettings)
- func (p *StdioPool) SetServerEventHandler(fn ServerEventHandler)
- func (p *StdioPool) SetServerMessageHandler(h ServerMessageHandler)
- func (p *StdioPool) StartAllServers(ctx context.Context, configs []*migrate.ServerConfig) error
- func (p *StdioPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
- func (p *StdioPool) StopServer(name string) error
- type StdioServerConfig
- type StdioServerV2
- type UnifiedPool
- func (p *UnifiedPool) Close() error
- func (p *UnifiedPool) GetServerState(name string) (ServerState, error)
- func (p *UnifiedPool) GetServerTransport(name string) (string, error)
- func (p *UnifiedPool) ListServers() []string
- func (p *UnifiedPool) RemoveServer(name string) error
- func (p *UnifiedPool) RestartServer(ctx context.Context, name string) error
- func (p *UnifiedPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, ...) (*proxy.JSONRPCResponse, error)
- func (p *UnifiedPool) SendRequestToServer(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *UnifiedPool) SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, ...) (*Response, error)
- func (p *UnifiedPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
- func (p *UnifiedPool) ServerInitializeResult(name string) (*InitializeResult, bool)
- func (p *UnifiedPool) SetServerEventHandler(fn ServerEventHandler)
- func (p *UnifiedPool) SetServerMessageHandler(h ServerMessageHandler)
- func (p *UnifiedPool) Snapshot(name string) (ServerSnapshot, bool)
- func (p *UnifiedPool) Snapshots() []ServerSnapshot
- func (p *UnifiedPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
Constants ¶
const ( MethodPing = "ping" MethodSamplingCreateMessage = "sampling/createMessage" MethodElicitationCreate = "elicitation/create" MethodRootsList = "roots/list" MethodProgressNotification = "notifications/progress" MethodCancelledNotification = methodCancelledNotification MethodResourcesUpdatedNotification = "notifications/resources/updated" MethodElicitationCompleteNotification = "notifications/elicitation/complete" MethodRootsListChangedNotification = "notifications/roots/list_changed" )
MCP methods an upstream server may send to the proxy.
const ( // MethodToolsListChanged is the notification an upstream sends when its // tool list changed; the pool surfaces it as EventToolsListChanged. MethodToolsListChanged = "notifications/tools/list_changed" // MethodResourcesListChanged and MethodPromptsListChanged are surfaced // as EventResourcesListChanged and EventPromptsListChanged. MethodResourcesListChanged = "notifications/resources/list_changed" MethodPromptsListChanged = "notifications/prompts/list_changed" )
MCP methods owned by the pool's handshake (issue #297). Callers never send them: the pool performs `initialize` + `notifications/initialized` exactly once per server process generation (stdio) or connection (HTTP/SSE).
const ( // DefaultMaxInFlight is the default per-server cap on requests // multiplexed concurrently over one stdio pipe (max_in_flight). DefaultMaxInFlight = 32 )
const ( // DefaultMaxResponseBytes is the default cap on one JSON-RPC message // (one stdout line) read from a stdio server (max_response_bytes). DefaultMaxResponseBytes = 64 << 20 )
const RequestedProtocolVersion = "2025-11-25"
RequestedProtocolVersion is the MCP revision the pool asks every upstream for in its initialize handshake: the latest one LeanProxy speaks (it must equal mcp.LatestProtocolVersion; pkg/mcp tests enforce it). The server may answer with an older revision; whatever it returns is accepted and stored in its InitializeResult with its capabilities.
Variables ¶
This section is empty.
Functions ¶
func CheckSandboxRuntime ¶ added in v1.1.1
CheckSandboxRuntime reports whether runtime ("docker" or "podman") is available on PATH, for `leanproxy doctor sandbox` (#312) to show without needing a live server config.
func ChildEnvReport ¶ added in v1.1.1
func ChildEnvReport(parentEnv []string, cfg StdioServerConfig) (passed, dropped []string, err error)
ChildEnvReport returns, for `leanproxy-mcp doctor` (#311), the sorted names of the environment variables that would be passed to cfg's child process and the sorted names of parent variables that would be dropped. It never returns or logs values.
func RequestIDKey ¶ added in v1.1.1
func RequestIDKey(raw json.RawMessage) (string, bool)
RequestIDKey normalizes a raw JSON-RPC id into a map key: strings and numbers get distinct prefixes (1 and "1" are different ids). ok is false for a missing, null or non-scalar id.
func ScrubURLs ¶ added in v1.1.1
ScrubURLs removes the credentials, query string and fragment of every http(s) URL in s. Transport errors quote the URL they failed on, and a configured URL may carry a key in its query or a password in its userinfo: the error is kept for display, so those parts must not be.
func UpstreamClientCapabilities ¶ added in v1.1.1
func UpstreamClientCapabilities(cfg *migrate.ServerConfig, acceptsRequests bool) mcp.ClientCapabilities
UpstreamClientCapabilities returns the client capabilities the pool declares to an upstream in its initialize handshake (issue #308):
- roots: always (answered from servers[].roots when configured, else relayed to the client; listChanged only in the relayed case, where the client's notifications/roots/list_changed is forwarded);
- elicitation (form and URL mode): relayed to the client;
- sampling: only with servers[].allow_sampling: true.
acceptsRequests is false for a transport that cannot receive server-to-client requests (legacy SSE): nothing is declared then, so the upstream never sends a request that could not be answered.
Types ¶
type HTTPClientPool ¶ added in v0.5.0
type HTTPClientPool struct {
// contains filtered or unexported fields
}
func NewHTTPClientPool ¶ added in v0.5.0
func NewHTTPClientPool(logger *slog.Logger) *HTTPClientPool
func (*HTTPClientPool) Close ¶ added in v0.5.0
func (p *HTTPClientPool) Close() error
func (*HTTPClientPool) GetServerState ¶ added in v0.5.0
func (p *HTTPClientPool) GetServerState(name string) (ServerState, error)
func (*HTTPClientPool) GetServerTransport ¶ added in v1.1.1
func (p *HTTPClientPool) GetServerTransport(name string) (string, error)
GetServerTransport reports the transport this server is configured with. It always returns "http" for an HTTPClientPool member.
func (*HTTPClientPool) HasServer ¶ added in v0.5.0
func (p *HTTPClientPool) HasServer(name string) bool
func (*HTTPClientPool) ListServers ¶ added in v0.5.0
func (p *HTTPClientPool) ListServers() []string
func (*HTTPClientPool) RemoveServer ¶ added in v1.1.1
func (p *HTTPClientPool) RemoveServer(name string) error
RemoveServer closes the named HTTP server's connection and forgets it.
func (*HTTPClientPool) RestartServer ¶ added in v0.5.0
func (p *HTTPClientPool) RestartServer(ctx context.Context, name string) error
func (*HTTPClientPool) SendRequest ¶ added in v0.5.0
func (p *HTTPClientPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, timeout time.Duration) (*proxy.JSONRPCResponse, error)
func (*HTTPClientPool) SendRequestToServer ¶ added in v0.5.0
func (*HTTPClientPool) SendRequestToServerWithID ¶ added in v0.5.0
func (*HTTPClientPool) SendServerNotification ¶ added in v0.5.0
func (p *HTTPClientPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
SendServerNotification sends a notification to the named server over its current connection (connecting first when needed).
func (*HTTPClientPool) ServerCount ¶ added in v0.5.0
func (p *HTTPClientPool) ServerCount() int
func (*HTTPClientPool) ServerInitializeResult ¶ added in v1.1.1
func (p *HTTPClientPool) ServerInitializeResult(name string) (*InitializeResult, bool)
ServerInitializeResult returns the InitializeResult of the named server's current connection.
func (*HTTPClientPool) SetServerEventHandler ¶ added in v1.1.1
func (p *HTTPClientPool) SetServerEventHandler(fn ServerEventHandler)
SetServerEventHandler registers the handler that receives every server's lifecycle events (new connection, tools/list_changed).
func (*HTTPClientPool) SetServerMessageHandler ¶ added in v1.1.1
func (p *HTTPClientPool) SetServerMessageHandler(h ServerMessageHandler)
SetServerMessageHandler registers the handler that receives what every server initiates (server-to-client requests, progress, ...).
func (*HTTPClientPool) StartServer ¶ added in v0.5.0
func (p *HTTPClientPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
type HTTPClientServer ¶ added in v0.5.0
type HTTPClientServer struct {
// contains filtered or unexported fields
}
func NewHTTPClientServer ¶ added in v0.5.0
func NewHTTPClientServer(name string, config *migrate.ServerConfig, logger *slog.Logger) *HTTPClientServer
func (*HTTPClientServer) CallTool ¶ added in v0.5.0
func (s *HTTPClientServer) CallTool(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error)
func (*HTTPClientServer) Close ¶ added in v0.5.0
func (s *HTTPClientServer) Close() error
func (*HTTPClientServer) Initialize ¶ added in v0.5.0
func (s *HTTPClientServer) Initialize(ctx context.Context) error
type HealthCheckResult ¶
type HealthChecker ¶
type HealthChecker struct {
// contains filtered or unexported fields
}
func NewHealthChecker ¶
func NewHealthChecker(pool *StdioPool, logger *slog.Logger) *HealthChecker
func (*HealthChecker) CheckServer ¶
func (hc *HealthChecker) CheckServer(ctx context.Context, name string) HealthCheckResult
func (*HealthChecker) GetAllHealth ¶
func (hc *HealthChecker) GetAllHealth() map[string]HealthCheckResult
func (*HealthChecker) GetServerHealth ¶
func (hc *HealthChecker) GetServerHealth(name string) (HealthStatus, error)
func (*HealthChecker) RegisterServer ¶
func (hc *HealthChecker) RegisterServer(name string)
func (*HealthChecker) SetMaxFailures ¶ added in v0.9.0
func (hc *HealthChecker) SetMaxFailures(n int)
func (*HealthChecker) Start ¶
func (hc *HealthChecker) Start(ctx context.Context, interval time.Duration)
func (*HealthChecker) Stop ¶
func (hc *HealthChecker) Stop()
Stop signals the checker loop to exit. It is idempotent.
func (*HealthChecker) UnregisterServer ¶
func (hc *HealthChecker) UnregisterServer(name string)
type HealthStatus ¶
type HealthStatus string
const ( HealthUnknown HealthStatus = "unknown" HealthHealthy HealthStatus = "healthy" HealthDegraded HealthStatus = "degraded" HealthUnhealthy HealthStatus = "unhealthy" HealthError HealthStatus = "error" )
type InitializeResult ¶ added in v1.1.1
type InitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities json.RawMessage `json:"capabilities,omitempty"`
ServerInfo ServerInfo `json:"serverInfo"`
Instructions string `json:"instructions,omitempty"`
// Generation is the process generation (stdio) or connection number
// (HTTP/SSE) this result belongs to.
Generation uint64 `json:"-"`
// Raw is the result exactly as the server sent it.
Raw json.RawMessage `json:"-"`
}
InitializeResult is what an upstream server answered to the MCP initialize handshake of its current session. It is stored per server so list_servers can show serverInfo/instructions and so a later protocol upgrade can inspect the negotiated version and capabilities.
type PingRequest ¶
type PingResponse ¶
type PingResponse struct {
ID interface{} `json:"id"`
JSONRPC string `json:"jsonrpc"`
Result json.RawMessage `json:"result,omitempty"`
Error *errors.JSONRPCError `json:"error,omitempty"`
}
type ReconnectSettings ¶ added in v0.9.0
type ReconnectSettings struct {
// Disabled is the reconnect.enabled=false master switch: crashed servers
// are left in the error state instead of being auto-restarted. Explicit
// restarts (request- or operator-triggered) still work.
Disabled bool
MaxRestartAttempts int
RestartBackoff time.Duration
StableWindow time.Duration
}
ReconnectSettings controls the automatic restart behavior of stdio servers.
type Request ¶
type Request struct {
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
ID interface{} `json:"id"`
Timeout time.Duration `json:"-"`
ResultCh chan *Response `json:"-"`
ErrorCh chan error `json:"-"`
}
Request represents a JSON-RPC request for an MCP server.
func (Request) MarshalJSON ¶ added in v0.3.0
MarshalJSON serializes the Request to JSON with JSON-RPC 2.0 formatting.
type Response ¶
type Response struct {
Result json.RawMessage `json:"result,omitempty"`
Error *errors.JSONRPCError `json:"error,omitempty"`
ID interface{} `json:"id"`
}
Response represents a JSON-RPC response from an MCP server.
type SSEPool ¶ added in v0.5.0
type SSEPool struct {
// contains filtered or unexported fields
}
func NewSSEPool ¶ added in v0.5.0
func (*SSEPool) GetServerState ¶ added in v0.5.0
func (p *SSEPool) GetServerState(name string) (ServerState, error)
func (*SSEPool) GetServerTransport ¶ added in v1.1.1
GetServerTransport reports the transport this server is configured with. It always returns "sse" for an SSEPool member.
func (*SSEPool) ListServers ¶ added in v0.5.0
func (*SSEPool) RemoveServer ¶ added in v1.1.1
RemoveServer closes the named SSE server's connection and forgets it.
func (*SSEPool) RestartServer ¶ added in v0.5.0
func (*SSEPool) SendRequest ¶ added in v0.5.0
func (*SSEPool) SendRequestToServer ¶ added in v0.5.0
func (*SSEPool) SendRequestToServerWithID ¶ added in v0.5.0
func (*SSEPool) SendServerNotification ¶ added in v0.5.0
func (p *SSEPool) SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
SendServerNotification sends a notification to the named server over its current connection (connecting first when needed).
func (*SSEPool) ServerCount ¶ added in v0.5.0
func (*SSEPool) ServerInitializeResult ¶ added in v1.1.1
func (p *SSEPool) ServerInitializeResult(name string) (*InitializeResult, bool)
ServerInitializeResult returns the InitializeResult of the named server's current connection.
func (*SSEPool) SetServerEventHandler ¶ added in v1.1.1
func (p *SSEPool) SetServerEventHandler(fn ServerEventHandler)
SetServerEventHandler registers the handler that receives every server's lifecycle events (new connection, tools/list_changed).
func (*SSEPool) SetServerMessageHandler ¶ added in v1.1.1
func (p *SSEPool) SetServerMessageHandler(h ServerMessageHandler)
SetServerMessageHandler registers the handler that receives the notifications every server initiates (progress, resource updates, ...).
func (*SSEPool) StartServer ¶ added in v0.5.0
type SSEServer ¶ added in v0.5.0
type SSEServer struct {
// contains filtered or unexported fields
}
func NewSSEServer ¶ added in v0.5.0
func (*SSEServer) Initialize ¶ added in v0.5.0
type ServerEvent ¶ added in v1.1.1
type ServerEvent struct {
Server string
Kind ServerEventKind
Generation uint64
}
ServerEvent is a lifecycle event of one upstream server.
type ServerEventHandler ¶ added in v1.1.1
type ServerEventHandler func(ServerEvent)
ServerEventHandler receives server events. It is called on its own goroutine and may block.
type ServerEventKind ¶ added in v1.1.1
type ServerEventKind int
ServerEventKind identifies a server lifecycle event.
const ( // EventSessionStarted fires when a server gets a new session: a stdio // process generation was spawned (initial start or restart) or an // HTTP/SSE client (re)connected. Its tool list may have changed. EventSessionStarted ServerEventKind = iota + 1 // EventToolsListChanged fires when an upstream sent // notifications/tools/list_changed. EventToolsListChanged // EventResourcesListChanged fires when an upstream sent // notifications/resources/list_changed. EventResourcesListChanged // EventPromptsListChanged fires when an upstream sent // notifications/prompts/list_changed. EventPromptsListChanged )
func (ServerEventKind) String ¶ added in v1.1.1
func (k ServerEventKind) String() string
type ServerEventSource ¶ added in v1.1.1
type ServerEventSource interface {
SetServerEventHandler(fn ServerEventHandler)
}
ServerEventSource is implemented by pools that report server lifecycle events (new session, tools/list_changed).
type ServerHandle ¶
type ServerHandle struct {
Name string
State ServerState
Stats ServerStats
}
type ServerInfo ¶ added in v1.1.1
ServerInfo is the upstream server's self-description from its InitializeResult.
type ServerMessageHandler ¶ added in v1.1.1
type ServerMessageHandler interface {
// HandleServerRequest answers a server-to-client request from the
// named upstream. It runs on its own goroutine. ctx ends when the
// upstream cancels the request (cancel notification) or its
// connection ends. When an HTTP upstream sends the request on the
// response stream of a call, ctx also carries that call's values; a
// request on the GET stream (or from a stdio upstream) carries none.
// The returned error, when non-nil, is sent to the upstream as the
// JSON-RPC error of the answer.
HandleServerRequest(ctx context.Context, server, method string, params json.RawMessage) (json.RawMessage, *errs.JSONRPCError)
// HandleServerNotification receives an upstream notification the pool
// does not consume itself (progress, resource updates, ...). It is
// called inline by the connection's reader, in arrival order, so it
// must not block for long.
HandleServerNotification(ctx context.Context, server, method string, params json.RawMessage)
}
ServerMessageHandler receives what an upstream initiates and the pool does not handle itself.
type ServerMessageSource ¶ added in v1.1.1
type ServerMessageSource interface {
SetServerMessageHandler(h ServerMessageHandler)
}
ServerMessageSource is implemented by pools that relay server-initiated messages.
type ServerSnapshot ¶ added in v1.1.1
type ServerSnapshot struct {
Name string `json:"name"`
Transport string `json:"transport"`
State ServerState `json:"state"`
// Initialized is true once the MCP handshake of the current process
// (stdio) or connection (HTTP/SSE) completed.
Initialized bool `json:"initialized"`
ProtocolVersion string `json:"protocol_version,omitempty"`
ServerName string `json:"server_name,omitempty"`
ServerVersion string `json:"server_version,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
// Generation counts the process spawns (stdio) or connections
// (HTTP/SSE) of this server since the proxy started.
Generation uint64 `json:"generation,omitempty"`
Requests int64 `json:"requests"`
Errors int64 `json:"errors"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
InFlight int `json:"in_flight"`
LastRequestAt time.Time `json:"last_request_at,omitzero"`
// LastError is the latest failure: a crash or spawn error (stdio), a
// failed connection (HTTP/SSE), or the latest failed call.
LastError string `json:"last_error,omitempty"`
LastErrorAt time.Time `json:"last_error_at,omitzero"`
// Stdio only.
PID int `json:"pid,omitempty"`
StartedAt time.Time `json:"started_at,omitzero"`
RestartCount int `json:"restart_count,omitempty"`
RecentStderr string `json:"recent_stderr,omitempty"`
// ConnectedAt is when the current connection was established (HTTP/SSE).
ConnectedAt time.Time `json:"connected_at,omitzero"`
}
ServerSnapshot is the runtime state of one upstream server, whatever its transport: what an operator needs to answer "is it up, and if not, why". It is a read-only copy; nothing in it is a secret (stderr lines are already redacted when they are captured).
type ServerSource ¶ added in v0.5.0
type ServerSource interface {
SendRequestToServer(ctx context.Context, name string, method string, params json.RawMessage, timeout time.Duration) (*Response, error)
SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, timeout time.Duration, id int) (*Response, error)
SendServerNotification(ctx context.Context, name string, method string, params map[string]interface{}) error
ListServers() []string
GetServerState(name string) (ServerState, error)
GetServerTransport(name string) (string, error)
RestartServer(ctx context.Context, name string) error
Close() error
}
ServerSource is the interface for sending requests to MCP servers. The MCP handshake is the pool's job (see session.go): callers just send requests. Pools may also implement SessionInfoProvider and ServerEventSource.
type ServerState ¶
type ServerState string
ServerState represents the current state of an MCP server.
const ( StateIdle ServerState = "idle" StateRunning ServerState = "running" StateBusy ServerState = "busy" StateStopping ServerState = "stopping" StateStopped ServerState = "stopped" StateStarting ServerState = "starting" StateError ServerState = "error" StateDisconnected ServerState = "disconnected" StateUnknown ServerState = "unknown" )
type ServerStats ¶
type ServerStats struct {
RequestCount int64
ErrorCount int64
AvgLatencyMs float64
// LastRequestAt is when the last real request started or completed.
// Health pings are not requests: they leave it (and the counters above)
// untouched.
LastRequestAt time.Time
RestartCount int
CurrentBackoff time.Duration
LastError string
LastErrorAt time.Time
// InFlight is the number of requests currently holding an in-flight
// slot.
InFlight int
// PID is the current process generation's pid, 0 when not running.
PID int
// StartedAt is when the current process generation was spawned, zero
// when not running.
StartedAt time.Time
}
type SessionInfoProvider ¶ added in v1.1.1
type SessionInfoProvider interface {
ServerInitializeResult(name string) (*InitializeResult, bool)
}
SessionInfoProvider is implemented by pools that store each server's InitializeResult.
type StdioPool ¶
type StdioPool struct {
// contains filtered or unexported fields
}
StdioPool manages multiple stdio-based MCP server subprocesses. Each server multiplexes concurrent requests over its single stdio pipe (see StdioServerV2.sendRequest), capped per server by max_in_flight.
func NewStdioPool ¶
NewStdioPool creates a new StdioPool with the given idle timeout.
maxPerServer is retained for API compatibility and is ignored: the number of concurrent requests per server is set by the server's max_in_flight config (default DefaultMaxInFlight).
func (*StdioPool) Close ¶
Close stops every server. The server list is taken (and the pool emptied) under the lock; the servers are then stopped in parallel outside it, so Close takes about one stop grace period however many servers ignore SIGTERM, bounded by an overall deadline.
func (*StdioPool) GetOrStartServer ¶ added in v0.6.1
func (*StdioPool) GetServerState ¶
func (p *StdioPool) GetServerState(name string) (ServerState, error)
func (*StdioPool) GetServerStats ¶
func (p *StdioPool) GetServerStats(name string) (ServerStats, error)
func (*StdioPool) GetServerTransport ¶ added in v1.1.1
GetServerTransport reports the transport this server is configured with. It always returns "stdio" for a StdioPool member.
func (*StdioPool) IsServerMCPInitialized ¶ added in v0.7.1
IsServerMCPInitialized reports whether the named server's current process generation completed its MCP handshake.
func (*StdioPool) ListServers ¶
func (*StdioPool) MarkServerMCPInitialized ¶ added in v0.7.1
MarkServerMCPInitialized marks the named server's current generation as initialized without a handshake (for callers, e.g. tests, that set the session up out of band).
func (*StdioPool) PutRequest ¶
PutRequest submits req to the named server asynchronously: once the server is resolved and any rate limit is satisfied it returns, and the response is delivered to req.ResultCh (always, with Error set on failure) and the failure, if any, to req.ErrorCh. The request is multiplexed with every other in-flight request to that server.
func (*StdioPool) RemoveServer ¶ added in v1.1.1
RemoveServer stops the named stdio server and removes it from the pool.
func (*StdioPool) RestartServer ¶
func (*StdioPool) SendNotificationToServer ¶ added in v0.3.0
func (*StdioPool) SendRequest ¶
func (*StdioPool) SendRequestToServer ¶ added in v0.3.0
func (*StdioPool) SendRequestToServerWithID ¶ added in v0.3.0
func (p *StdioPool) SendRequestToServerWithID(ctx context.Context, name string, method string, params json.RawMessage, timeout time.Duration, id int) (*Response, error)
SendRequestToServerWithID sends one request and waits for its response. Concurrent calls to the same server are multiplexed over its pipe. An upstream JSON-RPC error comes back as resp.Error (err == nil); a transport or proxy failure comes back as err.
func (*StdioPool) SendServerNotification ¶ added in v0.3.0
func (*StdioPool) ServerCount ¶
func (*StdioPool) ServerInitializeResult ¶ added in v1.1.1
func (p *StdioPool) ServerInitializeResult(name string) (*InitializeResult, bool)
ServerInitializeResult returns the InitializeResult stored by the most recent successful handshake with the named server.
func (*StdioPool) ServerRecentStderr ¶ added in v1.1.1
ServerRecentStderr returns the last stderr lines of the named server (already redacted), or "" when it wrote none.
func (*StdioPool) SetReconnect ¶ added in v0.9.0
func (p *StdioPool) SetReconnect(settings ReconnectSettings)
SetReconnect applies reconnect settings to the pool. It takes effect on servers already in the pool and on every server started afterwards.
func (*StdioPool) SetServerEventHandler ¶ added in v1.1.1
func (p *StdioPool) SetServerEventHandler(fn ServerEventHandler)
SetServerEventHandler registers the handler that receives every server's lifecycle events (new process generation, tools/list_changed).
func (*StdioPool) SetServerMessageHandler ¶ added in v1.1.1
func (p *StdioPool) SetServerMessageHandler(h ServerMessageHandler)
SetServerMessageHandler registers the handler that receives what every server initiates (server-to-client requests, progress, ...).
func (*StdioPool) StartAllServers ¶
func (*StdioPool) StartServer ¶
func (*StdioPool) StopServer ¶
type StdioServerConfig ¶
type StdioServerConfig struct {
Name string
Command string
Args []string
// Env holds explicit "KEY=VALUE" entries added on top of the minimal
// base environment (#311). A value may reference "${VAR}", expanded
// from the parent (proxy) environment at spawn time.
Env []string
CWD string
// EnvPassthrough lists parent environment variable names copied to the
// child as-is, in addition to the minimal base environment and Env
// (#311).
EnvPassthrough []string
// InheritEnv restores full inheritance of the proxy's environment
// (pre-#311 behavior), logging one warning per spawn.
InheritEnv bool
// Sandbox, when set with a runtime other than "none", runs this
// server's command inside a container (docker/podman) instead of
// spawning it directly on the host (#312).
Sandbox *migrate.SandboxConfig
// MaxInFlight caps the number of requests multiplexed concurrently
// over the server's stdio pipe. Callers beyond the cap wait (respecting
// their context) instead of being rejected. 0 means
// DefaultMaxInFlight.
MaxInFlight int
IdleTimeout time.Duration
RequestTimeout time.Duration
// MaxResponseSize caps one JSON-RPC message read from the server's
// stdout (max_response_bytes). A longer message fails only the request
// it answers. 0 means DefaultMaxResponseBytes.
MaxResponseSize int
// StopGracePeriod is how long stop waits after SIGTERM before sending
// SIGKILL to the server's process group. 0 means
// defaultStopGracePeriod.
StopGracePeriod time.Duration
// ClientCapabilities is what the pool declares to the server in its
// initialize handshake (see UpstreamClientCapabilities).
ClientCapabilities mcp.ClientCapabilities
}
type StdioServerV2 ¶
type StdioServerV2 struct {
// contains filtered or unexported fields
}
func (*StdioServerV2) InitializeResult ¶ added in v1.1.1
func (s *StdioServerV2) InitializeResult() *InitializeResult
InitializeResult returns the stored result of the most recent successful MCP handshake, or nil.
func (*StdioServerV2) IsMCPInitialized ¶ added in v0.7.1
func (s *StdioServerV2) IsMCPInitialized() bool
IsMCPInitialized reports whether the current process generation completed its MCP initialize handshake.
func (*StdioServerV2) SetMCPInitialized ¶ added in v0.7.1
func (s *StdioServerV2) SetMCPInitialized()
SetMCPInitialized marks the current process generation as initialized without performing the handshake. The pool performs the handshake itself; this only exists for callers (tests) that set the session up out of band.
type UnifiedPool ¶ added in v0.5.0
type UnifiedPool struct {
// contains filtered or unexported fields
}
func NewUnifiedPool ¶ added in v0.5.0
func NewUnifiedPool(stdio *StdioPool, http *HTTPClientPool, sse *SSEPool, logger *slog.Logger) *UnifiedPool
func (*UnifiedPool) Close ¶ added in v0.5.0
func (p *UnifiedPool) Close() error
func (*UnifiedPool) GetServerState ¶ added in v0.5.0
func (p *UnifiedPool) GetServerState(name string) (ServerState, error)
func (*UnifiedPool) GetServerTransport ¶ added in v1.1.1
func (p *UnifiedPool) GetServerTransport(name string) (string, error)
GetServerTransport reports which transport ("stdio", "http" or "sse") owns the named server.
func (*UnifiedPool) ListServers ¶ added in v0.5.0
func (p *UnifiedPool) ListServers() []string
func (*UnifiedPool) RemoveServer ¶ added in v1.1.1
func (p *UnifiedPool) RemoveServer(name string) error
RemoveServer stops the named server and forgets it. In-flight calls to it fail; later calls get "not found".
func (*UnifiedPool) RestartServer ¶ added in v0.5.0
func (p *UnifiedPool) RestartServer(ctx context.Context, name string) error
func (*UnifiedPool) SendRequest ¶ added in v0.5.0
func (p *UnifiedPool) SendRequest(ctx context.Context, serverName string, req *proxy.JSONRPCRequest, timeout time.Duration) (*proxy.JSONRPCResponse, error)
func (*UnifiedPool) SendRequestToServer ¶ added in v0.5.0
func (*UnifiedPool) SendRequestToServerWithID ¶ added in v0.5.0
func (*UnifiedPool) SendServerNotification ¶ added in v0.5.0
func (*UnifiedPool) ServerInitializeResult ¶ added in v1.1.1
func (p *UnifiedPool) ServerInitializeResult(name string) (*InitializeResult, bool)
ServerInitializeResult returns the stored InitializeResult of the named server's current session, whatever its transport.
func (*UnifiedPool) SetServerEventHandler ¶ added in v1.1.1
func (p *UnifiedPool) SetServerEventHandler(fn ServerEventHandler)
SetServerEventHandler registers fn with every underlying pool.
func (*UnifiedPool) SetServerMessageHandler ¶ added in v1.1.1
func (p *UnifiedPool) SetServerMessageHandler(h ServerMessageHandler)
SetServerMessageHandler registers h with every underlying pool.
func (*UnifiedPool) Snapshot ¶ added in v1.1.1
func (p *UnifiedPool) Snapshot(name string) (ServerSnapshot, bool)
Snapshot returns the runtime state of the named server.
func (*UnifiedPool) Snapshots ¶ added in v1.1.1
func (p *UnifiedPool) Snapshots() []ServerSnapshot
Snapshots returns the runtime state of every server, sorted by name.
func (*UnifiedPool) StartServer ¶ added in v1.1.1
func (p *UnifiedPool) StartServer(ctx context.Context, config *migrate.ServerConfig) error
StartServer adds a server to the pool that owns its transport. Starting a name that is already in a pool is an error: remove it first.