mcp

package
v1.54.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildAuthorizationURL

func BuildAuthorizationURL(authEndpoint, clientID, redirectURI, state, codeChallenge, resourceURL string, scopes []string) string

BuildAuthorizationURL builds the OAuth authorization URL with PKCE

func GeneratePKCEVerifier

func GeneratePKCEVerifier() string

GeneratePKCEVerifier generates a PKCE code verifier using oauth2 library

func GenerateState

func GenerateState() (string, error)

GenerateState generates a random state parameter for OAuth CSRF protection

func IsAuthorizationRequired added in v1.54.0

func IsAuthorizationRequired(err error) bool

IsAuthorizationRequired reports whether err (or any error wrapped by it) signals that the toolset failed to start because OAuth is needed and the caller chose to defer the prompt. Callers can use this to render a softer, "needs auth" notice instead of a red error.

func PerformOAuthLogin added in v1.44.0

func PerformOAuthLogin(ctx context.Context, serverURL string) error

PerformOAuthLogin performs a standalone OAuth flow for the given MCP server URL. It discovers the authorization server metadata, performs dynamic client registration, opens the browser for user authorization, and stores the resulting token in the keyring.

func RegisterClient

func RegisterClient(ctx context.Context, authMetadata *AuthorizationServerMetadata, redirectURI string, scopes []string) (clientID, clientSecret string, err error)

RegisterClient performs dynamic client registration

func RemoveOAuthToken added in v1.44.0

func RemoveOAuthToken(resourceURL string) error

RemoveOAuthToken deletes the token stored for resourceURL.

func RequestAuthorizationCode

func RequestAuthorizationCode(ctx context.Context, authURL string, callbackServer *CallbackServer, expectedState string) (string, string, error)

RequestAuthorizationCode requests the user to open the authorization URL and waits for the callback

func WithoutInteractivePrompts added in v1.54.0

func WithoutInteractivePrompts(ctx context.Context) context.Context

WithoutInteractivePrompts returns a context that asks the MCP transport stack to refuse any flow that would require user input. The canonical example is OAuth: a remote MCP server's first contact is typically a 401 Unauthorized that triggers an interactive elicitation flow ("approve OAuth authorization?"). During startup the TUI is not yet ready to surface that dialog, the user has no input field, and Ctrl-C cannot reach the elicitation goroutine because it is blocked on a synchronous send/receive.

Callers that prepare data eagerly (sidebar tool counts, dry-runs, health checks) should wrap their context with this helper so toolset Start() returns a meaningful error immediately instead of hanging the process.

Once a real user interaction is in progress (RunStream), the context should NOT carry this value so the user can complete OAuth normally.

Types

type AuthorizationRequiredError added in v1.54.0

type AuthorizationRequiredError struct {
	URL string
}

AuthorizationRequiredError is returned by the transport when an OAuth elicitation would be needed but the context disallows interactive prompts (see WithoutInteractivePrompts). Callers can detect it with IsAuthorizationRequired and decide how (or whether) to surface it.

The exported type is also useful in tests that want to simulate the deferred-OAuth path without spinning up a real HTTP server.

func (*AuthorizationRequiredError) Error added in v1.54.0

type AuthorizationServerMetadata

type AuthorizationServerMetadata struct {
	Issuer                                 string   `json:"issuer"`
	AuthorizationEndpoint                  string   `json:"authorization_endpoint"`
	TokenEndpoint                          string   `json:"token_endpoint"`
	RegistrationEndpoint                   string   `json:"registration_endpoint,omitempty"`
	RevocationEndpoint                     string   `json:"revocation_endpoint,omitempty"`
	IntrospectionEndpoint                  string   `json:"introspection_endpoint,omitempty"`
	JwksURI                                string   `json:"jwks_uri,omitempty"`
	ScopesSupported                        []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported                 []string `json:"response_types_supported"`
	ResponseModesSupported                 []string `json:"response_modes_supported,omitempty"`
	GrantTypesSupported                    []string `json:"grant_types_supported,omitempty"`
	TokenEndpointAuthMethodsSupported      []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty"`
	CodeChallengeMethodsSupported          []string `json:"code_challenge_methods_supported,omitempty"`
}

