By lantern light, the Ghost, a stone android kneeling beside a stone door with a crescent carved above it, holds up a brass medallion stamped with the same crescent to compare them, while the Gopher waits with its clipboard; farther along the wall, a second door is marked with a star.

Production

MCP authorization in Go: resource servers, audience-bound tokens, and step-up

An MCP server that accepts only tokens issued for it, a client that gets one, and the checks the SDK leaves to you.

Updated Advanced

On the agent compass Stage 3 of 4 · Run the tools

An MCP server started over stdio runs on the user’s machine and takes its credentials from the environment. A remote MCP server, reached over HTTP, is different: many users and many clients reach it over the network, and it has to know who is calling and what they may do. The MCP specification answers with OAuth 2.1: the MCP server is a resource server that accepts access tokens, the MCP client is an OAuth client acting for a user, and an authorization server, which may be your company’s identity provider, issues the tokens.

This page builds both sides in Go and runs them against each other, offline, with tests for the attacks the specification is written to stop. It follows the MCP authorization specification dated 2026-07-28, which changed in ways older write-ups miss: Client ID Metadata Documents are now the preferred way for a client to identify itself, Dynamic Client Registration is deprecated, and clients must check which authorization server answered them. The MCP transport and most of the client’s flow come from the official MCP Go SDK (v1.8.0). What the SDK leaves to the server, verifying the token, is where most of this page goes, because that is where the mistakes are.

One rule behind the rest

Every access token is issued for exactly one MCP server, and that server accepts no other.

The client names the server it wants a token for in a resource parameter (RFC 8707), on both the authorization request and the token request. The authorization server writes that server into the token’s audience, its aud claim. The MCP server refuses any token whose audience isn’t its own address, and it never sends a token it received on to anyone else.

The rule matters for agents because an agent connects to many servers at once. If one token worked everywhere, any server the agent talks to, including a malicious one or a compromised one, could take the token it was sent and use it at every other server the user has connected. That is a confused deputy and a token replay in one, and audience binding is what prevents both.

The whole flow, in one run

The example’s demo starts an authorization server, two MCP servers, a website hosting the client’s metadata, and a stand-in for the user’s browser, all on loopback addresses, and prints every HTTP request:

go run . (in code/mcpauth)
In the log: auth is the authorization server, mcp and other are
two MCP servers, client is the client's website, and loopback is
where the client receives the browser's redirect.

1. Connect with no token
   POST mcp      /mcp  server/discover  -> 401 scope="issues:read"
   GET  mcp      /.well-known/oauth-protected-resource/mcp  -> 200
   GET  auth     /.well-known/oauth-authorization-server  -> 200
   GET  client   /client.json  (the authorization server checks the client)
   GET  auth     /authorize  scope="issues:read" resource=mcp/mcp S256  -> 302
   GET  loopback /callback  with code, state, and iss=auth  -> 200
   POST auth     /token  -> 200
   POST mcp      /mcp  server/discover  -> 200

2. Search, which issues:read allows
   POST mcp      /mcp  tools/call issue_search  -> 200
   issue_search: #1 Panic in the reminder scheduler

3. File an issue, which needs issues:write too
   POST mcp      /mcp  tools/call issue_file  -> 403 insufficient_scope scope="issues:read issues:write"
   GET  mcp      /.well-known/oauth-protected-resource/mcp  -> 200
   GET  auth     /.well-known/oauth-authorization-server  -> 200
   GET  client   /client.json  (the authorization server checks the client)
   GET  auth     /authorize  scope="issues:read issues:write" resource=mcp/mcp S256  -> 302
   GET  loopback /callback  with code, state, and iss=auth  -> 200
   POST auth     /token  -> 200
   POST mcp      /mcp  tools/call issue_file  -> 200
   issue_file: filed #2 for reader@example.com

4. Replay the token at another MCP server
   other: 401 invalid token: issued for another resource
