mcpserver

package
v5.54.1 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 48 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcpserver provides MCP (Model Context Protocol) server management functionality.

This package enables the registration, configuration, and lifecycle management of MCP servers within the muster ecosystem. It supports both static configuration through YAML files and dynamic management through API operations.

MCP Server Types

Currently supported MCP server types:

  • **Stdio**: Execute MCP servers as local processes with configurable command lines
  • **Streamable-HTTP**: Connect to external MCP servers via HTTP transport
  • **SSE**: Connect to external MCP servers via Server-Sent Events transport

Authentication

Remote servers may be OAuth-protected, in which case the aggregator drives a per-user login flow and this package supplies the token on each request.

A streamable-HTTP server may instead sign each request with AWS Signature Version 4 (auth.type "sigv4"). That is a machine identity: the credential is muster's own rather than the caller's, so it uses the shared global client and never the session-scoped machinery. This package therefore also owns the AWS credential resolution for it — a process-wide default configuration, an optional per-server assume-role hop, and a signing http.RoundTripper. See sigv4_credentials.go and sigv4_transport.go.

Secrets

CredentialsAdapter reads the Secrets a server's spec names (headersFrom, the clientCredentialsSecretRef of auth.tokenExchange and auth.authorizationServer), never a Secret muster keeps for itself: its own and reserved Secret types (credentials_binding.go). Which Secrets a spec may name is the chart's admission policy: only those its writer may get. Secrets muster's own configuration names are read with LoadClientCredentialsForConfig; an MCPServer may share such a Secret.

Request metadata

A remote server may declare spec.meta, whose entries are merged into the params._meta object of every outbound JSON-RPC request that carries params. The merge is an http.RoundTripper shared by every remote client here, so it applies whatever the auth type is. For a SigV4 server it wraps the signing transport, because the body has to be rewritten before it is signed. See meta_transport.go.

Configuration Structure

MCP servers are defined using the MCPServer CRD or YAML configuration files. Each server definition includes metadata, type-specific configuration, and operational settings.

Basic configuration structure:

apiVersion: muster.giantswarm.io/v1alpha1
kind: MCPServer
metadata:
  name: example-server
  namespace: default
spec:
  description: Example MCP server for demonstration
  toolPrefix: example
  type: stdio
  autoStart: true
  command: npx
  args:
    - "@modelcontextprotocol/server-filesystem"
    - "/workspace"
  env:
    DEBUG: "1"

For remote servers:

spec:
  type: streamable-http
  url: "https://api.example.com/mcp"
  timeout: 30
  headers:
    Authorization: "Bearer token"

Static Configuration

MCP servers can be defined in YAML files for static configuration. These files are typically placed in the muster configuration directory and loaded at startup.

Static configuration example:

# Stdio server example
---
apiVersion: muster.giantswarm.io/v1alpha1
kind: MCPServer
metadata:
  name: filesystem-tools
spec:
  description: File system operations
  toolPrefix: fs
  type: stdio
  autoStart: true
  command: npx
  args: ["@modelcontextprotocol/server-filesystem", "/workspace"]

# Remote server example
---
apiVersion: muster.giantswarm.io/v1alpha1
kind: MCPServer
metadata:
  name: remote-api
spec:
  description: Remote API tools
  toolPrefix: api
  type: streamable-http
  url: "https://api.example.com/mcp"
  timeout: 60
  headers:
    Authorization: "Bearer token"

Dynamic Management

MCP servers can also be created, updated, and deleted dynamically through the muster API. This enables runtime configuration changes and programmatic server management.

API operations include:

  • Create: Register new MCP server definitions
  • Update: Modify existing server configurations
  • Delete: Remove server definitions
  • List: Retrieve all configured servers
  • Get: Fetch specific server details
  • Validate: Check server configuration validity

Lifecycle Management

The package handles the complete lifecycle of MCP servers:

  • **Registration**: Adding server definitions to the system
  • **Validation**: Ensuring configuration correctness
  • **Instantiation**: Creating service instances
  • **Startup**: Initializing server processes or connections
  • **Monitoring**: Tracking server health and status
  • **Shutdown**: Graceful termination of server instances

Integration Points

This package integrates with several muster components:

  • **Aggregator**: Registers tools provided by MCP servers
  • **Service Registry**: Manages server lifecycle as services
  • **Configuration System**: Loads static server definitions
  • **API Layer**: Exposes management operations as tools
  • **Orchestrator**: Coordinates server startup and dependencies

Index

Constants

View Source
const DefaultClientIDKey = "client-id"

DefaultClientIDKey is the default key for client ID in the secret.

View Source
const DefaultClientSecretKey = "client-secret"

DefaultClientSecretKey is the default key for client secret in the secret.

View Source
const DefaultDetectTimeout = 10 * time.Second

DefaultDetectTimeout bounds a whole DetectTransport run when the caller does not pass an explicit timeout.

View Source
const DefaultMaxCallDuration = time.Hour

DefaultMaxCallDuration bounds a tool call kept going by progress on a server whose definition sets no spec.progress.maxDuration.

View Source
const DefaultStdioInitTimeout = 10 * time.Second

DefaultStdioInitTimeout is the default timeout for stdio client initialization. This covers the time needed to start the subprocess and complete the MCP handshake.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout bounds an operation on a server whose definition sets no spec.timeout, whatever its transport. It is that field's CRD default; the service layer's DefaultRemoteTimeout is derived from it.

View Source
const TransportUnknown = "unknown"

TransportUnknown is reported when neither transport probe produced a usable signal (server unreachable, or the responses fit neither transport).

Variables

View Source
var ErrAWSCredentialsUnavailable = errors.New("sigv4: failed to retrieve AWS credentials")

ErrAWSCredentialsUnavailable reports that the signing transport could not resolve AWS credentials. It wraps the SDK's own error, and the service layer treats it as a transient connectivity failure so the reconnect backoff picks the server up once the credential becomes available. Every cause is external and fixable while muster keeps running: a projected web-identity token that has not appeared yet, a role that is not deployed, a trust policy being corrected, an STS outage.

View Source
var ErrNotRepeated = errors.New("MCP session re-established; the request was not sent again, it may have run on the backend")

ErrNotRepeated marks an operation that failed while the MCP session was lost but may have reached the backend: the session has been re-established for the next operation, and this one is not sent again, since it may have run already. Whether to repeat it -- a tool call may write -- is the caller's decision.

View Source
var ErrSubscriptionsListenUnsupported = errors.New("the server does not serve subscriptions/listen (MCP " + mcp.ProtocolVersion20260728 + ")")

ErrSubscriptionsListenUnsupported is returned by Initialize on a client in listen mode (UseSubscriptionsListen) whose server does not speak protocol revision 2026-07-28: subscriptions/listen does not exist before it.