AuthorizationServerMetadata represents OAuth 2.0 Authorization Server Metadata (RFC 8414)

type CallbackServer

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

CallbackServer handles OAuth callback requests

func NewCallbackServer

func NewCallbackServer() (*CallbackServer, error)

NewCallbackServer creates a new OAuth callback server on a random available port

func NewCallbackServerOnPort added in v1.46.0

func NewCallbackServerOnPort(port int) (*CallbackServer, error)

NewCallbackServerOnPort creates a new OAuth callback server on a specific port. Use port 0 to let the OS pick a random available port.

func (*CallbackServer) GetRedirectURI

func (cs *CallbackServer) GetRedirectURI() string

func (*CallbackServer) Port added in v1.50.0

func (cs *CallbackServer) Port() int

Port returns the local TCP port the callback server is listening on. This is useful when a fixed port was not requested (i.e. port 0 was passed) and the caller needs to know which port the OS assigned.

func (*CallbackServer) SetExpectedState

func (cs *CallbackServer) SetExpectedState(state string)

func (*CallbackServer) Shutdown

func (cs *CallbackServer) Shutdown(ctx context.Context) error

func (*CallbackServer) Start

func (cs *CallbackServer) Start() error

func (*CallbackServer) WaitForCallback

func (cs *CallbackServer) WaitForCallback(ctx context.Context) (code, state string, err error)

type GatewayToolset

type GatewayToolset struct {
	*Toolset
	// contains filtered or unexported fields
}

func NewGatewayToolset

func NewGatewayToolset(ctx context.Context, name, mcpServerName string, secrets []gateway.Secret, config any, envProvider environment.Provider, cwd string) (*GatewayToolset, error)

func (*GatewayToolset) Stop

func (t *GatewayToolset) Stop(ctx context.Context) error

type InMemoryTokenStore

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

InMemoryTokenStore implements OAuthTokenStore in memory

func (*InMemoryTokenStore) GetToken

func (s *InMemoryTokenStore) GetToken(resourceURL string) (*OAuthToken, error)

func (*InMemoryTokenStore) RemoveToken

func (s *InMemoryTokenStore) RemoveToken(resourceURL string) error

func (*InMemoryTokenStore) StoreToken

func (s *InMemoryTokenStore) StoreToken(resourceURL string, token *OAuthToken) error

type KeyringTokenStore added in v1.44.0

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

KeyringTokenStore implements OAuthTokenStore by caching the bundled keyring item in memory: the OAuth transport's hot path stays in memory after the first hit, and writes always target the same keyring item so the user's "Always Allow" decision keeps applying to refreshes and to new MCP servers.

func (*KeyringTokenStore) GetToken added in v1.44.0

func (s *KeyringTokenStore) GetToken(resourceURL string) (*OAuthToken, error)

func (*KeyringTokenStore) RemoveToken added in v1.44.0

func (s *KeyringTokenStore) RemoveToken(resourceURL string) error

func (*KeyringTokenStore) StoreToken added in v1.44.0

func (s *KeyringTokenStore) StoreToken(resourceURL string, token *OAuthToken) error

type OAuthToken