A sequence of three participants: the MCP client, the MCP server, and the authorization server. The client sends a request with no token and gets a 401 naming the resource metadata; it fetches the resource metadata, which names the resource and its authorization servers, then the authorization server's metadata, with its issuer, endpoints, and S256; it sends the user's browser to authorize with PKCE, the resource, and the scope, and the browser comes back with a code, state, and iss; the client checks state and iss, redeems the code with the verifier and the resource, and gets a token whose audience is the MCP server; it sends the request with the token, and the server checks its signature, type, issuer, audience, and expiry.A sequence of three participants: the MCP client, the MCP server, and the authorization server. The client sends a request with no token and gets a 401 naming the resource metadata; it fetches the resource metadata, which names the resource and its authorization servers, then the authorization server's metadata, with its issuer, endpoints, and S256; it sends the user's browser to authorize with PKCE, the resource, and the scope, and the browser comes back with a code, state, and iss; the client checks state and iss, redeems the code with the verifier and the resource, and gets a token whose audience is the MCP server; it sends the request with the token, and the server checks its signature, type, issuer, audience, and expiry.A sequence of three participants: the MCP client, the MCP server, and the authorization server. The client sends a request with no token and gets a 401 naming the resource metadata; it fetches the resource metadata, which names the resource and its authorization servers, then the authorization server's metadata, with its issuer, endpoints, and S256; it sends the user's browser to authorize with PKCE, the resource, and the scope, and the browser comes back with a code, state, and iss; the client checks state and iss, redeems the code with the verifier and the resource, and gets a token whose audience is the MCP server; it sends the request with the token, and the server checks its signature, type, issuer, audience, and expiry.A sequence of three participants: the MCP client, the MCP server, and the authorization server. The client sends a request with no token and gets a 401 naming the resource metadata; it fetches the resource metadata, which names the resource and its authorization servers, then the authorization server's metadata, with its issuer, endpoints, and S256; it sends the user's browser to authorize with PKCE, the resource, and the scope, and the browser comes back with a code, state, and iss; the client checks state and iss, redeems the code with the verifier and the resource, and gets a token whose audience is the MCP server; it sends the request with the token, and the server checks its signature, type, issuer, audience, and expiry.A sequence of three participants: the MCP client, the MCP server, and the authorization server. The client sends a request with no token and gets a 401 naming the resource metadata; it fetches the resource metadata, which names the resource and its authorization servers, then the authorization server's metadata, with its issuer, endpoints, and S256; it sends the user's browser to authorize with PKCE, the resource, and the scope, and the browser comes back with a code, state, and iss; the client checks state and iss, redeems the code with the verifier and the resource, and gets a token whose audience is the MCP server; it sends the request with the token, and the server checks its signature, type, issuer, audience, and expiry.
A client’s first connection, as in step 1 of the log. The authorization request goes through the user’s browser, where the authorization server also fetches the client’s metadata document.

Step 1 is the first connection. The client calls the server with no token and gets 401, with a WWW-Authenticate header that says where the server’s metadata is. From there the client finds the authorization server, sends the user to it, and comes back with a token. Step 2 uses that token. Step 3 calls a tool that needs more than the user granted at first, so the server answers 403, and the client asks the user for the extra scope and retries. Step 4 is the attack: the same token, sent to a second MCP server, is refused.

The rest of the page goes through the parts that make each step work.

The server: say where tokens come from

A protected MCP server publishes Protected Resource Metadata (RFC 9728): a small JSON document naming the server and the authorization servers it trusts. The specification requires it, and requires clients to use it to find the authorization server.

mcpauth/resource/server.go
// NewServer returns the handler for an MCP server that only answers
// requests carrying an access token issued for it. It serves its
// Protected Resource Metadata (RFC 9728) at the well-known URI built
// from its own path, and every 401 and 403 points there. The server is
// stateless, as MCP is from 2026-07-28: every request stands alone and
// carries its own token, and a client that gives up on a call cancels
// the handler running it.
func NewServer(c Config) (http.Handler, error) {
	u, err := url.Parse(c.Resource)
	if err != nil || u.Path == "" {
		return nil, fmt.Errorf("server: resource %q needs a path",
			c.Resource)
	}
	wellKnown := "/.well-known/oauth-protected-resource" + u.Path
	metadataURL := u.Scheme + "://" + u.Host + wellKnown
	v := &Verifier{Issuer: c.Issuer, Resource: c.Resource,
		JWKSURL: c.JWKSURL, Client: c.Client}
	opts := &mcp.StreamableHTTPOptions{Stateless: true,
		PropagateRequestCancellation: true}
	var h http.Handler = mcp.NewStreamableHTTPHandler(
		func(*http.Request) *mcp.Server { return c.MCP }, opts)
	h = ToolScopes(c.ToolScopes, metadataURL)(h)
	h = auth.RequireBearerToken(v.Verify, &auth.RequireBearerTokenOptions{
		ResourceMetadataURL: metadataURL, Scopes: c.Starting})(h)
	mux := http.NewServeMux()
	meta := auth.ProtectedResourceMetadataHandler(
		Metadata(c.Resource, c.Issuer, c.Starting))
	mux.Handle("GET "+wellKnown, meta)
	mux.Handle(u.Path, h)
	return mux, nil
}