Functions

func DefinitionHeaders added in v5.28.1

func DefinitionHeaders(headers map[string]string) map[string]string

DefinitionHeaders is the part of an MCPServer's spec.headers a session-scoped client sends: every entry but Authorization, in a fresh map. The session's credential -- the person's grant, their forwarded login token, a token exchanged for it -- is the Authorization header of that connection, and a definition never names it for a session. The server-level client the client factory builds keeps the whole set: for it an Authorization entry of spec.headersFrom is the documented way to reach a server with one shared token.

The result is nil when nothing is left, so callers can test it with len.

func DescribeChallenge

func DescribeChallenge(challenge *pkgoauth.AuthChallenge) string

DescribeChallenge renders the parts of a backend's Bearer challenge that explain a rejection: the error code and error_description parameters. It returns "" when the challenge carries neither, so callers can append it to a diagnostic only when there is something to say.

func OAuthLoginGuidance

func OAuthLoginGuidance(name string) string

OAuthLoginGuidance is the user-facing guidance for services that require session-scoped OAuth authentication: starting or restarting them cannot authenticate a session, only core_auth_login can. Shared with the imperative path's formatOAuthAuthenticationError so both paths answer the same tool call with the same words.

func ResolveHeaders added in v5.41.0

func ResolveHeaders(ctx context.Context, owner api.SecretOwner, headers map[string]string, headersFrom []api.MCPServerHeaderFrom) (map[string]string, error)

ResolveHeaders returns the headers a connection to a server sends: its spec.headers, and each spec.headersFrom entry with its value read from the Secret it names in the server's namespace. An entry of headersFrom wins over a spec.headers entry of the same name, in any case.

owner is the MCPServer the headers are for: a Secret is read only when it is bound to that MCPServer (api.SecretCredentialsHandler), and a refusal fails the whole call, so no header of a refused Secret is ever sent.

muster calls it when it builds a connection's client, so a value lives in that client alone: never in the definition, the service data or the output of a core tool. The reference has no namespace, so the Secret is always in owner.Namespace, the server's own ("default" when empty, as in filesystem mode).

headers is returned unchanged when headersFrom is empty.

func WithProgressReporter added in v5.37.0

func WithProgressReporter(ctx context.Context, reporter *ProgressReporter) context.Context

WithProgressReporter returns a context whose tool calls relay downstream progress to reporter.

Types

type Adapter

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

Adapter provides MCP server management functionality using the unified client

func NewAdapterWithClient

func NewAdapterWithClient(musterClient client.MusterClient, namespace string) *Adapter

NewAdapterWithClient creates a new adapter with a specific client (for testing)

func (*Adapter) Close

func (a *Adapter) Close() error

Close performs cleanup for the adapter

func (*Adapter) EnableWritesAsCaller

func (a *Adapter) EnableWritesAsCaller(factory callerwrite.ClientFactory, kubernetesAudience string)

EnableWritesAsCaller switches session-initiated mutations to caller-identity writes; the app layer calls it whenever muster runs in Kubernetes mode. factory may be nil when muster has no Kubernetes API access; mutations then fail with an explicit configuration error instead of silently falling back to the SA path. An empty kubernetesAudience selects the default.

func (*Adapter) ExecuteTool

func (a *Adapter) ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}) (*api.CallToolResult, error)

ExecuteTool executes a tool by name

func (*Adapter) GetMCPServer

func (a *Adapter) GetMCPServer(ctx context.Context, key string) (*api.MCPServerInfo, error)

GetMCPServer returns information about a specific MCP server. key is the server's key (api.MCPServerKey): its name in muster's namespace, "<namespace>/<name>" outside it.

func (*Adapter) GetTools

func (a *Adapter) GetTools() []api.ToolMetadata

GetTools returns all tools this provider offers

func (*Adapter) ListMCPServers

func (a *Adapter) ListMCPServers(ctx context.Context) ([]api.MCPServerInfo, error)

ListMCPServers returns all MCP server definitions

func (*Adapter) Register

func (a *Adapter) Register()

Register registers the adapter with the API

func (*Adapter) RestartMCPServerAsCaller

func (a *Adapter) RestartMCPServerAsCaller(ctx context.Context, name string) (*api.CallToolResult, bool, error)

RestartMCPServerAsCaller handles core_service_restart as a CR write: it sets spec.restartRequestedAt with the caller's identity. The field itself is the audit record of who requested the restart and when; the reconciler processes it once and mirrors the value into status.lastRestartedAt. Second-granularity timestamps collapse repeated restarts within one second into a single one.

func (*Adapter) ServeAllNamespaces added in v5.47.0

func (a *Adapter) ServeAllNamespaces()

ServeAllNamespaces makes the adapter list MCPServer objects of every namespace, and get a server outside muster's namespace by its key ("<namespace>/<name>", api.MCPServerKey). core_mcpserver_create, update and delete still write in muster's namespace only; the lifecycle tools (core_service_start, stop, restart) write on the server's own object.

func (*Adapter) StartMCPServerAsCaller

func (a *Adapter) StartMCPServerAsCaller(ctx context.Context, name string) (*api.CallToolResult, bool, error)

StartMCPServerAsCaller handles core_service_start as a CR write: it clears spec.suspended and, whenever the service is down, also writes spec.restartRequestedAt — the one-shot "make it run now" request. The restart request is what starts autoStart=false and failed servers, and it makes a resume level-reconstructable even when the reconciler's in-memory suspension marker was lost to a muster restart. Timestamps have second granularity, so repeated starts within one second collapse into one request — the service was just started anyway.

func (*Adapter) StopMCPServerAsCaller

func (a *Adapter) StopMCPServerAsCaller(ctx context.Context, name string) (*api.CallToolResult, bool, error)

StopMCPServerAsCaller handles core_service_stop as a CR write: it sets spec.suspended=true with the caller's identity. The reconciler stops the service and keeps it stopped until it is resumed.

type AuthInfo

type AuthInfo struct {
	// Issuer is the OAuth issuer URL (from WWW-Authenticate realm)
	Issuer string

	// Scope is the OAuth scope required by the server
	Scope string

	// ResourceMetadataURL is the URL to fetch OAuth metadata (MCP-specific)
	ResourceMetadataURL string

	// Resource is the canonical URI the server declares for itself in its
	// RFC 9728 metadata. It is the RFC 8707 `resource` value muster sends on
	// authorization and token requests for this server.
	Resource string
}

AuthInfo contains OAuth authentication information extracted from a 401 response during MCP server initialization.

type AuthRequiredError

