transport

package
v0.41.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2025 License: MIT Imports: 22 Imported by: 80

Documentation

Index

Constants

View Source
const (
	HeaderKeySessionID       = "Mcp-Session-Id"
	HeaderKeyProtocolVersion = "Mcp-Protocol-Version"
)

Common HTTP header constants used across transports

Variables

View Source
var (
	ErrSessionTerminated   = fmt.Errorf("session terminated (404). need to re-initialize")
	ErrGetMethodNotAllowed = fmt.Errorf("GET method not allowed")
)
View Source
var ErrInvalidState = errors.New("invalid state parameter, possible CSRF attack")

ErrInvalidState is returned when the state parameter doesn't match the expected value

View Source
var ErrNoToken = errors.New("no token available")

ErrNoToken is returned when no token is available in the token store

View Source
var ErrOAuthAuthorizationRequired = errors.New("no valid token available, authorization required")

ErrOAuthAuthorizationRequired is a sentinel error for OAuth authorization required

Functions

func GenerateCodeChallenge added in v0.30.0

func GenerateCodeChallenge(codeVerifier string) string

GenerateCodeChallenge generates a code challenge from a code verifier

func GenerateCodeVerifier added in v0.30.0

func GenerateCodeVerifier() (string, error)

GenerateCodeVerifier generates a code verifier for PKCE

func GenerateRandomString added in v0.30.0

func GenerateRandomString(length int) (string, error)

GenerateRandomString generates a random string of the specified length

func GenerateState added in v0.30.0

func GenerateState() (string, error)

GenerateState generates a state parameter for OAuth

func ValidateRedirectURI added in v0.30.0

func ValidateRedirectURI(redirectURI string) error

ValidateRedirectURI validates that a redirect URI is secure

Types

type AuthServerMetadata added in v0.30.0

type AuthServerMetadata struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint"`
	TokenEndpoint                     string   `json:"token_endpoint"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	JwksURI                           string   `json:"jwks_uri,omitempty"`
	ScopesSupported                   []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported            []string `json:"response_types_supported"`
	GrantTypesSupported               []string `json:"grant_types_supported,omitempty"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
}

AuthServerMetadata represents the OAuth 2.0 Authorization Server Metadata

type BidirectionalInterface added in v0.33.0

type BidirectionalInterface interface {
	Interface

	// SetRequestHandler sets the handler for incoming requests from the server.
	// The handler should process the request and return a response.
	SetRequestHandler(handler RequestHandler)
}

BidirectionalInterface extends Interface to support incoming requests from the server. This is used for features like sampling where the server can send requests to the client.

type ClientOption

type ClientOption func(*SSE)

func WithHTTPClient added in v0.25.0

func WithHTTPClient(httpClient *http.Client) ClientOption

func WithHeaderFunc added in v0.30.0

func WithHeaderFunc(headerFunc HTTPHeaderFunc) ClientOption

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

func WithOAuth added in v0.30.0

func WithOAuth(config OAuthConfig) ClientOption

func WithSSELogger added in v0.37.0

func WithSSELogger(logger util.Logger) ClientOption

WithSSELogger sets a custom logger for the SSE client.

type CommandFunc added in v0.33.0

type CommandFunc func(ctx context.Context, command string, env []string, args []string) (*exec.Cmd, error)

CommandFunc is a factory function that returns a custom exec.Cmd used to launch the MCP subprocess. It can be used to apply sandboxing, custom environment control, working directories, etc.

type Error added in v0.34.0

type Error struct {
	Err error
}

Error wraps a low-level transport error in a concrete type.

func NewError added in v0.34.0

func NewError(err error) *Error

func (*Error) Error added in v0.34.0

func (e *Error) Error() string

func (*Error) Unwrap added in v0.34.0

func (e *Error) Unwrap() error

type HTTPConnection added in v0.35.0

type HTTPConnection interface {
	Interface
	SetProtocolVersion(version string)
}

HTTPConnection is a Transport that runs over HTTP and supports protocol version headers.

type HTTPHeaderFunc added in v0.30.0

type HTTPHeaderFunc func(context.Context) map[string]string

HTTPHeaderFunc is a function that extracts header entries from the given context and returns them as key-value pairs. This is typically used to add context values as HTTP headers in outgoing requests.

type InProcessOption added in v0.34.0