The server is stateless, as MCP is from the 2026-07-28 revision: there is no session to tie a token to, so every request carries its token and is checked on its own. The metadata lives at a well-known address built by inserting /.well-known/oauth-protected-resource between the host and the server’s path, so the server at /mcp publishes it at /.well-known/oauth-protected-resource/mcp, and every 401 and 403 names that address in resource_metadata. The handler, the SDK’s ProtectedResourceMetadataHandler, serves whatever it is given without checking it, so the values come from one function:

mcpauth/resource/server.go
// Metadata is the server's Protected Resource Metadata. Its resource
// must be the URL clients call, byte for byte, or they reject it (RFC
// 9728, section 3.3). scopes_supported is the least a client needs to
// start.
func Metadata(resource, issuer string,
	starting []string) *oauthex.ProtectedResourceMetadata {
	return &oauthex.ProtectedResourceMetadata{
		Resource:               resource,
		AuthorizationServers:   []string{issuer},
		ScopesSupported:        starting,
		BearerMethodsSupported: []string{"header"},
	}
}

Its resource must be the URL clients call, byte for byte. A client that fetches metadata through resource_metadata must check that resource is identical to the URL it requested, and discard the document if not (RFC 9728, section 3.3). Without that check, a malicious server could publish metadata claiming to be another server and get the client to fetch a token for the other one. TestImpersonatedMetadata runs that attack: the client refuses the metadata, and the victim’s authorization server never hears from it.

scopes_supported lists only issues:read. The specification asks for the smallest set a client needs to start, with more requested only when an operation needs it, so a user who only searches never grants write access.

The server: verify every token yourself

The SDK’s RequireBearerToken middleware takes the token out of the Authorization header and passes it to a TokenVerifier, a function you write. It checks the scopes and expiry you return, but deciding whether the token is genuine, whose it is, and who it was issued for is entirely the verifier’s job.

The tokens here are JWT access tokens as RFC 9068 profiles them, signed with ES256 by the authorization server. The verifier holds what it must check against:

mcpauth/resource/verify.go
// A Verifier checks the access tokens an MCP server receives: JWT
// access tokens (RFC 9068) signed by one authorization server, for
// this server only. The MCP SDK calls Verify for every request; what
// it checks is up to the server, and so is every mistake.
type Verifier struct {
	Issuer   string // the authorization server's issuer identifier
	Resource string // this server's canonical URI: the audience to expect
	JWKSURL  string // where the authorization server publishes its keys
	Client   *http.Client
	Leeway   time.Duration // clock skew allowed on exp, nbf, and iat
	Now      func() time.Time

	mu      sync.RWMutex
	keys    jose.JSONWebKeySet
	fetchMu sync.Mutex // one key fetch at a time
	fetched time.Time  // when the keys were last fetched
}

Resource is the server’s own canonical URI, the audience a token must name. Issuer is the authorization server’s issuer identifier, the one value an iss claim may have. The signature is checked with go-jose, a maintained JOSE library; the claim checks around it are written out, because those are the rules this specification adds and the ones a library won’t apply unless you ask:

mcpauth/resource/verify.go
// Verify checks token and returns what the server may rely on: who the
// user is, what they granted, and until when. Every failure wraps
// auth.ErrInvalidToken, which the SDK answers with 401.
func (v *Verifier) Verify(ctx context.Context, token string,
	_ *http.Request) (*auth.TokenInfo, error) {
	if v.Issuer == "" || v.Resource == "" {
		return nil, errors.New("verifier: issuer or resource unset")
	}
	algs := []jose.SignatureAlgorithm{jose.ES256}
	tok, err := jwt.ParseSigned(token, algs)
	if err != nil {
		return nil, invalid("malformed, or not signed with ES256")
	}
	h := tok.Headers[0]
	typ, _ := h.ExtraHeaders[jose.HeaderType].(string)
	if typ != "at+jwt" && typ != "application/at+jwt" {
		return nil, invalid("not a JWT access token")
	}
	key, err := v.key(ctx, h.KeyID)
	if err != nil {
		return nil, err
	}
	var std jwt.Claims
	var ext struct {
		Scope    string `json:"scope"`
		ClientID string `json:"client_id"`
		Act      *actor `json:"act"`
	}
	if err := tok.Claims(key, &std, &ext); err != nil {
		return nil, invalid("bad signature")
	}
	if std.Expiry == nil || std.Subject == "" {
		return nil, invalid("no expiry or no subject")
	}
	err = std.ValidateWithLeeway(jwt.Expected{Issuer: v.Issuer,
		AnyAudience: jwt.Audience{v.Resource}, Time: v.now()}, v.Leeway)
	if err != nil {
		return nil, invalid(claimError(err))
	}
	return &auth.TokenInfo{Scopes: strings.Fields(ext.Scope),
		Expiration: std.Expiry.Time(), UserID: std.Subject,
		Extra: map[string]any{"client_id": ext.ClientID,
			"actors": ext.Act.chain()}}, nil
}