type OAuthToken struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type"`
	ExpiresIn    int       `json:"expires_in,omitempty"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	Scope        string    `json:"scope,omitempty"`
	ExpiresAt    time.Time `json:"expires_at"`
	ClientID     string    `json:"client_id,omitempty"`
	ClientSecret string    `json:"client_secret,omitempty"`
	AuthServer   string    `json:"auth_server,omitempty"`

	// RequestedScopes records the scope list the config asked for when this
	// token was obtained. Unlike Scope (which is whatever the authorization
	// server chose to return, sometimes empty, sometimes comma/space
	// separated), RequestedScopes reflects our intent and is used to detect
	// when the config has changed and a new OAuth flow is required.
	RequestedScopes []string `json:"requested_scopes,omitempty"`
}

func ExchangeCodeForToken

func ExchangeCodeForToken(ctx context.Context, tokenEndpoint, code, codeVerifier, clientID, clientSecret, redirectURI string) (*OAuthToken, error)

ExchangeCodeForToken exchanges an authorization code for an access token

func RefreshAccessToken added in v1.44.0

func RefreshAccessToken(ctx context.Context, tokenEndpoint, refreshToken, clientID, clientSecret string) (*OAuthToken, error)

RefreshAccessToken uses a refresh token to obtain a new access token without user interaction.

func (*OAuthToken) IsExpired

func (t *OAuthToken) IsExpired() bool

IsExpired checks if the token is expired

type OAuthTokenEntry added in v1.44.0

type OAuthTokenEntry struct {
	ResourceURL string
	Token       *OAuthToken
}

OAuthTokenEntry pairs a stored OAuth token with its resource URL.

func ListOAuthTokens added in v1.44.0

func ListOAuthTokens() ([]OAuthTokenEntry, error)

ListOAuthTokens returns every OAuth token persisted in the keyring.

type OAuthTokenStore

type OAuthTokenStore interface {
	// GetToken retrieves a token for the given resource URL
	GetToken(resourceURL string) (*OAuthToken, error)
	// StoreToken stores a token for the given resource URL
	StoreToken(resourceURL string, token *OAuthToken) error
	// RemoveToken removes a token for the given resource URL
	RemoveToken(resourceURL string) error
}

OAuthTokenStore manages OAuth tokens

func NewInMemoryTokenStore

func NewInMemoryTokenStore() OAuthTokenStore

NewInMemoryTokenStore creates a new in-memory token store

func NewKeyringTokenStore added in v1.44.0

func NewKeyringTokenStore() OAuthTokenStore

NewKeyringTokenStore returns the process-wide token store backed by the OS keyring, falling back to InMemoryTokenStore when no backend is available. It always returns the same instance.

type PromptArgument

type PromptArgument struct {
	Name        string `json:"name"`        // The name of the argument
	Description string `json:"description"` // Human-readable description of the argument
	Required    bool   `json:"required"`    // Whether this argument is required
}

PromptArgument represents a single argument for an MCP prompt

type PromptInfo

type PromptInfo struct {
	Name        string           `json:"name"`        // The prompt name/identifier
	Description string           `json:"description"` // Human-readable description of what this prompt does
	Arguments   []PromptArgument `json:"arguments"`   // List of arguments this prompt accepts
}

PromptInfo contains metadata about an available MCP prompt

type Toolset

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

Toolset represents a set of MCP tools.

Connection lifecycle (initial connect, watcher goroutine, restart with backoff, graceful Stop) is delegated to a *lifecycle.Supervisor; the historical watchConnection / tryRestart / forceReconnectAndWait helpers have been replaced by the supervisor's Start / RestartAndWait / Stop.

func NewRemoteToolset

func NewRemoteToolset(name, urlString, transport string, headers map[string]string, oauthConfig *latest.RemoteOAuthConfig, policy ...lifecycle.Policy) *Toolset

NewRemoteToolset creates a new MCP toolset from a remote MCP Server.

The optional policy lets callers tune restart/backoff behaviour; see NewToolsetCommand for the semantics.

func NewToolsetCommand

func NewToolsetCommand(name, command string, args, env []string, cwd string, policy ...lifecycle.Policy) *Toolset

NewToolsetCommand creates a new MCP toolset from a command.

The optional policy lets callers tune restart/backoff behaviour. When the zero value is passed the supervisor uses its built-in defaults (RestartOnFailure, 5 attempts, 1s..32s backoff). Internal callbacks (OnDisconnect, OnRestart, Logger) are always set by the constructor and any values passed in for those fields are ignored.

func (*Toolset) Describe

func (ts *Toolset) Describe() string

Describe returns a short, user-visible description of this toolset instance. It never includes secrets.

func (*Toolset) GetPrompt

func (ts *Toolset) GetPrompt(ctx context.Context, name string, arguments map[string]string) (*mcp.GetPromptResult, error)

GetPrompt retrieves a specific prompt with provided arguments from the MCP server. This method executes the prompt and returns the result content.

func (*Toolset) Instructions

func (ts *Toolset) Instructions() string

func (*Toolset) IsStarted added in v1.54.0

func (ts *Toolset) IsStarted() bool

IsStarted reports whether the supervisor currently considers the toolset connected and serving requests. Used by tests and TUI status surfaces.

func (*Toolset) Kind added in v1.54.0

func (ts *Toolset) Kind() string

Kind returns a short, user-friendly classification of this toolset: "Remote MCP" for HTTP/SSE/streamable-HTTP transports and "MCP" for stdio-spawned servers. Used by status surfaces (e.g. the /tools dialog) to label the toolset without leaking Go type names.

func (*Toolset) ListPrompts

func (ts *Toolset) ListPrompts(ctx context.Context) ([]PromptInfo, error)

ListPrompts retrieves available prompts from the MCP server. Returns a slice of PromptInfo containing metadata about each available prompt including name, description, and argument specifications.

func (*Toolset) Name added in v1.54.0

func (ts *Toolset) Name() string

Name returns the user-facing identifier for this MCP toolset.

When the YAML provides a `name:` field it always wins (it's also the prefix applied to every tool exposed by the server, so a stable user choice). Otherwise we fall back to the description — "mcp(stdio cmd=docker)", "mcp(remote host=api.github.com)", "mcp(ref=duckduckgo)" — because that disambiguates between several unnamed MCP toolsets far better than the bare YAML type "mcp" the registry would otherwise fall back to.

func (*Toolset) Restart added in v1.54.0

func (ts *Toolset) Restart(ctx context.Context) error

Restart brings the toolset back up regardless of state. Failed or Stopped supervisors are recovered via Start (RestartAndWait would return immediately because `done` is closed). Otherwise the current session is dropped and we wait for the supervisor to reconnect, up to sessionMissingRetryTimeout.

func (*Toolset) SetElicitationHandler

func (ts *Toolset) SetElicitationHandler(handler tools.ElicitationHandler)

func (*Toolset) SetManagedOAuth

func (ts *Toolset) SetManagedOAuth(managed bool)

func (*Toolset) SetOAuthSuccessHandler

func (ts *Toolset) SetOAuthSuccessHandler(handler func())

func (*Toolset) SetToolsChangedHandler

func (ts *Toolset) SetToolsChangedHandler(handler func())

func (*Toolset) Start

func (ts *Toolset) Start(ctx context.Context) error

Start performs the initial connect via the supervisor. If the connect fails (e.g. the server binary is missing), Start returns the underlying error and the toolset stays in StateStopped; the caller is expected to retry.

func (*Toolset) State added in v1.54.0

func (ts *Toolset) State() lifecycle.StateInfo

State returns a snapshot of the toolset's lifecycle state, suitable for status displays.

func (*Toolset) Stop

func (ts *Toolset) Stop(ctx context.Context) error

Stop tears the supervisor down. Idempotent.

func (*Toolset) Tools

func (ts *Toolset) Tools(ctx context.Context) ([]tools.Tool, error)

func (*Toolset) WorkingDir added in v1.48.0

func (ts *Toolset) WorkingDir() string

WorkingDir returns the working directory of the underlying stdio client, or an empty string if this toolset uses a remote transport. This is intended for testing only.

Jump to

Keyboard shortcuts

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