Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/github-mcp-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ var (
Version: version,
Host: viper.GetString("host"),
Port: viper.GetInt("port"),
BaseURL: viper.GetString("base-url"),
ExportTranslations: viper.GetBool("export-translations"),
EnableCommandLogging: viper.GetBool("enable-command-logging"),
LogFilePath: viper.GetString("log-file"),
Expand Down Expand Up @@ -130,6 +131,7 @@ func init() {
rootCmd.PersistentFlags().Bool("lockdown-mode", false, "Enable lockdown mode")
rootCmd.PersistentFlags().Duration("repo-access-cache-ttl", 5*time.Minute, "Override the repo access cache TTL (e.g. 1m, 0s to disable)")
rootCmd.PersistentFlags().Int("port", 8082, "HTTP server port")
rootCmd.PersistentFlags().String("base-url", "", "Base URL where this server is publicly accessible (for OAuth resource metadata)")

// Bind flag to viper
_ = viper.BindPFlag("toolsets", rootCmd.PersistentFlags().Lookup("toolsets"))
Expand All @@ -145,6 +147,7 @@ func init() {
_ = viper.BindPFlag("lockdown-mode", rootCmd.PersistentFlags().Lookup("lockdown-mode"))
_ = viper.BindPFlag("repo-access-cache-ttl", rootCmd.PersistentFlags().Lookup("repo-access-cache-ttl"))
_ = viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))
_ = viper.BindPFlag("base-url", rootCmd.PersistentFlags().Lookup("base-url"))

// Add subcommands
rootCmd.AddCommand(stdioCmd)
Expand Down
12 changes: 11 additions & 1 deletion pkg/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"github.com/github/github-mcp-server/pkg/github"
"github.com/github/github-mcp-server/pkg/http/headers"
"github.com/github/github-mcp-server/pkg/http/middleware"
"github.com/github/github-mcp-server/pkg/http/oauth"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/go-chi/chi/v5"
Expand All @@ -18,21 +19,23 @@
type InventoryFactoryFunc func(r *http.Request) *inventory.Inventory
type GitHubMCPServerFactoryFunc func(ctx context.Context, r *http.Request, deps github.ToolDependencies, inventory *inventory.Inventory, cfg *github.MCPServerConfig) (*mcp.Server, error)

type HTTPMcpHandler struct {

Check failure on line 22 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

exported: type name will be used as http.HTTPMcpHandler by other packages, and that stutters; consider calling this McpHandler (revive)
config *HTTPServerConfig
deps github.ToolDependencies
logger *slog.Logger
t translations.TranslationHelperFunc
githubMcpServerFactory GitHubMCPServerFactoryFunc
inventoryFactoryFunc InventoryFactoryFunc
oauthCfg *oauth.Config
}

type HTTPMcpHandlerOptions struct {

Check failure on line 32 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

exported: type name will be used as http.HTTPMcpHandlerOptions by other packages, and that stutters; consider calling this McpHandlerOptions (revive)
GitHubMcpServerFactory GitHubMCPServerFactoryFunc
InventoryFactory InventoryFactoryFunc
OAuthConfig *oauth.Config
}

type HTTPMcpHandlerOption func(*HTTPMcpHandlerOptions)

Check failure on line 38 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

exported: type name will be used as http.HTTPMcpHandlerOption by other packages, and that stutters; consider calling this McpHandlerOption (revive)

func WithGitHubMCPServerFactory(f GitHubMCPServerFactoryFunc) HTTPMcpHandlerOption {
return func(o *HTTPMcpHandlerOptions) {
Expand All @@ -46,6 +49,12 @@
}
}

func WithOAuthConfig(cfg *oauth.Config) HTTPMcpHandlerOption {
return func(o *HTTPMcpHandlerOptions) {
o.OAuthConfig = cfg
}
}

func NewHTTPMcpHandler(cfg *HTTPServerConfig,
deps github.ToolDependencies,
t translations.TranslationHelperFunc,
Expand Down Expand Up @@ -73,6 +82,7 @@
t: t,
githubMcpServerFactory: githubMcpServerFactory,
inventoryFactoryFunc: inventoryFactory,
oauthCfg: opts.OAuthConfig,
}
}