In order:

  1. A verifier with no issuer or resource refuses to run. go-jose’s Expected skips any check left empty: an empty Issuer accepts every issuer, an empty audience accepts every audience. A configuration mistake would turn verification off with no error, so the verifier fails with a server error instead.
  2. The algorithm is pinned to ES256. ParseSigned takes the list of algorithms to accept, which rejects a token whose header says "alg": "none" and a token signed with HS256 using the server’s public key as the secret, the algorithm-confusion attack against libraries that let the token choose how it is verified.
  3. The token must be an access token. RFC 9068 gives access tokens the type at+jwt so a resource server can tell them from OpenID Connect ID tokens, which are JWTs from the same issuer with the same keys. Without the check, an ID token issued to some other client, for login, would be accepted as an access token.
  4. The key comes from the key ID, fetched from the authorization server’s key set; the next section covers rotation.
  5. Expiry and subject are required. go-jose checks exp only when it is present, and RFC 9068 requires it, so a token with no expiry, which would be valid forever, is refused here.
  6. Issuer and audience must match, with a small leeway for clock skew between servers. The audience check is the one rule from the start of the page.
  7. The user becomes TokenInfo.UserID, which tool handlers read: issue_file records who filed the issue. A token a gateway obtained for the user also names who acted for them, in its act claim, and the verifier passes that on as actors (see Agent gateways).

Every refusal wraps auth.ErrInvalidToken, which the SDK answers with 401, and its message names the reason without echoing the token. A failure that isn’t the token’s fault, such as the key set being unreachable, is returned unwrapped and becomes a 500, so a client doesn’t throw away a good token because a server had trouble.

TestVerifyRefuses sends each of those tokens and checks the reason it was refused:

mcpauth/resource/verify_test.go
// TestVerifyRefuses checks each way a token can fail. Every refusal
// must be an ErrInvalidToken, which the SDK answers with 401.
func TestVerifyRefuses(t *testing.T) {
	ks := newKeyServer(t)
	other, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	with := func(f func(*claims)) claims {
		c := goodClaims()
		f(&c)
		return c
	}
	cases := []struct {
		name, token, want string
	}{
		{"for another resource", ks.sign(t, with(func(c *claims) {
			c.Audience = jwt.Audience{"https://other.example.com/mcp"}
		}), "at+jwt"), "another resource"},
		{"no audience", ks.sign(t, with(func(c *claims) {
			c.Audience = nil
		}), "at+jwt"), "another resource"},
		{"another issuer", ks.sign(t, with(func(c *claims) {
			c.Issuer = "https://evil.example.com"
		}), "at+jwt"), "another authorization server"},
		{"expired past the leeway", ks.sign(t, with(func(c *claims) {
			c.Expiry = jwt.NewNumericDate(testNow.Add(-time.Minute))
		}), "at+jwt"), "expired"},
		{"no expiry", ks.sign(t, with(func(c *claims) {
			c.Expiry = nil
		}), "at+jwt"), "no expiry"},
		{"an ID token", ks.sign(t, goodClaims(), "JWT"),
			"not a JWT access token"},
		{"alg none", unsigned(t, goodClaims()), "not signed with ES256"},
		{"HS256 keyed with the public key",
			hmacWithPublicKey(t, ks, goodClaims()), "not signed with ES256"},
		{"signed by another key",
			signWith(t, other, "k1", goodClaims(), "at+jwt"), "bad signature"},
		{"garbage", "not.a.token", "malformed"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			_, err := newVerifier(ks).Verify(t.Context(), tc.token, nil)
			if !errors.Is(err, auth.ErrInvalidToken) ||
				!strings.Contains(err.Error(), tc.want) {
				t.Errorf("err = %v, want ErrInvalidToken with %q",
					err, tc.want)
			}
		})
	}
}

Keys that rotate

An authorization server rotates its signing key from time to time, publishing the new one in its key set under a new key ID. The verifier caches the key set and fetches it again when it sees a key ID it doesn’t know:

