An issuer identifier written with a terminating slash, like
`https://auth.example.com/`, makes authorization server metadata
discovery miss every endpoint. `GetAuthServerMetadata` probes three URLs
that no conformant server serves, finds nothing, and the caller falls
back to the guessed 2025-03-26 endpoints, which are themselves malformed
because they are built by appending to the same slash-terminated issuer.
`authorizationServerMetadataURLs` in `auth/shared.go` decides whether
the issuer has a path component with `baseURL.Path == ""` (line 47), and
a trailing-slash issuer has `Path == "/"`, so it takes the
path-insertion branch. That branch inserts
`strings.TrimLeft(originalPath, "/")` (lines 59 and 62), which strips
the leading slash but keeps the trailing one. For
`https://auth.example.com/` the probes come out as
`/.well-known/oauth-authorization-server/`,
`/.well-known/openid-configuration/` and
`//.well-known/openid-configuration`. For
`https://auth.example.com/tenant1/` the two path-insertion probes come
out with a trailing slash. Only the path-appending form was already
right, because it uses `strings.Trim`.
RFC 8414 section 3.1 settles it: "If the issuer identifier value
contains a path component, any terminating "/" MUST be removed before
inserting "/.well-known/" and the well-known URI suffix between the host
component and the path component." So `https://auth.example.com/` has no
path component and gets the two root forms, which is the list the MCP
authorization spec gives for issuers without a path component.
The change trims slashes off both ends of the issuer path once, uses
that to pick between the root and path-insertion branches, and reuses it
for all three URLs. An issuer without a terminating slash produces
exactly the same list as before.
`TestAuthorizationServerMetadataURLs` pins the URL list for all four
issuer shapes. `TestGetAuthServerMetadataTrailingSlashIssuer` drives the
whole lookup against the existing fake authorization server, serving
metadata at the root well-known path. On unmodified main the first fails
on both trailing-slash cases and the second fails with
`GetAuthServerMetadata() error = Get
"/.well-known/openid-configuration": redirect into loopback address
"127.0.0.1"`, because `//.well-known/openid-configuration` makes
`net/http.ServeMux` issue a canonicalizing redirect that the discovery
client's `CheckRedirect` refuses. Both pass with the change.
Verification on go1.26.4: `gofmt -l .` clean, `go vet ./...` clean,
`staticcheck ./...` clean at v0.6.1 (the version the Test workflow
pins), `go test ./auth/...` ok, `go test ./...` ok.
I did not file an issue first. The fix is self-contained, confined to
one unexported helper, and every issuer shape other than the
slash-terminated ones is byte-identical to before.
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
## Summary
Fixes#1152.
Sentry, Linear, and Notion omit
`authorization_response_iss_parameter_supported` from their
authorization-server metadata. Sentry still sends a correct `iss` in the
authorization response, so sign-in fails after the browser step: the
user has already consented and an authorization code has been issued,
but `validateIssuerResponse` rejects the exchange solely because the
server did not advertise RFC 9207 support.
RFC 9207 §2.4 says clients MUST extract and compare `iss` when the
parameter is present. §2.4 also notes that clients SHOULD discard an
unadvertised `iss`, but that is a recommendation and local policy may
accept servers that send `iss` without advertising. Validating a
matching `iss` is interoperable with those hosted MCP servers and still
catches mix-up attacks: a wrong `iss` is rejected whether or not support
was advertised.
When `iss` is present, this change always compares it to the expected
issuer (simple string equality). A match is accepted even if the server
did not advertise support. A mismatch still returns `authorization
response issuer %q does not match expected issuer %q`. Absence of `iss`
remains an error only when the server advertised support.
## Test plan
- [x] `go test ./auth/ -run TestValidateIssuerResponse -count=1`
- [x] `go test ./auth/...`
New `TestValidateIssuerResponse` cases:
- `UnadvertisedIssCorrect`: `iss == expectedIssuer`, `issSupported ==
false` → no error
- `UnadvertisedIssWrong`: `iss == "https://attacker.example.com"`,
`issSupported == false` → error containing `does not match expected
issuer`
Existing advertised+match / advertised+mismatch / missing-iss cases are
unchanged.
---------
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
## Summary
The authorization-code handler requests every scope advertised in the
protected resource's metadata `scopes_supported` (or named in the
`WWW-Authenticate` challenge), and offers the caller no way to adjust
that set. Some servers advertise a scope a client should *not* request:
- Google's Gmail MCP server advertises `gmail.metadata` in
`scopes_supported`.
- The Gmail API refuses the search `q` parameter on any token that
carries `gmail.metadata` — **even when `gmail.readonly` is also
granted** (a long-standing documented Gmail restriction, see
googleapis/google-api-python-client#582).
Because the handler requests the full advertised set, `gmail.metadata`
ends up in the grant and breaks search, with no client-side remedy.
## Change
Add an optional `ScopeFilter func(discovered []string) []string`
callback to `AuthorizationCodeHandlerConfig`. When non-nil, it receives
the discovered scopes and returns the set to request, giving the client
full control to narrow, extend, or reorder them. It runs **before** the
`offline_access` (SEP-2207) and step-up union (SEP-2350) logic, so
refresh-token support and scope accumulation are unaffected.
(Started as a static `Scopes []string` allowlist; switched to a callback
per review feedback for more flexibility.)
## Test
`TestAuthorize_ScopeFilter` drives a full authorize flow and asserts the
requested `scope` parameter for a nil filter (unchanged), a filter that
drops a scope, and one that replaces the set entirely. `go test
./auth/...` (incl. `-race`), `go vet`, and `gofmt` are clean.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
This change adds NewTokenSource and InitialTokenSource fields to
AuthorizationCodeHandlerConfig. NewTokenSource enables wrapping the
underlying token source to intercept token refreshes. InitialTokenSource
enables configuring the token source used by the
AuthorizationCodeHandler on initialization. Together these features
facilitate persisting OAuth2 sessions across restarts.
Includes a package example demonstrating the persistence pattern.
Fixes: #901.
See #901 for the previous discussion behind this design.
---------
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
Co-authored-by: Jonathan Amsterdam <jba@users.noreply.github.com>
## Problem
`AuthorizationCodeHandler.exchangeAuthorizationCode` builds the
long-lived token source from the **request context** passed to
`Authorize()`:
```go
clientCtx := context.WithValue(ctx, oauth2.HTTPClient, h.config.Client)
...
h.tokenSource = cfg.TokenSource(clientCtx, token)
```
`golang.org/x/oauth2` captures that context and reuses it for **every**
future refresh:
- `oauth2.go`: `Config.TokenSource(ctx, …)` stores `ctx` in
`tokenRefresher{ctx}`
- `tokenRefresher.Token()` (no ctx arg) calls `retrieveToken(tf.ctx, …)`
- `internal/token.go`: `ContextClient(ctx).Do(req.WithContext(ctx))`
`Authorize()` is normally invoked from a request- or connect-scoped
context — e.g. the streamable client transport calls it during
`setMCPHeaders`/`initialize`, and that context is cancelled once the
operation completes. The cached access token works until expiry; the
**first refresh after expiry** then fails instantly with `context
canceled`, before any HTTP request is sent. The connection can no longer
refresh.
`setMCPHeaders` only re-invokes `Authorize()` for an `invalid_grant`
`oauth2.RetrieveError` (#917). A `context canceled` is not a
`RetrieveError`, so it is never recovered — the connection is wedged
until the client reconnects.
### Reproduce
1. Connect a `StreamableClientTransport` with an
`AuthorizationCodeHandler` to a server whose `initialize` returns 401
(so `Authorize()` runs during connect, under the connect context).
2. Let the connect context be cancelled after connect returns (the
common pattern: a `context.WithTimeout(parent, …)` + `defer cancel()`
bounding the interactive flow).
3. Wait for the access token to expire and issue a request.
4. Every request fails with `Post "<token endpoint>": context canceled`
and `dur≈0` — the refresh never hits the network.
## Fix
A token source outlives the request that created it, so bind its
refreshes to `context.Background()` (still carrying the configured HTTP
client via `oauth2.HTTPClient`). The one-shot token exchange keeps using
the request context.
```go
refreshCtx := context.WithValue(context.Background(), oauth2.HTTPClient, h.config.Client)
h.tokenSource = cfg.TokenSource(refreshCtx, token)
```
`auth` package tests pass. Behaviour is otherwise unchanged: the same
HTTP client value is carried; only the cancellation parent differs.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
## Summary
- Add a \`ClockSkew time.Duration\` field to
\`RequireBearerTokenOptions\` that bounds the tolerance applied to a
token's \`Expiration\` when checking elapsed validity.
- Default zero preserves the existing strict comparison; positive values
let resource servers tolerate the drift typical of distributed
deployments and cloud-managed IdPs.
## Motivation
Real-world resource servers running behind a CDN, in distributed
deployments, or talking to an authorization server whose clock drifts a
few seconds (common with cloud-managed IdPs) need a small positive
tolerance when checking token expiration. Strict-equality comparison
rejects tokens that are valid by the issuer's clock but momentarily
appear expired by the verifier's. The reverse case — an issuer's clock
running slightly fast at /token issuance — also reaches the verifier as
a token whose \`exp\` lies microseconds in the past.
## Test plan
- [x] \`go test ./auth/...\` passes.
- [x] New \`TestRequireBearerToken_ClockSkew\` exercises four cases:
fresh accept, strict-expired reject, within-skew accept, beyond-skew
reject.
- [x] Existing \`TestRequireBearerToken\` continues to pass with
\`ClockSkew\` defaulting to zero.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
## Summary
- Add an `AllowMissingExpiration bool` field to
`RequireBearerTokenOptions` that opts the middleware out of the existing
`tokenInfo.Expiration.IsZero()` reject.
- Default false preserves the existing strict behaviour: every TokenInfo
must carry an Expiration.
## Motivation
Some IdPs emit session-bound bearer tokens that do not carry a
standalone `exp` claim — the token's lifetime is bounded by an external
session and is not advertised in-band. Resource servers integrating with
such IdPs today have to synthesise a fake Expiration from their
TokenVerifier callback (dishonest data through the auth layer) or fork
`RequireBearerToken` to bypass the check.
This option lets the verifier honestly report "no expiration in the
token" via a zero `Expiration` and have the middleware accept it — while
still applying the elapsed-validity check for tokens that DO carry an
Expiration.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Guglielmo Colombo <guglielmoc@google.com>
This PR functions as a Reference implementation of
[SEP-2468](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2468)
/ [RFC9207](https://datatracker.ietf.org/doc/rfc9207/).
This PR hardens the MCP OAuth Client functionality against Mix-Up
attacks:
> Mix-up attacks aim to steal an authorization code or access token by
> tricking the client into sending the authorization code or access
> token to the attacker instead of the honest authorization or resource
> server
This PR hardens the client by adding support for a new `iss` parameter
in authorization responses:
- Authorization Servers broadcast support for the `iss` parameter via
the `authorization_response_iss_parameter_supported` metadata parameter
- If the parameter is supported, clients expect to receive the `iss`
parameter in the authorization response
- Clients compare the `iss` parameter in the authorization response to
the `Issuer` parameter in the authorization metadata. The two must match
exactly for the response to be processed.
Fixes#941
## Summary
- Add `ClientCredentialsHandler` implementing `auth.OAuthHandler` using
the OAuth 2.0 Client Credentials grant (RFC 6749 Section 4.4) for
service-to-service authentication with pre-registered credentials.
- Bypasses both dynamic client registration and the authorization code
flow — the handler takes a client ID + secret directly and exchanges
them at the token endpoint.
- Supports two modes: direct `TokenEndpoint` URL, or metadata discovery
via `AuthServerURL` (RFC 8414).
- Add `client_credentials` grant type support to the fake authorization
server in `internal/oauthtest` for testing.
## Context
Per @jba's [comment on
#627](https://github.com/modelcontextprotocol/go-sdk/issues/627#issuecomment-3640982691):
> Our default implementation for that framework should support client ID
and client secret as options, to handle that variant. [...] If those are
set, our implementation would bypass dynamic client reservation. That is
just a couple of lines of code, I believe.
The client-side OAuth scaffolding (#785) that this was blocked on is now
complete, as @brkane noted.
Implements the client credentials variant of
[SEP-1046](https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1046).
The JWT Assertions variant (RFC 7523) is left for a follow-up as its API
surface needs more design discussion.
## Test plan
- [x] `TestNewClientCredentialsHandler_Validation` — validates all
config error cases (nil config, missing fields, mutual exclusivity)
- [x] `TestClientCredentialsHandler_Authorize/direct_token_endpoint` —
end-to-end with fake auth server
- [x] `TestClientCredentialsHandler_Authorize/metadata_discovery` —
discovers token endpoint via RFC 8414 metadata
- [x] `TestClientCredentialsHandler_Authorize/bad_credentials` —
verifies failure with wrong secret
- [x] `go test ./... -count=1` passes
- [x] `go vet ./...` clean
Refs #627
Co-authored-by: Maciej Kisiel <mkisiel@google.com>
`auth`, `oauthex`: implement Enterprise Managed Authorization (SEP-990)
This PR implements Enterprise Managed Authorization (SEP-990) for the Go
MCP SDK, enabling MCP Clients and Servers to leverage enterprise
Identity Providers for seamless authorization without requiring users to
authenticate separately to each MCP Server.
Overview
Enterprise Managed Authorization follows the Identity Assertion
Authorization Grant specification
(draft-ietf-oauth-identity-assertion-authz-grant), implementing a
three-step flow:
1. **Single Sign-On (SSO)**: User authenticates to the MCP Client via
enterprise IdP (Okta, Auth0, Azure AD, etc.)
2. **Token Exchange (RFC 8693)**: Client exchanges ID Token for Identity
Assertion JWT Authorization Grant (ID-JAG) at the IdP
3. **JWT Bearer Grant (RFC 7523)**: Client exchanges ID-JAG for Access
Token at the MCP Server
This enables:
- **For end users**: Single sign-on across MCP Clients and Servers—no
manual connection/authorization per server
- **For enterprise admins**: Centralized visibility and control over
which MCP Servers can be used within the organization
- **For MCP clients**: Automatic token acquisition without user
interaction for each server
Closes:
[#628](https://github.com/modelcontextprotocol/go-sdk/issues/628)
---------
Co-authored-by: Maciej Kisiel <mkisiel@google.com>
This PR introduces client-side OAuth support.
# Overall design philosophy
The main new interface introduced to support client-side OAuth is the
`OAuthHandler`. Contrary to its counter-parts in some other SDKs, it is
intentionally small and generic so that it can support most of the OAuth
authorization flow variants. The main `mcp` package purposefully
delegates almost all auth handling to `OAuthHandler` implementations.
This way, the `mcp` package continues to be largely OAuth agnostic.
The `auth` package comes with a default `OAuthHandler` implementation –
`AuthorizationCodeHandler`, which implements the authorization flow
for the `authorization_code` grant type, as defined in the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
It is expected that the `OAuthHandler` implementation granularity will
be roughly per grant type, as this parameter influences the
authorization flow the most.
# Detailed design
## `OAuthHandler` (auth/client.go)
The main interface for the integration consists of two methods:
```go
type OAuthHandler interface {
// TokenSource returns a token source to be used for outgoing requests.
// Returned token source might be nil. In that case, the transport will not
// add any authorization headers to the request.
TokenSource(context.Context) (oauth2.TokenSource, error)
// Authorize is called when an HTTP request results in an error that may
// be addressed by the authorization flow (currently 401 Unauthorized and 403 Forbidden).
// It is responsible for performing the OAuth flow to obtain an access token.
// The arguments are the request that failed and the response that was received for it.
// The headers of the request are available, but the body will have already been consumed
// when Authorize is called.
// If the returned error is nil, TokenSource is expected to return a non-nil token source.
// After a successful call to Authorize, the HTTP request will be retried by the transport.
// The function is responsible for closing the response body.
Authorize(context.Context, *http.Request, *http.Response) error
}
```
`StreamableClientTransport` accepts this interface as a field and uses
the `TokenSource` method to add an `Authorization: Bearer` header to
outgoing requests to the MCP server. If the request fails with `401:
Unauthorized` or `403: Forbidden`, the transport calls `Authorize` to
perform the authorization flow. If `Authorize` returns a non-nil error,
the request is retried once. `Authorize` errors do not result in
termination of the client session (unless they happen during
connection initialization), as some OAuth flows are multi-legged and it should be
acceptable to retry for example when the authorization grant was
received.
*Note:* There was already an `OAuthHandler` type defined as part of a
previous iteration of OAuth support. It was renamed to
`OAuthHandlerLegacy`. This is the only backwards incompatible API change
in the experimental client `auth` part (protected by the
`mcp_go_client_oauth` Go build tag). The cost of replacing previous
usages is deemed worthwhile to maintain clear naming, under the
assumption that the experimental client `auth` part was not widely used.
## `AuthorizationCodeHandler` (auth/authorization_code.go)
This is the `OAuthHandler` implementation that fulfills the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
In particular, in supports:
- Protected Resource Metadata discovery and fetching
- Authorization Server Metadata discovery and fetching
- Client registration
- OpenID Connect metadata document
- Pre-registration
- Dynamic Client Registration
- PKCE
- `client_secret_post`, `client_secret_basic` token endpoint
auth methods
- Automatic refresh of tokens
### Authorization Server redirect
As part of the flow for the `authorization_code` grant type, the client
needs to point the user to the authorization URL, so that they confirm
the access request. This design proposes that it will be supported via a
pluggable dependency that will initiate this process in an
application-specific way:
```go
type AuthorizationCodeHandler struct {
...
// AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
// It is responsible for opening the URL in a browser for the user to start the authorization process.
// It should return the authorization code and state once the Authorization Server
// redirects back to the RedirectURL.
AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)
...
}
```
The function is supposed perform any application specific logic to handle the redirect
from the Authorization Server and return the resulting code and state.
## `oauthex` changes
Some additional/adjusted building blocks that may be useful when
creating `OAuthHandler` implementations are present in the `oauthex`
package:
- `auth_meta.go`: Authorization Server Metadata utilities:
- `GetAuthServerMeta`: get Authorization Server Metadata from a URL
- `dcr.go`: Dynamic Client Registration utilities (unchanged)
- `resource_meta.go`: Protected Resource Metadata utilities:
- `GetProtectedResourceMetadata`: get Protected Resource Metadata from a
URL
- `ParseWWWAuthenticate` – as per name (unchanged)
- [deprecated] `GetProtectedResourceMetadataFromID` and
`GetProtectedResourceMetadataFromHeader` in favor of more generic
`GetProtectedResourceMetadata`. They will be kept under the Go build tag
and removed one version of the SDK in the future.
This change adds support for RFC 9728 (OAuth 2.0 Protected Resource Metadata)
by introducing a `ProtectedResourceMetadataHandler`.
The handler includes built-in CORS support with `Access-Control-Allow-Origin: *`
by default, as OAuth metadata is public information meant for client discovery.
Documentation includes examples for using custom CORS policies with
popular middleware libraries (github.com/rs/cors and github.com/jub0bs/cors).
The implementation follows RFC 9728 §3.1 for OAuth 2.0 Authorization Server
Metadata discovery, enabling clients to discover protected resource capabilities
and authentication requirements.
Add a UserID field to auth.TokenInfo that TokenVerifiers can populate
from JWT "sub" claims or token introspection. The streamable HTTP
transport uses this to bind sessions to users, rejecting requests where
the user ID doesn't match the session's original user.
Fixes#589
Change OAuthHandler signature from func(context.Context,
OAuthHandlerArgs) to func(req *http.Request, res *http.Response).
- Remove OAuthHandlerArgs struct
- Update HTTPTransport to pass req and resp to handler
- Update tests to use new signature
- Handler can now call oauthex.GetProtectedResourceMetadataFromHeader
with proper validation against request URL
This change fixes an impedance mismatch between OAuthHandler and the
protected resource metadata functions of the oauthex package. The new
signature allows handlers to properly validate resource metadata against
the request URL, as required by RFC 9728.
Fixes#600
RoundTrippers may read and close the body, so be careful to clone before
roundtripping during client oauth, as the request may be issued multiple
times.
Fixes#590
This is a preliminary implementation of OAuth 2.1 for the client.
When a StreamableClientTransport encounters a 401 Unauthorized response
from the server, it initiates the OAuth flow described in thec
authorization section of the MCP spec
(https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization).
On success, the transport obtains an access token which it passes
to all subsequent requests.
Much remains to be done here:
* Resource Indicators, as described in section 2.5.1 of the MCP spec.
* All of this is unexported, so it is available only to our own
StreamingClientTransport. We should add API so people can use it
with their own transports.
* And, of course, tests. We should test against fake implementations
but also, if we can find any, real reference implementations.
For #19
Co-authored-by: Jonathan Amsterdam <jba@google.com>
---------
Co-authored-by: Jonathan Amsterdam <jba@google.com>
Add ErrOAuth error type and handling to match TypeScript SDK behavior.
OAuth protocol errors now return HTTP 400 instead of 500, providing
better error classification for authentication issues.
Changes
- Add ErrOAuth variable for OAuth-specific protocol errors
- Update verify function to return 400 for OAuth errors
- Add test case for OAuth error handling
Fixes compatibility with TypeScript SDK error handling patterns.
If there is a TokenInfo in the request context of a
StreamableServerTransport, then propagate it through to the
ServerRequest that is passed to server methods like callTool.
Fixes#317.
Add auth.RequireBearerToken and associated types.
This piece of middleware authenticates clients using OAuth 2.0, as
specified in the MCP spec.
For #237.
Usage:
```
st := mcp.NewStreamableServerTransport(...)
http.Handle(path, auth.RequireBearerToken(verifier, nil)(st.ServeHTTP))
```