type AuthRequiredError struct {
	// URL is the endpoint that returned the 401
	URL string

	// AuthInfo contains the OAuth parameters extracted from the 401 response
	AuthInfo AuthInfo

	// Challenge is the backend's WWW-Authenticate challenge from the 401 that
	// produced this error, when the client's transport recorded one (see
	// challengeRecorder). Its error and error_description parameters say why
	// the credential was refused; the request and the token are never kept.
	// nil when the 401 carried no parseable challenge or the transport does
	// not record them.
	Challenge *pkgoauth.AuthChallenge

	// Err is the underlying error
	Err error
}

AuthRequiredError is returned when an MCP server requires OAuth authentication before the protocol handshake can complete. This error contains the information needed to initiate the OAuth flow.

func CheckForAuthRequiredError

func CheckForAuthRequiredError(ctx context.Context, err error, url string) *AuthRequiredError

CheckForAuthRequiredError examines an error to determine if it's a 401 authentication required error. It uses mcp-go's typed error detection instead of string parsing:

  • transport.OAuthAuthorizationRequiredError: returned when WithHTTPOAuth is set. The error carries an OAuthHandler that can discover server metadata (issuer, scopes).
  • transport.ErrUnauthorized ("unauthorized (401)"): returned by some paths when no OAuth handler is configured.
  • transport.ErrAuthorizationRequired ("authorization required"): introduced in mcp-go v0.49.0 and returned by the streamable-http transport for 401 responses when the client has no valid token. Muster must treat this identically to the other two so that auth-required servers get registered in pending-auth state instead of failing outright.

func (*AuthRequiredError) AuthRequired

func (e *AuthRequiredError) AuthRequired() bool

AuthRequired is a marker method that satisfies api.authRequiredError, enabling detection via api.IsAuthRequiredError without direct imports.

func (*AuthRequiredError) Error

func (e *AuthRequiredError) Error() string

Error implements the error interface

func (*AuthRequiredError) GetIssuer

func (e *AuthRequiredError) GetIssuer() string

GetIssuer returns the OAuth issuer URL from the error.

func (*AuthRequiredError) GetResourceMetadataURL

func (e *AuthRequiredError) GetResourceMetadataURL() string

GetResourceMetadataURL returns the resource metadata URL from the error.

func (*AuthRequiredError) GetScope

func (e *AuthRequiredError) GetScope() string

GetScope returns the OAuth scope from the error.

func (*AuthRequiredError) HasValidChallenge

func (e *AuthRequiredError) HasValidChallenge() bool

HasValidChallenge returns true if the error contains valid auth challenge information.

func (*AuthRequiredError) Unwrap

func (e *AuthRequiredError) Unwrap() error

Unwrap returns the underlying error

type CredentialsAdapter

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

CredentialsAdapter implements the SecretCredentialsHandler interface for loading OAuth client credentials from Kubernetes secrets.

func NewCredentialsAdapter

func NewCredentialsAdapter(k8sClient client.Client, opts ...CredentialsOption) *CredentialsAdapter

NewCredentialsAdapter creates a new credentials adapter.

Args:

  • k8sClient: The Kubernetes client for reading secrets
  • opts: secret binding options (WithProtectedSecrets, WithSecretReferencePolicy)

Returns:

  • *CredentialsAdapter: The adapter instance

func (*CredentialsAdapter) LoadClientCredentialsForConfig added in v5.53.1

func (a *CredentialsAdapter) LoadClientCredentialsForConfig(
	ctx context.Context,
	secretRef *api.ClientCredentialsSecretRef,
	defaultNamespace string,
) (*api.ClientCredentials, error)

LoadClientCredentialsForConfig loads OAuth client credentials from a Secret muster's configuration names. No binding is checked.

func (*CredentialsAdapter) LoadMCPServerClientCredentials added in v5.53.1

func (a *CredentialsAdapter) LoadMCPServerClientCredentials(
	ctx context.Context,
	owner api.SecretOwner,
	field string,
	secretRef *api.ClientCredentialsSecretRef,
) (*api.ClientCredentials, error)

LoadMCPServerClientCredentials loads OAuth client credentials from a Secret an MCPServer's spec names, if the Secret may be read on its behalf.

func (*CredentialsAdapter) LoadMCPServerSecretKey added in v5.53.1

func (a *CredentialsAdapter) LoadMCPServerSecretKey(
	ctx context.Context,
	owner api.SecretOwner,
	field string,
	secretRef *api.ClientCredentialsSecretRef,
	key string,
) ([]byte, error)

LoadMCPServerSecretKey loads raw bytes for a single named key from a Secret an MCPServer's spec names, if the Secret may be read on its behalf.

func (*CredentialsAdapter) Register

func (a *CredentialsAdapter) Register()

Register registers the adapter with the API.

type CredentialsOption added in v5.53.1

type CredentialsOption func(*CredentialsAdapter)

CredentialsOption configures a CredentialsAdapter.

func WithProtectedSecrets added in v5.53.1

func WithProtectedSecrets(secrets ...types.NamespacedName) CredentialsOption

WithProtectedSecrets names Secrets no MCPServer may read: muster's own (secretBinding.protectedSecrets).

func WithSecretReferencePolicy added in v5.53.4

func WithSecretReferencePolicy(bindingName string) CredentialsOption

WithSecretReferencePolicy makes every read on behalf of an MCPServer depend on the chart's admission policy: the ValidatingAdmissionPolicyBinding named bindingName must exist, deny (validationActions holds Deny) for every MCPServer (no matchResources), and bind a policy that exists and fails closed. Otherwise the read is refused with api.ErrSecretReferencePolicyInactive. An empty bindingName refuses every such read: no policy is configured.

type DynamicAuthClient

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

DynamicAuthClient implements the MCPClient interface using StreamableHTTP transport with mcp-go's built-in OAuth handler for automatic bearer token injection and typed 401 error handling.

Instead of manually injecting Authorization headers via WithHTTPHeaderFunc, this client delegates token management to mcp-go's WithHTTPOAuth transport option. The transport.TokenStore adapter bridges muster's session-scoped token management to mcp-go's OAuth handler, enabling:

  • Automatic bearer token injection on every request
  • Typed OAuthAuthorizationRequiredError on 401 (preserving error details)
  • Transparent token refresh via the TokenStore

func NewDynamicAuthClient

func NewDynamicAuthClient(url string, tokenStore transport.TokenStore, scope, clientID, clientSecret string) *DynamicAuthClient

NewDynamicAuthClient creates a new StreamableHTTP-based MCP client with mcp-go's built-in OAuth handler. The TokenStore is queried on each HTTP request to get the current access token for bearer injection.

