mcpauth

package
v0.7.28-dev.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package mcpauth signs a person in to a remote MCP server by OAuth, as the MCP authorization specification (2026-07-28) asks of a client: Protected Resource Metadata (RFC 9728) from the server's 401, the authorization server's metadata (RFC 8414, OpenID discovery), the client the vendor will take (the person's own, Agentry's Client ID Metadata Document, or dynamic registration, in that order here), PKCE with S256, the resource parameter (RFC 8707), the iss check on the redirect (RFC 9207), the code exchange, refresh and revocation (RFC 7009).

It also carries the client half of MCP's Enterprise-Managed Authorization extension (idjag.go): an Identity Assertion JWT Authorization Grant asked of an organization's identity provider by token exchange (RFC 8693) and redeemed at an MCP server's authorization server by the JWT bearer grant (RFC 7523), with no consent screen.

Every request to a vendor goes through Guard: https, public addresses only, no redirect, no proxy from the environment. Nothing here logs or returns a vendor's answer: an error carries the OAuth error code and never a body, which can hold a token.

What a run receives is an access token and nothing else: the refresh token and any client secret stay with the caller's store (pkg/runner/connection) and this package's callers.

Index

Constants

View Source
const (
	ChatGPTIssuer       = "https://auth.openai.com"
	ChatGPTAuthorizeURL = ChatGPTIssuer + "/api/accounts/authorize"
	ChatGPTTokenURL     = ChatGPTIssuer + "/api/accounts/oauth/token"
	ChatGPTDiscoveryURL = ChatGPTIssuer + "/.well-known/openid-configuration"
	// ChatGPTResource is the resource every request names, and the base of
	// the inference API the plan's token is good for.
	ChatGPTResource = "https://api.openai.com/v1"
	// ChatGPTCallbackPath is the loopback redirect's fixed path.
	ChatGPTCallbackPath = "/auth/callback"
	// ChatGPTDynamicClient is the client id of a first authorization, which
	// registers the app.
	ChatGPTDynamicClient = "dynamic_agent_client"
	// ChatGPTAgentName is the app's name at registration. Codex's
	// app-server sends its initialize clientInfo.name as the request
	// originator, which OpenAI asks to match it.
	ChatGPTAgentName = "Agentry"
	// ChatGPTPlanScope is the scope that allows plan usage.
	ChatGPTPlanScope = "chatgpt.tokens.use.direct"
)

OpenAI's endpoints and constants for ChatGPT plan usage.

View Source
const (
	OpenRouterAuthURL = "https://openrouter.ai/auth"
	OpenRouterKeysURL = "https://openrouter.ai/api/v1/auth/keys"
	// OpenRouterKeyPrefix starts every key OpenRouter issues.
	OpenRouterKeyPrefix = "sk-or-"
	// OpenRouterKeysPage is where a person deletes a key at OpenRouter.
	OpenRouterKeysPage = "https://openrouter.ai/settings/keys"
)

OpenRouter's endpoints.

View Source
const (
	PoeIssuer       = "https://poe.com"
	PoeAuthorizeURL = PoeIssuer + "/oauth/authorize"
	PoeTokenURL     = "https://api.poe.com/token"
	PoeBalanceURL   = "https://api.poe.com/usage/current_balance"
	PoeScope        = "apikey:create"
	// PoeKeysPage is where a person deletes a key at Poe.
	PoeKeysPage = "https://poe.com/api/keys"
	// PoeClientIDEnv names a Poe client id for a build that carries none.
	PoeClientIDEnv = "AGENTRY_POE_CLIENT_ID"
)

Poe's endpoints and its one scope.

View Source
const (
	HuggingFaceIssuer = "https://huggingface.co"
	// HuggingFaceClientIDEnv names another client id (a public app
	// registered at huggingface.co) in place of the document.
	HuggingFaceClientIDEnv = "AGENTRY_HF_CLIENT_ID"
	// HuggingFaceInferenceScope lets the token make inference requests to
	// Inference Providers for the person.
	HuggingFaceInferenceScope = "inference-api"
	// HuggingFaceAppsPage is where a person removes an app's access.
	HuggingFaceAppsPage = "https://huggingface.co/settings/connected-applications"
)

Hugging Face's issuer, Agentry's client for it, and what a connect asks.

View Source
const (
	GitHubDeviceCodeURL = "https://github.com/login/device/code"
	GitHubTokenURL      = "https://github.com/login/oauth/access_token"
	GitHubDevicePage    = "https://github.com/login/device"
	GitHubAPI           = "https://api.github.com"
)

GitHub's endpoints for the device flow, the account and revocation.

View Source
const (
	// GitHubApp is Agentry's GitHub App: user tokens it is granted no
	// permission for, outside organizations' OAuth App restrictions.
	GitHubApp = "github-app"
	// GitHubOAuthApp is Agentry's OAuth App, with expiring tokens.
	GitHubOAuthApp = "oauth-app"
)

