Documentation
¶
Overview ¶
Package mcp implements Dynamic Client Registration Protocol (RFC 7591)
Package mcp provides a client for the Model Control Protocol (MCP) that allows the AI plugin to access external tools provided by MCP servers.
The UserClients represents a single user's connection to multiple MCP servers. The Client represents a connection to a single MCP server. The UserClients currently only supports authentication via Mattermost user ID header X-Mattermost-UserID. In the future it will support our OAuth implementation.
The ClientManager manages multiple UserClients, allowing for efficient mangement of connections. It is responsible for creating and closing UserClients as needed.
The organization reflects the need for each user to have their own connection to the MCP server given the design of MCP.
Index ¶
- Constants
- func GetRegistrationEndpoint(ctx context.Context, httpClient *http.Client, serverURL string) (string, error)
- type AuthorizationServerMetadata
- type CachedTools
- type Client
- type ClientCredentials
- type ClientManager
- func (m *ClientManager) Close()
- func (m *ClientManager) EnsureMCPSessionID(userID string) (string, error)
- func (m *ClientManager) GetEmbeddedServer() EmbeddedMCPServer
- func (m *ClientManager) GetHTTPClient() *http.Client
- func (m *ClientManager) GetOAuthManager() *OAuthManager
- func (m *ClientManager) GetToolsCache() *ToolsCache
- func (m *ClientManager) GetToolsForUser(userID string) ([]llm.Tool, *Errors)
- func (m *ClientManager) ProcessOAuthCallback(ctx context.Context, userID, state, code string) (*OAuthSession, error)
- func (m *ClientManager) ReInit(config Config, embeddedServer EmbeddedMCPServer)
- type Config
- type EmbeddedMCPServer
- type EmbeddedServerClient
- type EmbeddedServerConfig
- type Errors
- type KVStore
- type Logger
- type OAuthManager
- type OAuthNeededError
- type OAuthSession
- type ProtectedResourceMetadata
- type RegistrationError
- type RegistrationRequest
- type RegistrationResponse
- type ServerConfig
- type ToolInfo
- type ToolsCache
- type UserClients
Constants ¶
const ( MMUserIDHeader = "X-Mattermost-UserID" EmbeddedServerName = "Mattermost" EmbeddedClientKey = "embedded://mattermost" )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AuthorizationServerMetadata ¶ added in v1.4.0
type AuthorizationServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
ResponseTypesSupported []string `json:"response_types_supported"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
}
AuthorizationServerMetadata represents the OAuth 2.0 Authorization Server Metadata (RFC 8414)
type CachedTools ¶ added in v1.5.0
type CachedTools struct {
Tools map[string]*mcp.Tool `json:"tools"`
Timestamp time.Time `json:"timestamp"`
ServerURL string `json:"server_url"`
ServerName string `json:"server_name"`
}
CachedTools represents a cached set of tools for a specific MCP server
type Client ¶ added in v1.4.0
type Client struct {
// contains filtered or unexported fields
}
Client represents the connection to a single MCP server
func NewClient ¶ added in v1.4.0
func NewClient(ctx context.Context, userID string, serverConfig ServerConfig, log pluginapi.LogService, oauthManager *OAuthManager, httpClient *http.Client, toolsCache *ToolsCache) (*Client, error)
NewClient creates a new MCP client for the given server and user and connects to the specified MCP server
func (*Client) CallTool ¶ added in v1.4.0
func (c *Client) CallTool(ctx context.Context, toolName string, args map[string]any) (string, error)
CallTool calls a tool on this MCP server
func (*Client) CallToolWithMetadata ¶ added in v1.6.0
func (c *Client) CallToolWithMetadata(ctx context.Context, toolName string, args map[string]any, metadata map[string]any) (string, error)
CallToolWithMetadata calls a tool on this MCP server with optional metadata
type ClientCredentials ¶ added in v1.4.0
type ClientManager ¶
type ClientManager struct {
// contains filtered or unexported fields
}
ClientManager manages MCP clients for multiple users
func NewClientManager ¶
func NewClientManager(config Config, log pluginapi.LogService, pluginAPI *pluginapi.Client, oauthManager *OAuthManager, embeddedServer EmbeddedMCPServer, httpClient *http.Client) *ClientManager
NewClientManager creates a new MCP client manager embeddedServer can be nil if embedded server is not available
func (*ClientManager) Close ¶
func (m *ClientManager) Close()
Close closes the client manager and all managed clients The client manger should not be used after Close is called
func (*ClientManager) EnsureMCPSessionID ¶ added in v1.6.0
func (m *ClientManager) EnsureMCPSessionID(userID string) (string, error)
EnsureMCPSessionID ensures there is a valid MCP session for the user This is used by both embedded and HTTP MCP servers to get a dedicated session
func (*ClientManager) GetEmbeddedServer ¶ added in v1.5.0
func (m *ClientManager) GetEmbeddedServer() EmbeddedMCPServer
GetEmbeddedServer returns the embedded MCP server instance (may be nil) This method is kept for API compatibility
func (*ClientManager) GetHTTPClient ¶ added in v1.7.0
func (m *ClientManager) GetHTTPClient() *http.Client
GetHTTPClient returns the HTTP client for upstream requests
func (*ClientManager) GetOAuthManager ¶ added in v1.4.0
func (m *ClientManager) GetOAuthManager() *OAuthManager
GetOAuthManager returns the OAuth manager instance
func (*ClientManager) GetToolsCache ¶ added in v1.5.0
func (m *ClientManager) GetToolsCache() *ToolsCache
GetToolsCache returns the tools cache instance
func (*ClientManager) GetToolsForUser ¶
func (m *ClientManager) GetToolsForUser(userID string) ([]llm.Tool, *Errors)
GetToolsForUser returns the tools available for a specific user, connecting to embedded server if session ID provided
func (*ClientManager) ProcessOAuthCallback ¶ added in v1.4.0
func (m *ClientManager) ProcessOAuthCallback(ctx context.Context, userID, state, code string) (*OAuthSession, error)
ProcessOAuthCallback processes the OAuth callback for a user
func (*ClientManager) ReInit ¶
func (m *ClientManager) ReInit(config Config, embeddedServer EmbeddedMCPServer)
ReInit re-initializes the client manager with a new configuration and embedded server
type Config ¶
type Config struct {
Enabled bool `json:"enabled"`
EnablePluginServer bool `json:"enablePluginServer"`
Servers []ServerConfig `json:"servers"`
EmbeddedServer EmbeddedServerConfig `json:"embeddedServer"`
IdleTimeoutMinutes int `json:"idleTimeoutMinutes"`
}
Config contains the configuration for the MCP servers
type EmbeddedMCPServer ¶ added in v1.5.0
type EmbeddedMCPServer interface {
CreateClientTransport(userID, sessionID string, pluginAPI *pluginapi.Client) (*mcp.InMemoryTransport, error)
}
EmbeddedMCPServer interface for dependency injection
type EmbeddedServerClient ¶ added in v1.5.0
type EmbeddedServerClient struct {
// contains filtered or unexported fields
}
EmbeddedServerClient handles connections to the embedded MCP server
func NewEmbeddedServerClient ¶ added in v1.5.0
func NewEmbeddedServerClient(server EmbeddedMCPServer, log pluginapi.LogService, pluginAPI *pluginapi.Client) *EmbeddedServerClient
func (*EmbeddedServerClient) CreateClient ¶ added in v1.5.0
func (c *EmbeddedServerClient) CreateClient(ctx context.Context, userID, sessionID string) (*Client, error)
CreateClient creates an embedded MCP client using session ID for authentication If sessionID is empty, creates an unauthenticated client (used for tool discovery)
type EmbeddedServerConfig ¶ added in v1.5.0
type EmbeddedServerConfig struct {
Enabled bool `json:"enabled"`
}
EmbeddedServerConfig contains configuration for the embedded MCP server
type Errors ¶ added in v1.4.0
type Errors struct {
ToolAuthErrors []llm.ToolAuthError // Authentication errors users need to resolve
Errors []error // Generic errors (connection, config, etc.)
}
Errors represents a collection of errors from MCP operations.
type KVStore ¶ added in v1.5.0
type KVStore interface {
Get(key string, o any) error
Set(key string, value any, options ...pluginapi.KVSetOption) (bool, error)
Delete(key string) error
ListKeys(page, count int, options ...pluginapi.ListKeysOption) ([]string, error)
}
KVStore interface for key-value operations
type Logger ¶ added in v1.5.0
type Logger interface {
Debug(msg string, keyValuePairs ...interface{})
Info(msg string, keyValuePairs ...interface{})
Warn(msg string, keyValuePairs ...interface{})
Error(msg string, keyValuePairs ...interface{})
}
Logger interface for logging operations
type OAuthManager ¶ added in v1.4.0
type OAuthManager struct {
// contains filtered or unexported fields
}
func NewOAuthManager ¶ added in v1.4.0
func (*OAuthManager) InitiateOAuthFlow ¶ added in v1.4.0
func (*OAuthManager) ProcessCallback ¶ added in v1.4.0
func (m *OAuthManager) ProcessCallback(ctx context.Context, loggedInUserID, state, code string) (*OAuthSession, error)
type OAuthNeededError ¶ added in v1.4.0
type OAuthNeededError struct {
// contains filtered or unexported fields
}
func (*OAuthNeededError) AuthURL ¶ added in v1.4.0
func (e *OAuthNeededError) AuthURL() string
func (*OAuthNeededError) Error ¶ added in v1.4.0
func (e *OAuthNeededError) Error() string
func (*OAuthNeededError) Unwrap ¶ added in v1.4.0
func (e *OAuthNeededError) Unwrap() error
type OAuthSession ¶ added in v1.4.0
type ProtectedResourceMetadata ¶ added in v1.4.0
type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
}
ProtectedResourceMetadata represents the OAuth 2.0 Protected Resource Metadata (RFC 9728)
type RegistrationError ¶ added in v1.4.0
type RegistrationError struct {
ErrorCode string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
HTTPStatusCode int `json:"-"`
HTTPResponse *http.Response `json:"-"`
}
RegistrationError represents an error response per RFC 7591
func (*RegistrationError) Error ¶ added in v1.4.0
func (e *RegistrationError) Error() string
type RegistrationRequest ¶ added in v1.4.0
type RegistrationRequest struct {
// Required fields
RedirectURIs []string `json:"redirect_uris"`
// Optional fields commonly used
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
ClientName string `json:"client_name,omitempty"`
Scope string `json:"scope,omitempty"`
Contacts []string `json:"contacts,omitempty"`
// Additional optional fields can be added as needed
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
ToSURI string `json:"tos_uri,omitempty"`
PolicyURI string `json:"policy_uri,omitempty"`
}
RegistrationRequest represents a client registration request per RFC 7591
func DefaultRegistrationRequest ¶ added in v1.4.0
func DefaultRegistrationRequest(redirectURI, clientName string) *RegistrationRequest
DefaultRegistrationRequest creates a default registration request for MCP clients
type RegistrationResponse ¶ added in v1.4.0
type RegistrationResponse struct {
// Required fields
ClientID string `json:"client_id"`
// Optional fields
ClientSecret string `json:"client_secret,omitempty"`
ClientIDIssuedAt *int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt *int64 `json:"client_secret_expires_at,omitempty"`
// Echo back the registration metadata
RedirectURIs []string `json:"redirect_uris,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
ClientName string `json:"client_name,omitempty"`
Scope string `json:"scope,omitempty"`
Contacts []string `json:"contacts,omitempty"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
ToSURI string `json:"tos_uri,omitempty"`
PolicyURI string `json:"policy_uri,omitempty"`
}
RegistrationResponse represents the server's response per RFC 7591
func DiscoverAndRegisterClient ¶ added in v1.4.0
func DiscoverAndRegisterClient(ctx context.Context, httpClient *http.Client, serverURL, callbackURL, clientID, initialAccessToken string) (*RegistrationResponse, error)
DiscoverAndRegisterClient performs the complete client registration flow: 1. Discovers the registration endpoint from server metadata 2. Creates a default registration request 3. Registers the client with the server
func RegisterClient ¶ added in v1.4.0
func RegisterClient(ctx context.Context, httpClient *http.Client, registrationEndpoint string, request *RegistrationRequest, initialAccessToken string) (*RegistrationResponse, error)
RegisterClient performs dynamic client registration per RFC 7591
type ServerConfig ¶
type ServerConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
BaseURL string `json:"baseURL"`
Headers map[string]string `json:"headers,omitempty"`
}
ServerConfig contains the configuration for a single MCP server
type ToolInfo ¶ added in v1.4.0
type ToolInfo struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema any `json:"inputSchema"`
}
ToolInfo represents a tool's metadata for discovery purposes
func DiscoverEmbeddedServerTools ¶ added in v1.5.0
func DiscoverEmbeddedServerTools( ctx context.Context, userID string, sessionID string, embeddedServerConfig EmbeddedServerConfig, embeddedServer EmbeddedMCPServer, log pluginapi.LogService, pluginAPI *pluginapi.Client, ) ([]ToolInfo, error)
DiscoverEmbeddedServerTools creates a temporary connection to an embedded MCP server and discovers its tools
func DiscoverRemoteServerTools ¶ added in v1.5.0
func DiscoverRemoteServerTools( ctx context.Context, userID string, serverConfig ServerConfig, log pluginapi.LogService, oauthManger *OAuthManager, httpClient *http.Client, toolsCache *ToolsCache, ) ([]ToolInfo, error)
DiscoverRemoteServerTools creates a temporary connection to a remote MCP server and discovers its tools
type ToolsCache ¶ added in v1.5.0
type ToolsCache struct {
// contains filtered or unexported fields
}
ToolsCache manages the global cache of MCP tools across all users It uses the KV store directly for HA mode compatibility
func NewToolsCache ¶ added in v1.5.0
func NewToolsCache(kvAPI KVStore, log Logger) *ToolsCache
NewToolsCache creates a new ToolsCache instance
func (*ToolsCache) ClearAll ¶ added in v1.5.0
func (tc *ToolsCache) ClearAll() (int, error)
ClearAll removes all cached tools from KV store
func (*ToolsCache) GetTools ¶ added in v1.5.0
func (tc *ToolsCache) GetTools(serverID string) map[string]*mcp.Tool
GetTools retrieves cached tools for a server, returns nil if missing
func (*ToolsCache) InvalidateServer ¶ added in v1.5.0
func (tc *ToolsCache) InvalidateServer(serverID string) error
InvalidateServer removes a server's cache entry from KV store Delete returns no error for non-existent keys, only errors on actual failures
type UserClients ¶ added in v1.4.0
type UserClients struct {
// contains filtered or unexported fields
}
UserClients represents a per-user MCP client with multiple server connections
func NewUserClients ¶ added in v1.4.0
func NewUserClients(userID string, log pluginapi.LogService, oauthManager *OAuthManager, httpClient *http.Client, toolsCache *ToolsCache) *UserClients
func (*UserClients) Close ¶ added in v1.4.0
func (c *UserClients) Close()
Close closes all server connections for a user client
func (*UserClients) ConnectToEmbeddedServerIfAvailable ¶ added in v1.5.0
func (c *UserClients) ConnectToEmbeddedServerIfAvailable(sessionID string, embeddedClient *EmbeddedServerClient, embeddedConfig EmbeddedServerConfig) error
ConnectToEmbeddedServerIfAvailable connects to the embedded server if session ID is provided
func (*UserClients) ConnectToRemoteServers ¶ added in v1.5.0
func (c *UserClients) ConnectToRemoteServers(servers []ServerConfig) *Errors
ConnectToRemoteServers initializes connections to remote MCP servers
func (*UserClients) GetTools ¶ added in v1.4.0
func (c *UserClients) GetTools() []llm.Tool
GetTools returns the tools available from the clients