Args:

  • url: The MCP server URL
  • tokenStore: Adapter providing OAuth tokens (implements transport.TokenStore)
  • scope: The OAuth scope for this connection
  • clientID: The OAuth client_id the tokens were issued under (CIMD URL or DCR-registered id); mcp-go sends it on token refresh requests
  • clientSecret: The client secret when the issuer registered muster as a confidential client via DCR; empty for public clients

Returns a new DynamicAuthClient ready for initialization.

func (*DynamicAuthClient) CallTool

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

CallTool executes a specific tool and returns the result

func (*DynamicAuthClient) Close

func (c *DynamicAuthClient) Close() error

Close cleanly shuts down the client connection

func (*DynamicAuthClient) GetPrompt

func (c *DynamicAuthClient) GetPrompt(ctx context.Context, name string, args map[string]interface{}) (*mcp.GetPromptResult, error)

GetPrompt retrieves a specific prompt

func (*DynamicAuthClient) Initialize

func (c *DynamicAuthClient) Initialize(ctx context.Context) error

Initialize establishes the connection and performs protocol handshake. Uses mcp-go's WithHTTPOAuth for automatic token injection and typed 401 handling.

func (*DynamicAuthClient) ListPrompts

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

ListPrompts returns all available prompts from the server

func (*DynamicAuthClient) ListResources

func (c *DynamicAuthClient) ListResources(ctx context.Context) ([]mcp.Resource, error)

ListResources returns all available resources from the server

func (*DynamicAuthClient) ListTools

func (c *DynamicAuthClient) ListTools(ctx context.Context) ([]mcp.Tool, error)

ListTools returns all available tools from the server

func (*DynamicAuthClient) ListenResources added in v5.47.0

func (b *DynamicAuthClient) ListenResources(ctx context.Context, uris []string) error

ListenResources opens a subscriptions/listen stream; see ResourceListener. The lock is not held while the stream is open, so Close can end it.

func (*DynamicAuthClient) NegotiatedProtocolVersion

func (b *DynamicAuthClient) NegotiatedProtocolVersion() string

NegotiatedProtocolVersion returns the MCP revision the server answered with during the handshake, or "" when the client is not connected.

func (*DynamicAuthClient) OnNotification

func (c *DynamicAuthClient) OnNotification(handler func(mcp.JSONRPCNotification))

OnNotification registers a handler for server-pushed notifications.

func (*DynamicAuthClient) OnSessionRecovered added in v5.39.1

func (b *DynamicAuthClient) OnSessionRecovered(handler func())

OnSessionRecovered registers a handler called after the client lost its MCP session and re-established it with a fresh handshake (session recovery, client_session_recovery.go). A backend forgets a session when a new process took over behind its address: the handler is where a caller re-reads what that process serves. It runs on a goroutine of its own, so it may use the client. Transports without a session to lose never call it.

func (*DynamicAuthClient) Ping

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

Ping checks if the server is responsive

func (*DynamicAuthClient) ReadResource

func (c *DynamicAuthClient) ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)

ReadResource retrieves a specific resource

func (*DynamicAuthClient) ServerCapabilities added in v5.29.1

func (b *DynamicAuthClient) ServerCapabilities() mcp.ServerCapabilities

ServerCapabilities returns the capabilities the server declared during the handshake, or the zero value when the client is not connected.

func (*DynamicAuthClient) SetBudget added in v5.52.17

func (b *DynamicAuthClient) SetBudget(timeout, maxCallDuration time.Duration)

SetBudget replaces the client's timeout and maxCallDuration while it is in use: the server's spec.timeout or spec.progress.maxDuration changed and the connection stays. Every operation started after it runs under the new budget; one in flight keeps the budget it started with. Safe for concurrent use.

func (*DynamicAuthClient) UseSubscriptionsListen added in v5.47.0

func (b *DynamicAuthClient) UseSubscriptionsListen()

UseSubscriptionsListen puts the client in listen mode; see ResourceListener.

func (*DynamicAuthClient) WithAuthLossHandler

func (c *DynamicAuthClient) WithAuthLossHandler(fn func(reason string)) *DynamicAuthClient

WithAuthLossHandler registers a function invoked once when the client's authentication is observed lost: the token store no longer holds a token, or the server keeps rejecting the held token with 401 (authLossThreshold consecutive failures either way). The handler runs on its own goroutine and is expected to retire this client — a lost grant never heals on its own, it needs a human to re-authenticate, so leaving the client running means mcp-go's continuous listener retries (and logs) every second forever.

Returns the client so a construction site reads as one expression.

func (*DynamicAuthClient) WithHeaderFunc added in v5.31.0

WithHeaderFunc sets a function whose headers are added to every request, resolved per request so a value that changes over the connection's life (the session's ID token of spec.auth.forwardIdentity) is current on each call. The headers are set after the OAuth handler's bearer, so the function must not return Authorization. A nil function adds nothing. Returns the client so a construction site reads as one expression.

func (*DynamicAuthClient) WithHeaders added in v5.28.1

func (c *DynamicAuthClient) WithHeaders(headers map[string]string) *DynamicAuthClient

WithHeaders sets the definition's spec.headers the client sends with every request, next to the bearer the OAuth handler injects, and returns the client so a construction site reads as one expression. Callers pass the set through DefinitionHeaders; an Authorization entry would be overridden by the handler's bearer anyway.

func (*DynamicAuthClient) WithMaxCallDuration added in v5.40.0

func (c *DynamicAuthClient) WithMaxCallDuration(maxCallDuration time.Duration) *DynamicAuthClient

WithMaxCallDuration sets how long progress may keep a tool call going, the server's spec.progress.maxDuration (see baseMCPClient.maxCallDuration), and returns the client so a construction site reads as one expression.

func (*DynamicAuthClient) WithMeta

func (c *DynamicAuthClient) WithMeta(meta map[string]string) *DynamicAuthClient

WithMeta sets the entries merged into the params._meta object of every outbound JSON-RPC request that carries params, and returns the client so a construction site reads as one expression.

func (*DynamicAuthClient) WithTimeout added in v5.27.3

func (c *DynamicAuthClient) WithTimeout(timeout time.Duration) *DynamicAuthClient

WithTimeout sets the budget every operation on the client runs under, the server's spec.timeout (see baseMCPClient.timeout), and returns the client so a construction site reads as one expression.

type HeaderSecretError added in v5.41.0

type HeaderSecretError struct {
	// Header is the name of the header the Secret's value is for.
	Header string
	Err    error
}

HeaderSecretError reports that the Secret of a spec.headersFrom entry could not be read: it does not exist, is not readable or lacks the key. GitOps applies an MCPServer and its Secret in any order, so the server is retried with backoff until the Secret exists.

func (*HeaderSecretError) Error added in v5.41.0

func (e *HeaderSecretError) Error() string