mcpauth/resource/verify.go
// key returns the public key with ID kid, fetching the authorization
// server's key set again when kid is new: that is how a rotated key
// arrives. The fast path takes only a read lock.
func (v *Verifier) key(ctx context.Context, kid string) (any, error) {
	if kid == "" {
		return nil, invalid("no key ID")
	}
	if k, ok := v.cached(kid); ok {
		return k, nil
	}
	v.fetchMu.Lock()
	defer v.fetchMu.Unlock()
	if k, ok := v.cached(kid); ok { // fetched while we waited
		return k, nil
	}
	if v.now().Sub(v.fetched) < minRefetch {
		return nil, invalid("unknown key ID")
	}
	set, err := v.fetchKeys(ctx)
	if err != nil {
		return nil, err // a 500: not the token's fault
	}
	v.mu.Lock()
	v.keys, v.fetched = set, v.now()
	v.mu.Unlock()
	if k, ok := v.cached(kid); ok {
		return k, nil
	}
	return nil, invalid("unknown key ID")
}

The fast path, a known key, takes a read lock only, so verifications don’t queue behind each other. A new key ID takes the fetch lock, checks the cache again in case another request fetched while it waited, and fetches. Fetches are spaced at least 30 seconds apart, because anyone can send a token with a made-up key ID: without the limit, a stream of such tokens would become a stream of requests to the authorization server. TestKeyRotation checks both sides: a token signed with a rotated key verifies after one fetch, and fifty tokens with made-up key IDs add no fetches at all.

Why verify locally

A JWT can be checked with a public key the server already holds, so verifying costs no network call per request. The price is revocation: a signed token stays valid until it expires, even if the user revokes access a second after it was issued. The demo’s tokens live five minutes, short enough that a revoked user loses access quickly, and the client gets a new token when the old one runs out. The alternative is token introspection (RFC 7662), where the server asks the authorization server about each token: revocation takes effect at once, at the cost of a call per request, usually cached for a short time. Some identity providers issue opaque tokens that only introspection can read. For an MCP server whose tools change things, short-lived JWTs plus a way to revoke the user’s refresh tokens is the common choice; when a revocation must take effect before the token expires, introspect.

Scopes per tool, and a challenge the client can use

RequireBearerToken checks one set of scopes for the whole endpoint. An MCP server has one endpoint, so with the SDK alone every tool needs the same grant: a client that only wants to search must still ask for permission to file issues. Per-tool scopes need a check that knows which tool a request calls, so it goes inside the SDK’s middleware, after the token is verified:

mcpauth/servers/tracker.go
// TrackerScopes are the scopes this server defines. issues:read is
// what the server advertises for a first connection; issues:write is
// asked for only when a client calls the tool that needs it.
var TrackerScopes = map[string][]string{
	"issue_search": {"issues:read"},
	"issue_file":   {"issues:read", "issues:write"},
}
mcpauth/resource/scopes.go
// ToolScopes returns middleware that checks each tools/call request
// against the scopes its tool needs. The SDK's RequireBearerToken
// checks one set of scopes for the whole endpoint; this goes inside it,
// so reading issues and filing one can need different grants. A token
// without a tool's scopes gets 403 with the challenge the MCP spec
// describes, naming every scope the call needs, which is what a client
// needs to step up. A tool with no entry is refused: the policy fails
// closed.
func ToolScopes(need map[string][]string,
	metadataURL string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter,
			r *http.Request) {
			tool, ok, err := calledTool(w, r)
			if err != nil {
				http.Error(w, "bad request body", http.StatusBadRequest)
				return
			}
			if !ok { // not a tool call: the endpoint's scopes suffice
				next.ServeHTTP(w, r)
				return
			}
			want, listed := need[tool]
			info := auth.TokenInfoFromContext(r.Context())
			if listed && info != nil && hasAll(info.Scopes, want) {
				next.ServeHTTP(w, r)
				return
			}
			w.Header().Set("WWW-Authenticate", fmt.Sprintf(
				`Bearer error="insufficient_scope", scope=%q, `+
					`resource_metadata=%q`, strings.Join(want, " "),
				metadataURL))
			http.Error(w, "insufficient scope for "+tool,
				http.StatusForbidden)
		})
	}
}

The middleware reads the JSON-RPC request, and for a tools/call it checks the token’s scopes against the tool’s. A body it can’t read as exactly one JSON-RPC message gets 400, never a pass: the SDK’s own decoder accepts some bodies a stricter parser refuses, such as a batch (an array of messages, accepted before protocol version 2025-06-18) or an object that names a key twice (the SDK keeps the last), and reads them as a tool call. Before companion code v1.9 the check passed such bodies on, and a token that could only read issues filed them that way; TestToolScopesReadsEveryBody in servers/tracker_test.go sends each body and checks that nothing is filed. A tool missing from the map is refused, so a tool added later without a scope can’t be called by everyone by default.

