
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.
On the agent compass Stage 3 of 4 · Run the toolsAn 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:
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
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.
// 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:
// 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:
// 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:
// 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:
- A verifier with no issuer or resource refuses to run. go-jose’s
Expectedskips any check left empty: an emptyIssueraccepts 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. - The algorithm is pinned to ES256.
ParseSignedtakes 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. - The token must be an access token. RFC 9068 gives access tokens the type
at+jwtso 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. - The key comes from the key ID, fetched from the authorization server’s key set; the next section covers rotation.
- Expiry and subject are required. go-jose checks
exponly when it is present, and RFC 9068 requires it, so a token with no expiry, which would be valid forever, is refused here. - 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.
- The user becomes
TokenInfo.UserID, which tool handlers read:issue_filerecords who filed the issue. A token a gateway obtained for the user also names who acted for them, in itsactclaim, and the verifier passes that on asactors(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:
// 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:
// 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:
// 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"},
}
// 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:
// 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-Authenticateand fetches the Protected Resource Metadata, trying the address in the header first, then the path-specific well-known address, then the root, and checks thatresourcematches the URL it called; - finds the authorization server’s metadata, trying the RFC 8414 address before OpenID Connect discovery, and checks that its
issuermatches 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, andresource; - checks
stateandisson the response, and redeems the code with the verifier andresourceagain.
Configuring it takes the client’s identity, its redirect address, and one function:
// 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:
// 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:
// 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.
// 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
resourceparameter and write it intoaud; 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
typtoat+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.MatchesResourcetolerates 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:
$ go run .
$ go test -race ./...
- In
resource/verify.go, delete the check ontypand rungo test ./resource -run TestVerifyRefuses. The “an ID token” case fails: the verifier now accepts a token issued for login. - In
resource/server.go, remove the line that wraps the handler inToolScopes, and rungo test -run TestDemo. Step 3 no longer steps up, because the read-only token can now file an issue. - In
resource/verify.go, setminRefetchto zero and rungo 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.
func NewServer(c Config) (http.Handler, error)
NewServer returns the handler for an MCP server that only answers requests carrying an access token issued for it.
NewServer returns the handler for an MCP server that only answers requests carrying an access token issued for it. func NewServer(c Config) (http.Handler, error). In mcpauth/resource/server.go, line 44.
type Config struct {
Resource string // canonical URI, such as https://mcp.example.com/mcp
Issuer string // the one authorization server it trusts
JWKSURL string
Client *http.Client // for fetching the authorization server's keys
MCP *mcp.Server // the server's tools
// ToolScopes maps each tool to the scopes a call needs, and
// Starting is the scopes a first connection needs: the least, as
// the server's metadata advertises them.
// ...
}
Config describes a protected MCP server.
Config describes a protected MCP server. type Config struct { Resource string // canonical URI, such as https://mcp.example.com/mcp Issuer string // the one authorization server it trusts JWKSURL string Client *http.Client // for fetching the authorization server's keys MCP *mcp.Server // the server's tools // ToolScopes maps each tool to the scopes a call needs, and // Starting is the scopes a first connection needs: the least, as // the server's metadata advertises them. // ... }. In mcpauth/resource/server.go, line 19.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
A Handler responds to an HTTP request.
A Handler responds to an HTTP request. type Handler interface { ServeHTTP(ResponseWriter, *Request) }. Documented at pkg.go.dev, net/http.Handler.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
package url ("net/url")
Package url parses URLs and implements query escaping.
Package url parses URLs and implements query escaping. package url ("net/url"). Documented at pkg.go.dev, net/url.
func Parse(rawURL string) (*URL, error)
Parse parses a raw url into a [URL] structure.
Parse parses a raw url into a [URL] structure. func Parse(rawURL string) (*URL, error). Documented at pkg.go.dev, net/url.Parse.
field Resource string
canonical URI, such as https://mcp.example.com/mcp
canonical URI, such as https://mcp.example.com/mcp field Resource string. In mcpauth/resource/server.go, line 20.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
field Path string
path (relative paths may omit leading slash)
path (relative paths may omit leading slash) field Path string. Documented at pkg.go.dev, net/url.URL.Path.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
var wellKnown string
var wellKnown string. In mcpauth/resource/server.go, line 50.
var metadataURL string
var metadataURL string. In mcpauth/resource/server.go, line 51.
field Scheme string
field Scheme string. Documented at pkg.go.dev, net/url.URL.Scheme.
field Host string
"host" or "host:port" (see Hostname and Port methods)
"host" or "host:port" (see Hostname and Port methods) field Host string. Documented at pkg.go.dev, net/url.URL.Host.
var v *Verifier
var v *Verifier. In mcpauth/resource/server.go, line 52.
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
// ...
}
A Verifier checks the access tokens an MCP server receives: JWT access tokens (RFC 9068) signed by one authorization server, for this server only.
A Verifier checks the access tokens an MCP server receives: JWT access tokens (RFC 9068) signed by one authorization server, for this server only. 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 // ... }. In mcpauth/resource/verify.go, line 25.
field Issuer string
the authorization server's issuer identifier
the authorization server's issuer identifier field Issuer string. In mcpauth/resource/verify.go, line 26.
field Issuer string
the one authorization server it trusts
the one authorization server it trusts field Issuer string. In mcpauth/resource/server.go, line 21.
field Resource string
this server's canonical URI: the audience to expect
this server's canonical URI: the audience to expect field Resource string. In mcpauth/resource/verify.go, line 27.
field JWKSURL string
where the authorization server publishes its keys
where the authorization server publishes its keys field JWKSURL string. In mcpauth/resource/verify.go, line 28.
field JWKSURL string
field JWKSURL string. In mcpauth/resource/server.go, line 22.
field Client *http.Client
field Client *http.Client. In mcpauth/resource/verify.go, line 29.
field Client *http.Client
for fetching the authorization server's keys
for fetching the authorization server's keys field Client *http.Client. In mcpauth/resource/server.go, line 23.
var opts *mcp.StreamableHTTPOptions
var opts *mcp.StreamableHTTPOptions. In mcpauth/resource/server.go, line 54.
package mcp ("github.com/modelcontextprotocol/go-sdk/mcp")
package mcp ("github.com/modelcontextprotocol/go-sdk/mcp").
type StreamableHTTPOptions struct {
// Stateless controls whether the session is 'stateless'.
//
// A stateless server does not read or set the Mcp-Session-Id header, and
// uses a temporary session with default initialization parameters for each
// request. [ServerOptions.GetSessionID] is not consulted. Any
// server->client request is rejected immediately as there's no way for the
// client to respond. Server->Client notifications may reach the client if
// they are made in the context of an incoming request, as described in the
// documentation for [StreamableServerTransport].
// ...
}
StreamableHTTPOptions configures the StreamableHTTPHandler.
github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions
StreamableHTTPOptions configures the StreamableHTTPHandler. type StreamableHTTPOptions struct { // Stateless controls whether the session is 'stateless'. // // A stateless server does not read or set the Mcp-Session-Id header, and // uses a temporary session with default initialization parameters for each // request. [ServerOptions.GetSessionID] is not consulted. Any // server->client request is rejected immediately as there's no way for the // client to respond. Server->Client notifications may reach the client if // they are made in the context of an incoming request, as described in the // documentation for [StreamableServerTransport]. // ... }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions.
field Stateless bool
Stateless controls whether the session is 'stateless'.
github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions.Stateless
Stateless controls whether the session is 'stateless'. field Stateless bool. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions.Stateless.
const true = 0 == 0
Untyped bool.
Untyped bool. const true = 0 == 0. Documented at pkg.go.dev, builtin.true.
field PropagateRequestCancellation bool
PropagateRequestCancellation, when true, ties the in-flight handler context to the originating HTTP request's context.
github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions.PropagateRequestCancellation
PropagateRequestCancellation, when true, ties the in-flight handler context to the originating HTTP request's context. field PropagateRequestCancellation bool. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/mcp.StreamableHTTPOptions.PropagateRequestCancellation.
var h http.Handler
var h http.Handler. In mcpauth/resource/server.go, line 56.
func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler
NewStreamableHTTPHandler returns a new [StreamableHTTPHandler].
github.com/modelcontextprotocol/go-sdk/mcp.NewStreamableHTTPHandler
NewStreamableHTTPHandler returns a new [StreamableHTTPHandler]. func NewStreamableHTTPHandler(getServer func(*http.Request) *Server, opts *StreamableHTTPOptions) *StreamableHTTPHandler. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/mcp.NewStreamableHTTPHandler.
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
// For client requests, an empty string means GET.
Method string
// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// ...
}
A Request represents an HTTP request received by a server or to be sent by a client.
A Request represents an HTTP request received by a server or to be sent by a client. type Request struct { // Method specifies the HTTP method (GET, POST, PUT, etc.). // For client requests, an empty string means GET. Method string // URL specifies either the URI being requested (for server // requests) or the URL to access (for client requests). // // For server requests, the URL is parsed from the URI // supplied on the Request-Line as stored in RequestURI. For // ... }. Documented at pkg.go.dev, net/http.Request.
type Server struct {
// fixed at creation
impl *Implementation
opts ServerOptions
// protocolVersions is the descending-ordered list of protocol versions
// this server advertises and negotiates: [supportedProtocolVersions],
// narrowed by [ServerOptions.SupportedProtocolVersions].
protocolVersions []string
mu sync.Mutex
// ...
}
A Server is an instance of an MCP server.
github.com/modelcontextprotocol/go-sdk/mcp.Server
A Server is an instance of an MCP server. type Server struct { // fixed at creation impl *Implementation opts ServerOptions // protocolVersions is the descending-ordered list of protocol versions // this server advertises and negotiates: [supportedProtocolVersions], // narrowed by [ServerOptions.SupportedProtocolVersions]. protocolVersions []string mu sync.Mutex // ... }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/mcp.Server.
field MCP *mcp.Server
the server's tools
the server's tools field MCP *mcp.Server. In mcpauth/resource/server.go, line 24.
func ToolScopes(need map[string][]string,
metadataURL string) func(http.Handler) http.Handler
ToolScopes returns middleware that checks each tools/call request against the scopes its tool needs.
ToolScopes returns middleware that checks each tools/call request against the scopes its tool needs. func ToolScopes(need map[string][]string, metadataURL string) func(http.Handler) http.Handler. In mcpauth/resource/scopes.go, line 25.
field ToolScopes map[string][]string
ToolScopes maps each tool to the scopes a call needs, and Starting is the scopes a first connection needs: the least, as the server's metadata advertises them.
ToolScopes maps each tool to the scopes a call needs, and Starting is the scopes a first connection needs: the least, as the server's metadata advertises them. field ToolScopes map[string][]string. In mcpauth/resource/server.go, line 29.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler
RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier.
github.com/modelcontextprotocol/go-sdk/auth.RequireBearerToken
RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier. func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.RequireBearerToken.
func (v *Verifier) Verify(ctx context.Context, token string,
_ *http.Request) (*auth.TokenInfo, error)
Verify checks token and returns what the server may rely on: who the user is, what they granted, and until when.
Verify checks token and returns what the server may rely on: who the user is, what they granted, and until when. func (v *Verifier) Verify(ctx context.Context, token string, _ *http.Request) (*auth.TokenInfo, error). In mcpauth/resource/verify.go, line 51.
type RequireBearerTokenOptions struct {
// The URL for the resource server metadata OAuth flow, to be returned as part
// of the WWW-Authenticate header.
ResourceMetadataURL string
// The required scopes.
Scopes []string
// AllowMissingExpiration opts the middleware out of the
// `tokenInfo.Expiration.IsZero()` reject. Default false preserves the
// existing strict behaviour (every TokenInfo must carry an Expiration).
//
// ...
}
RequireBearerTokenOptions are options for [RequireBearerToken].
github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions
RequireBearerTokenOptions are options for [RequireBearerToken]. type RequireBearerTokenOptions struct { // The URL for the resource server metadata OAuth flow, to be returned as part // of the WWW-Authenticate header. ResourceMetadataURL string // The required scopes. Scopes []string // AllowMissingExpiration opts the middleware out of the // `tokenInfo.Expiration.IsZero()` reject. Default false preserves the // existing strict behaviour (every TokenInfo must carry an Expiration). // // ... }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions.
field ResourceMetadataURL string
The URL for the resource server metadata OAuth flow, to be returned as part of the WWW-Authenticate header.
github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions.ResourceMetadataURL
The URL for the resource server metadata OAuth flow, to be returned as part of the WWW-Authenticate header. field ResourceMetadataURL string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions.ResourceMetadataURL.
field Scopes []string
The required scopes.
github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions.Scopes
The required scopes. field Scopes []string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.RequireBearerTokenOptions.Scopes.
field Starting []string
field Starting []string. In mcpauth/resource/server.go, line 30.
var mux *http.ServeMux
var mux *http.ServeMux. In mcpauth/resource/server.go, line 61.
func NewServeMux() *ServeMux
NewServeMux allocates and returns a new [ServeMux].
NewServeMux allocates and returns a new [ServeMux]. func NewServeMux() *ServeMux. Documented at pkg.go.dev, net/http.NewServeMux.
var meta http.Handler
var meta http.Handler. In mcpauth/resource/server.go, line 62.
func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler
ProtectedResourceMetadataHandler returns an http.Handler that serves OAuth 2.0 protected resource metadata (RFC 9728) with CORS support.
github.com/modelcontextprotocol/go-sdk/auth.ProtectedResourceMetadataHandler
ProtectedResourceMetadataHandler returns an http.Handler that serves OAuth 2.0 protected resource metadata (RFC 9728) with CORS support. func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.ProtectedResourceMetadataHandler.
func Metadata(resource, issuer string,
starting []string) *oauthex.ProtectedResourceMetadata
Metadata is the server's Protected Resource Metadata.
Metadata is the server's Protected Resource Metadata. func Metadata(resource, issuer string, starting []string) *oauthex.ProtectedResourceMetadata. In mcpauth/resource/server.go, line 77.
func (mux *ServeMux) Handle(pattern string, handler Handler)
Handle registers the handler for the given pattern.
Handle registers the handler for the given pattern. func (mux *ServeMux) Handle(pattern string, handler Handler). Documented at pkg.go.dev, net/http.ServeMux.Handle.
var resource string
var resource string. In mcpauth/resource/server.go, line 77.
var issuer string
var issuer string. In mcpauth/resource/server.go, line 77.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
var starting []string
var starting []string. In mcpauth/resource/server.go, line 78.
package oauthex ("github.com/modelcontextprotocol/go-sdk/oauthex")
package oauthex ("github.com/modelcontextprotocol/go-sdk/oauthex").
type ProtectedResourceMetadata struct {
// Resource (resource) is the protected resource's resource identifier.
// Required.
Resource string `json:"resource"`
// AuthorizationServers (authorization_servers) is an optional slice containing a list of
// OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be
// used with this protected resource.
AuthorizationServers []string `json:"authorization_servers,omitempty"`
// ...
}
ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource, as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html.
github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata
ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource, as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html. type ProtectedResourceMetadata struct { // Resource (resource) is the protected resource's resource identifier. // Required. Resource string `json:"resource"` // AuthorizationServers (authorization_servers) is an optional slice containing a list of // OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be // used with this protected resource. AuthorizationServers []string `json:"authorization_servers,omitempty"` // ... }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.
field Resource string `json:"resource"`
Resource (resource) is the protected resource's resource identifier.
github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.Resource
Resource (resource) is the protected resource's resource identifier. field Resource string `json:"resource"`. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.Resource.
field AuthorizationServers []string `json:"authorization_servers,omitempty"`
github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.AuthorizationServers
field AuthorizationServers []string `json:"authorization_servers,omitempty"`. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.AuthorizationServers.
field ScopesSupported []string `json:"scopes_supported,omitempty"`
ScopesSupported (scopes_supported) is a recommended slice containing a list of scope values (as defined in RFC 6749) used in authorization requests to request access to this protected resource.
github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.ScopesSupported
ScopesSupported (scopes_supported) is a recommended slice containing a list of scope values (as defined in RFC 6749) used in authorization requests to request access to this protected resource. field ScopesSupported []string `json:"scopes_supported,omitempty"`. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.ScopesSupported.
field BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
BearerMethodsSupported (bearer_methods_supported) is an optional slice containing a list of the supported methods of sending an OAuth 2.0 bearer token to the protected resource.
github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.BearerMethodsSupported
BearerMethodsSupported (bearer_methods_supported) is an optional slice containing a list of the supported methods of sending an OAuth 2.0 bearer token to the protected resource. field BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.ProtectedResourceMetadata.BearerMethodsSupported.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper
// CheckRedirect specifies the policy for handling redirects.
// If CheckRedirect is not nil, the client calls it before
// following an HTTP redirect. The arguments req and via are
// the upcoming request and the requests made already, oldest
// ...
}
A Client is an HTTP client.
A Client is an HTTP client. type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // ... }. Documented at pkg.go.dev, net/http.Client.
field Leeway time.Duration
clock skew allowed on exp, nbf, and iat
clock skew allowed on exp, nbf, and iat field Leeway time.Duration. In mcpauth/resource/verify.go, line 30.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count.
A Duration represents the elapsed time between two instants as an int64 nanosecond count. type Duration int64. Documented at pkg.go.dev, time.Duration.
field Now func() time.Time
field Now func() time.Time. In mcpauth/resource/verify.go, line 31.
type Time struct {
// wall and ext encode the wall time seconds, wall time nanoseconds,
// and optional monotonic clock reading in nanoseconds.
//
// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
// The nanoseconds field is in the range [0, 999999999].
// If the hasMonotonic bit is 0, then the 33-bit field must be zero
// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
// ...
}
A Time represents an instant in time with nanosecond precision.
A Time represents an instant in time with nanosecond precision. type Time struct { // wall and ext encode the wall time seconds, wall time nanoseconds, // and optional monotonic clock reading in nanoseconds. // // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic), // a 33-bit seconds field, and a 30-bit wall time nanoseconds field. // The nanoseconds field is in the range [0, 999999999]. // If the hasMonotonic bit is 0, then the 33-bit field must be zero // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext. // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit // ... }. Documented at pkg.go.dev, time.Time.
field mu sync.RWMutex
field mu sync.RWMutex. In mcpauth/resource/verify.go, line 33.
package sync ("sync")
Package sync provides basic synchronization primitives such as mutual exclusion locks.
Package sync provides basic synchronization primitives such as mutual exclusion locks. package sync ("sync"). Documented at pkg.go.dev, sync.
type RWMutex struct {
w Mutex // held if there are pending writers
writerSem uint32 // semaphore for writers to wait for completing readers
readerSem uint32 // semaphore for readers to wait for completing writers
readerCount atomic.Int32 // number of pending readers
readerWait atomic.Int32 // number of departing readers
}
A RWMutex is a reader/writer mutual exclusion lock.
A RWMutex is a reader/writer mutual exclusion lock. type RWMutex struct { w Mutex // held if there are pending writers writerSem uint32 // semaphore for writers to wait for completing readers readerSem uint32 // semaphore for readers to wait for completing writers readerCount atomic.Int32 // number of pending readers readerWait atomic.Int32 // number of departing readers }. Documented at pkg.go.dev, sync.RWMutex.
field keys jose.JSONWebKeySet
field keys jose.JSONWebKeySet. In mcpauth/resource/verify.go, line 34.
package jose ("github.com/go-jose/go-jose/v4")
package jose ("github.com/go-jose/go-jose/v4").
type JSONWebKeySet struct {
Keys []JSONWebKey `json:"keys"`
}
JSONWebKeySet represents a JWK Set object.
github.com/go-jose/go-jose/v4.JSONWebKeySet
JSONWebKeySet represents a JWK Set object. type JSONWebKeySet struct { Keys []JSONWebKey `json:"keys"` }. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.JSONWebKeySet.
field fetchMu sync.Mutex
one key fetch at a time
one key fetch at a time field fetchMu sync.Mutex. In mcpauth/resource/verify.go, line 35.
type Mutex struct {
_ noCopy
mu isync.Mutex
}
A Mutex is a mutual exclusion lock.
A Mutex is a mutual exclusion lock. type Mutex struct { _ noCopy mu isync.Mutex }. Documented at pkg.go.dev, sync.Mutex.
field fetched time.Time
when the keys were last fetched
when the keys were last fetched field fetched time.Time. In mcpauth/resource/verify.go, line 36.
var v *Verifier
var v *Verifier. In mcpauth/resource/verify.go, line 51.
var ctx context.Context
var ctx context.Context. In mcpauth/resource/verify.go, line 51.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
var token string
var token string. In mcpauth/resource/verify.go, line 51.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
type TokenInfo struct {
Scopes []string
Expiration time.Time
// UserID is an optional identifier for the authenticated user.
// If set by a TokenVerifier, it can be used by transports to prevent
// session hijacking by ensuring that all requests for a given session
// come from the same user.
UserID string
Extra map[string]any
}
TokenInfo holds information from a bearer token.
github.com/modelcontextprotocol/go-sdk/auth.TokenInfo
TokenInfo holds information from a bearer token. type TokenInfo struct { Scopes []string Expiration time.Time // UserID is an optional identifier for the authenticated user. // If set by a TokenVerifier, it can be used by transports to prevent // session hijacking by ensuring that all requests for a given session // come from the same user. UserID string Extra map[string]any }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func New(text string) error
New returns an error that formats as the given text.
New returns an error that formats as the given text. func New(text string) error. Documented at pkg.go.dev, errors.New.
var algs []jose.SignatureAlgorithm
var algs []jose.SignatureAlgorithm. In mcpauth/resource/verify.go, line 56.
type SignatureAlgorithm string
SignatureAlgorithm represents a signature (or MAC) algorithm.
github.com/go-jose/go-jose/v4.SignatureAlgorithm
SignatureAlgorithm represents a signature (or MAC) algorithm. type SignatureAlgorithm string. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.SignatureAlgorithm.
const ES256 = SignatureAlgorithm("ES256")
ECDSA using P-256 and SHA-256
github.com/go-jose/go-jose/v4.ES256
ECDSA using P-256 and SHA-256 const ES256 = SignatureAlgorithm("ES256"). Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.ES256.
var tok *jwt.JSONWebToken
var tok *jwt.JSONWebToken. In mcpauth/resource/verify.go, line 57.
package jwt ("github.com/go-jose/go-jose/v4/jwt")
package jwt ("github.com/go-jose/go-jose/v4/jwt").
func ParseSigned(s string, signatureAlgorithms []jose.SignatureAlgorithm) (*JSONWebToken, error)
ParseSigned parses token from JWS form.
github.com/go-jose/go-jose/v4/jwt.ParseSigned
ParseSigned parses token from JWS form. func ParseSigned(s string, signatureAlgorithms []jose.SignatureAlgorithm) (*JSONWebToken, error). Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.ParseSigned.
func invalid(why string) error
invalid is a token the server refuses, with a reason that is safe to show: it never includes the token.
mcpauth/resource/verify.go:211
invalid is a token the server refuses, with a reason that is safe to show: it never includes the token. func invalid(why string) error. In mcpauth/resource/verify.go, line 211.
var h jose.Header
var h jose.Header. In mcpauth/resource/verify.go, line 61.
field Headers []jose.Header
github.com/go-jose/go-jose/v4/jwt.JSONWebToken.Headers
field Headers []jose.Header. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.JSONWebToken.Headers.
field ExtraHeaders map[HeaderKey]interface{}
At parse time, each header parameter with a name other than "kid", "jwk", "alg", "nonce", or "x5c" will have its value passed to [json.Unmarshal] to unmarshal it into an interface value.
github.com/go-jose/go-jose/v4.Header.ExtraHeaders
At parse time, each header parameter with a name other than "kid", "jwk", "alg", "nonce", or "x5c" will have its value passed to [json.Unmarshal] to unmarshal it into an interface value. field ExtraHeaders map[HeaderKey]interface{}. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.Header.ExtraHeaders.
const HeaderType = "typ"
string
github.com/go-jose/go-jose/v4.HeaderType
string const HeaderType = "typ". Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.HeaderType.
func (v *Verifier) key(ctx context.Context, kid string) (any, error)
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.
mcpauth/resource/verify.go:117
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. func (v *Verifier) key(ctx context.Context, kid string) (any, error). In mcpauth/resource/verify.go, line 117.
field KeyID string
github.com/go-jose/go-jose/v4.Header.KeyID
field KeyID string. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4.Header.KeyID.
var std jwt.Claims
var std jwt.Claims. In mcpauth/resource/verify.go, line 70.
type Claims struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience Audience `json:"aud,omitempty"`
Expiry *NumericDate `json:"exp,omitempty"`
NotBefore *NumericDate `json:"nbf,omitempty"`
IssuedAt *NumericDate `json:"iat,omitempty"`
ID string `json:"jti,omitempty"`
}
Claims represents public claim values (as specified in RFC 7519).
github.com/go-jose/go-jose/v4/jwt.Claims
Claims represents public claim values (as specified in RFC 7519). type Claims struct { Issuer string `json:"iss,omitempty"` Subject string `json:"sub,omitempty"` Audience Audience `json:"aud,omitempty"` Expiry *NumericDate `json:"exp,omitempty"` NotBefore *NumericDate `json:"nbf,omitempty"` IssuedAt *NumericDate `json:"iat,omitempty"` ID string `json:"jti,omitempty"` }. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.
var ext struct{Scope string "json:\"scope\""; ClientID string "json:\"client_id\""; Act *actor "json:\"act\""}
var ext struct{Scope string "json:\"scope\""; ClientID string "json:\"client_id\""; Act *actor "json:\"act\""}. In mcpauth/resource/verify.go, line 71.
field Scope string
field Scope string. In mcpauth/resource/verify.go, line 72.
field ClientID string
field ClientID string. In mcpauth/resource/verify.go, line 73.
field Act *actor
field Act *actor. In mcpauth/resource/verify.go, line 74.
type actor struct {
Sub string `json:"sub"`
Act *actor `json:"act"`
}
An actor is a token's act claim (RFC 8693, section 4.1): who is acting for the subject, and inside it, who acted before them.
An actor is a token's act claim (RFC 8693, section 4.1): who is acting for the subject, and inside it, who acted before them. type actor struct { Sub string `json:"sub"` Act *actor `json:"act"` }. In mcpauth/resource/verify.go, line 97.
func (t *JSONWebToken) Claims(key interface{}, dest ...interface{}) error
Claims deserializes a JSONWebToken into dest using the provided key.
github.com/go-jose/go-jose/v4/jwt.JSONWebToken.Claims
Claims deserializes a JSONWebToken into dest using the provided key. func (t *JSONWebToken) Claims(key interface{}, dest ...interface{}) error. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.JSONWebToken.Claims.
field Expiry *NumericDate `json:"exp,omitempty"`
github.com/go-jose/go-jose/v4/jwt.Claims.Expiry
field Expiry *NumericDate `json:"exp,omitempty"`. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.Expiry.
field Subject string `json:"sub,omitempty"`
github.com/go-jose/go-jose/v4/jwt.Claims.Subject
field Subject string `json:"sub,omitempty"`. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.Subject.
func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error
ValidateWithLeeway checks claims in a token against expected values.
github.com/go-jose/go-jose/v4/jwt.Claims.ValidateWithLeeway
ValidateWithLeeway checks claims in a token against expected values. func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.ValidateWithLeeway.
type Expected struct {
// Issuer matches the "iss" claim exactly.
Issuer string
// Subject matches the "sub" claim exactly.
Subject string
// AnyAudience matches if there is a non-empty intersection between
// its values and the values in the "aud" claim.
AnyAudience Audience
// ID matches the "jti" claim exactly.
ID string
// ...
}
Expected defines values used for protected claims validation.
github.com/go-jose/go-jose/v4/jwt.Expected
Expected defines values used for protected claims validation. type Expected struct { // Issuer matches the "iss" claim exactly. Issuer string // Subject matches the "sub" claim exactly. Subject string // AnyAudience matches if there is a non-empty intersection between // its values and the values in the "aud" claim. AnyAudience Audience // ID matches the "jti" claim exactly. ID string // ... }. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Expected.
field Issuer string
Issuer matches the "iss" claim exactly.
github.com/go-jose/go-jose/v4/jwt.Expected.Issuer
Issuer matches the "iss" claim exactly. field Issuer string. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Expected.Issuer.
field AnyAudience Audience
AnyAudience matches if there is a non-empty intersection between its values and the values in the "aud" claim.
github.com/go-jose/go-jose/v4/jwt.Expected.AnyAudience
AnyAudience matches if there is a non-empty intersection between its values and the values in the "aud" claim. field AnyAudience Audience. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Expected.AnyAudience.
type Audience []string
Audience represents the recipients that the token is intended for.
github.com/go-jose/go-jose/v4/jwt.Audience
Audience represents the recipients that the token is intended for. type Audience []string. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Audience.
field Time time.Time
Time matches the "exp", "nbf" and "iat" claims with leeway.
github.com/go-jose/go-jose/v4/jwt.Expected.Time
Time matches the "exp", "nbf" and "iat" claims with leeway. field Time time.Time. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Expected.Time.
func (v *Verifier) now() time.Time
mcpauth/resource/verify.go:202
func (v *Verifier) now() time.Time. In mcpauth/resource/verify.go, line 202.
func claimError(err error) string
claimError says why a token's claims failed, in words for the client rather than the library's.
mcpauth/resource/verify.go:188
claimError says why a token's claims failed, in words for the client rather than the library's. func claimError(err error) string. In mcpauth/resource/verify.go, line 188.
field Scopes []string
github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Scopes
field Scopes []string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Scopes.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func Fields(s string) []string
Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space.
Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space. func Fields(s string) []string. Documented at pkg.go.dev, strings.Fields.
field Expiration time.Time
github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Expiration
field Expiration time.Time. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Expiration.
func (n *NumericDate) Time() time.Time
Time returns time.Time representation of NumericDate.
github.com/go-jose/go-jose/v4/jwt.NumericDate.Time
Time returns time.Time representation of NumericDate. func (n *NumericDate) Time() time.Time. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.NumericDate.Time.
field UserID string
UserID is an optional identifier for the authenticated user.
github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.UserID
UserID is an optional identifier for the authenticated user. field UserID string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.UserID.
field Extra map[string]any
github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Extra
field Extra map[string]any. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfo.Extra.
type any = interface{}
any is an alias for interface{} and is equivalent to interface{} in all ways.
any is an alias for interface{} and is equivalent to interface{} in all ways. type any = interface{}. Documented at pkg.go.dev, builtin.any.
func (a *actor) chain() []string
chain lists the actors, the current one first.
mcpauth/resource/verify.go:104
chain lists the actors, the current one first. func (a *actor) chain() []string. In mcpauth/resource/verify.go, line 104.
func TestVerifyRefuses(t *testing.T)
TestVerifyRefuses checks each way a token can fail.
mcpauth/resource/verify_test.go:143
TestVerifyRefuses checks each way a token can fail. func TestVerifyRefuses(t *testing.T). In mcpauth/resource/verify_test.go, line 143.
var t *testing.T
mcpauth/resource/verify_test.go:143
var t *testing.T. In mcpauth/resource/verify_test.go, line 143.
package testing ("testing")
Package testing provides support for automated testing of Go packages.
Package testing provides support for automated testing of Go packages. package testing ("testing"). Documented at pkg.go.dev, testing.
type T struct {
common
denyParallel bool
tstate *testState // For running tests and subtests.
}
T is a type passed to Test functions to manage test state and support formatted test logs.
T is a type passed to Test functions to manage test state and support formatted test logs. type T struct { common denyParallel bool tstate *testState // For running tests and subtests. }. Documented at pkg.go.dev, testing.T.
var ks *keyServer
mcpauth/resource/verify_test.go:144
var ks *keyServer. In mcpauth/resource/verify_test.go, line 144.
func newKeyServer(t *testing.T) *keyServer
mcpauth/resource/verify_test.go:41
func newKeyServer(t *testing.T) *keyServer. In mcpauth/resource/verify_test.go, line 41.
var other *ecdsa.PrivateKey
mcpauth/resource/verify_test.go:145
var other *ecdsa.PrivateKey. In mcpauth/resource/verify_test.go, line 145.
package ecdsa ("crypto/ecdsa")
Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in [FIPS 186-5].
Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in [FIPS 186-5]. package ecdsa ("crypto/ecdsa"). Documented at pkg.go.dev, crypto/ecdsa.
func GenerateKey(c elliptic.Curve, r io.Reader) (*PrivateKey, error)
GenerateKey generates a new ECDSA private key for the specified curve.
GenerateKey generates a new ECDSA private key for the specified curve. func GenerateKey(c elliptic.Curve, r io.Reader) (*PrivateKey, error). Documented at pkg.go.dev, crypto/ecdsa.GenerateKey.
package elliptic ("crypto/elliptic")
Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields.
Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521 elliptic curves over prime fields. package elliptic ("crypto/elliptic"). Documented at pkg.go.dev, crypto/elliptic.
func P256() Curve
P256 returns a [Curve] which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1.
P256 returns a [Curve] which implements NIST P-256 (FIPS 186-3, section D.2.3), also known as secp256r1 or prime256v1. func P256() Curve. Documented at pkg.go.dev, crypto/elliptic.P256.
package rand ("crypto/rand")
Package rand implements a cryptographically secure random number generator.
Package rand implements a cryptographically secure random number generator. package rand ("crypto/rand"). Documented at pkg.go.dev, crypto/rand.
var Reader io.Reader = rand.Reader
Reader is a global, shared instance of a cryptographically secure random number generator.
Reader is a global, shared instance of a cryptographically secure random number generator. var Reader io.Reader = rand.Reader. Documented at pkg.go.dev, crypto/rand.Reader.
var with func(f func(*claims)) claims
mcpauth/resource/verify_test.go:146
var with func(f func(*claims)) claims. In mcpauth/resource/verify_test.go, line 146.
var f func(*claims)
mcpauth/resource/verify_test.go:146
var f func(*claims). In mcpauth/resource/verify_test.go, line 146.
type claims struct {
jwt.Claims
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
}
claims is what a test token carries; nil fields are left out.
mcpauth/resource/verify_test.go:67
claims is what a test token carries; nil fields are left out. type claims struct { jwt.Claims Scope string `json:"scope,omitempty"` ClientID string `json:"client_id,omitempty"` }. In mcpauth/resource/verify_test.go, line 67.
var c claims
mcpauth/resource/verify_test.go:147
var c claims. In mcpauth/resource/verify_test.go, line 147.
func goodClaims() claims
mcpauth/resource/verify_test.go:73
func goodClaims() claims. In mcpauth/resource/verify_test.go, line 73.
var cases []struct{name string; token string; want string}
mcpauth/resource/verify_test.go:151
var cases []struct{name string; token string; want string}. In mcpauth/resource/verify_test.go, line 151.
field name string
mcpauth/resource/verify_test.go:152
field name string. In mcpauth/resource/verify_test.go, line 152.
field token string
mcpauth/resource/verify_test.go:152
field token string. In mcpauth/resource/verify_test.go, line 152.
field want string
mcpauth/resource/verify_test.go:152
field want string. In mcpauth/resource/verify_test.go, line 152.
func (ks *keyServer) sign(t *testing.T, c claims, typ string) string
sign signs c with the key server's key, as typ.
mcpauth/resource/verify_test.go:83
sign signs c with the key server's key, as typ. func (ks *keyServer) sign(t *testing.T, c claims, typ string) string. In mcpauth/resource/verify_test.go, line 83.
var c *claims
mcpauth/resource/verify_test.go:154
var c *claims. In mcpauth/resource/verify_test.go, line 154.
field Audience Audience `json:"aud,omitempty"`
github.com/go-jose/go-jose/v4/jwt.Claims.Audience
field Audience Audience `json:"aud,omitempty"`. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.Audience.
package jwt ("github.com/go-jose/go-jose/v4/jwt")
package jwt ("github.com/go-jose/go-jose/v4/jwt").
var c *claims
mcpauth/resource/verify_test.go:157
var c *claims. In mcpauth/resource/verify_test.go, line 157.
var c *claims
mcpauth/resource/verify_test.go:160
var c *claims. In mcpauth/resource/verify_test.go, line 160.
field Issuer string `json:"iss,omitempty"`
github.com/go-jose/go-jose/v4/jwt.Claims.Issuer
field Issuer string `json:"iss,omitempty"`. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.Claims.Issuer.
var c *claims
mcpauth/resource/verify_test.go:163
var c *claims. In mcpauth/resource/verify_test.go, line 163.
func NewNumericDate(t time.Time) *NumericDate
NewNumericDate constructs NumericDate from time.Time value.
github.com/go-jose/go-jose/v4/jwt.NewNumericDate
NewNumericDate constructs NumericDate from time.Time value. func NewNumericDate(t time.Time) *NumericDate. Documented at pkg.go.dev, github.com/go-jose/go-jose/v4/jwt.NewNumericDate.
var testNow = time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)
mcpauth/resource/verify_test.go:29
var testNow = time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC). In mcpauth/resource/verify_test.go, line 29.
func (t Time) Add(d Duration) Time
Add returns the time t+d.
Add returns the time t+d. func (t Time) Add(d Duration) Time. Documented at pkg.go.dev, time.Time.Add.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
const Minute = 60 * Second
const Minute = 60 * Second. Documented at pkg.go.dev, time.Minute.
var c *claims
mcpauth/resource/verify_test.go:166
var c *claims. In mcpauth/resource/verify_test.go, line 166.
func unsigned(t *testing.T, c claims) string
unsigned is the "alg": "none" token an attacker would send.
mcpauth/resource/verify_test.go:105
unsigned is the "alg": "none" token an attacker would send. func unsigned(t *testing.T, c claims) string. In mcpauth/resource/verify_test.go, line 105.
func hmacWithPublicKey(t *testing.T, ks *keyServer, c claims) string
hmacWithPublicKey is the algorithm-confusion attack: an HS256 token whose secret is the server's public key, which an attacker knows.
mcpauth/resource/verify_test.go:116
hmacWithPublicKey is the algorithm-confusion attack: an HS256 token whose secret is the server's public key, which an attacker knows. func hmacWithPublicKey(t *testing.T, ks *keyServer, c claims) string. In mcpauth/resource/verify_test.go, line 116.
func signWith(t *testing.T, key *ecdsa.PrivateKey, kid string, c claims, typ string) string
mcpauth/resource/verify_test.go:90
func signWith(t *testing.T, key *ecdsa.PrivateKey, kid string, c claims, typ string) string. In mcpauth/resource/verify_test.go, line 90.
var tc struct{name string; token string; want string}
mcpauth/resource/verify_test.go:178
var tc struct{name string; token string; want string}. In mcpauth/resource/verify_test.go, line 178.
func (t *T) Run(name string, f func(t *T)) bool
Run runs f as a subtest of t called name.
Run runs f as a subtest of t called name. func (t *T) Run(name string, f func(t *T)) bool. Documented at pkg.go.dev, testing.T.Run.
var t *testing.T
mcpauth/resource/verify_test.go:179
var t *testing.T. In mcpauth/resource/verify_test.go, line 179.
var err error
mcpauth/resource/verify_test.go:180
var err error. In mcpauth/resource/verify_test.go, line 180.
func newVerifier(ks *keyServer) *Verifier
mcpauth/resource/verify_test.go:133
func newVerifier(ks *keyServer) *Verifier. In mcpauth/resource/verify_test.go, line 133.
func (c *common) Context() context.Context
Context returns a context that is canceled just before Cleanup-registered functions are called.
Context returns a context that is canceled just before Cleanup-registered functions are called. func (c *common) Context() context.Context. Documented at pkg.go.dev, testing.common.Context.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func Is(err, target error) bool
Is reports whether any error in err's tree matches target.
Is reports whether any error in err's tree matches target. func Is(err, target error) bool. Documented at pkg.go.dev, errors.Is.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
var ErrInvalidToken = errors.New("invalid token")
The error that a TokenVerifier should return if the token cannot be verified.
github.com/modelcontextprotocol/go-sdk/auth.ErrInvalidToken
The error that a TokenVerifier should return if the token cannot be verified. var ErrInvalidToken = errors.New("invalid token"). Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.ErrInvalidToken.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func Contains(s, substr string) bool
Contains reports whether substr is within s.
Contains reports whether substr is within s. func Contains(s, substr string) bool. Documented at pkg.go.dev, strings.Contains.
func (error).Error() string
func (error).Error() string.
func (c *common) Errorf(format string, args ...any)
Errorf is equivalent to Logf followed by Fail.
Errorf is equivalent to Logf followed by Fail. func (c *common) Errorf(format string, args ...any). Documented at pkg.go.dev, testing.common.Errorf.
var v *Verifier
mcpauth/resource/verify.go:117
var v *Verifier. In mcpauth/resource/verify.go, line 117.
var ctx context.Context
mcpauth/resource/verify.go:117
var ctx context.Context. In mcpauth/resource/verify.go, line 117.
var kid string
mcpauth/resource/verify.go:117
var kid string. In mcpauth/resource/verify.go, line 117.
func (v *Verifier) cached(kid string) (any, bool)
mcpauth/resource/verify.go:147
func (v *Verifier) cached(kid string) (any, bool). In mcpauth/resource/verify.go, line 147.
func (m *Mutex) Lock()
Lock locks m.
Lock locks m. func (m *Mutex) Lock(). Documented at pkg.go.dev, sync.Mutex.Lock.
func (m *Mutex) Unlock()
Unlock unlocks m.
Unlock unlocks m. func (m *Mutex) Unlock(). Documented at pkg.go.dev, sync.Mutex.Unlock.
func (t Time) Sub(u Time) Duration
Sub returns the duration t-u.
Sub returns the duration t-u. func (t Time) Sub(u Time) Duration. Documented at pkg.go.dev, time.Time.Sub.
const minRefetch = 30 * time.Second
minRefetch spaces out key fetches, so a stream of tokens with made-up key IDs can't turn into a stream of requests to the authorization server.
minRefetch spaces out key fetches, so a stream of tokens with made-up key IDs can't turn into a stream of requests to the authorization server. const minRefetch = 30 * time.Second. In mcpauth/resource/verify.go, line 44.
var set jose.JSONWebKeySet
mcpauth/resource/verify.go:132
var set jose.JSONWebKeySet. In mcpauth/resource/verify.go, line 132.
func (v *Verifier) fetchKeys(ctx context.Context) (jose.JSONWebKeySet, error)
mcpauth/resource/verify.go:156
func (v *Verifier) fetchKeys(ctx context.Context) (jose.JSONWebKeySet, error). In mcpauth/resource/verify.go, line 156.
func (rw *RWMutex) Lock()
Lock locks rw for writing.
Lock locks rw for writing. func (rw *RWMutex) Lock(). Documented at pkg.go.dev, sync.RWMutex.Lock.
func (rw *RWMutex) Unlock()
Unlock unlocks rw for writing.
Unlock unlocks rw for writing. func (rw *RWMutex) Unlock(). Documented at pkg.go.dev, sync.RWMutex.Unlock.
var TrackerScopes = map[string][]string{ ...
TrackerScopes are the scopes this server defines.
TrackerScopes are the scopes this server defines. var TrackerScopes = map[string][]string{ .... In mcpauth/servers/tracker.go, line 21.
var need map[string][]string
var need map[string][]string. In mcpauth/resource/scopes.go, line 25.
var metadataURL string
var metadataURL string. In mcpauth/resource/scopes.go, line 26.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
var next http.Handler
var next http.Handler. In mcpauth/resource/scopes.go, line 27.
type HandlerFunc func(ResponseWriter, *Request)
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers.
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. type HandlerFunc func(ResponseWriter, *Request). Documented at pkg.go.dev, net/http.HandlerFunc.
var w http.ResponseWriter
var w http.ResponseWriter. In mcpauth/resource/scopes.go, line 28.
type ResponseWriter interface {
// Header returns the header map that will be sent by
// [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
// [Handler] implementations can set HTTP trailers.
//
// Changing the header map after a call to [ResponseWriter.WriteHeader] (or
// [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
// 1xx class or the modified headers are trailers.
//
// There are two ways to set Trailers. The preferred way is to
// ...
}
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response. type ResponseWriter interface { // Header returns the header map that will be sent by // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which // [Handler] implementations can set HTTP trailers. // // Changing the header map after a call to [ResponseWriter.WriteHeader] (or // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the // 1xx class or the modified headers are trailers. // // There are two ways to set Trailers. The preferred way is to // ... }. Documented at pkg.go.dev, net/http.ResponseWriter.
var r *http.Request
var r *http.Request. In mcpauth/resource/scopes.go, line 29.
var tool string
var tool string. In mcpauth/resource/scopes.go, line 30.
func calledTool(w http.ResponseWriter, r *http.Request) (string, bool, error)
calledTool reports the tool a JSON-RPC tools/call request names.
calledTool reports the tool a JSON-RPC tools/call request names. func calledTool(w http.ResponseWriter, r *http.Request) (string, bool, error). In mcpauth/resource/scopes.go, line 69.
func Error(w ResponseWriter, error string, code int)
Error replies to the request with the specified error message and HTTP code.
Error replies to the request with the specified error message and HTTP code. func Error(w ResponseWriter, error string, code int). Documented at pkg.go.dev, net/http.Error.
const StatusBadRequest = 400
RFC 9110, 15.5.1
RFC 9110, 15.5.1 const StatusBadRequest = 400. Documented at pkg.go.dev, net/http.StatusBadRequest.
func (Handler) ServeHTTP(ResponseWriter, *Request)
func (Handler) ServeHTTP(ResponseWriter, *Request). Documented at pkg.go.dev, net/http.Handler.ServeHTTP.
var want []string
var want []string. In mcpauth/resource/scopes.go, line 39.
var listed bool
var listed bool. In mcpauth/resource/scopes.go, line 39.
var info *auth.TokenInfo
var info *auth.TokenInfo. In mcpauth/resource/scopes.go, line 40.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
func TokenInfoFromContext(ctx context.Context) *TokenInfo
TokenInfoFromContext returns the [TokenInfo] stored in ctx, or nil if none.
github.com/modelcontextprotocol/go-sdk/auth.TokenInfoFromContext
TokenInfoFromContext returns the [TokenInfo] stored in ctx, or nil if none. func TokenInfoFromContext(ctx context.Context) *TokenInfo. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.TokenInfoFromContext.
func (r *Request) Context() context.Context
Context returns the request's context.
Context returns the request's context. func (r *Request) Context() context.Context. Documented at pkg.go.dev, net/http.Request.Context.
func hasAll(have, want []string) bool
func hasAll(have, want []string) bool. In mcpauth/resource/scopes.go, line 94.
func (ResponseWriter) Header() Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader].
net/http.ResponseWriter.Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader]. func (ResponseWriter) Header() Header. Documented at pkg.go.dev, net/http.ResponseWriter.Header.
func (h Header) Set(key, value string)
Set sets the header entries associated with key to the single element value.
Set sets the header entries associated with key to the single element value. func (h Header) Set(key, value string). Documented at pkg.go.dev, net/http.Header.Set.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Sprintf(format string, a ...any) string
Sprintf formats according to a format specifier and returns the resulting string.
Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...any) string. Documented at pkg.go.dev, fmt.Sprintf.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func Join(elems []string, sep string) string
Join concatenates the elements of its first argument to create a single string.
Join concatenates the elements of its first argument to create a single string. func Join(elems []string, sep string) string. Documented at pkg.go.dev, strings.Join.
const StatusForbidden = 403
RFC 9110, 15.5.4
RFC 9110, 15.5.4 const StatusForbidden = 403. Documented at pkg.go.dev, net/http.StatusForbidden.
func TestStepUp(t *testing.T)
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.
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. func TestStepUp(t *testing.T). In mcpauth/flow_test.go, line 172.
package testing ("testing")
Package testing provides support for automated testing of Go packages.
Package testing provides support for automated testing of Go packages. package testing ("testing"). Documented at pkg.go.dev, testing.
var tc struct{name string; challenge bool; wantAuthorizes int32; wantErr bool}
var tc struct{name string; challenge bool; wantAuthorizes int32; wantErr bool}. In mcpauth/flow_test.go, line 173.
field challenge bool
field challenge bool. In mcpauth/flow_test.go, line 175.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
field wantAuthorizes int32
field wantAuthorizes int32. In mcpauth/flow_test.go, line 176.
type int32 int32
int32 is the set of all signed 32-bit integers.
int32 is the set of all signed 32-bit integers. type int32 int32. Documented at pkg.go.dev, builtin.int32.
const false = 0 != 0
Untyped bool.
Untyped bool. const false = 0 != 0. Documented at pkg.go.dev, builtin.false.
func NewOAuthHandler(clientID, redirect string,
fetch auth.AuthorizationCodeFetcher,
c *http.Client) (*auth.AuthorizationCodeHandler, error)
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.
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. func NewOAuthHandler(clientID, redirect string, fetch auth.AuthorizationCodeFetcher, c *http.Client) (*auth.AuthorizationCodeHandler, error). In mcpauth/client.go, line 26.
var fetch auth.AuthorizationCodeFetcher
var fetch auth.AuthorizationCodeFetcher. In mcpauth/client.go, line 27.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
type AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeFetcher
type AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error). Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeFetcher.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type AuthorizationCodeHandler struct {
config *AuthorizationCodeHandlerConfig
// mu protects concurrent access to tokenSource and grantedScopes.
mu sync.RWMutex
// tokenSource is the token source to use for authorization.
tokenSource oauth2.TokenSource
// grantedScopes maps authorization server issuer to the list of scopes granted by that issuer.
grantedScopes map[string][]string
}
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandler
type AuthorizationCodeHandler struct { config *AuthorizationCodeHandlerConfig // mu protects concurrent access to tokenSource and grantedScopes. mu sync.RWMutex // tokenSource is the token source to use for authorization. tokenSource oauth2.TokenSource // grantedScopes maps authorization server issuer to the list of scopes granted by that issuer. grantedScopes map[string][]string }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandler.
var cimd *auth.ClientIDMetadataDocumentConfig
var cimd *auth.ClientIDMetadataDocumentConfig. In mcpauth/client.go, line 29.
type ClientIDMetadataDocumentConfig struct {
// URL is the client identifier URL as per
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3.
URL string
}
ClientIDMetadataDocumentConfig is used to configure the Client ID Metadata Document based client registration per https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents.
github.com/modelcontextprotocol/go-sdk/auth.ClientIDMetadataDocumentConfig
ClientIDMetadataDocumentConfig is used to configure the Client ID Metadata Document based client registration per https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents. type ClientIDMetadataDocumentConfig struct { // URL is the client identifier URL as per // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3. URL string }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.ClientIDMetadataDocumentConfig.
field URL string
URL is the client identifier URL as per https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3.
github.com/modelcontextprotocol/go-sdk/auth.ClientIDMetadataDocumentConfig.URL
URL is the client identifier URL as per https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3. field URL string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.ClientIDMetadataDocumentConfig.URL.
var h *auth.AuthorizationCodeHandler
var h *auth.AuthorizationCodeHandler. In mcpauth/client.go, line 30.
func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*AuthorizationCodeHandler, error)
NewAuthorizationCodeHandler creates a new AuthorizationCodeHandler.
github.com/modelcontextprotocol/go-sdk/auth.NewAuthorizationCodeHandler
NewAuthorizationCodeHandler creates a new AuthorizationCodeHandler. func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*AuthorizationCodeHandler, error). Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.NewAuthorizationCodeHandler.
type AuthorizationCodeHandlerConfig struct {
// Client registration configuration.
// It is attempted in the following order:
// 1. Client ID Metadata Document
// 2. Preregistration
// 3. Dynamic Client Registration
// At least one method must be configured.
ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig
PreregisteredClient *oauthex.ClientCredentials
DynamicClientRegistrationConfig *DynamicClientRegistrationConfig
// ...
}
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig
type AuthorizationCodeHandlerConfig struct { // Client registration configuration. // It is attempted in the following order: // 1. Client ID Metadata Document // 2. Preregistration // 3. Dynamic Client Registration // At least one method must be configured. ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig PreregisteredClient *oauthex.ClientCredentials DynamicClientRegistrationConfig *DynamicClientRegistrationConfig // ... }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.
field ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig
Client registration configuration.
Client registration configuration. field ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.ClientIDMetadataDocumentConfig.
field RedirectURL string
RedirectURL is a required URL to redirect to after authorization.
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.RedirectURL
RedirectURL is a required URL to redirect to after authorization. field RedirectURL string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.RedirectURL.
field AuthorizationCodeFetcher AuthorizationCodeFetcher
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.AuthorizationCodeFetcher
field AuthorizationCodeFetcher AuthorizationCodeFetcher. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.AuthorizationCodeFetcher.
field Client *http.Client
Client is an optional HTTP client to use for HTTP requests.
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.Client
Client is an optional HTTP client to use for HTTP requests. field Client *http.Client. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandlerConfig.Client.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func LoopbackFetcher(redirect string,
open func(authURL string) error) auth.AuthorizationCodeFetcher
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.
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. func LoopbackFetcher(redirect string, open func(authURL string) error) auth.AuthorizationCodeFetcher. In mcpauth/client.go, line 78.
var open func(authURL string) error
var open func(authURL string) error. In mcpauth/client.go, line 79.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
var args *auth.AuthorizationArgs
var args *auth.AuthorizationArgs. In mcpauth/client.go, line 81.
type AuthorizationArgs struct {
// Authorization URL to be opened in a browser for the user to start the authorization process.
URL string
}
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationArgs
type AuthorizationArgs struct { // Authorization URL to be opened in a browser for the user to start the authorization process. URL string }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationArgs.
type AuthorizationResult struct {
// Code is the authorization code obtained from the authorization server.
Code string
// State string returned by the authorization server.
State string
// Iss is the issuer identifier returned by the authorization server in the
// authorization response per [RFC 9207]. The AuthorizationCodeFetcher should
// populate this from the "iss" query parameter in the redirect URI if present.
//
// [RFC 9207]: https://www.rfc-editor.org/rfc/rfc9207
Iss string
}
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult
type AuthorizationResult struct { // Code is the authorization code obtained from the authorization server. Code string // State string returned by the authorization server. State string // Iss is the issuer identifier returned by the authorization server in the // authorization response per [RFC 9207]. The AuthorizationCodeFetcher should // populate this from the "iss" query parameter in the redirect URI if present. // // [RFC 9207]: https://www.rfc-editor.org/rfc/rfc9207 Iss string }. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.
package url ("net/url")
Package url parses URLs and implements query escaping.
Package url parses URLs and implements query escaping. package url ("net/url"). Documented at pkg.go.dev, net/url.
package net ("net")
Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets. package net ("net"). Documented at pkg.go.dev, net.
type ListenConfig struct {
// If Control is not nil, it is called after creating the network
// connection but before binding it to the operating system.
//
// Network and address parameters passed to Control function are not
// necessarily the ones passed to Listen. Calling Listen with TCP networks
// will cause the Control function to be called with "tcp4" or "tcp6",
// UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6",
// and other known networks are passed as-is.
Control func(network, address string, c syscall.RawConn) error
// ...
}
ListenConfig contains options for listening to an address.
ListenConfig contains options for listening to an address. type ListenConfig struct { // If Control is not nil, it is called after creating the network // connection but before binding it to the operating system. // // Network and address parameters passed to Control function are not // necessarily the ones passed to Listen. Calling Listen with TCP networks // will cause the Control function to be called with "tcp4" or "tcp6", // UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6", // and other known networks are passed as-is. Control func(network, address string, c syscall.RawConn) error // ... }. Documented at pkg.go.dev, net.ListenConfig.
func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
Listen announces on the local network address.
Listen announces on the local network address. func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error). Documented at pkg.go.dev, net.ListenConfig.Listen.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
type Values map[string][]string
Values maps a string key to a list of values.
Values maps a string key to a list of values. type Values map[string][]string. Documented at pkg.go.dev, net/url.Values.
var callback func(w http.ResponseWriter, r *http.Request)
var callback func(w http.ResponseWriter, r *http.Request). In mcpauth/client.go, line 91.
var w http.ResponseWriter
var w http.ResponseWriter. In mcpauth/client.go, line 91.
field URL *url.URL
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests).
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests). field URL *url.URL. Documented at pkg.go.dev, net/http.Request.URL.
func NotFound(w ResponseWriter, r *Request)
NotFound replies to the request with an HTTP 404 not found error.
NotFound replies to the request with an HTTP 404 not found error. func NotFound(w ResponseWriter, r *Request). Documented at pkg.go.dev, net/http.NotFound.
func (u *URL) Query() Values
Query parses RawQuery and returns the corresponding values.
Query parses RawQuery and returns the corresponding values. func (u *URL) Query() Values. Documented at pkg.go.dev, net/url.URL.Query.
func Fprintln(w io.Writer, a ...any) (n int, err error)
Fprintln formats using the default formats for its operands and writes to w.
Fprintln formats using the default formats for its operands and writes to w. func Fprintln(w io.Writer, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprintln.
type Server struct {
// Addr optionally specifies the TCP address for the server to listen on,
// in the form "host:port". If empty, ":http" (port 80) is used.
// The service names are defined in RFC 6335 and assigned by IANA.
// See net.Dial for details of the address format.
Addr string
Handler Handler // handler to invoke, http.DefaultServeMux if nil
// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
// ...
}
A Server defines parameters for running an HTTP server.
A Server defines parameters for running an HTTP server. type Server struct { // Addr optionally specifies the TCP address for the server to listen on, // in the form "host:port". If empty, ":http" (port 80) is used. // The service names are defined in RFC 6335 and assigned by IANA. // See net.Dial for details of the address format. Addr string Handler Handler // handler to invoke, http.DefaultServeMux if nil // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, // ... }. Documented at pkg.go.dev, net/http.Server.
field Handler Handler
handler to invoke, http.DefaultServeMux if nil
handler to invoke, http.DefaultServeMux if nil field Handler Handler. Documented at pkg.go.dev, net/http.Server.Handler.
field ReadHeaderTimeout time.Duration
ReadHeaderTimeout is the amount of time allowed to read request headers.
net/http.Server.ReadHeaderTimeout
ReadHeaderTimeout is the amount of time allowed to read request headers. field ReadHeaderTimeout time.Duration. Documented at pkg.go.dev, net/http.Server.ReadHeaderTimeout.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
const Second = 1000 * Millisecond
const Second = 1000 * Millisecond. Documented at pkg.go.dev, time.Second.
func (s *Server) Serve(l net.Listener) error
Serve accepts incoming connections on the Listener l, creating a new service goroutine for each.
Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. func (s *Server) Serve(l net.Listener) error. Documented at pkg.go.dev, net/http.Server.Serve.
func (s *Server) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the server without interrupting any active connections.
Shutdown gracefully shuts down the server without interrupting any active connections. func (s *Server) Shutdown(ctx context.Context) error. Documented at pkg.go.dev, net/http.Server.Shutdown.
func WithoutCancel(parent Context) Context
WithoutCancel returns a derived context that points to the parent context and is not canceled when parent is canceled.
WithoutCancel returns a derived context that points to the parent context and is not canceled when parent is canceled. func WithoutCancel(parent Context) Context. Documented at pkg.go.dev, context.WithoutCancel.
field URL string
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationArgs.URL
field URL string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationArgs.URL.
func (v Values) Get(key string) string
Get gets the first value associated with the given key.
Get gets the first value associated with the given key. func (v Values) Get(key string) string. Documented at pkg.go.dev, net/url.Values.Get.
var errNotGranted = errors.New("loopback: authorization was not granted")
var errNotGranted = errors.New("loopback: authorization was not granted"). In mcpauth/client.go, line 124.
field Code string
Code is the authorization code obtained from the authorization server.
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.Code
Code is the authorization code obtained from the authorization server. field Code string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.Code.
field State string
State string returned by the authorization server.
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.State
State string returned by the authorization server. field State string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.State.
field Iss string
Iss is the issuer identifier returned by the authorization server in the authorization response per [RFC 9207].
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.Iss
Iss is the issuer identifier returned by the authorization server in the authorization response per [RFC 9207]. field Iss string. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationResult.Iss.
func (Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled.
Done returns a channel that's closed when work done on behalf of this context should be canceled. func (Context) Done() <-chan struct{}. Documented at pkg.go.dev, context.Context.Done.
func (Context) Err() error
If Done is not yet closed, Err returns nil.
If Done is not yet closed, Err returns nil. func (Context) Err() error. Documented at pkg.go.dev, context.Context.Err.
func ClientMetadata(clientID, name string,
redirects []string) http.Handler
ClientMetadata serves a Client ID Metadata Document: the JSON an authorization server fetches from the URL a client uses as its client_id.
ClientMetadata serves a Client ID Metadata Document: the JSON an authorization server fetches from the URL a client uses as its client_id. func ClientMetadata(clientID, name string, redirects []string) http.Handler. In mcpauth/client.go, line 51.
var w http.ResponseWriter
var w http.ResponseWriter. In mcpauth/client.go, line 61.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func MarshalWrite(out io.Writer, in any, opts ...Options) (err error)
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options).
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options). func MarshalWrite(out io.Writer, in any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.MarshalWrite.
func replay(ctx context.Context, out io.Writer,
h *auth.AuthorizationCodeHandler, other string) error
replay sends the client's access token, issued for the first MCP server, to the second, as a server that passed tokens through would.
replay sends the client's access token, issued for the first MCP server, to the second, as a server that passed tokens through would. func replay(ctx context.Context, out io.Writer, h *auth.AuthorizationCodeHandler, other string) error. In mcpauth/demo.go, line 39.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
type Writer interface {
Write(p []byte) (n int, err error)
}
Writer is the interface that wraps the basic Write method.
Writer is the interface that wraps the basic Write method. type Writer interface { Write(p []byte) (n int, err error) }. Documented at pkg.go.dev, io.Writer.
var h *auth.AuthorizationCodeHandler
var h *auth.AuthorizationCodeHandler. In mcpauth/demo.go, line 40.
package auth ("github.com/modelcontextprotocol/go-sdk/auth")
package auth ("github.com/modelcontextprotocol/go-sdk/auth").
func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error)
github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandler.TokenSource
func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error). Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/auth.AuthorizationCodeHandler.TokenSource.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func (TokenSource) Token() (*Token, error)
Token returns a token or an error.
golang.org/x/oauth2.TokenSource.Token
Token returns a token or an error. func (TokenSource) Token() (*Token, error). Documented at pkg.go.dev, golang.org/x/oauth2.TokenSource.Token.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext returns a new [Request] given a method, URL, and optional body.
net/http.NewRequestWithContext
NewRequestWithContext returns a new [Request] given a method, URL, and optional body. func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error). Documented at pkg.go.dev, net/http.NewRequestWithContext.
const MethodPost = "POST"
const MethodPost = "POST". Documented at pkg.go.dev, net/http.MethodPost.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func NewReader(s string) *Reader
NewReader returns a new [Reader] reading from s.
NewReader returns a new [Reader] reading from s. func NewReader(s string) *Reader. Documented at pkg.go.dev, strings.NewReader.
field Header Header
Header contains the request header fields either received by the server or to be sent by the client.
Header contains the request header fields either received by the server or to be sent by the client. field Header Header. Documented at pkg.go.dev, net/http.Request.Header.
field AccessToken string `json:"access_token"`
AccessToken is the token that authorizes and authenticates the requests.
golang.org/x/oauth2.Token.AccessToken
AccessToken is the token that authorizes and authenticates the requests. field AccessToken string `json:"access_token"`. Documented at pkg.go.dev, golang.org/x/oauth2.Token.AccessToken.
var DefaultClient = &Client{}
DefaultClient is the default [Client] and is used by [Get], [Head], and [Post].
DefaultClient is the default [Client] and is used by [Get], [Head], and [Post]. var DefaultClient = &Client{}. Documented at pkg.go.dev, net/http.DefaultClient.
func (c *Client) Do(req *Request) (*Response, error)
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. func (c *Client) Do(req *Request) (*Response, error). Documented at pkg.go.dev, net/http.Client.Do.
field Body io.ReadCloser
Body represents the response body.
Body represents the response body. field Body io.ReadCloser. Documented at pkg.go.dev, net/http.Response.Body.
func (Closer) Close() error
func (Closer) Close() error. Documented at pkg.go.dev, io.Closer.Close.
func ReadAll(r Reader) ([]byte, error)
ReadAll reads from r until an error or EOF and returns the data it read.
ReadAll reads from r until an error or EOF and returns the data it read. func ReadAll(r Reader) ([]byte, error). Documented at pkg.go.dev, io.ReadAll.
func LimitReader(r Reader, n int64) Reader
LimitReader returns a Reader that reads from r but stops with EOF after n bytes.
LimitReader returns a Reader that reads from r but stops with EOF after n bytes. func LimitReader(r Reader, n int64) Reader. Documented at pkg.go.dev, io.LimitReader.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)
Fprintf formats according to a format specifier and writes to w.
Fprintf formats according to a format specifier and writes to w. func Fprintf(w io.Writer, format string, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprintf.
field StatusCode int
e.g.
e.g. field StatusCode int. Documented at pkg.go.dev, net/http.Response.StatusCode.
func TrimSpace(s string) string
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode.
TrimSpace returns a slice (substring) of the string s, with all leading and trailing white space removed, as defined by Unicode. func TrimSpace(s string) string. Documented at pkg.go.dev, strings.TrimSpace.
func MatchesResource(claims []string, resource string) bool
MatchesResource reports whether any of claims matches resource under RFC 3986 §6.2.3 scheme-based normalization, narrowed to the empty-path case: a URI with an empty path is treated as equivalent to one with a path of "/".
github.com/modelcontextprotocol/go-sdk/oauthex.MatchesResource
MatchesResource reports whether any of claims matches resource under RFC 3986 §6.2.3 scheme-based normalization, narrowed to the empty-path case: a URI with an empty path is treated as equivalent to one with a path of "/". func MatchesResource(claims []string, resource string) bool. Documented at pkg.go.dev, github.com/modelcontextprotocol/go-sdk/oauthex.MatchesResource.