The apps a Copilot sign-in may go through.

View Source
const (
	GrantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
	GrantJWTBearer     = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	// GrantProfileIDJAG is what an authorization server that redeems
	// ID-JAGs lists in authorization_grant_profiles_supported.
	GrantProfileIDJAG = "urn:ietf:params:oauth:grant-profile:id-jag"
	TokenTypeIDJAG    = "urn:ietf:params:oauth:token-type:id-jag"
	TokenTypeIDToken  = "urn:ietf:params:oauth:token-type:id_token"
)

The grant types, token types and grant profile the two requests use.

View Source
const (
	AuthNone        = "none"
	AuthSecretBasic = "client_secret_basic"
	AuthSecretPost  = "client_secret_post"
	// AuthPrivateKeyJWT authenticates with a JWT the client signs (RFC 7523
	// §2.2), its key held by the Client's Signer.
	AuthPrivateKeyJWT = "private_key_jwt"
)

Token endpoint authentication methods (RFC 7591 §2).

View Source
const (
	ClientOwn  = "own"  // the person's own, made at the vendor
	ClientCIMD = "cimd" // Agentry's Client ID Metadata Document
	ClientDCR  = "dcr"  // dynamically registered for this connection
	// ClientAgentry is Agentry's own public client for a connector Agentry
	// vetted, its id served by the registry; it has no secret.
	ClientAgentry = "agentry"
)

The kinds of Client.

View Source
const CallbackPath = "/callback"

CallbackPath is the loopback redirect's path.

View Source
const ConsentTimeout = 10 * time.Minute

ConsentTimeout bounds how long a consent may wait on the person.

View Source
const EntraHost = "login.microsoftonline.com"

Microsoft Entra ID's v2.0 authorities publish OpenID discovery that the general checks refuse, though they serve a sign-in correctly:

  • the multi-tenant authorities (/common/v2.0, /organizations/v2.0) name the issuer https://login.microsoftonline.com/{tenantid}/v2.0, the placeholder and all, and /consumers/v2.0 names the tenant id of personal Microsoft accounts; only a tenant-id authority names itself;
  • no authority lists code_challenge_methods_supported, though every one takes PKCE with S256;
  • none publishes RFC 8414 metadata (only OpenID discovery), names a revocation endpoint (RFC 7009), or takes the resource parameter (RFC 8707): it refuses a request carrying one (AADSTS9010010), since a token's audience comes from the scopes.

The profile below relaxes exactly those checks, and only for an authority on Entra's own host; every other issuer is held to the general rules. In exchange its endpoints must be on that host too.

View Source
const ExtensionEnterpriseManagedAuthorization = "io.modelcontextprotocol/enterprise-managed-authorization"

ExtensionEnterpriseManagedAuthorization is the extension's identifier, as a client declares it in a request's client capabilities.

View Source
const FetchTimeout = 20 * time.Second

FetchTimeout bounds one request to a vendor: discovery, registration, the code exchange, a refresh or a revocation.

View Source
const GitHubOAuthScope = "read:user"

GitHubOAuthScope is what a sign-in through the OAuth App asks for: the account's profile, which names it. Which scope, if any, Copilot itself needs of an OAuth App's token is not documented. A GitHub App's device flow takes no scope: its token holds the permissions the app is granted, none.

View Source
const NativeClientName = "Agentry Desktop"

NativeClientName is the name a dynamically registered client gives.

Variables

View Source
var ChatGPTScopes = []string{"openid", "profile", "email", "offline_access", "resource.invoke", ChatGPTPlanScope}

ChatGPTScopes are what a sign-in asks for.

View Source
var ErrChatGPTNoPlanScope = errors.New("the sign-in did not grant ChatGPT plan usage (" + ChatGPTPlanScope + "): your plan or workspace may not allow it in other apps; use an OpenAI API key instead")

ErrChatGPTNoPlanScope is a sign-in that did not grant plan usage.

View Source
var ErrGitHubDeclined = errors.New("the authorization was declined on GitHub; nothing was kept")

ErrGitHubDeclined is a person who declined the authorization.

View Source
var ErrGitHubExpired = errors.New("the code expired before it was entered on GitHub; nothing was kept: sign in again")

ErrGitHubExpired is a device code that expired before it was entered.

View Source
var ErrNoIDJAGProfile = errors.New("the authorization server does not say it takes ID-JAGs")

ErrNoIDJAGProfile is an authorization server whose metadata does not say it redeems ID-JAGs; RedeemIDJAG refuses it before any request.

View Source
var ErrRevokeNotOffered = errors.New("the vendor offers apps no revocation")