func (*HeaderSecretError) Unwrap added in v5.41.0

func (e *HeaderSecretError) Unwrap() error

type InitializeRefusedError added in v5.27.10

type InitializeRefusedError struct {
	// URL is the endpoint that refused the initialize.
	URL string

	// StatusCode is the HTTP status the endpoint answered with; 0 when the
	// transport did not record one.
	StatusCode int

	// RetryAfter is the delay the endpoint asked to be retried after (the
	// Retry-After header of a 429 or 503); 0 when none was sent.
	RetryAfter time.Duration

	// Err is the underlying error mcp-go returned (transport.ErrLegacySSEServer
	// for a 4xx, a status-in-text error for a 503).
	Err error
}

InitializeRefusedError is returned when the endpoint answered the initialize POST with a status that is up and routing -- it is not a connection failure -- but that does not let the handshake complete right now. Two kinds, told apart by the status so the log and the CR status name the real cause and the caller acts on it:

  • The path does not serve the MCP protocol (yet): a backend whose route is being rolled out answers 404 until the new pod takes it over, a server that speaks only the legacy SSE transport answers 405. Corrected outside muster, so the caller retries with muster's backoff instead of settling the server in Failed (issue #1295).
  • The endpoint is temporarily refusing the load: 429 Too Many Requests or 503 Service Unavailable, a transient refusal with a Retry-After, never a transport mismatch. The session's connection is kept and retried after the Retry-After the server asked for, not dropped (issue #1303).

mcp-go reduces a 4xx on the initialize POST to transport.ErrLegacySSEServer and a 503 to a status-in-text error, both without the Retry-After; the client's transport records the status and the Retry-After header (see challengeRecorder) so they reach the log and the CR status.

func (*InitializeRefusedError) Error added in v5.27.10

func (e *InitializeRefusedError) Error() string

Error implements the error interface. It names the status and, for a 429 or 503, the Retry-After. "likely a legacy SSE server" is said only for the 405 that actually means it, never for a status that has its own meaning (issue #1303).

func (*InitializeRefusedError) Unwrap added in v5.27.10

func (e *InitializeRefusedError) Unwrap() error

Unwrap returns the underlying error.

type MCPClient

type MCPClient interface {
	// Initialize establishes the connection and performs protocol handshake
	Initialize(ctx context.Context) error
	// Close cleanly shuts down the client connection
	Close() error
	// ListTools returns all available tools from the server
	ListTools(ctx context.Context) ([]mcp.Tool, error)
	// CallTool executes a specific tool and returns the result
	CallTool(ctx context.Context, name string, args map[string]interface{}) (*mcp.CallToolResult, error)
	// ListResources returns all available resources from the server
	ListResources(ctx context.Context) ([]mcp.Resource, error)
	// ReadResource retrieves a specific resource
	ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)
	// ListPrompts returns all available prompts from the server
	ListPrompts(ctx context.Context) ([]mcp.Prompt, error)
	// GetPrompt retrieves a specific prompt
	GetPrompt(ctx context.Context, name string, args map[string]interface{}) (*mcp.GetPromptResult, error)
	// Ping checks if the server is responsive
	Ping(ctx context.Context) error
	// OnNotification registers a handler that is called when the server
	// sends a JSON-RPC notification (e.g. notifications/tools/list_changed).
	// The handler is wired to the underlying mcp-go client during Initialize.
	OnNotification(handler func(mcp.JSONRPCNotification))
	// NegotiatedProtocolVersion returns the MCP revision the server answered
	// with during the handshake, or "" before a successful Initialize. It can
	// be older than api.ClientProtocolVersion: a server that supports only
	// an earlier revision answers with that one, and the client accepts it.
	NegotiatedProtocolVersion() string
	// ServerCapabilities returns the capabilities the server declared in its
	// initialize result, or the zero value before a successful Initialize. A
	// caller lists only what the server declared: the protocol reserves
	// resources/list and prompts/list for servers that offer them.
	ServerCapabilities() mcp.ServerCapabilities
}

MCPClient defines the interface for MCP client implementations. All transport types (stdio, SSE, streamable-http) implement this interface, enabling polymorphic usage and easier testing with mocks.

func NewMCPClientFromType

func NewMCPClientFromType(serverType api.MCPServerType, config MCPClientConfig) (MCPClient, error)

NewMCPClientFromType creates the appropriate MCP client based on the server type.

Supported types:

  • "stdio": Creates a StdioClient for local subprocess communication
  • "streamable-http": Creates a StreamableHTTPClient for HTTP-based servers, or a SigV4-signing one when the auth type is "sigv4"
  • "sse": Creates an SSEClient for Server-Sent Events communication

type MCPClientConfig

type MCPClientConfig struct {
	// Command is the executable path for stdio servers
	Command string
	// Args are the command line arguments for stdio servers
	Args []string
	// Env contains environment variables for stdio servers
	Env map[string]string
	// URL is the endpoint for remote servers (streamable-http, sse)
	URL string
	// Headers are HTTP headers for remote servers
	Headers map[string]string
	// Meta contains entries merged into the params._meta object of every
	// outbound JSON-RPC request that carries params
	Meta map[string]string
	// Auth is the authentication configuration for remote servers. Only the
	// machine-identity modes are handled here; the session-scoped OAuth modes
	// are resolved by the aggregator, not by this factory.
	Auth *api.MCPServerAuth
	// Timeout is the server's spec.timeout: the one budget every operation
	// on the client runs under, whatever its transport -- each request, a
	// tool call above all, and the handshake a session recovery performs on
	// the way. Zero means DefaultTimeout.
	Timeout time.Duration
	// MaxCallDuration is the server's spec.progress.maxDuration: how long
	// progress may keep a tool call going. Zero means DefaultMaxCallDuration;
	// at or below Timeout, progress extends nothing.
	MaxCallDuration time.Duration
}

MCPClientConfig contains configuration for creating an MCP client. This provides a unified configuration structure for all client types.

type McpDiscreteStatusUpdate

type McpDiscreteStatusUpdate struct {
	Name          string // The unique label of the MCP server instance
	ProcessStatus string // A string indicating the process status, e.g., "ProcessInitializing", "ProcessStarting", "ProcessRunning", "ProcessExitedWithError"
	ProcessErr    error  // The actual Go error object if the process failed or exited with an error
}

McpDiscreteStatusUpdate is used to report discrete status changes from a running MCP process. It focuses on the state, not verbose logs.

type McpUpdateFunc

type McpUpdateFunc func(update McpDiscreteStatusUpdate)

McpUpdateFunc is a callback function type for receiving McpDiscreteStatusUpdate messages.

type MusterTokenStore

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