Expand All @@ -95,16 +105,16 @@
w.WriteHeader(http.StatusInternalServerError)
}

mcpHandler := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {

Check failure on line 108 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
return ghServer
}, &mcp.StreamableHTTPOptions{
Stateless: true,
})

middleware.ExtractUserToken()(mcpHandler).ServeHTTP(w, r)
middleware.ExtractUserToken(h.oauthCfg)(mcpHandler).ServeHTTP(w, r)
}

func DefaultGitHubMCPServerFactory(ctx context.Context, _ *http.Request, deps github.ToolDependencies, inventory *inventory.Inventory, cfg *github.MCPServerConfig) (*mcp.Server, error) {

Check failure on line 117 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
return github.NewMCPServer(&github.MCPServerConfig{
Version: cfg.Version,
Translator: cfg.Translator,
Expand All @@ -114,7 +124,7 @@
}, deps, inventory)
}

func DefaultInventoryFactory(cfg *HTTPServerConfig, t translations.TranslationHelperFunc, staticChecker inventory.FeatureFlagChecker) InventoryFactoryFunc {

Check failure on line 127 in pkg/http/handler.go

View workflow job for this annotation

GitHub Actions / lint

unused-parameter: parameter 'cfg' seems to be unused, consider removing or renaming it as _ (revive)
return func(r *http.Request) *inventory.Inventory {
b := github.NewInventory(t).WithDeprecatedAliases(github.DeprecatedToolAliases)

Expand Down
5 changes: 5 additions & 0 deletions pkg/http/headers/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ const (
// RealIPHeader is a standard HTTP Header used to indicate the real IP address of the client.
RealIPHeader = "X-Real-IP"

// ForwardedHostHeader is a standard HTTP Header for preserving the original Host header when proxying.
ForwardedHostHeader = "X-Forwarded-Host"
// ForwardedProtoHeader is a standard HTTP Header for preserving the original protocol when proxying.
ForwardedProtoHeader = "X-Forwarded-Proto"

// RequestHmacHeader is used to authenticate requests to the Raw API.
RequestHmacHeader = "Request-Hmac"

Expand Down
14 changes: 12 additions & 2 deletions pkg/http/middleware/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
ghcontext "github.com/github/github-mcp-server/pkg/context"
httpheaders "github.com/github/github-mcp-server/pkg/http/headers"
"github.com/github/github-mcp-server/pkg/http/mark"
"github.com/github/github-mcp-server/pkg/http/oauth"
)

type authType int
Expand All @@ -24,7 +25,7 @@
errMissingAuthorizationHeader = fmt.Errorf("%w: missing required Authorization header", mark.ErrBadRequest)
errBadAuthorizationHeader = fmt.Errorf("%w: Authorization header is badly formatted", mark.ErrBadRequest)
errUnsupportedAuthorizationHeader = fmt.Errorf("%w: unsupported Authorization header", mark.ErrBadRequest)
errMissingTokenInfoHeader = fmt.Errorf("%w: missing required token info header", mark.ErrBadRequest)

Check failure on line 28 in pkg/http/middleware/token.go

View workflow job for this annotation

GitHub Actions / lint

var errMissingTokenInfoHeader is unused (unused)
)

var supportedThirdPartyTokenPrefixes = []string{
Expand All @@ -40,14 +41,14 @@
// were 40 characters long and only contained the characters a-f and 0-9.
var oldPatternRegexp = regexp.MustCompile(`\A[a-f0-9]{40}\z`)

func ExtractUserToken() func(next http.Handler) http.Handler {
func ExtractUserToken(oauthCfg *oauth.Config) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, token, err := parseAuthorizationHeader(r)
if err != nil {
// For missing Authorization header, return 401 with WWW-Authenticate header per MCP spec
if errors.Is(err, errMissingAuthorizationHeader) {
// sendAuthChallenge(w, r, cfg, obsv)
sendAuthChallenge(w, r, oauthCfg)
return
}
// For other auth errors (bad format, unsupported), return 400
Expand All @@ -63,6 +64,15 @@
})
}
}