type InProcessOption func(*InProcessTransport)

func WithElicitationHandler added in v0.40.0

func WithElicitationHandler(handler server.ElicitationHandler) InProcessOption

func WithSamplingHandler added in v0.34.0

func WithSamplingHandler(handler server.SamplingHandler) InProcessOption

type InProcessTransport added in v0.23.0

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

func NewInProcessTransport added in v0.23.0

func NewInProcessTransport(server *server.MCPServer) *InProcessTransport

func NewInProcessTransportWithOptions added in v0.34.0

func NewInProcessTransportWithOptions(server *server.MCPServer, opts ...InProcessOption) *InProcessTransport

func (*InProcessTransport) Close added in v0.23.0

func (c *InProcessTransport) Close() error

func (*InProcessTransport) GetSessionId added in v0.33.0

func (c *InProcessTransport) GetSessionId() string

func (*InProcessTransport) SendNotification added in v0.23.0

func (c *InProcessTransport) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error

func (*InProcessTransport) SendRequest added in v0.23.0

func (c *InProcessTransport) SendRequest(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error)

func (*InProcessTransport) SetNotificationHandler added in v0.23.0

func (c *InProcessTransport) SetNotificationHandler(handler func(notification mcp.JSONRPCNotification))

func (*InProcessTransport) Start added in v0.23.0

func (c *InProcessTransport) Start(ctx context.Context) error

type Interface

type Interface interface {
	// Start the connection. Start should only be called once.
	Start(ctx context.Context) error

	// SendRequest sends a json RPC request and returns the response synchronously.
	SendRequest(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error)

	// SendNotification sends a json RPC Notification to the server.
	SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error

	// SetNotificationHandler sets the handler for notifications.
	// Any notification before the handler is set will be discarded.
	SetNotificationHandler(handler func(notification mcp.JSONRPCNotification))

	// Close the connection.
	Close() error

	// GetSessionId returns the session ID of the transport.
	GetSessionId() string
}

Interface for the transport layer.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string        `json:"jsonrpc"`
	ID      mcp.RequestId `json:"id"`
	Method  string        `json:"method"`
	Params  any           `json:"params,omitempty"`
}

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string                   `json:"jsonrpc"`
	ID      mcp.RequestId            `json:"id"`
	Result  json.RawMessage          `json:"result,omitempty"`
	Error   *mcp.JSONRPCErrorDetails `json:"error,omitempty"`
}

JSONRPCResponse represents a JSON-RPC 2.0 response message. Use NewJSONRPCResultResponse to create a JSONRPCResponse with a result. Use NewJSONRPCErrorResponse to create a JSONRPCResponse with an error.

func NewJSONRPCErrorResponse added in v0.41.0

func NewJSONRPCErrorResponse(id mcp.RequestId, code int, message string, data any) *JSONRPCResponse

NewJSONRPCErrorResponse creates a new JSONRPCResponse with an error.

func NewJSONRPCResultResponse added in v0.41.0

func NewJSONRPCResultResponse(id mcp.RequestId, result json.RawMessage) *JSONRPCResponse

NewJSONRPCResultResponse creates a new JSONRPCResponse with a result.

type MemoryTokenStore added in v0.30.0

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

MemoryTokenStore is a simple in-memory token store

func NewMemoryTokenStore added in v0.30.0

func NewMemoryTokenStore() *MemoryTokenStore

NewMemoryTokenStore creates a new in-memory token store

func (*MemoryTokenStore) GetToken added in v0.30.0

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

GetToken returns the current token. Returns ErrNoToken if no token is available. Returns context.Canceled or context.DeadlineExceeded if ctx is cancelled.

func (*MemoryTokenStore) SaveToken added in v0.30.0

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

SaveToken saves a token. Returns context.Canceled or context.DeadlineExceeded if ctx is cancelled.

type OAuthAuthorizationRequiredError added in v0.30.0

type OAuthAuthorizationRequiredError struct {
	Handler *OAuthHandler
}

OAuthAuthorizationRequiredError is returned when OAuth authorization is required

func (*OAuthAuthorizationRequiredError) Error added in v0.30.0

func (*OAuthAuthorizationRequiredError) Unwrap added in v0.30.0

type OAuthConfig added in v0.30.0