The second thing it adds is the response. The MCP specification says a server refusing a call for lack of scope should answer 403 with error="insufficient_scope", every scope the operation needs, and the metadata address. That is what lets a client step up: ask the user for the extra scope, get a new token, and retry. The SDK’s own middleware answers 403 without error="insufficient_scope", and the SDK’s client only steps up when it sees it. TestStepUp shows the result. A server starts by requiring issues:read and then, as after a deploy, issues:write as well; with the SDK’s middleware alone the client authorizes once and then fails, and with ToolScopes it authorizes a second time and the call succeeds:

mcpauth/flow_test.go
// TestStepUp checks the claim the guide makes about the SDK: its
// client steps up only on a 403 that says error="insufficient_scope",
// and its RequireBearerToken middleware doesn't say so. The server here
// starts by requiring issues:read for everything, and then, as after a
// deploy, issues:write too. With the SDK's middleware alone, the client
// gives up; with ToolScopes' challenge, it asks the user for the new
// scope and carries on.
func TestStepUp(t *testing.T) {
	for _, tc := range []struct {
		name           string
		challenge      bool // answer with ToolScopes' challenge
		wantAuthorizes int32
		wantErr        bool
	}{
		{"SDK middleware alone", false, 1, true},
		{"with the insufficient_scope challenge", true, 2, false},

When it steps up, the SDK’s client asks for the union of the scopes it already had and the ones challenged, so the new token can still do what the old one could. The scopes here are flat; a server whose scopes form a hierarchy, where a broader scope implies narrower ones, has to account for that when it decides a token is enough, which the specification requires.

The tool handlers themselves never see a token: by the time a call reaches them, the middleware has checked who sent it and what they may do. That keeps authorization out of the code the model’s arguments flow into, and out of the model’s reach entirely: the model asks for a tool, and the harness and the server decide whether the user it acts for may use it.

The client: what the SDK does and what it leaves to you

The client’s side is mostly the SDK’s AuthorizationCodeHandler, attached to the transport. On a 401, or a 403 with insufficient_scope, the transport calls it, and it:

  • parses WWW-Authenticate and fetches the Protected Resource Metadata, trying the address in the header first, then the path-specific well-known address, then the root, and checks that resource matches the URL it called;
  • finds the authorization server’s metadata, trying the RFC 8414 address before OpenID Connect discovery, and checks that its issuer matches the URL it was fetched from;
  • refuses an authorization server whose metadata doesn’t list code_challenge_methods_supported, since the specification forbids proceeding without PKCE;
  • chooses how to identify the client, in the specification’s order: a pre-registered client, then a Client ID Metadata Document, then Dynamic Client Registration;
  • builds the authorization URL with an S256 PKCE challenge, a random state, the scopes, and resource;
  • checks state and iss on the response, and redeems the code with the verifier and resource again.

Configuring it takes the client’s identity, its redirect address, and one function:

mcpauth/client.go
// NewOAuthHandler returns the SDK's authorization code handler for a
// client identified by a Client ID Metadata Document: clientID is the
// HTTPS URL of that document, and redirect is a loopback URL listed in
// it. On a 401 or a 403 with insufficient_scope, the SDK discovers the
// authorization server, sends the user there with PKCE and the
// resource parameter, checks the iss in the response, and redeems the
// code; fetch is the part only the application can do, getting the
// user to the authorization URL and the code back.
func NewOAuthHandler(clientID, redirect string,
	fetch auth.AuthorizationCodeFetcher,
	c *http.Client) (*auth.AuthorizationCodeHandler, error) {
	cimd := &auth.ClientIDMetadataDocumentConfig{URL: clientID}
	h, err := auth.NewAuthorizationCodeHandler(
		&auth.AuthorizationCodeHandlerConfig{
			ClientIDMetadataDocumentConfig: cimd,
			RedirectURL:                    redirect,
			AuthorizationCodeFetcher:       fetch,
			Client:                         c,
		})
	if err != nil {
		return nil, fmt.Errorf("oauth handler: %w", err)
	}
	return h, nil
}

The function is the part only an application can do: getting the user to the authorization URL and the code back. For a program on the user’s machine, that means listening on a loopback address and opening the browser:

mcpauth/client.go
// LoopbackFetcher returns an AuthorizationCodeFetcher for a program on
// the user's machine: it listens on the redirect URL's loopback
// address, has open send the user's browser to the authorization URL,
// and waits for the one redirect that comes back. The SDK checks state
// and iss; an error response is reported without its description,
// since the spec forbids acting on or showing an error whose issuer
// hasn't been checked.
func LoopbackFetcher(redirect string,
	open func(authURL string) error) auth.AuthorizationCodeFetcher {
	return func(ctx context.Context,
		args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) {
		u, err := url.Parse(redirect)
		if err != nil {
			return nil, fmt.Errorf("loopback: %w", err)
		}
		ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", u.Host)
		if err != nil {
			return nil, fmt.Errorf("loopback: %w", err)
		}
		got := make(chan url.Values, 1)
		callback := func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path != u.Path {
				http.NotFound(w, r)
				return
			}
			select {
			case got <- r.URL.Query(): // the first redirect only
			default:
			}
			fmt.Fprintln(w, "Done. You can close this tab.")
		}
		srv := &http.Server{Handler: http.HandlerFunc(callback),
			ReadHeaderTimeout: 5 * time.Second}
		go srv.Serve(ln) //nolint:errcheck // stopped by Shutdown below
		defer func() { _ = srv.Shutdown(context.WithoutCancel(ctx)) }()
		if err := open(args.URL); err != nil {
			return nil, fmt.Errorf("loopback: open browser: %w", err)
		}
		select {
		case q := <-got:
			if q.Get("error") != "" {
				return nil, errNotGranted
			}
			return &auth.AuthorizationResult{Code: q.Get("code"),
				State: q.Get("state"), Iss: q.Get("iss")}, nil
		case <-ctx.Done():
			return nil, fmt.Errorf("loopback: %w", ctx.Err())
		}
	}
}

It takes the first redirect only, and it doesn’t pass on an error’s description. The specification forbids a client from acting on or displaying an error response before checking which authorization server sent it, and the issuer check happens after this function returns.

Client ID Metadata Documents

A client and an MCP server usually have no prior relationship, so the client needs a way to identify itself to an authorization server it has never seen. The specification used to point to Dynamic Client Registration, where each client registers itself with each authorization server and gets back an ID; it is now deprecated, kept for servers that support nothing newer. Its replacement, a Client ID Metadata Document, makes the client’s ID an HTTPS URL on the client’s own site, pointing to a JSON document that describes it:

mcpauth/client.go
// ClientMetadata serves a Client ID Metadata Document: the JSON an
// authorization server fetches from the URL a client uses as its
// client_id. In production it is a static file on the client's own
// HTTPS site; its client_id must be that URL exactly.
func ClientMetadata(clientID, name string,
	redirects []string) http.Handler {
	doc := map[string]any{
		"client_id":                  clientID,
		"client_name":                name,
		"redirect_uris":              redirects,
		"grant_types":                []string{"authorization_code"},
		"response_types":             []string{"code"},
		"token_endpoint_auth_method": "none", // a public client: no secret
	}
	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.MarshalWrite(w, doc)
	})
}