// sendAuthChallenge sends a 401 Unauthorized response with WWW-Authenticate header
// containing the OAuth protected resource metadata URL as per RFC 6750 and MCP spec.
func sendAuthChallenge(w http.ResponseWriter, r *http.Request, oauthCfg *oauth.Config) {
resourceMetadataURL := oauth.BuildResourceMetadataURL(r, oauthCfg, "mcp")
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata=%q`, resourceMetadataURL))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}

func parseAuthorizationHeader(req *http.Request) (authType authType, token string, _ error) {
authHeader := req.Header.Get(httpheaders.AuthorizationHeader)
if authHeader == "" {
Expand Down
225 changes: 225 additions & 0 deletions pkg/http/oauth/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Package oauth provides OAuth 2.0 Protected Resource Metadata (RFC 9728) support
// for the GitHub MCP Server HTTP mode.
package oauth

import (
"bytes"
_ "embed"
"fmt"
"html"
"net/http"
"strings"
"text/template"

"github.com/github/github-mcp-server/pkg/http/headers"
"github.com/go-chi/chi/v5"
)

const (
// OAuthProtectedResourcePrefix is the well-known path prefix for OAuth protected resource metadata.
OAuthProtectedResourcePrefix = "/.well-known/oauth-protected-resource"

// DefaultAuthorizationServer is GitHub's OAuth authorization server.
DefaultAuthorizationServer = "https://github.com/login/oauth"
)

//go:embed protected_resource.json.tmpl
var protectedResourceTemplate []byte

// SupportedScopes lists all OAuth scopes that may be required by MCP tools.
var SupportedScopes = []string{
"repo",
"read:org",
"read:user",
"user:email",
"read:packages",
"write:packages",
"read:project",
"project",
"gist",
"notifications",
"workflow",
"codespace",
}

// Config holds the OAuth configuration for the MCP server.
type Config struct {
// BaseURL is the publicly accessible URL where this server is hosted.
// This is used to construct the OAuth resource URL.
// Example: "https://mcp.example.com"
BaseURL string

// AuthorizationServer is the OAuth authorization server URL.
// Defaults to GitHub's OAuth server if not specified.
AuthorizationServer string

// ResourcePath is the resource path suffix (e.g., "/mcp").
// If empty, defaults to "/"
ResourcePath string
}

// ProtectedResourceData contains the data needed to build an OAuth protected resource response.
type ProtectedResourceData struct {
ResourceURL string
AuthorizationServer string
}

// AuthHandler handles OAuth-related HTTP endpoints.
type AuthHandler struct {
cfg *Config
protectedResourceTemplate *template.Template
}

// NewAuthHandler creates a new OAuth auth handler.
func NewAuthHandler(cfg *Config) (*AuthHandler, error) {
if cfg == nil {
cfg = &Config{}
}

// Default authorization server to GitHub
if cfg.AuthorizationServer == "" {
cfg.AuthorizationServer = DefaultAuthorizationServer
}

tmpl, err := template.New("protected-resource").Parse(string(protectedResourceTemplate))
if err != nil {
return nil, fmt.Errorf("failed to parse protected resource template: %w", err)
}

return &AuthHandler{
cfg: cfg,
protectedResourceTemplate: tmpl,
}, nil
}

// routePatterns defines the route patterns for OAuth protected resource metadata.
var routePatterns = []string{
"", // Root: /.well-known/oauth-protected-resource
"/readonly", // Read-only mode
"/x/{toolset}",
"/x/{toolset}/readonly",
}

// RegisterRoutes registers the OAuth protected resource metadata routes.
func (h *AuthHandler) RegisterRoutes(r chi.Router) {
for _, pattern := range routePatterns {
for _, route := range h.routesForPattern(pattern) {
path := OAuthProtectedResourcePrefix + route
r.Get(path, h.handleProtectedResource)
r.Options(path, h.handleProtectedResource) // CORS support
}
}
}

// routesForPattern generates route variants for a given pattern.
func (h *AuthHandler) routesForPattern(pattern string) []string {
routes := []string{
pattern,
pattern + "/",
pattern + "/mcp",
pattern + "/mcp/",
}
return routes
}

// handleProtectedResource handles requests for OAuth protected resource metadata.
func (h *AuthHandler) handleProtectedResource(w http.ResponseWriter, r *http.Request) {
// Extract the resource path from the URL
resourcePath := strings.TrimPrefix(r.URL.Path, OAuthProtectedResourcePrefix)
if resourcePath == "" || resourcePath == "/" {
resourcePath = "/"
} else {
resourcePath = strings.TrimPrefix(resourcePath, "/")
}

data, err := h.GetProtectedResourceData(r, html.EscapeString(resourcePath))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

var buf bytes.Buffer
if err := h.protectedResourceTemplate.Execute(&buf, data); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}

// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(buf.Bytes())
}

// GetProtectedResourceData builds the OAuth protected resource data for a request.
func (h *AuthHandler) GetProtectedResourceData(r *http.Request, resourcePath string) (*ProtectedResourceData, error) {
host, scheme := GetEffectiveHostAndScheme(r, h.cfg)

// Build the resource URL
var resourceURL string
if h.cfg.BaseURL != "" {
// Use configured base URL
baseURL := strings.TrimSuffix(h.cfg.BaseURL, "/")
if resourcePath == "/" {
resourceURL = baseURL + "/"
} else {
resourceURL = baseURL + "/" + resourcePath
}
} else {
// Derive from request
if resourcePath == "/" {
resourceURL = fmt.Sprintf("%s://%s/", scheme, host)
} else {
resourceURL = fmt.Sprintf("%s://%s/%s", scheme, host, resourcePath)
}
}

return &ProtectedResourceData{
ResourceURL: resourceURL,
AuthorizationServer: h.cfg.AuthorizationServer,
}, nil
}

// GetEffectiveHostAndScheme returns the effective host and scheme for a request.
// It checks X-Forwarded-Host and X-Forwarded-Proto headers first (set by proxies),
// then falls back to the request's Host and TLS state.
func GetEffectiveHostAndScheme(r *http.Request, cfg *Config) (host, scheme string) { //nolint:revive // parameters are required by http.oauth.BuildResourceMetadataURL signature
// Check for forwarded headers first (typically set by reverse proxies)
if forwardedHost := r.Header.Get(headers.ForwardedHostHeader); forwardedHost != "" {
host = forwardedHost
} else {
host = r.Host
}

// Determine scheme
switch {
case r.Header.Get(headers.ForwardedProtoHeader) != "":
scheme = strings.ToLower(r.Header.Get(headers.ForwardedProtoHeader))
case r.TLS != nil:
scheme = "https"
default:
// Default to HTTPS in production scenarios
scheme = "https"
}

return host, scheme
}

// BuildResourceMetadataURL constructs the full URL to the OAuth protected resource metadata endpoint.
func BuildResourceMetadataURL(r *http.Request, cfg *Config, resourcePath string) string {
host, scheme := GetEffectiveHostAndScheme(r, cfg)

if cfg != nil && cfg.BaseURL != "" {
baseURL := strings.TrimSuffix(cfg.BaseURL, "/")
return baseURL + OAuthProtectedResourcePrefix + "/" + strings.TrimPrefix(resourcePath, "/")
}

path := OAuthProtectedResourcePrefix
if resourcePath != "" && resourcePath != "/" {
path = path + "/" + strings.TrimPrefix(resourcePath, "/")
}

return fmt.Sprintf("%s://%s%s", scheme, host, path)
}
20 changes: 20 additions & 0 deletions pkg/http/oauth/protected_resource.json.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"resource_name": "GitHub MCP Server",
"resource": "{{.ResourceURL}}",
"authorization_servers": ["{{.AuthorizationServer}}"],
"bearer_methods_supported": ["header"],
"scopes_supported": [
"repo",
"read:org",
"read:user",
"user:email",
"read:packages",
"write:packages",
"read:project",
"project",
"gist",
"notifications",
"workflow",
"codespace"
]
}
Loading
Loading