type OAuthConfig struct {
	// ClientID is the OAuth client ID
	ClientID string
	// ClientSecret is the OAuth client secret (for confidential clients)
	ClientSecret string
	// RedirectURI is the redirect URI for the OAuth flow
	RedirectURI string
	// Scopes is the list of OAuth scopes to request
	Scopes []string
	// TokenStore is the storage for OAuth tokens
	TokenStore TokenStore
	// AuthServerMetadataURL is the URL to the OAuth server metadata
	// If empty, the client will attempt to discover it from the base URL
	AuthServerMetadataURL string
	// PKCEEnabled enables PKCE for the OAuth flow (recommended for public clients)
	PKCEEnabled bool
}

OAuthConfig holds the OAuth configuration for the client

type OAuthError added in v0.30.0

type OAuthError struct {
	ErrorCode        string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
	ErrorURI         string `json:"error_uri,omitempty"`
}

OAuthError represents a standard OAuth 2.0 error response

func (OAuthError) Error added in v0.30.0

func (e OAuthError) Error() string

Error implements the error interface

type OAuthHandler added in v0.30.0

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

OAuthHandler handles OAuth authentication for HTTP requests

func NewOAuthHandler added in v0.30.0

func NewOAuthHandler(config OAuthConfig) *OAuthHandler

NewOAuthHandler creates a new OAuth handler

func (*OAuthHandler) GetAuthorizationHeader added in v0.30.0

func (h *OAuthHandler) GetAuthorizationHeader(ctx context.Context) (string, error)

GetAuthorizationHeader returns the Authorization header value for a request

func (*OAuthHandler) GetAuthorizationURL added in v0.30.0

func (h *OAuthHandler) GetAuthorizationURL(ctx context.Context, state, codeChallenge string) (string, error)

GetAuthorizationURL returns the URL for the authorization endpoint

func (*OAuthHandler) GetClientID added in v0.30.0

func (h *OAuthHandler) GetClientID() string

GetClientID returns the client ID

func (*OAuthHandler) GetClientSecret added in v0.30.0

func (h *OAuthHandler) GetClientSecret() string

GetClientSecret returns the client secret

func (*OAuthHandler) GetExpectedState added in v0.30.0

func (h *OAuthHandler) GetExpectedState() string

GetExpectedState returns the expected state value (for testing purposes)

func (*OAuthHandler) GetServerMetadata added in v0.30.0

func (h *OAuthHandler) GetServerMetadata(ctx context.Context) (*AuthServerMetadata, error)

GetServerMetadata is a public wrapper for getServerMetadata

func (*OAuthHandler) ProcessAuthorizationResponse added in v0.30.0

func (h *OAuthHandler) ProcessAuthorizationResponse(ctx context.Context, code, state, codeVerifier string) error

ProcessAuthorizationResponse processes the authorization response and exchanges the code for a token

func (*OAuthHandler) RefreshToken added in v0.30.0

func (h *OAuthHandler) RefreshToken(ctx context.Context, refreshToken string) (*Token, error)

RefreshToken is a public wrapper for refreshToken

func (*OAuthHandler) RegisterClient added in v0.30.0

func (h *OAuthHandler) RegisterClient(ctx context.Context, clientName string) error

RegisterClient performs dynamic client registration

func (*OAuthHandler) SetBaseURL added in v0.30.0

func (h *OAuthHandler) SetBaseURL(baseURL string)

SetBaseURL sets the base URL for the API server

func (*OAuthHandler) SetExpectedState added in v0.37.0

func (h *OAuthHandler) SetExpectedState(expectedState string)

SetExpectedState sets the expected state value.

This can be useful if you cannot maintain an OAuthHandler instance throughout the authentication flow; for example, if the initialization and callback steps are handled in different requests.

In such cases, this should be called with the state value generated during the initial authentication request (e.g. by GenerateState) and included in the authorization URL.

type OAuthProtectedResource added in v0.30.0

type OAuthProtectedResource struct {
	AuthorizationServers []string `json:"authorization_servers"`
	Resource             string   `json:"resource"`
	ResourceName         string   `json:"resource_name,omitempty"`
}

OAuthProtectedResource represents the response from /.well-known/oauth-protected-resource

type RequestHandler added in v0.33.0

type RequestHandler func(ctx context.Context, request JSONRPCRequest) (*JSONRPCResponse, error)

RequestHandler defines a function that handles incoming requests from the server.

