Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/shared.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 // This file contains shared utilities for OAuth handlers.
6
7 package auth
8
9 import (
10 "context"
11 "net/http"
12 "net/url"
13 "strings"
14
15 "github.com/modelcontextprotocol/go-sdk/oauthex"
16 )
17
18 // GetAuthServerMetadata fetches authorization server metadata for the given issuer URL.
19 // It tries standard well-known endpoints (OAuth 2.0 and OIDC) and returns the first successful result.
20 //
21 // Returns (nil, nil) when no metadata endpoints respond (404s), allowing callers to implement
22 // fallback logic. Returns an error for any non-client error (network failures, invalid JSON, etc.).
23 func GetAuthServerMetadata(ctx context.Context, issuerURL string, httpClient *http.Client) (*oauthex.AuthServerMeta, error) {
24 for _, metadataURL := range authorizationServerMetadataURLs(issuerURL) {
25 asm, err := oauthex.GetAuthServerMeta(ctx, metadataURL, issuerURL, httpClient)
26 if err != nil {
27 return nil, err
28 }
29 if asm != nil {
30 return asm, nil
31 }
32 }
33 return nil, nil
34 }
35
36 // authorizationServerMetadataURLs returns a list of URLs to try when looking for
37 // authorization server metadata as mandated by the MCP specification:
38 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery.
39 func authorizationServerMetadataURLs(issuerURL string) []string {
40 var urls []string
41
42 baseURL, err := url.Parse(issuerURL)
43 if err != nil {
44 return nil
45 }
46
47 if baseURL.Path == "" {
48 // "OAuth 2.0 Authorization Server Metadata".
49 baseURL.Path = "/.well-known/oauth-authorization-server"
50 urls = append(urls, baseURL.String())
51 // "OpenID Connect Discovery 1.0".
52 baseURL.Path = "/.well-known/openid-configuration"
53 urls = append(urls, baseURL.String())
54 return urls
55 }
56
57 originalPath := baseURL.Path
58 // "OAuth 2.0 Authorization Server Metadata with path insertion".
59 baseURL.Path = "/.well-known/oauth-authorization-server/" + strings.TrimLeft(originalPath, "/")
60 urls = append(urls, baseURL.String())
61 // "OpenID Connect Discovery 1.0 with path insertion".
62 baseURL.Path = "/.well-known/openid-configuration/" + strings.TrimLeft(originalPath, "/")
63 urls = append(urls, baseURL.String())
64 // "OpenID Connect Discovery 1.0 with path appending".
65 baseURL.Path = "/" + strings.Trim(originalPath, "/") + "/.well-known/openid-configuration"
66 urls = append(urls, baseURL.String())
67
68 return urls
69 }