MusterTokenStore is a thin context-binder that implements mcp-go's transport.TokenStore interface by binding {sessionID, userID, issuer} context to the single backing store exposed through api.OAuthHandler.

It has no storage of its own -- all reads and writes go through api.OAuthHandler. The only local state is a cached copy of the ID token, because mcp-go's transport.Token doesn't track ID tokens.

mcp-go owns token refresh and 401 handling. This store simply returns the current token as-is and persists whatever mcp-go writes back after a successful refresh.

func NewMusterTokenStore

func NewMusterTokenStore(sessionID, userID, issuer string, oauthHandler api.OAuthHandler) *MusterTokenStore

NewMusterTokenStore creates a new token store that binds the given session ID, user ID, and issuer context to the api.OAuthHandler backing store.

func (*MusterTokenStore) GetIDToken

func (s *MusterTokenStore) GetIDToken() string

GetIDToken returns the last cached ID token. mcp-go's transport.Token doesn't track ID tokens, so we cache them from the backing store on each GetToken() call for SSO forwarding.

func (*MusterTokenStore) GetToken

func (s *MusterTokenStore) GetToken(ctx context.Context) (*transport.Token, error)

GetToken returns the current OAuth token from the backing store. Returns transport.ErrNoToken when no token is available, which signals mcp-go to initiate the OAuth authorization flow.

mcp-go decides when to refresh based on the ExpiresAt field, and refreshes only a token whose Issuer is the authorization server's metadata issuer: the plain issuer of the store's key.

func (*MusterTokenStore) SaveToken

func (s *MusterTokenStore) SaveToken(ctx context.Context, token *transport.Token) error

SaveToken persists a refreshed token to the backing store via api.OAuthHandler.StoreToken. mcp-go calls this after a successful token refresh.

The cached IDToken is preserved because refresh responses typically don't include ID tokens.

type ProgressReporter added in v5.37.0

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

ProgressReporter sends a downstream tool's progress to the caller of one tool call, under the progressToken the caller chose.

A call that reaches several downstream tools (a workflow) shares one reporter, and each tool counts from its own start; the protocol requires the progress a caller sees to increase, so a value that does not exceed the last one sent is dropped and counted.

func NewProgressReporter added in v5.37.0

func NewProgressReporter(token mcp.ProgressToken, send func(params map[string]any) error) *ProgressReporter

NewProgressReporter returns a reporter for the caller's token; send delivers a notifications/progress with the given params to the caller. A nil send makes a reporter for a caller that asked for no progress: the downstream call still gets a token, and its progress still keeps the call alive, but none reaches the caller.

type ResourceListener added in v5.47.0

type ResourceListener interface {
	MCPClient
	// UseSubscriptionsListen puts the client, before Initialize, in listen
	// mode: it negotiates protocol revision 2026-07-28 and opens no
	// standalone notification stream.
	UseSubscriptionsListen()
	// ListenResources opens a subscriptions/listen stream for the resource
	// URIs and blocks until ctx ends or the server closes the stream. The
	// server's notifications arrive at the OnNotification handler, its
	// notifications/subscriptions/acknowledged first.
	ListenResources(ctx context.Context, uris []string) error
}

ResourceListener is implemented by the clients that can hold a subscriptions/listen stream open to their server: the streamable-http ones in listen mode.

type SSEClient

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

SSEClient implements the MCPClient interface using SSE transport. It connects to remote MCP servers using Server-Sent Events for communication.

func NewSSEClientWithHeaders

func NewSSEClientWithHeaders(url string, headers map[string]string) *SSEClient

NewSSEClientWithHeaders creates a new SSE-based MCP client with custom headers

func (*SSEClient) CallTool

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

CallTool executes a specific tool and returns the result

func (*SSEClient) Close

func (c *SSEClient) Close() error

Close cleanly shuts down the client connection

func (*SSEClient) GetPrompt

func (c *SSEClient) GetPrompt(ctx context.Context, name string, args map[string]interface{}) (*mcp.GetPromptResult, error)

GetPrompt retrieves a specific prompt

func (*SSEClient) Initialize

func (c *SSEClient) Initialize(ctx context.Context) error

Initialize establishes the connection and performs protocol handshake

func (*SSEClient) ListPrompts

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

ListPrompts returns all available prompts from the server

func (*SSEClient) ListResources

func (c *SSEClient) ListResources(ctx context.Context) ([]mcp.Resource, error)

ListResources returns all available resources from the server

func (*SSEClient) ListTools

func (c *SSEClient) ListTools(ctx context.Context) ([]mcp.Tool, error)

ListTools returns all available tools from the server

func (*SSEClient) ListenResources added in v5.47.0

func (b *SSEClient) ListenResources(ctx context.Context, uris []string) error

ListenResources opens a subscriptions/listen stream; see ResourceListener. The lock is not held while the stream is open, so Close can end it.

func (*SSEClient) NegotiatedProtocolVersion

func (b *SSEClient) NegotiatedProtocolVersion() string

NegotiatedProtocolVersion returns the MCP revision the server answered with during the handshake, or "" when the client is not connected.

func (*SSEClient) OnNotification

func (c *SSEClient) OnNotification(handler func(mcp.JSONRPCNotification))

OnNotification registers a handler for server-pushed notifications.

func (*SSEClient) OnSessionRecovered added in v5.39.1

func (b *SSEClient) OnSessionRecovered(handler func())

OnSessionRecovered registers a handler called after the client lost its MCP session and re-established it with a fresh handshake (session recovery, client_session_recovery.go). A backend forgets a session when a new process took over behind its address: the handler is where a caller re-reads what that process serves. It runs on a goroutine of its own, so it may use the client. Transports without a session to lose never call it.

func (*SSEClient) Ping

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

Ping checks if the server is responsive

func (*SSEClient) ReadResource

func (c *SSEClient) ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)

ReadResource retrieves a specific resource

func (*SSEClient) ServerCapabilities added in v5.29.1

func (b *SSEClient) ServerCapabilities() mcp.ServerCapabilities

ServerCapabilities returns the capabilities the server declared during the handshake, or the zero value when the client is not connected.

func (*SSEClient) SetBudget added in v5.52.17

func (b *SSEClient) SetBudget(timeout, maxCallDuration time.Duration)

SetBudget replaces the client's timeout and maxCallDuration while it is in use: the server's spec.timeout or spec.progress.maxDuration changed and the connection stays. Every operation started after it runs under the new budget; one in flight keeps the budget it started with. Safe for concurrent use.

func (*SSEClient) UseSubscriptionsListen added in v5.47.0

func (b *SSEClient) UseSubscriptionsListen()

UseSubscriptionsListen puts the client in listen mode; see ResourceListener.

func (*SSEClient) WithMaxCallDuration added in v5.40.0