type SSE

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

SSE implements the transport layer of the MCP protocol using Server-Sent Events (SSE). It maintains a persistent HTTP connection to receive server-pushed events while sending requests over regular HTTP POST calls. The client handles automatic reconnection and message routing between requests and responses.

func NewSSE

func NewSSE(baseURL string, options ...ClientOption) (*SSE, error)

NewSSE creates a new SSE-based MCP client with the given base URL. Returns an error if the URL is invalid.

func (*SSE) Close

func (c *SSE) Close() error

Close shuts down the SSE client connection and cleans up any pending responses. Returns an error if the shutdown process fails.

func (*SSE) GetBaseURL

func (c *SSE) GetBaseURL() *url.URL

GetBaseURL returns the base URL set in the SSE constructor.

func (*SSE) GetEndpoint

func (c *SSE) GetEndpoint() *url.URL

GetEndpoint returns the current endpoint URL for the SSE connection.

func (*SSE) GetOAuthHandler added in v0.32.0

func (c *SSE) GetOAuthHandler() *OAuthHandler

GetOAuthHandler returns the OAuth handler if configured

func (*SSE) GetSessionId added in v0.33.0

func (c *SSE) GetSessionId() string

GetSessionId returns the session ID of the transport. Since SSE does not maintain a session ID, it returns an empty string.

func (*SSE) IsOAuthEnabled added in v0.32.0

func (c *SSE) IsOAuthEnabled() bool

IsOAuthEnabled returns true if OAuth is enabled

func (*SSE) SendNotification

func (c *SSE) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error

SendNotification sends a JSON-RPC notification to the server without expecting a response.

func (*SSE) SendRequest

func (c *SSE) SendRequest(
	ctx context.Context,
	request JSONRPCRequest,
) (*JSONRPCResponse, error)

SendRequest sends a JSON-RPC request to the server and waits for a response. Returns the raw JSON response message or an error if the request fails.

func (*SSE) SetConnectionLostHandler added in v0.37.0

func (c *SSE) SetConnectionLostHandler(handler func(error))

func (*SSE) SetNotificationHandler

func (c *SSE) SetNotificationHandler(handler func(notification mcp.JSONRPCNotification))

func (*SSE) SetProtocolVersion added in v0.35.0

func (c *SSE) SetProtocolVersion(version string)

SetProtocolVersion sets the negotiated protocol version for this connection.

func (*SSE) Start

func (c *SSE) Start(ctx context.Context) error

Start initiates the SSE connection to the server and waits for the endpoint information. Returns an error if the connection fails or times out waiting for the endpoint.

type Stdio

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

Stdio implements the transport layer of the MCP protocol using stdio communication. It launches a subprocess and communicates with it via standard input/output streams using JSON-RPC messages. The client handles message routing between requests and responses, and supports asynchronous notifications.

func NewIO added in v0.24.0

func NewIO(input io.Reader, output io.WriteCloser, logging io.ReadCloser) *Stdio

NewIO returns a new stdio-based transport using existing input, output, and logging streams instead of spawning a subprocess. This is useful for testing and simulating client behavior.

func NewStdio

func NewStdio(
	command string,
	env []string,
	args ...string,
) *Stdio

NewStdio creates a new stdio transport to communicate with a subprocess. It launches the specified command with given arguments and sets up stdin/stdout pipes for communication. Returns an error if the subprocess cannot be started or the pipes cannot be created.

func NewStdioWithOptions added in v0.33.0

func NewStdioWithOptions(
	command string,
	env []string,
	args []string,
	opts ...StdioOption,
) *Stdio

NewStdioWithOptions creates a new stdio transport to communicate with a subprocess. It launches the specified command with given arguments and sets up stdin/stdout pipes for communication. Returns an error if the subprocess cannot be started or the pipes cannot be created. Optional configuration functions can be provided to customize the transport before it starts, such as setting a custom command factory.

func (*Stdio) Close

func (c *Stdio) Close() error

Close shuts down the stdio client, closing the stdin pipe and waiting for the subprocess to exit. Returns an error if there are issues closing stdin or waiting for the subprocess to terminate.

func (*Stdio) GetSessionId added in v0.33.0

func (c *Stdio) GetSessionId() string

GetSessionId returns the session ID of the transport. Since stdio does not maintain a session ID, it returns an empty string.

