Documentation
¶
Overview ¶
Package mcp provides Model Context Protocol (MCP) client functionality. MCP enables connecting to external servers that provide tools and resources for AI models.
Index ¶
- Constants
- Variables
- func ExtractResourceMetadataURL(resp *http.Response) *url.URL
- type AuthOptions
- type AuthResult
- type AuthorizationServerMetadata
- type Client
- func (c *Client) Connect(ctx context.Context, config ServerConfig) error
- func (c *Client) Disconnect(name string) error
- func (c *Client) DisconnectAll() error
- func (c *Client) GetResources() []Resource
- func (c *Client) GetServerInstructions(name string) string
- func (c *Client) GetTools() tool.Set
- func (c *Client) ReadResource(ctx context.Context, uri string) (*ResourceContent, error)
- type ClientAuthenticator
- type ClientInformationSaver
- type CredentialInvalidator
- type HTTPTransport
- type InvalidClientError
- type InvalidGrantError
- type MCPClientOAuthError
- type MockContent
- type MockResource
- type MockResourceContent
- type MockTool
- type MockToolResult
- type MockTransport
- type OAuthClientInformation
- type OAuthClientInformationFull
- type OAuthClientMetadata
- type OAuthClientProvider
- type OAuthErrorResponse
- type OAuthProtectedResourceMetadata
- type OAuthTokens
- type Resource
- type ResourceContent
- type ResourceURLValidator
- type SSETransport
- type ServerConfig
- type ServerConnection
- type ServerError
- type StateGenerator
- type StdioTransport
- type Transport
- type UnauthorizedClientError
- type UnauthorizedError
Constants ¶
const ( LatestProtocolVersion = "2025-11-25" HeaderProtocolVersion = "mcp-protocol-version" HeaderSessionID = "mcp-session-id" HeaderLastEventID = "last-event-id" UserAgentSuffix = "goai-mcp/1.0" )
Variables ¶
var SupportedProtocolVersions = []string{ LatestProtocolVersion, "2025-06-18", "2025-03-26", "2024-11-05", }
Functions ¶
func ExtractResourceMetadataURL ¶ added in v0.1.2
ExtractResourceMetadataURL pulls the protected-resource-metadata URL from a 401 response's WWW-Authenticate header. Returns nil when the header is missing, not bearer, or has no resource_metadata parameter.
Types ¶
type AuthOptions ¶ added in v0.1.2
type AuthOptions struct {
ServerURL string
AuthorizationCode string
CallbackState string
Scope string
ResourceMetadataURL *url.URL
HTTPClient httpDoer
}
AuthOptions controls a single Auth call.
type AuthResult ¶ added in v0.1.2
type AuthResult string
AuthResult is the return value of Auth — either the caller is ready to retry (AuthResultAuthorized) or they need to wait for a redirect-driven authorization code to come back (AuthResultRedirect).
const ( AuthResultAuthorized AuthResult = "AUTHORIZED" AuthResultRedirect AuthResult = "REDIRECT" )
func Auth ¶ added in v0.1.2
func Auth(ctx context.Context, provider OAuthClientProvider, opts AuthOptions) (AuthResult, error)
Auth runs the OAuth flow once and returns whether the caller is ready to retry (AUTHORIZED) or needs to wait for the redirect (REDIRECT). Auth transparently retries authInternal once when refresh hits InvalidClient or InvalidGrant — mirrors oauth.ts:833-860.
type AuthorizationServerMetadata ¶ added in v0.1.2
type AuthorizationServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
TokenEndpointAuthSigningAlgValuesSupp []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
// OIDC-only fields (populated when discovery returned an OIDC document).
UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`
JwksURI string `json:"jwks_uri,omitempty"`
SubjectTypesSupported []string `json:"subject_types_supported,omitempty"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`
ClaimsSupported []string `json:"claims_supported,omitempty"`
}
AuthorizationServerMetadata is the union of OAuth 2.0 metadata (RFC 8414) and OpenID Connect Discovery 1.0 metadata. We carry the superset in a single struct; consumers check non-zero fields before use.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client manages connections to MCP servers.
func (*Client) Connect ¶
func (c *Client) Connect(ctx context.Context, config ServerConfig) error
Connect connects to an MCP server.
func (*Client) Disconnect ¶
Disconnect disconnects from an MCP server.
func (*Client) DisconnectAll ¶
DisconnectAll disconnects from all MCP servers.
func (*Client) GetResources ¶
GetResources returns all resources from all connected servers.
func (*Client) GetServerInstructions ¶ added in v0.1.2
GetServerInstructions returns the instructions string the named server emitted during the initialize handshake (empty when absent or unknown). Servers use this to describe how to use the server and its tools — a good candidate to splice into the LLM system prompt. Mirrors ai-sdk #14764.
func (*Client) ReadResource ¶
ReadResource reads the content of a resource.
type ClientAuthenticator ¶ added in v0.1.2
type ClientAuthenticator interface {
AddClientAuthentication(ctx context.Context, headers http.Header, params url.Values, tokenURL *url.URL, metadata *AuthorizationServerMetadata) error
}
ClientAuthenticator opts into custom client authentication on token requests, replacing the default Basic/POST/none selection logic.
type ClientInformationSaver ¶ added in v0.1.2
type ClientInformationSaver interface {
SaveClientInformation(ctx context.Context, info *OAuthClientInformationFull) error
}
ClientInformationSaver opts the provider into dynamic registration — without it, registerClient cannot persist the issued client_id.
type CredentialInvalidator ¶ added in v0.1.2
type CredentialInvalidator interface {
// Scope is one of "all", "client", "tokens", "verifier".
InvalidateCredentials(ctx context.Context, scope string) error
}
CredentialInvalidator opts into local cleanup when the server reports credentials are no longer valid (so the user doesn't have to intervene).
type HTTPTransport ¶
type HTTPTransport struct {
// contains filtered or unexported fields
}
HTTPTransport implements the MCP Streamable HTTP transport. Each JSON-RPC call is a POST; the server may respond with a single application/json body, a JSON array, or an SSE stream. A long-lived inbound GET stream carries server-initiated notifications. Mirrors references/ai-sdk/packages/mcp/src/tool/mcp-http-transport.ts.
func NewHTTPTransport ¶
func NewHTTPTransport(serverURL string, headers map[string]string, authProvider OAuthClientProvider) *HTTPTransport
NewHTTPTransport creates a new HTTP transport. authProvider is optional; pass nil to skip OAuth.
func (*HTTPTransport) Close ¶
func (t *HTTPTransport) Close() error
Close terminates the session via DELETE (when a session-id is set), stops the inbound SSE goroutine, and closes the HTTP client.
func (*HTTPTransport) Connect ¶
func (t *HTTPTransport) Connect(ctx context.Context) error
Connect spawns the optional inbound SSE goroutine. The MCP HTTP transport is otherwise per-request — no long-lived connection state up front.
func (*HTTPTransport) OnNotification ¶
func (t *HTTPTransport) OnNotification(handler func(method string, params json.RawMessage))
OnNotification registers a handler for server notifications.
func (*HTTPTransport) Send ¶
func (t *HTTPTransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)
Send posts a JSON-RPC request to the server. Notifications skip the response wait; non-notifications return either the inline result (JSON or SSE) or an error.
type InvalidClientError ¶ added in v0.1.2
type InvalidClientError struct{ MCPClientOAuthError }
InvalidClientError corresponds to OAuth "invalid_client".
type InvalidGrantError ¶ added in v0.1.2
type InvalidGrantError struct{ MCPClientOAuthError }
InvalidGrantError corresponds to OAuth "invalid_grant".
type MCPClientOAuthError ¶ added in v0.1.2
MCPClientOAuthError is the base type for all OAuth-flow errors raised by this package. Code is the OAuth 2.0 error code from RFC 6749 §5.2 (or "server_error" / a synthetic code when we couldn't parse the response).
func (*MCPClientOAuthError) Error ¶ added in v0.1.2
func (e *MCPClientOAuthError) Error() string
func (*MCPClientOAuthError) Unwrap ¶ added in v0.1.2
func (e *MCPClientOAuthError) Unwrap() error
type MockContent ¶
MockContent is a content block in a tool result.
type MockResource ¶
type MockResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
MockResource defines a resource in the mock server.
func DefaultMockResources ¶
func DefaultMockResources() []MockResource
DefaultMockResources returns the default resources used by MockTransport.
type MockResourceContent ¶
type MockResourceContent struct {
URI string `json:"uri"`
Text string `json:"text,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
MockResourceContent defines the content returned for a resource.
func DefaultMockResourceContents ¶
func DefaultMockResourceContents() []MockResourceContent
DefaultMockResourceContents returns the default resource contents.
type MockTool ¶
type MockTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
}
MockTool defines a tool in the mock server.
func DefaultMockTools ¶
func DefaultMockTools() []MockTool
DefaultMockTools returns the default tools used by MockTransport.
type MockToolResult ¶
type MockToolResult struct {
Content []MockContent `json:"content"`
IsError bool `json:"isError,omitempty"`
}
MockToolResult defines a custom tool call result.
type MockTransport ¶
type MockTransport struct {
Tools []MockTool
Resources []MockResource
ResourceContents []MockResourceContent
ToolCallResults map[string]MockToolResult // tool name -> custom result
// FailOnInvalidToolParams makes tools/call return an error for any call.
FailOnInvalidToolParams bool
// InitializeResult overrides the initialize response.
InitializeResult json.RawMessage
// SendError makes Connect return an error.
SendError bool
// contains filtered or unexported fields
}
MockTransport implements the Transport interface for testing. It simulates an MCP server in-memory without any network I/O. Mirrors ai-sdk: packages/mcp/src/tool/mock-mcp-transport.ts
func NewMockTransport ¶
func NewMockTransport() *MockTransport
NewMockTransport creates a MockTransport with default tools and resources.
func (*MockTransport) Close ¶
func (t *MockTransport) Close() error
func (*MockTransport) OnNotification ¶
func (t *MockTransport) OnNotification(handler func(method string, params json.RawMessage))
func (*MockTransport) Send ¶
func (t *MockTransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)
type OAuthClientInformation ¶ added in v0.1.2
type OAuthClientInformation struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
}
OAuthClientInformation is the registered-client identity (id + secret).
type OAuthClientInformationFull ¶ added in v0.1.2
type OAuthClientInformationFull struct {
OAuthClientMetadata
OAuthClientInformation
}
OAuthClientInformationFull combines registration response fields. It embeds both OAuthClientMetadata (the request body the server echoes back) and OAuthClientInformation (id/secret it issues).
type OAuthClientMetadata ¶ added in v0.1.2
type OAuthClientMetadata struct {
RedirectURIs []string `json:"redirect_uris"`
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"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
Scope string `json:"scope,omitempty"`
Contacts []string `json:"contacts,omitempty"`
TosURI string `json:"tos_uri,omitempty"`
PolicyURI string `json:"policy_uri,omitempty"`
JwksURI string `json:"jwks_uri,omitempty"`
Jwks any `json:"jwks,omitempty"`
SoftwareID string `json:"software_id,omitempty"`
SoftwareVersion string `json:"software_version,omitempty"`
SoftwareStatement string `json:"software_statement,omitempty"`
}
OAuthClientMetadata is the registration request body shape (RFC 7591).
type OAuthClientProvider ¶ added in v0.1.2
type OAuthClientProvider interface {
Tokens(ctx context.Context) (*OAuthTokens, error)
SaveTokens(ctx context.Context, t *OAuthTokens) error
RedirectToAuthorization(ctx context.Context, authURL *url.URL) error
SaveCodeVerifier(ctx context.Context, v string) error
CodeVerifier(ctx context.Context) (string, error)
RedirectURL() string
ClientMetadata() OAuthClientMetadata
ClientInformation(ctx context.Context) (*OAuthClientInformation, error)
}
OAuthClientProvider is the integration point for OAuth-protected MCP servers. Mirrors ai-sdk's OAuthClientProvider — callers implement it to own token storage, redirect handling, and (optionally) dynamic client registration.
type OAuthErrorResponse ¶ added in v0.1.2
type OAuthErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
ErrorURI string `json:"error_uri,omitempty"`
}
OAuthErrorResponse is the body shape of a token/registration error per RFC 6749 §5.2.
type OAuthProtectedResourceMetadata ¶ added in v0.1.2
type OAuthProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers,omitempty"`
JwksURI string `json:"jwks_uri,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
ResourceName string `json:"resource_name,omitempty"`
ResourceDocumentation string `json:"resource_documentation,omitempty"`
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
ResourceTosURI string `json:"resource_tos_uri,omitempty"`
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
DPopSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
DPopBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
}
OAuthProtectedResourceMetadata is RFC 9728 protected-resource metadata.
type OAuthTokens ¶ added in v0.1.2
type OAuthTokens struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token,omitempty"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in,omitempty"`
Scope string `json:"scope,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
OAuthTokens is the OAuth 2.1 token response.
type Resource ¶
type Resource struct {
// URI is the unique identifier for the resource.
URI string
// Name is the human-readable name.
Name string
// Description describes the resource.
Description string
// MimeType is the content type.
MimeType string
}
Resource represents an MCP resource.
type ResourceContent ¶
type ResourceContent struct {
// URI is the resource URI.
URI string
// MimeType is the content type.
MimeType string
// Text is the text content (for text resources).
Text string
// Blob is the binary content (for binary resources, base64 encoded).
Blob string
}
ResourceContent contains the content of a resource.
type ResourceURLValidator ¶ added in v0.1.2
type ResourceURLValidator interface {
ValidateResourceURL(ctx context.Context, serverURL, resource string) (*url.URL, error)
}
ResourceURLValidator opts into custom resource-URL validation, replacing the default same-origin check against the protected-resource metadata.
type SSETransport ¶
type SSETransport struct {
// contains filtered or unexported fields
}
SSETransport implements the MCP SSE transport — server streams events from a long-lived GET, and the client POSTs JSON-RPC requests to a per-session "endpoint" URL the server emits on connect. Mirrors references/ai-sdk/packages/mcp/src/tool/mcp-sse-transport.ts.
func NewSSETransport ¶
func NewSSETransport(serverURL string, headers map[string]string, authProvider OAuthClientProvider) *SSETransport
NewSSETransport creates a new SSE transport. authProvider is optional; pass nil to skip OAuth.
func (*SSETransport) Connect ¶
func (t *SSETransport) Connect(ctx context.Context) error
Connect opens the SSE GET stream and waits for the server's first `endpoint` event before returning. Per the MCP SSE spec, the endpoint event's data is the URL to POST messages to (relative or absolute, but must be same-origin).
func (*SSETransport) OnNotification ¶
func (t *SSETransport) OnNotification(handler func(method string, params json.RawMessage))
OnNotification registers a handler for server-pushed notifications.
func (*SSETransport) Send ¶
func (t *SSETransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)
Send sends a JSON-RPC request via HTTP POST to the per-session endpoint returned during connect, awaiting the response on the SSE stream.
type ServerConfig ¶
type ServerConfig struct {
// Name is a unique identifier for this server.
Name string
// ClientName is the name advertised to the server in the initialize
// handshake's clientInfo.name. Defaults to "goai" when empty. Mirrors
// ai-sdk #14966 (clientName, replacing the older `name` field on the
// JS createMCPClient config — which was unrelated to the per-server
// identifier).
ClientName string
// Transport specifies how to connect to the server.
// Options: "stdio", "sse", "http"
Transport string
// Command is the command to run for stdio transport.
Command string
// Args are arguments for the command.
Args []string
// Env are environment variables for the command.
Env map[string]string
// URL is the server URL for sse/http transport.
URL string
// Headers are HTTP headers for sse/http transport.
Headers map[string]string
// AuthProvider is the optional OAuth integration. nil = no OAuth.
AuthProvider OAuthClientProvider
}
ServerConfig contains configuration for an MCP server.
type ServerConnection ¶
type ServerConnection struct {
// contains filtered or unexported fields
}
ServerConnection represents a connection to an MCP server.
type ServerError ¶ added in v0.1.2
type ServerError struct{ MCPClientOAuthError }
ServerError corresponds to OAuth "server_error".
type StateGenerator ¶ added in v0.1.2
type StateGenerator interface {
State(ctx context.Context) (string, error)
SaveState(ctx context.Context, s string) error
StoredState(ctx context.Context) (string, error)
}
StateGenerator opts into CSRF state on the authorization redirect.
type StdioTransport ¶
type StdioTransport struct {
// contains filtered or unexported fields
}
StdioTransport implements the Transport interface using stdio.
func NewStdioTransport ¶
func NewStdioTransport(command string, args []string, env map[string]string) *StdioTransport
NewStdioTransport creates a new stdio transport.
func (*StdioTransport) Close ¶
func (t *StdioTransport) Close() error
Close terminates the subprocess.
func (*StdioTransport) Connect ¶
func (t *StdioTransport) Connect(ctx context.Context) error
Connect starts the subprocess and establishes communication.
func (*StdioTransport) OnNotification ¶
func (t *StdioTransport) OnNotification(handler func(method string, params json.RawMessage))
OnNotification registers a handler for server notifications.
func (*StdioTransport) Send ¶
func (t *StdioTransport) Send(ctx context.Context, method string, params any) (json.RawMessage, error)
Send sends a JSON-RPC request and waits for the response. Notifications (methods starting with "notifications/") are fire-and-forget: sent without an id and no response is expected.
type Transport ¶
type Transport interface {
// Connect establishes the connection.
Connect(ctx context.Context) error
// Close closes the connection.
Close() error
// Send sends a request and returns the response.
Send(ctx context.Context, method string, params any) (json.RawMessage, error)
// OnNotification registers a handler for server notifications.
OnNotification(handler func(method string, params json.RawMessage))
}
Transport is the interface for MCP transports.
type UnauthorizedClientError ¶ added in v0.1.2
UnauthorizedClientError corresponds to OAuth "unauthorized_client".
type UnauthorizedError ¶ added in v0.1.2
UnauthorizedError signals that auth failed and the caller should treat the request as unauthenticated. Returned by transports when a 401 cannot be recovered from (no provider, refresh failed, second 401, etc.).
func (*UnauthorizedError) Error ¶ added in v0.1.2
func (e *UnauthorizedError) Error() string