func (c *SSEClient) WithMaxCallDuration(maxCallDuration time.Duration) *SSEClient

WithMaxCallDuration sets how long progress may keep a tool call going, the server's spec.progress.maxDuration (see baseMCPClient.maxCallDuration), and returns the client so a construction site reads as one expression.

func (*SSEClient) WithMeta

func (c *SSEClient) WithMeta(meta map[string]string) *SSEClient

WithMeta sets the entries merged into the params._meta object of every outbound JSON-RPC request that carries params, and returns the client so a construction site reads as one expression.

func (*SSEClient) WithTimeout added in v5.27.2

func (c *SSEClient) WithTimeout(timeout time.Duration) *SSEClient

WithTimeout sets the budget every operation on the client runs under, the server's spec.timeout (see baseMCPClient.timeout), and returns the client so a construction site reads as one expression.

type StdioClient

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

StdioClient implements the MCPClient interface using stdio transport. It manages a local subprocess that communicates via stdin/stdout.

func NewStdioClientWithEnv

func NewStdioClientWithEnv(command string, args []string, env map[string]string) *StdioClient

NewStdioClientWithEnv creates a new stdio-based MCP client with environment variables

func (*StdioClient) CallTool

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

CallTool executes a specific tool and returns the result

func (*StdioClient) Close

func (c *StdioClient) Close() error

Close cleanly shuts down the client connection

func (*StdioClient) GetPrompt

func (c *StdioClient) GetPrompt(ctx context.Context, name string, args map[string]interface{}) (*mcp.GetPromptResult, error)

GetPrompt retrieves a specific prompt

func (*StdioClient) GetStderr

func (c *StdioClient) GetStderr() (io.Reader, bool)

GetStderr returns a reader for the stderr output of the subprocess

func (*StdioClient) Initialize

func (c *StdioClient) Initialize(ctx context.Context) error

Initialize establishes the connection and performs protocol handshake

func (*StdioClient) ListPrompts

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

ListPrompts returns all available prompts from the server

func (*StdioClient) ListResources

func (c *StdioClient) ListResources(ctx context.Context) ([]mcp.Resource, error)

ListResources returns all available resources from the server

func (*StdioClient) ListTools

func (c *StdioClient) ListTools(ctx context.Context) ([]mcp.Tool, error)

ListTools returns all available tools from the server

func (*StdioClient) ListenResources added in v5.47.0

func (b *StdioClient) ListenResources(ctx context.Context, uris []string) error

ListenResources opens a subscriptions/listen stream; see ResourceListener. The lock is not held while the stream is open, so Close can end it.

func (*StdioClient) NegotiatedProtocolVersion

func (b *StdioClient) NegotiatedProtocolVersion() string

NegotiatedProtocolVersion returns the MCP revision the server answered with during the handshake, or "" when the client is not connected.

func (*StdioClient) OnNotification

func (c *StdioClient) OnNotification(handler func(mcp.JSONRPCNotification))

OnNotification registers a handler for server-pushed notifications.

func (*StdioClient) OnSessionRecovered added in v5.39.1

func (b *StdioClient) OnSessionRecovered(handler func())

OnSessionRecovered registers a handler called after the client lost its MCP session and re-established it with a fresh handshake (session recovery, client_session_recovery.go). A backend forgets a session when a new process took over behind its address: the handler is where a caller re-reads what that process serves. It runs on a goroutine of its own, so it may use the client. Transports without a session to lose never call it.

func (*StdioClient) Ping

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

Ping checks if the server is responsive

func (*StdioClient) ReadResource

func (c *StdioClient) ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)

ReadResource retrieves a specific resource

func (*StdioClient) ServerCapabilities added in v5.29.1

func (b *StdioClient) ServerCapabilities() mcp.ServerCapabilities

ServerCapabilities returns the capabilities the server declared during the handshake, or the zero value when the client is not connected.

func (*StdioClient) SetBudget added in v5.52.17

func (b *StdioClient) SetBudget(timeout, maxCallDuration time.Duration)

SetBudget replaces the client's timeout and maxCallDuration while it is in use: the server's spec.timeout or spec.progress.maxDuration changed and the connection stays. Every operation started after it runs under the new budget; one in flight keeps the budget it started with. Safe for concurrent use.

func (*StdioClient) UseSubscriptionsListen added in v5.47.0

func (b *StdioClient) UseSubscriptionsListen()

UseSubscriptionsListen puts the client in listen mode; see ResourceListener.

type StreamableHTTPClient

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

StreamableHTTPClient implements the MCPClient interface using StreamableHTTP transport. It connects to remote MCP servers using HTTP with streaming support.

func NewStreamableHTTPClientWithHeaderFunc

func NewStreamableHTTPClientWithHeaderFunc(url string, headerFunc transport.HTTPHeaderFunc) *StreamableHTTPClient

NewStreamableHTTPClientWithHeaderFunc creates a new StreamableHTTP-based MCP client with a dynamic header function that is called on every request. This enables token refresh by resolving the latest token at call time instead of baking in a static header.

func NewStreamableHTTPClientWithHeaders

func NewStreamableHTTPClientWithHeaders(url string, headers map[string]string) *StreamableHTTPClient

NewStreamableHTTPClientWithHeaders creates a new StreamableHTTP-based MCP client with custom headers

func (*StreamableHTTPClient) CallTool

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

CallTool executes a specific tool and returns the result

func (*StreamableHTTPClient) Close

func (c *StreamableHTTPClient) Close() error

Close cleanly shuts down the client connection

func (*StreamableHTTPClient) GetPrompt

func (c *StreamableHTTPClient) GetPrompt(ctx context.Context, name string, args map[string]interface{}) (*mcp.GetPromptResult, error)

GetPrompt retrieves a specific prompt

func (*StreamableHTTPClient) Initialize

func (c *StreamableHTTPClient) Initialize(ctx context.Context) error

Initialize establishes the connection and performs protocol handshake, under the client's timeout like every other operation.

func (*StreamableHTTPClient) ListPrompts

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

ListPrompts returns all available prompts from the server

func (*StreamableHTTPClient) ListResources

func (c *StreamableHTTPClient) ListResources(ctx context.Context) ([]mcp.Resource, error)

ListResources returns all available resources from the server

func (*StreamableHTTPClient) ListTools

func (c *StreamableHTTPClient) ListTools(ctx context.Context) ([]mcp.Tool, error)

ListTools returns all available tools from the server

func (*StreamableHTTPClient) ListenResources added in v5.47.0

func (b *StreamableHTTPClient) ListenResources(ctx context.Context, uris []string) error

ListenResources opens a subscriptions/listen stream; see ResourceListener. The lock is not held while the stream is open, so Close can end it.