func (*Stdio) SendNotification

func (c *Stdio) SendNotification(
	ctx context.Context,
	notification mcp.JSONRPCNotification,
) error

SendNotification sends a json RPC Notification to the server.

func (*Stdio) SendRequest

func (c *Stdio) SendRequest(
	ctx context.Context,
	request JSONRPCRequest,
) (*JSONRPCResponse, error)

SendRequest sends a JSON-RPC request to the server and waits for a response. It creates a unique request ID, sends the request over stdin, and waits for the corresponding response or context cancellation. Returns the raw JSON response message or an error if the request fails.

func (*Stdio) SetNotificationHandler

func (c *Stdio) SetNotificationHandler(
	handler func(notification mcp.JSONRPCNotification),
)

SetNotificationHandler sets the handler function to be called when a notification is received. Only one handler can be set at a time; setting a new one replaces the previous handler.

func (*Stdio) SetRequestHandler added in v0.33.0

func (c *Stdio) SetRequestHandler(handler RequestHandler)

SetRequestHandler sets the handler function to be called when a request is received from the server. This enables bidirectional communication for features like sampling.

func (*Stdio) Start

func (c *Stdio) Start(ctx context.Context) error

func (*Stdio) Stderr

func (c *Stdio) Stderr() io.Reader

Stderr returns a reader for the stderr output of the subprocess. This can be used to capture error messages or logs from the subprocess.

type StdioOption added in v0.33.0

type StdioOption func(*Stdio)

StdioOption defines a function that configures a Stdio transport instance. Options can be used to customize the behavior of the transport before it starts, such as setting a custom command function.

func WithCommandFunc added in v0.33.0

func WithCommandFunc(f CommandFunc) StdioOption

WithCommandFunc sets a custom command factory function for the stdio transport. The CommandFunc is responsible for constructing the exec.Cmd used to launch the subprocess, allowing control over attributes like environment, working directory, and system-level sandboxing.

func WithCommandLogger added in v0.37.0

func WithCommandLogger(logger util.Logger) StdioOption

WithCommandLogger sets a custom logger for the stdio transport.

type StreamableHTTP added in v0.22.0

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

StreamableHTTP implements Streamable HTTP transport.

It transmits JSON-RPC messages over individual HTTP requests. One message per request. The HTTP response body can either be a single JSON-RPC response, or an upgraded SSE stream that concludes with a JSON-RPC response for the same request.

https://modelcontextprotocol.io/specification/2025-03-26/basic/transports

The current implementation does not support the following features:

func NewStreamableHTTP added in v0.22.0

func NewStreamableHTTP(serverURL string, options ...StreamableHTTPCOption) (*StreamableHTTP, error)

NewStreamableHTTP creates a new Streamable HTTP transport with the given server URL. Returns an error if the URL is invalid.

func (*StreamableHTTP) Close added in v0.22.0

func (c *StreamableHTTP) Close() error

Close closes the all the HTTP connections to the server.

func (*StreamableHTTP) GetOAuthHandler added in v0.30.0

func (c *StreamableHTTP) GetOAuthHandler() *OAuthHandler

GetOAuthHandler returns the OAuth handler if configured

func (*StreamableHTTP) GetSessionId added in v0.22.0

func (c *StreamableHTTP) GetSessionId() string

func (*StreamableHTTP) IsOAuthEnabled added in v0.30.0

func (c *StreamableHTTP) IsOAuthEnabled() bool

IsOAuthEnabled returns true if OAuth is enabled

func (*StreamableHTTP) SendNotification added in v0.22.0

func (c *StreamableHTTP) SendNotification(ctx context.Context, notification mcp.JSONRPCNotification) error

func (*StreamableHTTP) SendRequest added in v0.22.0

func (c *StreamableHTTP) SendRequest(
	ctx context.Context,
	request JSONRPCRequest,
) (*JSONRPCResponse, error)

SendRequest sends a JSON-RPC request to the server and waits for a response. Returns the raw JSON response message or an error if the request fails.

func (*StreamableHTTP) SetNotificationHandler added in v0.22.0

func (c *StreamableHTTP) SetNotificationHandler(handler func(mcp.JSONRPCNotification))

func (*StreamableHTTP) SetProtocolVersion added in v0.35.0

func (c *StreamableHTTP) SetProtocolVersion(version string)

