Documentation
¶
Overview ¶
Package mcp adapts the official MCP Go SDK to GoAI tools.
Index ¶
- Constants
- 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(ctx context.Context) ([]Resource, error)
- func (c *Client) GetServerInstructions(name string) string
- func (c *Client) GetTools(ctx context.Context) (tool.Set, error)
- func (c *Client) ReadResource(ctx context.Context, uri string) (*ResourceContent, error)
- type ClientAuthenticator
- type ClientInformationSaver
- type CredentialInvalidator
- type InvalidClientError
- type InvalidGrantError
- type MCPClientError
- type MCPClientOAuthError
- type OAuthClientInformation
- type OAuthClientInformationFull
- type OAuthClientMetadata
- type OAuthClientProvider
- type OAuthErrorResponse
- type OAuthMetadataDiscovery
- type OAuthProtectedResourceMetadata
- type OAuthTokens
- type Resource
- type ResourceContent
- type ResourceURLValidator
- type ServerConfig
- type ServerConnection
- type ServerError
- type Session
- func (s *Session) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*sdk.CallToolResult, error)
- func (s *Session) Close() error
- func (s *Session) Instructions() string
- func (s *Session) ListResources(ctx context.Context) ([]*sdk.Resource, error)
- func (s *Session) ListTools(ctx context.Context) ([]*sdk.Tool, error)
- func (s *Session) ReadResource(ctx context.Context, uri string) (*sdk.ReadResourceResult, error)
- type StateGenerator
- type UnauthorizedClientError
- type UnauthorizedError
Constants ¶
const ( LatestProtocolVersion = "2026-07-28" HeaderProtocolVersion = "mcp-protocol-version" HeaderSessionID = "mcp-session-id" HeaderLastEventID = "last-event-id" UserAgentSuffix = "goai-mcp/1.0" )
const MaxHTTPResponseBytes = 20 << 20
Variables ¶
This section is empty.
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
}
func (*Client) Disconnect ¶
func (*Client) DisconnectAll ¶
func (*Client) GetResources ¶
func (*Client) GetServerInstructions ¶ added in v0.1.2
func (*Client) ReadResource ¶
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 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 MCPClientError ¶ added in v0.1.4
type MCPClientError struct {
Message string
// StatusCode is the HTTP status of the failing response. Zero when the
// error has no associated response.
StatusCode int
// URL is the MCP endpoint the failing request was sent to.
URL string
// ResponseBody is the failing response body decoded as text, when read.
ResponseBody string
}
MCPClientError carries structured HTTP context for failures that originate from the streamable HTTP transport, so callers can branch on the response status without parsing the message string — e.g. to decide whether to fall back from HTTP to SSE transport on a 404/405 per the MCP spec. Mirrors ai-sdk's MCPClientError HTTP fields (references/ai-sdk/packages/mcp/src/error/mcp-client-error.ts).
The fields are zero/empty for non-HTTP failures (network errors, parse errors without a response).
func (*MCPClientError) Error ¶ added in v0.1.4
func (e *MCPClientError) Error() string
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 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 OAuthMetadataDiscovery ¶ added in v0.1.5
type OAuthMetadataDiscovery struct {
ProtectedResource OAuthProtectedResourceMetadata
AuthorizationServer string
Metadata AuthorizationServerMetadata
}
OAuthMetadataDiscovery is the passive RFC 9728 and RFC 8414 discovery result for an MCP resource. AuthorizationServer is the first server listed by the protected resource, matching the server selected by Auth.
func DiscoverOAuthMetadata ¶ added in v0.1.5
func DiscoverOAuthMetadata(ctx context.Context, client *http.Client, serverURL string) (*OAuthMetadataDiscovery, error)
DiscoverOAuthMetadata passively discovers OAuth metadata for an MCP resource. It only performs metadata GET requests; in particular, it never sends a dynamic client registration request.
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 ResourceContent ¶
type ResourceContent struct{ URI, MimeType, Text, Blob string }
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 ServerConfig ¶
type ServerConnection ¶
type ServerConnection struct {
// contains filtered or unexported fields
}
type ServerError ¶ added in v0.1.2
type ServerError struct{ MCPClientOAuthError }
ServerError corresponds to OAuth "server_error".
type Session ¶ added in v0.2.0
type Session struct {
// contains filtered or unexported fields
}
Session owns an official MCP SDK connection. Callers must close it. Protocol-aware callers retain the SDK's complete typed results.
func Connect ¶ added in v0.2.0
func Connect(ctx context.Context, config ServerConfig) (*Session, error)
Connect opens a connection without projecting its results into model output.
func (*Session) CallTool ¶ added in v0.2.0
func (s *Session) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*sdk.CallToolResult, error)
func (*Session) Instructions ¶ added in v0.2.0
func (*Session) ListResources ¶ added in v0.2.0
func (*Session) ListTools ¶ added in v0.2.0
ListTools returns a bounded complete discovery snapshot.
func (*Session) ReadResource ¶ added in v0.2.0
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 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