Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/mcp/oauth"

Package oauth connects zelk’s MCP client to remote servers that require OAuth, as the MCP authorization specification describes: discovery of the server’s protected resource metadata (RFC 9728) and its authorization server’s metadata (RFC 8414, or OpenID Connect discovery), dynamic client registration (RFC 7591) when no client is configured, the authorization code flow with PKCE and a loopback redirect (RFC 8252), resource indicators (RFC 8707), and token refresh.

Core’s MCP client stays free of OAuth: it takes an *http.Client, and a host gives it one whose Transport adds the tokens a Store keeps. SignIn is interactive and the host’s to start; the Transport never opens a browser. When the user has to sign in, requests fail with a *SignInRequired error that names the server.

var ErrAccessDenied = errors.New("mcp oauth: the sign-in was declined")

ErrAccessDenied is the error of a sign-in the user declined.

var ErrSignInRequired = errors.New("mcp oauth: sign-in required")

ErrSignInRequired is what a *SignInRequired error is: the server needs the user to sign in before zelk can reach it.

func SignIn(ctx context.Context, store Store, req SignInRequest, opts ...Option) error

SignIn signs the user in to req.Server in the browser and keeps the tokens in store: discovery, registration if needed, the authorization code flow with PKCE and a loopback redirect, then the code exchange. It waits for the browser until ctx ends.

func SignOut(ctx context.Context, store Store, server string) error

SignOut forgets the server’s tokens. The client is kept, so signing in again reuses its registration rather than registering another. Nothing is revoked: the authorization server keeps the grant it issued until it expires or the user removes it there.

func SignedIn(ctx context.Context, store Store, server string) (bool, error)

SignedIn reports whether store keeps tokens for server.

type Error struct {
StatusCode int
Code string
Description string
}

Error is an error an authorization server returned (RFC 6749 §5.2).

func (e *Error) Error() string
type File struct {
// contains filtered or unexported fields
}

File is a Store in one JSON file, readable only by its owner, beside a lock file of the same name with “.lock” added, with the same safety checks as the ChatGPT sign-in’s file. It is safe for concurrent use, also by other processes.

func NewFile(path string, opts ...secret.Option) *File

NewFile returns the store kept at path. Its directory is created, private, on the first Update. opts choose a keychain (secret.WithVault, secret.WithNewIn).

func (f *File) Document() *secret.Document

Document returns the secret document the sign-ins are kept in, for listing it and moving it between a file and a keychain.

func (f *File) Load(ctx context.Context, server string) (Token, error)

Load returns the server’s Token.

func (f *File) Update(ctx context.Context, server string, fn func(*Token) error) error

Update changes the server’s Token under the file’s lock.

type Option func(*settings)

Option configures SignIn and NewTransport.

func WithClock(now func() time.Time) Option

WithClock sets the clock tokens expire by.

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the client used for discovery, registration and token requests. SignIn’s default ignores proxy environment variables; a Transport’s sends through its base. Either way, redirects are not followed: credentials travel in these requests.

type SignInRequest struct {
// Server is the MCP server's URL. Required.
Server string
// Open shows the user the authorization URL, normally by opening the
// browser or printing it. Required.
Open func(ctx context.Context, authURL string) error
// ClientID and ClientSecret are a client registered for zelk ahead of
// time. Without one, SignIn registers a client dynamically, or reuses
// the one it registered before.
ClientID string
ClientSecret string
// Scopes replaces the scopes the server asks for.
Scopes []string
// ClientName is the name a registered client shows the user; zelk by
// default.
ClientName string
// Listener, if set, takes the browser's redirect: a TCP listener on
// 127.0.0.1. SignIn closes it. By default SignIn listens on the port a
// registered client was registered with, else any free one.
Listener net.Listener
}

SignInRequest says what SignIn signs in to.

type SignInRequired struct {
// Server is the MCP server's URL.
Server string
// Reason says why, when there is more to say than that no tokens are
// kept.
Reason error
}

SignInRequired is the error of a request to a server that needs the user to sign in: no tokens are kept for it, or its authorization server no longer renews them. The request never reached the server’s tools, so it also wraps mcp.ErrNotSent.

func (e *SignInRequired) Error() string
func (e *SignInRequired) Unwrap() []error

Unwrap returns ErrSignInRequired, mcp.ErrNotSent and the reason.

type Store interface {
// Load returns the server's Token, zero if none is kept.
Load(ctx context.Context, server string) (Token, error)
// Update replaces the server's Token with what f makes of it, holding
// a lock that keeps every other Update waiting, in any process: a
// refresh token may rotate as it is used, so renewals must never
// overlap. When f fails nothing is saved. A zero Token removes the
// server's entry.
Update(ctx context.Context, server string, f func(*Token) error) error
}

Store keeps Tokens by server URL.

type Token struct {
// ClientID and ClientSecret are the client: configured, or registered
// at sign-in. RedirectURI is the loopback redirect a registered client
// was registered with, reused so the registration stays valid.
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
RedirectURI string `json:"redirect_uri,omitempty"`
// Registered says zelk registered the client itself, rather than it
// being configured.
Registered bool `json:"registered,omitempty"`
// Issuer is the authorization server; TokenEndpoint where tokens are
// renewed; Resource the resource indicator tokens are bound to.
Issuer string `json:"issuer"`
TokenEndpoint string `json:"token_endpoint"`
Resource string `json:"resource"`
Scope string `json:"scope,omitempty"`
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
// Expiry is when the access token lapses; zero when the server didn't
// say.
Expiry time.Time `json:"expiry,omitzero"`
}

Token is what zelk keeps for one MCP server: the client it signs in as, where it renews tokens, and the tokens.

func (t Token) SignedIn() bool

SignedIn reports whether t holds tokens to use or renew.

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

Transport is the http.RoundTripper of one MCP server that requires OAuth. It adds the server’s access token from a Store to requests for the server’s origin, renews it when it is due or the server refuses it, and fails with *SignInRequired when the user has to sign in. Requests to any other origin, and requests that already carry an Authorization header, pass through untouched: a token is never sent where it wasn’t issued for. It is safe for concurrent use.

func NewTransport(server string, store Store, base http.RoundTripper, opts ...Option) (*Transport, error)

NewTransport returns the Transport of the MCP server at server, sending requests and token renewals through base.

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip sends req with the server’s token.

func (t *Transport) Server() string

Server returns the server’s URL as tokens are kept under it, and as a *SignInRequired from this Transport names it.