SetProtocolVersion sets the negotiated protocol version for this connection.

func (*StreamableHTTP) SetRequestHandler added in v0.37.0

func (c *StreamableHTTP) SetRequestHandler(handler RequestHandler)

SetRequestHandler sets the handler for incoming requests from the server.

func (*StreamableHTTP) Start added in v0.22.0

func (c *StreamableHTTP) Start(ctx context.Context) error

Start initiates the HTTP connection to the server.

type StreamableHTTPCOption added in v0.22.0

type StreamableHTTPCOption func(*StreamableHTTP)

func WithContinuousListening added in v0.33.0

func WithContinuousListening() StreamableHTTPCOption

WithContinuousListening enables receiving server-to-client notifications when no request is in flight. In particular, if you want to receive global notifications from the server (like ToolListChangedNotification), you should enable this option.

It will establish a standalone long-live GET HTTP connection to the server. https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#listening-for-messages-from-the-server NOTICE: Even enabled, the server may not support this feature.

func WithHTTPBasicClient added in v0.32.0

func WithHTTPBasicClient(client *http.Client) StreamableHTTPCOption

WithHTTPClient sets a custom HTTP client on the StreamableHTTP transport.

func WithHTTPHeaderFunc added in v0.30.0

func WithHTTPHeaderFunc(headerFunc HTTPHeaderFunc) StreamableHTTPCOption

func WithHTTPHeaders added in v0.22.0

func WithHTTPHeaders(headers map[string]string) StreamableHTTPCOption

func WithHTTPLogger added in v0.37.0

func WithHTTPLogger(logger util.Logger) StreamableHTTPCOption

WithHTTPLogger sets a custom logger for the StreamableHTTP transport.

func WithHTTPOAuth added in v0.32.0

func WithHTTPOAuth(config OAuthConfig) StreamableHTTPCOption

WithHTTPOAuth enables OAuth authentication for the client.

func WithHTTPTimeout added in v0.22.0

func WithHTTPTimeout(timeout time.Duration) StreamableHTTPCOption

WithHTTPTimeout sets the timeout for a HTTP request and stream.

func WithLogger deprecated added in v0.33.0

func WithLogger(logger util.Logger) StreamableHTTPCOption

Deprecated: Use WithHTTPLogger instead.

func WithSession added in v0.33.0

func WithSession(sessionID string) StreamableHTTPCOption

WithSession creates a client with a pre-configured session

type Token added in v0.30.0

type Token struct {
	// AccessToken is the OAuth access token
	AccessToken string `json:"access_token"`
	// TokenType is the type of token (usually "Bearer")
	TokenType string `json:"token_type"`
	// RefreshToken is the OAuth refresh token
	RefreshToken string `json:"refresh_token,omitempty"`
	// ExpiresIn is the number of seconds until the token expires
	ExpiresIn int64 `json:"expires_in,omitempty"`
	// Scope is the scope of the token
	Scope string `json:"scope,omitempty"`
	// ExpiresAt is the time when the token expires
	ExpiresAt time.Time `json:"expires_at,omitempty"`
}

Token represents an OAuth token

func (*Token) IsExpired added in v0.30.0

func (t *Token) IsExpired() bool

IsExpired returns true if the token is expired

type TokenStore added in v0.30.0

type TokenStore interface {
	// GetToken returns the current token.
	// Returns ErrNoToken if no token is available.
	// Returns context.Canceled or context.DeadlineExceeded if ctx is cancelled.
	// Returns other errors for operational failures (I/O, database, etc.).
	GetToken(ctx context.Context) (*Token, error)

	// SaveToken saves a token.
	// Returns context.Canceled or context.DeadlineExceeded if ctx is cancelled.
	// Returns other errors for operational failures (I/O, database, etc.).
	SaveToken(ctx context.Context, token *Token) error
}

TokenStore is an interface for storing and retrieving OAuth tokens.

Implementations must:

  • Honor context cancellation and deadlines, returning context.Canceled or context.DeadlineExceeded as appropriate
  • Return ErrNoToken (or a sentinel error that wraps it) when no token is available, rather than conflating this with other operational errors
  • Properly propagate all other errors (database failures, I/O errors, etc.)
  • Check ctx.Done() before performing operations and return ctx.Err() if cancelled

Jump to

Keyboard shortcuts

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