ErrRevokeNotOffered is a vendor that offers no way for the app to revoke what it was given: the person revokes it at the vendor.

View Source
var ErrStateMismatch = errors.New("the redirect is not the answer to this sign-in (its state does not match)")

ErrStateMismatch is a redirect that is not the answer to this request.

View Source
var HuggingFaceClientMetadataURL = ""

HuggingFaceClientMetadataURL is the address of the Client ID Metadata Document a Hugging Face connect presents: a public native client with loopback redirects on 127.0.0.1 and localhost. A release build sets it with -ldflags "-X github.com/blaktron/agentry-cli/pkg/mcpauth.HuggingFaceClientMetadataURL=…"; a source build has none, and HuggingFaceClientIDEnv supplies a client.

View Source
var HuggingFaceScopes = []string{"openid", "profile", HuggingFaceInferenceScope}

HuggingFaceScopes are what a connect asks for: the inference scope, and the profile that names the account.

View Source
var NativeClientMetadataURL = ""

NativeClientMetadataURL is the address of the Client ID Metadata Document the CLI and the desktop present ("Agentry Desktop", loopback redirects); a CIMD's client id is its own address. A release build sets it with -ldflags "-X github.com/blaktron/agentry-cli/pkg/mcpauth.NativeClientMetadataURL=…". A source build has none, so a sign-in registers a client with the vendor where it allows that and otherwise asks for the person's own.

View Source
var NativeRegistration = Registration{Name: NativeClientName, ApplicationType: "native"}

NativeRegistration is the CLI's and the desktop's: "Agentry Desktop", a native client.

Functions

func CIMDServed

func CIMDServed(ctx context.Context, c *http.Client, docURL string) bool

CIMDServed reports whether Agentry's client metadata document is served at its address and names itself there, with a loopback redirect: a vendor fetching it would otherwise refuse the sign-in in the browser, past where the CLI can fall back to registering.

func ChatGPTGrantGone

func ChatGPTGrantGone(err error) bool