When an authorization request arrives with a URL as its client_id, the authorization server fetches the document, checks that its client_id is that URL exactly, and checks the request’s redirect address against redirect_uris. Nothing is registered in advance, the same ID works with every authorization server, and the client’s site vouches for it, which is visible in the demo’s log as the authorization server’s fetch of /client.json during each authorization.

One weakness remains, and the specification says so: a document can list a loopback redirect address, and nothing stops another program on the user’s machine from listening there. An authorization server should show the redirect address’s host on its consent page and warn when it is loopback-only.

Two attacks the client refuses

A mix-up attack tricks a client that talks to two authorization servers into sending a code from the honest one to the attacker’s. The defense, RFC 9207, has the authorization server put its issuer in the redirect, and the client compare it with the issuer it recorded before sending the user there. TestMixUp changes the iss in the response, and the SDK refuses to redeem the code.

TestImpersonatedMetadata is the second, described above: metadata that names another server is discarded before any authorization starts. Its log shows what the SDK does next: after discarding the metadata, it falls back to an older version of the specification and looks for an authorization server at the MCP server’s own address. That fallback can only produce a token for the server the client is calling, so the victim’s tokens stay safe, but it means a client keeps trying after the metadata check fails.

Never pass a token on

Step 4 of the demo is the attack the audience rule exists for: the token the client got for the first MCP server, sent to the second.

mcpauth/demo.go
// replay sends the client's access token, issued for the first MCP
// server, to the second, as a server that passed tokens through would.
// The second server refuses it: the token's audience is the first.
func replay(ctx context.Context, out io.Writer,
	h *auth.AuthorizationCodeHandler, other string) error {
	ts, err := h.TokenSource(ctx)
	if err != nil {
		return fmt.Errorf("replay: %w", err)
	}
	tok, err := ts.Token()
	if err != nil {
		return fmt.Errorf("replay: %w", err)
	}
	body := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, other,
		strings.NewReader(body))
	if err != nil {
		return fmt.Errorf("replay: %w", err)
	}
	req.Header.Set("Authorization", "Bearer "+tok.AccessToken)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json, text/event-stream")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return fmt.Errorf("replay: %w", err)
	}
	defer resp.Body.Close()
	why, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
	fmt.Fprintf(out, "   other: %d %s\n", resp.StatusCode,
		strings.TrimSpace(string(why)))
	return nil
}