func (*StreamableHTTPClient) NegotiatedProtocolVersion

func (b *StreamableHTTPClient) NegotiatedProtocolVersion() string

NegotiatedProtocolVersion returns the MCP revision the server answered with during the handshake, or "" when the client is not connected.

func (*StreamableHTTPClient) OnNotification

func (c *StreamableHTTPClient) OnNotification(handler func(mcp.JSONRPCNotification))

OnNotification registers a handler for server-pushed notifications.

func (*StreamableHTTPClient) OnSessionRecovered added in v5.39.1

func (b *StreamableHTTPClient) OnSessionRecovered(handler func())

OnSessionRecovered registers a handler called after the client lost its MCP session and re-established it with a fresh handshake (session recovery, client_session_recovery.go). A backend forgets a session when a new process took over behind its address: the handler is where a caller re-reads what that process serves. It runs on a goroutine of its own, so it may use the client. Transports without a session to lose never call it.

func (*StreamableHTTPClient) Ping

Ping checks if the server is responsive

func (*StreamableHTTPClient) ReadResource

func (c *StreamableHTTPClient) ReadResource(ctx context.Context, uri string) (*mcp.ReadResourceResult, error)

ReadResource retrieves a specific resource

func (*StreamableHTTPClient) ServerCapabilities added in v5.29.1

func (b *StreamableHTTPClient) ServerCapabilities() mcp.ServerCapabilities

ServerCapabilities returns the capabilities the server declared during the handshake, or the zero value when the client is not connected.

func (*StreamableHTTPClient) SetBudget added in v5.52.17

func (b *StreamableHTTPClient) SetBudget(timeout, maxCallDuration time.Duration)

SetBudget replaces the client's timeout and maxCallDuration while it is in use: the server's spec.timeout or spec.progress.maxDuration changed and the connection stays. Every operation started after it runs under the new budget; one in flight keeps the budget it started with. Safe for concurrent use.

func (*StreamableHTTPClient) UseSubscriptionsListen added in v5.47.0

func (b *StreamableHTTPClient) UseSubscriptionsListen()

UseSubscriptionsListen puts the client in listen mode; see ResourceListener.

func (*StreamableHTTPClient) WithHeaders added in v5.28.1

func (c *StreamableHTTPClient) WithHeaders(headers map[string]string) *StreamableHTTPClient

WithHeaders adds static headers sent with every request -- the definition's spec.headers on a client whose credential comes from a header func -- and returns the client so a construction site reads as one expression. The header func's entries win over a static one of the same name, so the credential stays the session's.

func (*StreamableHTTPClient) WithMaxCallDuration added in v5.40.0

func (c *StreamableHTTPClient) WithMaxCallDuration(maxCallDuration time.Duration) *StreamableHTTPClient

WithMaxCallDuration sets how long progress may keep a tool call going, the server's spec.progress.maxDuration (see baseMCPClient.maxCallDuration), and returns the client so a construction site reads as one expression.

func (*StreamableHTTPClient) WithMeta

func (c *StreamableHTTPClient) WithMeta(meta map[string]string) *StreamableHTTPClient

WithMeta sets the entries merged into the params._meta object of every outbound JSON-RPC request that carries params, and returns the client so a construction site reads as one expression.

func (*StreamableHTTPClient) WithTimeout added in v5.27.2

func (c *StreamableHTTPClient) WithTimeout(timeout time.Duration) *StreamableHTTPClient

WithTimeout sets the budget every operation on the client runs under, the server's spec.timeout (see baseMCPClient.timeout), and returns the client so a construction site reads as one expression.

type TransportDetectionResult

type TransportDetectionResult struct {
	// URL is the probed endpoint.
	URL string `json:"url"`

	// Transport is the detected transport: "streamable-http", "sse", or
	// "unknown" when detection was inconclusive.
	Transport string `json:"transport"`

	// Reachable reports whether the server answered either probe at the
	// HTTP level (including with a 401 challenge).
	Reachable bool `json:"reachable"`

	// RequiresAuth reports that a probe was answered with a 401 challenge,
	// meaning the server exists but wants OAuth before the handshake.
	RequiresAuth bool `json:"requiresAuth"`

	// ServerName and ServerVersion carry the server implementation info
	// from a successful initialize handshake, when one completed.
	ServerName    string `json:"serverName,omitempty"`
	ServerVersion string `json:"serverVersion,omitempty"`

	// Detail is a human-readable explanation of how the verdict was reached.
	Detail string `json:"detail"`
}

TransportDetectionResult is the outcome of probing a remote MCP server URL to determine which transport it speaks. Detection never fails hard: an unreachable or unclassifiable server yields Transport "unknown" so callers (e.g. a registration wizard) can fall back to manual selection.

func DetectTransport

func DetectTransport(ctx context.Context, url string, headers map[string]string, timeout time.Duration) *TransportDetectionResult

DetectTransport probes url to determine whether it speaks the streamable-http or the legacy SSE MCP transport.

The streamable-http probe runs first: a successful initialize POST is definitive for streamable-http, and probing order matters because a streamable-http server may hold a GET stream open without ever sending the endpoint event the SSE probe waits for. The SSE probe is equally definitive when it completes, since only SSE servers emit the endpoint event. A 401 challenge identifies a live MCP endpoint without revealing the transport by itself; when that is the only signal, streamable-http is reported because the WWW-Authenticate challenge flow is part of the modern spec generation that also introduced streamable-http.

type Visibility added in v5.47.0

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

Visibility answers which MCP servers a caller may see (agent-permissions D9): muster lists MCPServer objects as the caller, with the caller's own ID token, once per namespace that holds servers, and the caller sees the servers of every namespace where the API server allows the list. muster's ServiceAccount gets no new right and muster keeps no copy of the claim mapping: RBAC answers.

func NewVisibility added in v5.47.0

func NewVisibility(servers client.MusterClient, factory callerwrite.ClientFactory, audience, musterNamespace string) *Visibility

NewVisibility returns the visibility handler. servers reads the MCPServer objects of every namespace as muster (to learn which namespaces hold servers); factory builds a client with the caller's token; audience is the audience the API server needs on that token (empty: the default).

func (*Visibility) CallerVisibility added in v5.47.0

func (v *Visibility) CallerVisibility(ctx context.Context) api.ServerVisibility

CallerVisibility implements api.MCPServerVisibilityHandler. It fails closed: a session without an ID token, with a token that lacks the API server's audience or that the API server rejects sees no server, not even the servers of muster's namespace, and is told to sign in again.

func (*Visibility) LoginAudience added in v5.47.0

func (v *Visibility) LoginAudience() string

LoginAudience implements api.MCPServerVisibilityHandler.

Jump to

Keyboard shortcuts

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