ChatGPTGrantGone reports whether a refresh error means the grant is gone and the person must sign in again (OpenAI's errors-and-recovery page: these codes, plus the OAuth ones GrantRevoked knows).

func GitHubAppName

func GitHubAppName(app string) string

GitHubAppName is how app is named to a person.

func GitHubClientID

func GitHubClientID(app string) (string, error)

GitHubClientID is app's public client id, and an error naming what is missing when this build has none.

func GitHubGrantGone

func GitHubGrantGone(err error) bool

GitHubGrantGone reports whether err is GitHub refusing a refresh because the grant is gone (revoked, expired, or the app's authorization removed).

func GrantRevoked

func GrantRevoked(err error) bool

GrantRevoked reports whether err is the vendor saying the grant is no longer good: a new consent is the only way on.

func HuggingFaceClientID

func HuggingFaceClientID() string

HuggingFaceClientID is the client a Hugging Face connect presents: the variable's, else this build's metadata document, else "" (Connect then says the client is not configured).

func IsEntra added in v0.6.1007

func IsEntra(issuer string) bool

IsEntra reports whether issuer is a Microsoft Entra v2.0 authority, which takes no resource parameter and offers no revocation.

func NewChatGPTHostID

func NewChatGPTHostID() (string, error)

NewChatGPTHostID makes a host id: an opaque UUIDv4 URN, which OpenAI takes as ext_agent_host_id. It is not a secret and proves nothing.

func PoeClientID

func PoeClientID() (string, error)

PoeClientID is Agentry's Poe client id, and an error naming what is missing when this build has none.

func Revoke

func Revoke(ctx context.Context, c *http.Client, endpoint string, client Client, token, hint string) error

Revoke asks the vendor to revoke a token (RFC 7009). An endpoint of "" is a vendor that offers none, which the caller records as such.

Types

type BlockedAddressError

type BlockedAddressError = egressguard.BlockedAddressError

BlockedAddressError is a vendor address that resolved to a non-public one, or to none.

type ChatGPT

type ChatGPT struct {
	// HTTP reaches OpenAI; Guard{}.Client() in production.
	HTTP *http.Client
	// Issuer, AuthorizeURL, TokenURL, DiscoveryURL and APIBase are OpenAI's
	// when empty.
	Issuer, AuthorizeURL, TokenURL, DiscoveryURL, APIBase string
	// Present shows the consent address and, where it can, opens it.
	Present func(authURL string)
	// Pasted carries redirect addresses the person pasted back; nil where
	// none can be.
	Pasted <-chan string
	// Say tells the person something mid-sign-in.
	Say func(string)
	// Timeout bounds the wait on the browser; ConsentTimeout when zero.
	Timeout time.Duration
	// Now is the clock for the ID token's expiry; time.Now when nil.
	Now func() time.Time
}

ChatGPT signs in, refreshes and revokes against OpenAI's authorization server, or a test's (the endpoint fields; zero is OpenAI's).

func (ChatGPT) Models

func (g ChatGPT) Models(ctx context.Context, accessToken string) ([]string, error)

Models lists the models the account's plan may use (OpenAI: the catalog at /v1/models with the plan's token, those of visibility "list"). It is also the eligibility check: OpenAI's 403 subscription_sharing_user_not_eligible is a *ChatGPTNotEligibleError.

func (ChatGPT) Refresh

func (g ChatGPT) Refresh(ctx context.Context, clientID, refreshToken string) (*Token, error)

Refresh trades the refresh token for a new access token and the replacement refresh token, as the issued client.

func (ChatGPT) Revoke

func (g ChatGPT) Revoke(ctx context.Context, clientID, refreshToken string) error

Revoke revokes the refresh token at the revocation endpoint OpenAI's discovery document names, as the issued client. An empty 200 is success, for a token already invalid too.

func (ChatGPT) SignIn

SignIn runs the authorization in the person's browser and returns the grant. reg is this host's registration: a host id always, and the client id and account of an earlier sign-in, which a sign-in again reuses (OpenAI's reauthorization). A sign-in as another account than reg's is refused: that account needs its own registration (reg with the host id alone). The grant is checked for plan usage, and the account for its eligibility, before it is returned; a caller keeps nothing it got an error for.

type ChatGPTNotEligibleError

type ChatGPTNotEligibleError struct{ Detail string }

ChatGPTNotEligibleError is OpenAI's 403 subscription_sharing_user_not_eligible: the account, its workspace or a policy does not allow plan usage here. OpenAI's advice is to say so and not to retry or sign in again.

func (*ChatGPTNotEligibleError) Error

func (e *ChatGPTNotEligibleError) Error() string

type ChatGPTRegistration

type ChatGPTRegistration struct {
	HostID   string `json:"hostId"`
	ClientID string `json:"clientId,omitempty"`
	Subject  string `json:"subject,omitempty"`
}

ChatGPTRegistration is what this host keeps of its registration with OpenAI between sign-ins, sign-outs included: the host's stable id, the client id OpenAI issued, and the account (the ID token's subject) it was issued for. A first sign-in has only the host id.

type ChatGPTSignIn

type ChatGPTSignIn struct {
	ClientID string
	Subject  string
	// Email is the account's address, for "Signed in as …"; "" when the ID
	// token carried none.
	Email  string
	Token  Token
	Models []string
}

ChatGPTSignIn is a finished sign-in: the registration to keep, the account it is, the grant, and the models the account may use.

type Client

type Client struct {
	ID     string `json:"clientId"`
	Secret string `json:"-"`
	// Kind is how it was obtained: ClientOwn, ClientCIMD, ClientDCR or
	// ClientAgentry.
	Kind string `json:"kind"`
	// AuthMethod is how it authenticates at the token endpoint: AuthNone,
	// AuthSecretBasic, AuthSecretPost or AuthPrivateKeyJWT.
	AuthMethod string `json:"authMethod"`
	// Signer signs the client assertion of an AuthPrivateKeyJWT client, so
	// its key can stay in a key service; it is never serialised.
	Signer Signer `json:"-"`
	// AssertionAudience is the aud of an AuthPrivateKeyJWT client's
	// assertion. Empty is the token endpoint the request is sent to, which
	// is what most authorization servers ask; some ask for their issuer.
	AssertionAudience string `json:"-"`
}

Client is the identity a sign-in presents. Secret is empty for a public client; it is kept by the caller's store and never sent into a run.

func Register

func Register(ctx context.Context, c *http.Client, md ServerMetadata, redirectURI string) (Client, error)

Register registers a public native client for this redirect (RFC 7591).

func RegisterAs

func RegisterAs(ctx context.Context, c *http.Client, md ServerMetadata, redirectURI string, reg Registration) (Client, error)

RegisterAs registers a client for this redirect under the name and the application type given (the registry's hosted consent registers a web client named Agentry). It asks to be public where the token endpoint takes a public client; a vendor that issues a secret all the same gets the secret sent the way its metadata allows, never none.

type ConnectedKey

type ConnectedKey struct {
	// Key is the API key (OpenRouter, Poe) or the access token (Hugging
	// Face).
	Key string
	// ExpiresAt is when Key stops working: Poe's chosen expiry, Hugging
	// Face's token lifetime; zero when it does not expire or nothing said.
	ExpiresAt time.Time
	// RefreshToken renews a Hugging Face token; "" for a key.
	RefreshToken string
	// Label names the account ("Connected as …"); "" when the vendor said
	// nothing of it.
	Label string
	// ClientID is the client the connect presented; "" for OpenRouter,
	// which takes none.
	ClientID string
	Scopes   []string
}

ConnectedKey is a finished connect: the key or token to keep, with what the person knows the account by. Key is a secret: it goes to the model key's keychain entry and nowhere else.

type Consent struct {
	// HTTP reaches the vendor; Guard{}.Client() in production.
	HTTP *http.Client
	// ServerURL is the remote server's address, discovered from its own
	// metadata. Issuer, for a package server, which has no address, is
	// the authorization server its oauth block names; no resource
	// parameter is sent then. Exactly one is set. Scopes are the
	// manifest's.
	ServerURL string
	Issuer    string
	Scopes    []string
	// AgentryClient is the client id of Agentry's own public client for a
	// sign-in at issuer, where the server is one Agentry vetted for its
	// connector and the registry serves that connector's id; "" for none.
	// It comes first, before the person's own client.
	AgentryClient func(ctx context.Context, issuer string) string
	// OwnClient is the person's own client for an issuer, or nil for none.
	OwnClient func(issuer string) (*Client, error)
	// CIMDURL is Agentry's client metadata document; "" leaves it out.
	CIMDURL string
	// Present shows the consent address and, where it can, opens it.
	Present func(authURL string)
	// Pasted carries redirect addresses the person pasted back; nil
	// where none can be.
	Pasted <-chan string
	// Say tells the person something mid-consent.
	Say func(string)
	// Timeout bounds the wait; ConsentTimeout when zero.
	Timeout time.Duration
}

Consent is one sign-in to a remote server, or at a package server's issuer.

func (Consent) Run

func (c Consent) Run(ctx context.Context) (*Grant, error)

Run discovers the server, picks a client, opens consent, and exchanges the code the redirect brings back.

type Discovery

type Discovery struct {
	// Resource is the server's canonical address, sent as the resource
	// parameter.
	Resource string
	// ChallengeScopes are the scopes its 401 named; ResourceScopes the ones
	// its metadata lists.
	ChallengeScopes []string
	ResourceScopes  []string
	Server          ServerMetadata
}

Discovery is what a remote server says about how it is signed in to.

func DiscoverRemote

func DiscoverRemote(ctx context.Context, c *http.Client, serverURL string) (*Discovery, error)

DiscoverRemote reads how serverURL is signed in to: an unauthenticated initialize, whose 401 names the resource metadata (else the well-known addresses on the server's origin), then the first authorization server's metadata.

type GitHub

type GitHub struct {
	// HTTP reaches GitHub; Guard{}.Client() in production.
	HTTP *http.Client
	// DeviceCodeURL, TokenURL, DevicePage and API are GitHub's when empty.
	DeviceCodeURL, TokenURL, DevicePage, API string
	// Present shows the person the page and the code to enter there, and
	// opens the page where it can.
	Present func(page, code string)
	// Sleep waits between polls; a context-aware time.Sleep when nil.
	Sleep func(context.Context, time.Duration) error
	// Now is the clock for expiries; time.Now when nil.
	Now func() time.Time
}

GitHub signs in, refreshes and revokes against GitHub, or a test's (the endpoint fields; zero is GitHub's).

func (GitHub) Login

func (g GitHub) Login(ctx context.Context, accessToken string) (string, error)

Login is the account accessToken is for: GitHub's /user, its login.

func (GitHub) Refresh

func (g GitHub) Refresh(ctx context.Context, clientID, refreshToken string) (GitHubTokens, error)

Refresh trades refreshToken for a new pair, through clientID with no secret (the device flow issued it).

func (GitHub) Revoke

func (g GitHub) Revoke(ctx context.Context, tokens ...string) error

Revoke revokes each token for good through GitHub's credential revocation, which takes no authentication and no client secret (an authenticated call is refused there). GitHub tells the account's owner. Empty tokens are skipped; none at all is nothing to do.

func (GitHub) SignIn

func (g GitHub) SignIn(ctx context.Context, clientID, scope string) (*GitHubSignedIn, error)

SignIn runs the device flow for clientID (scope "" for a GitHub App), and names the account. A grant without a refresh token is revoked and refused. The tokens are the caller's to keep: the access token is the one a first run may use, the refresh token is the grant.

type GitHubError

type GitHubError struct {
	Code, Description string
}

GitHubError is an error GitHub's OAuth endpoints answered.

func (*GitHubError) Error

func (e *GitHubError) Error() string

type GitHubSignedIn

type GitHubSignedIn struct {
	Tokens GitHubTokens
	Login  string
}

GitHubSignedIn is a completed sign-in: the grant and the account's login.

type GitHubTokens

type GitHubTokens struct {
	AccessToken      string
	ExpiresAt        time.Time
	RefreshToken     string
	RefreshExpiresAt time.Time
	Scopes           []string
}

GitHubTokens is a grant as GitHub issues it: an access token, its refresh token, and when each expires.

type Grant

type Grant struct {
	Discovery Discovery
	Client    Client
	// Scopes are what was asked; Token.Scopes what was granted, if said.
	Scopes []string
	Token  Token
}

Grant is a finished consent: what to keep, and the first access token.

type Guard

type Guard struct {
	AllowLoopback bool
	TLS           *tls.Config
	LookupNetIP   func(ctx context.Context, host string) ([]netip.Addr, error)
}

Guard is the egress rule every fetch to a vendor goes through: https only, each candidate address public unicast, the address dialled the one checked, no redirect followed and no proxy taken from the environment. The rule is the registry's egress guard (package egressguard); Guard fixes its timeout at FetchTimeout and its scheme at https, and leaves no way to name a proxy.

AllowLoopback, TLS and LookupNetIP are test seams: a test's httptest server is on loopback with its own certificate, and a lookup answers a name with an address of the test's choosing. Production leaves all three zero.

func (Guard) Client

func (g Guard) Client() *http.Client

Client is the HTTP client bound to the guard.

func (Guard) IsAllowedIP

func (g Guard) IsAllowedIP(ip netip.Addr) bool

IsAllowedIP reports whether ip is a public unicast address: not loopback, private, link-local (the cloud metadata address included), multicast, unspecified, 0.0.0.0/8 or carrier-grade NAT; IPv4-mapped addresses are unmapped and an IPv6 address embedding an IPv4 one (6to4, NAT64, IPv4-compatible) is judged by the address it embeds.

type HuggingFace

type HuggingFace struct {
	KeyConnect
	Issuer string
}

HuggingFace connects a Hugging Face account: an OAuth token with the inference-api scope, renewed with its refresh token. Issuer is Hugging Face's when empty; its endpoints come from its discovery document.

func (HuggingFace) Connect

func (h HuggingFace) Connect(ctx context.Context, clientID string) (*ConnectedKey, error)

Connect runs Hugging Face's authorization as clientID (HuggingFaceClientID) and returns the token it granted. A client id that is an address is a metadata document, which must be served before Hugging Face is sent to it: it would refuse the connect in the browser.

func (HuggingFace) Refresh

func (h HuggingFace) Refresh(ctx context.Context, clientID, refreshToken string) (*Token, error)

Refresh trades a Hugging Face refresh token for a new access token (and, should Hugging Face rotate it, a new refresh token).

func (HuggingFace) Revoke

func (h HuggingFace) Revoke(ctx context.Context, clientID, refreshToken string) error

Revoke revokes a Hugging Face refresh token where its discovery names a revocation endpoint on Hugging Face's own host, ErrRevokeNotOffered where it names none.

type IDJAG added in v0.7.16

type IDJAG struct {
	Assertion string `json:"-"`
	ExpiresAt time.Time
	Scopes    []string
}

IDJAG is an identity provider's grant: Assertion is the signed JWT to redeem, a credential of the person's that the caller keeps out of logs and sends only to RedeemIDJAG, and that is never serialised; ExpiresAt is when the provider said it lapses, zero when it did not; Scopes the scopes it granted, when it said.

func RequestIDJAG added in v0.7.16

func RequestIDJAG(ctx context.Context, c *http.Client, idp ServerMetadata, r IDJAGRequest) (*IDJAG, error)

RequestIDJAG asks the identity provider whose metadata is idp for an ID-JAG addressed to r.Audience, by token exchange. The answer must say it issued an ID-JAG (issued_token_type) of token type N_A, and the grant must be a compact JWS; anything else is refused.

type IDJAGRequest added in v0.7.16

type IDJAGRequest struct {
	// Client is the requesting app as the identity provider knows it.
	Client Client
	// SubjectToken is the person's OpenID Connect ID token from that
	// identity provider. It is never serialised.
	SubjectToken string `json:"-"`
	// Audience is the issuer of the MCP server's authorization server.
	Audience string
	// Resource is the MCP server's address, where there is one.
	Resource string
	// Scopes are the scopes asked of the MCP server, if any.
	Scopes []string
}

IDJAGRequest is a request to an identity provider for an ID-JAG.

type KeyConnect

type KeyConnect struct {
	// HTTP reaches the vendor; Guard{}.Client() in production.
	HTTP *http.Client
	// Present shows the consent address and, where it can, opens it.
	Present func(authURL string)
	// Pasted carries redirect addresses the person pasted back; nil where
	// none can be.
	Pasted <-chan string
	// Say tells the person something mid-connect.
	Say func(string)
	// Timeout bounds the wait on the browser; ConsentTimeout when zero.
	Timeout time.Duration
}

KeyConnect is how a connect meets the person: the browser, the pasted redirect, the wait.

type Loopback

type Loopback struct {
	RedirectURI string
	// contains filtered or unexported fields
}

Loopback is the one-shot redirect listener on 127.0.0.1.

func Listen

func Listen() (*Loopback, error)

Listen binds 127.0.0.1:0 and serves CallbackPath.

func ListenAt

func ListenAt(path string) (*Loopback, error)

ListenAt binds 127.0.0.1:0 and serves path, for a vendor that fixes the redirect's path (ChatGPT's /auth/callback): only the port may vary.

func (*Loopback) Close

func (l *Loopback) Close()

Close stops the listener.

func (*Loopback) Expect

func (l *Loopback) Expect(r *Request)

Expect sets the request whose redirect the listener takes.

type NeedsOwnClientError

type NeedsOwnClientError struct{ Issuer string }

NeedsOwnClientError is a vendor that takes no client Agentry can present for itself (no CIMD, no dynamic registration), so the person's own OAuth client is the way: Google is the first.

func (*NeedsOwnClientError) Error

func (e *NeedsOwnClientError) Error() string

type OAuthError

type OAuthError struct {
	Status      int
	Code        string
	Description string
}

OAuthError is an authorization server's refusal: the RFC 6749 error code and, trimmed, its description. Never the body.

func (*OAuthError) Error

func (e *OAuthError) Error() string

type OpenRouter

type OpenRouter struct {
	KeyConnect
	AuthURL, KeysURL string
}

OpenRouter connects an OpenRouter account: its PKCE flow mints an API key. AuthURL and KeysURL are OpenRouter's when empty.

func (OpenRouter) Connect

func (o OpenRouter) Connect(ctx context.Context) (*ConnectedKey, error)

Connect runs OpenRouter's flow in the person's browser and returns the key it minted.

type Poe

type Poe struct {
	KeyConnect
	AuthorizeURL, TokenURL, BalanceURL string
}

Poe connects a Poe account: Sign in with Poe mints an API key with the expiry the person chooses on Poe's consent screen. The endpoint fields are Poe's when empty.

func (Poe) Connect

func (p Poe) Connect(ctx context.Context, clientID string) (*ConnectedKey, error)

Connect runs Sign in with Poe as clientID (PoeClientID) and returns the key it minted.

type RedeemRequest added in v0.7.16

type RedeemRequest struct {
	// Client is the identity the ID-JAG names as its client_id, as the
	// authorization server knows it.
	Client Client
	// Assertion is the ID-JAG. It is never serialised.
	Assertion string `json:"-"`
	// Resource is the MCP server's address, sent where there is one
	// (RFC 8707).
	Resource string
	// Scopes narrow what the ID-JAG granted, if any.
	Scopes []string
}

RedeemRequest is an ID-JAG presented at an MCP server's authorization server.

type Registration

type Registration struct {
	Name            string
	ApplicationType string
}

Registration is how a client describes itself when it registers (RFC 7591 §2): its name, shown on the vendor's consent screen, and its application type, "native" for a loopback redirect or "web" for an HTTPS one (OpenID Connect Dynamic Client Registration §2).

type Request

type Request struct {
	Server      ServerMetadata
	Client      Client
	RedirectURI string
	Resource    string
	Scopes      []string
	State       string
	// Extra are further authorization parameters the consent address
	// carries, such as Google's access_type=offline and prompt=consent,
	// without which a web client is given no refresh token. They never
	// replace one the request sets itself.
	Extra url.Values
	// contains filtered or unexported fields
}

Request is one authorization request, kept until its redirect returns. A client whose redirect returns to another process (the registry's HTTPS callback, answered after the start's request has ended) keeps the state and the verifier itself and rebuilds the request with ResumeRequest.

func NewRequest

func NewRequest(md ServerMetadata, client Client, redirectURI, resource string, scopes []string) (*Request, error)

NewRequest makes a request with a fresh state and PKCE verifier.

func ResumeRequest

func ResumeRequest(md ServerMetadata, client Client, redirectURI, resource string, scopes []string, state, verifier string) *Request

ResumeRequest rebuilds a request from the state and the PKCE verifier its client kept: the registry seals the verifier between the consent's start and its callback, which arrive as two requests.

func (*Request) Callback

func (r *Request) Callback(u *url.URL) (string, error)

Callback reads the redirect the vendor sent the browser to: the code, if the state is this request's and the issuer is the one asked (RFC 9207).

func (*Request) URL

func (r *Request) URL() string

URL is the consent address to open in the person's browser.

func (*Request) Verifier

func (r *Request) Verifier() string

Verifier is the request's PKCE verifier, for a client that must keep it (sealed) until the redirect returns. It is a secret of the sign-in: never logged, never sent but to the token endpoint.

type ResourceMetadata

type ResourceMetadata struct {
	Resource             string   `json:"resource"`
	AuthorizationServers []string `json:"authorization_servers"`
	ScopesSupported      []string `json:"scopes_supported,omitempty"`
}

ResourceMetadata is a protected resource's metadata (RFC 9728).

type ServerMetadata

type ServerMetadata struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint"`
	TokenEndpoint                     string   `json:"token_endpoint"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	RevocationEndpoint                string   `json:"revocation_endpoint,omitempty"`
	UserinfoEndpoint                  string   `json:"userinfo_endpoint,omitempty"`
	CodeChallengeMethodsSupported     []string `json:"code_challenge_methods_supported,omitempty"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	ISSParameterSupported             bool     `json:"authorization_response_iss_parameter_supported,omitempty"`
	CIMDSupported                     bool     `json:"client_id_metadata_document_supported,omitempty"`
	GrantTypesSupported               []string `json:"grant_types_supported,omitempty"`
	// AuthorizationGrantProfilesSupported names the authorization grant
	// profiles the server takes, such as the ID-JAG profile.
	AuthorizationGrantProfilesSupported []string `json:"authorization_grant_profiles_supported,omitempty"`
}

ServerMetadata is an authorization server's metadata (RFC 8414), the fields a client uses.

func DiscoverIssuer

func DiscoverIssuer(ctx context.Context, c *http.Client, issuer string) (*ServerMetadata, error)

DiscoverIssuer reads an authorization server's metadata from the well-known addresses the specification orders, and holds it to its own issuer and to what a sign-in in the browser needs: https authorization and token endpoints, and PKCE with S256.

func DiscoverTokenIssuer added in v0.7.16

func DiscoverTokenIssuer(ctx context.Context, c *http.Client, issuer string) (*ServerMetadata, error)

DiscoverTokenIssuer reads an authorization server's metadata under the same issuer and https checks as DiscoverIssuer, for a server that is only sent token requests: it needs an https token endpoint, and neither an authorization endpoint nor PKCE. An MCP server's authorization server that redeems ID-JAGs alone is such a server.

func (ServerMetadata) AcceptsIDJAG added in v0.7.16

func (md ServerMetadata) AcceptsIDJAG() bool

AcceptsIDJAG reports whether the metadata says the server redeems ID-JAGs: the ID-JAG grant profile among its authorization grant profiles and the JWT bearer grant among its grant types.

type SignError added in v0.7.16

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

SignError is a Signer that could not sign a client assertion. Its message is fixed, because a key service's error can carry its own response; the cause is kept for errors.Is and errors.As.

func (*SignError) Error added in v0.7.16

func (e *SignError) Error() string

func (*SignError) Unwrap added in v0.7.16

func (e *SignError) Unwrap() error

type Signer added in v0.7.16

type Signer interface {
	Algorithm() string
	KeyID() string
	Sign(ctx context.Context, input []byte) ([]byte, error)
}

Signer signs a private_key_jwt client's assertions, so the key can stay in a key service. Algorithm is the JWS algorithm ("ES256", "RS256", "EdDSA"); KeyID the key's id in the client's published key set, or "". Sign returns the JWS signature over input, in the form the algorithm's JWS encoding takes (for ES256, R and S of 32 bytes each, not ASN.1).

type Token

type Token struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time // zero when the vendor did not say
	Scopes       []string  // as granted, when the vendor said
	// IDToken is the OpenID Connect ID token, when the vendor sent one
	// (a sign-in that asked for openid); "" otherwise.
	IDToken string
}