The second server trusts the same authorization server, and the token’s signature, issuer, and expiry are all valid. Its audience is the first server, so the second refuses it: 401 invalid token: issued for another resource.

The specification makes this a rule for servers as well as a check: an MCP server must not accept tokens meant for others, and must not pass on the token it received. An MCP server that calls an upstream API, a ticketing system behind an issue tool, say, is a client of that API, and it uses a token issued for that API, obtained through its own grant or by token exchange, as Agent identity describes, and as an MCP gateway does for every server behind it.

Why this way and not another

  • API keys in an environment variable. That is what the specification says for stdio, and it is right for a server on the user’s own machine. For a remote server with many users, a static key identifies no user, carries no scopes, never expires, and can’t be revoked for one person without breaking everyone.
  • One token for all of an agent’s servers. Simpler for the client, and it hands every server the power to act at every other one. Audience binding costs one authorization per server and contains each compromise to one server.
  • Scopes for the whole endpoint. What the SDK supports alone. It makes every client ask for everything up front, and it means a read-only user’s token can file issues.
  • Letting the model decide. The model chooses tools; it doesn’t hold tokens or decide what a user may do. Authorization happens in middleware, before a tool handler runs, on a token the model never sees, so no prompt can talk its way past it.
  • Writing the client flow by hand. Possible, and instructive, but the SDK already does discovery, PKCE, the issuer check, and the scope union, and tracks the specification as it changes. Read what it checks, as this page does, and test the parts it leaves to you.
  • Dynamic Client Registration. Deprecated in the current specification. A Client ID Metadata Document needs no registration endpoint and works with every authorization server.

With a real identity provider

The example’s authorization server is a test double that approves every request. In production the authorization server is your identity provider, and the server’s configuration becomes its values: Issuer is the provider’s issuer identifier, and JWKSURL comes from its metadata. Before trusting the verifier with a provider, check what it puts in a token, by decoding one:

  • The audience. Some providers honor the resource parameter and write it into aud; others ignore it and use an audience configured per API. Either way, the MCP server must find its own canonical URI there, or the audience check will refuse every token.
  • The type. Not every provider sets typ to at+jwt. If yours doesn’t, keep the protection the check gives by another means, such as a dedicated audience no ID token will carry, and change the check rather than delete it.
  • The signing algorithm. Pin the one the provider uses; RS256 is common.
  • Opaque tokens. If the provider’s access tokens aren’t JWTs, use its introspection endpoint instead of local verification.
  • Support for the MCP flow. The client needs the provider to publish RFC 8414 or OpenID Connect metadata with code_challenge_methods_supported, and, for Client ID Metadata Documents, client_id_metadata_document_supported. Without it, register the client in advance.

The code here was tested against its own authorization server only. Run the same tests against your provider’s test tenant before relying on it.

Mistakes to avoid

  • Leaving an expected value empty. JWT libraries commonly skip checks with no expected value. Refuse to verify with no issuer or audience configured.
  • Letting the token choose its algorithm. Pin the algorithms you accept.
  • Accepting any JWT from the issuer. ID tokens are JWTs from the same issuer. Check typ, and the audience.
  • Comparing the audience loosely. Use the exact canonical URI. The SDK’s oauthex.MatchesResource tolerates a trailing slash and nothing else, which is as loose as it should get.
  • Fetching keys on every unknown key ID. Space the fetches, or anyone can make your server hammer the authorization server.
  • Logging the token. Tokens in logs are tokens anyone with the logs can use. Log the subject, client, and token ID instead.
  • Forwarding the token upstream. Get a token for the upstream API.
  • Asking for every scope at the first connection. Start with the least, and step up.

Try it

From the code/mcpauth directory of a clone of the companion repository:

terminal
$ go run .
$ go test -race ./...
  1. In resource/verify.go, delete the check on typ and run go test ./resource -run TestVerifyRefuses. The “an ID token” case fails: the verifier now accepts a token issued for login.
  2. In resource/server.go, remove the line that wraps the handler in ToolScopes, and run go test -run TestDemo. Step 3 no longer steps up, because the read-only token can now file an issue.
  3. In resource/verify.go, set minRefetch to zero and run go test ./resource -run TestKeyRotation: every made-up key ID now costs a request to the authorization server.

Undo your edits with git restore . in the code directory. The specification is still changing; the version this page follows is 2026-07-28.