Token is a token endpoint's answer.

func Exchange

func Exchange(ctx context.Context, c *http.Client, r *Request, code string) (*Token, error)

Exchange trades the code for tokens.

func RedeemIDJAG added in v0.7.16

func RedeemIDJAG(ctx context.Context, c *http.Client, as ServerMetadata, r RedeemRequest) (*Token, error)

RedeemIDJAG presents an ID-JAG at the MCP server's authorization server, whose metadata is as, by the JWT bearer grant, for a bearer access token. A server whose metadata does not say it redeems ID-JAGs is refused before any request, with ErrNoIDJAGProfile.

func Refresh

func Refresh(ctx context.Context, c *http.Client, tokenEndpoint string, client Client, refreshToken, resource string) (*Token, error)

Refresh trades a refresh token for a new access token (and, from a vendor that rotates them, a new refresh token).

Directories

Path Synopsis
Package mcpauthtest is a fake vendor for tests of OAuth connections: a remote MCP server that answers 401 with its resource metadata, and the authorization server behind it (metadata, consent, the token endpoint with refresh-token rotation, dynamic registration, revocation), on one TLS httptest server.
Package mcpauthtest is a fake vendor for tests of OAuth connections: a remote MCP server that answers 401 with its resource metadata, and the authorization server behind it (metadata, consent, the token endpoint with refresh-token rotation, dynamic registration, revocation), on one TLS httptest server.

Jump to

Keyboard shortcuts

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