|
| 1 | +package ghmcp |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + stdErrors "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "log/slog" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "os/signal" |
| 12 | + "strings" |
| 13 | + "syscall" |
| 14 | + "time" |
| 15 | + |
| 16 | + pkgErrors "github.com/github/github-mcp-server/pkg/errors" |
| 17 | + "github.com/github/github-mcp-server/pkg/translations" |
| 18 | + "github.com/mark3labs/mcp-go/server" |
| 19 | +) |
| 20 | + |
| 21 | +// HTTPServerConfig captures configuration for the HTTP transport. |
| 22 | +type HTTPServerConfig struct { |
| 23 | + Version string |
| 24 | + Host string |
| 25 | + EnabledToolsets []string |
| 26 | + DynamicToolsets bool |
| 27 | + ReadOnly bool |
| 28 | + ContentWindowSize int |
| 29 | + ListenAddress string |
| 30 | + EndpointPath string |
| 31 | + HealthPath string |
| 32 | + ShutdownTimeout time.Duration |
| 33 | + LogFilePath string |
| 34 | +} |
| 35 | + |
| 36 | +const ( |
| 37 | + defaultHTTPListenAddress = ":8080" |
| 38 | + defaultHTTPEndpoint = "/mcp" |
| 39 | + defaultHTTPHealthPath = "/health" |
| 40 | + defaultShutdownTimeout = 10 * time.Second |
| 41 | +) |
| 42 | + |
| 43 | +// RunHTTPServer starts an MCP server over the Streamable HTTP transport. |
| 44 | +func RunHTTPServer(cfg HTTPServerConfig) error { |
| 45 | + listenAddress := cfg.ListenAddress |
| 46 | + if strings.TrimSpace(listenAddress) == "" { |
| 47 | + listenAddress = defaultHTTPListenAddress |
| 48 | + } |
| 49 | + |
| 50 | + endpointPath := normalizePath(cfg.EndpointPath, defaultHTTPEndpoint) |
| 51 | + healthPath := normalizePath(cfg.HealthPath, defaultHTTPHealthPath) |
| 52 | + |
| 53 | + shutdownTimeout := cfg.ShutdownTimeout |
| 54 | + if shutdownTimeout <= 0 { |
| 55 | + shutdownTimeout = defaultShutdownTimeout |
| 56 | + } |
| 57 | + |
| 58 | + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 59 | + defer stop() |
| 60 | + |
| 61 | + translator, _ := translations.TranslationHelper() |
| 62 | + |
| 63 | + ghServer, err := NewMCPServer(MCPServerConfig{ |
| 64 | + Version: cfg.Version, |
| 65 | + Host: cfg.Host, |
| 66 | + EnabledToolsets: cfg.EnabledToolsets, |
| 67 | + DynamicToolsets: cfg.DynamicToolsets, |
| 68 | + ReadOnly: cfg.ReadOnly, |
| 69 | + Translator: translator, |
| 70 | + ContentWindowSize: cfg.ContentWindowSize, |
| 71 | + TokenProvider: TokenFromContext, |
| 72 | + }) |
| 73 | + if err != nil { |
| 74 | + return fmt.Errorf("failed to create MCP server: %w", err) |
| 75 | + } |
| 76 | + |
| 77 | + var logOutput io.Writer |
| 78 | + var logFile *os.File |
| 79 | + var slogHandler slog.Handler |
| 80 | + |
| 81 | + if strings.TrimSpace(cfg.LogFilePath) != "" { |
| 82 | + file, fileErr := os.OpenFile(cfg.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) |
| 83 | + if fileErr != nil { |
| 84 | + return fmt.Errorf("failed to open log file: %w", fileErr) |
| 85 | + } |
| 86 | + logOutput = file |
| 87 | + logFile = file |
| 88 | + slogHandler = slog.NewTextHandler(logOutput, &slog.HandlerOptions{Level: slog.LevelDebug}) |
| 89 | + } else { |
| 90 | + logOutput = os.Stderr |
| 91 | + slogHandler = slog.NewTextHandler(logOutput, &slog.HandlerOptions{Level: slog.LevelInfo}) |
| 92 | + } |
| 93 | + |
| 94 | + logger := slog.New(slogHandler) |
| 95 | + if logFile != nil { |
| 96 | + defer func() { _ = logFile.Close() }() |
| 97 | + } |
| 98 | + httpServer := &http.Server{Addr: listenAddress} |
| 99 | + |
| 100 | + streamServer := server.NewStreamableHTTPServer( |
| 101 | + ghServer, |
| 102 | + server.WithStreamableHTTPServer(httpServer), |
| 103 | + server.WithHTTPContextFunc(func(ctx context.Context, r *http.Request) context.Context { |
| 104 | + return pkgErrors.ContextWithGitHubErrors(ctx) |
| 105 | + }), |
| 106 | + ) |
| 107 | + |
| 108 | + mux := http.NewServeMux() |
| 109 | + mux.HandleFunc(healthPath, healthHandler) |
| 110 | + |
| 111 | + protectedHandler := tokenMiddleware(streamServer) |
| 112 | + mux.Handle(endpointPath, protectedHandler) |
| 113 | + if !strings.HasSuffix(endpointPath, "/") { |
| 114 | + mux.Handle(endpointPath+"/", protectedHandler) |
| 115 | + } |
| 116 | + |
| 117 | + httpServer.Handler = mux |
| 118 | + |
| 119 | + errCh := make(chan error, 1) |
| 120 | + go func() { |
| 121 | + logger.Info("starting HTTP server", "address", listenAddress, "endpoint", endpointPath, "health", healthPath, "dynamicToolsets", cfg.DynamicToolsets, "readOnly", cfg.ReadOnly) |
| 122 | + if serveErr := httpServer.ListenAndServe(); serveErr != nil && !stdErrors.Is(serveErr, http.ErrServerClosed) { |
| 123 | + errCh <- serveErr |
| 124 | + return |
| 125 | + } |
| 126 | + errCh <- nil |
| 127 | + }() |
| 128 | + |
| 129 | + select { |
| 130 | + case <-ctx.Done(): |
| 131 | + logger.Info("shutting down HTTP server", "reason", ctx.Err()) |
| 132 | + case serveErr := <-errCh: |
| 133 | + if serveErr != nil { |
| 134 | + logger.Error("error running HTTP server", "error", serveErr) |
| 135 | + return fmt.Errorf("error running HTTP server: %w", serveErr) |
| 136 | + } |
| 137 | + logger.Info("HTTP server stopped") |
| 138 | + return nil |
| 139 | + } |
| 140 | + |
| 141 | + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) |
| 142 | + defer cancel() |
| 143 | + |
| 144 | + if shutdownErr := streamServer.Shutdown(shutdownCtx); shutdownErr != nil && !stdErrors.Is(shutdownErr, http.ErrServerClosed) && !stdErrors.Is(shutdownErr, context.Canceled) { |
| 145 | + logger.Error("error during server shutdown", "error", shutdownErr) |
| 146 | + return fmt.Errorf("failed to shutdown HTTP server: %w", shutdownErr) |
| 147 | + } |
| 148 | + |
| 149 | + if serveErr := <-errCh; serveErr != nil && !stdErrors.Is(serveErr, http.ErrServerClosed) { |
| 150 | + logger.Error("error after server shutdown", "error", serveErr) |
| 151 | + return fmt.Errorf("error shutting down HTTP server: %w", serveErr) |
| 152 | + } |
| 153 | + |
| 154 | + logger.Info("HTTP server shutdown complete") |
| 155 | + return nil |
| 156 | +} |
| 157 | + |
| 158 | +func normalizePath(path string, fallback string) string { |
| 159 | + trimmed := strings.TrimSpace(path) |
| 160 | + if trimmed == "" { |
| 161 | + return fallback |
| 162 | + } |
| 163 | + if !strings.HasPrefix(trimmed, "/") { |
| 164 | + trimmed = "/" + trimmed |
| 165 | + } |
| 166 | + if len(trimmed) > 1 && strings.HasSuffix(trimmed, "/") { |
| 167 | + trimmed = strings.TrimSuffix(trimmed, "/") |
| 168 | + } |
| 169 | + return trimmed |
| 170 | +} |
| 171 | + |
| 172 | +func healthHandler(w http.ResponseWriter, r *http.Request) { |
| 173 | + if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 174 | + w.WriteHeader(http.StatusMethodNotAllowed) |
| 175 | + return |
| 176 | + } |
| 177 | + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| 178 | + w.WriteHeader(http.StatusOK) |
| 179 | + if r.Method == http.MethodHead { |
| 180 | + return |
| 181 | + } |
| 182 | + _, _ = w.Write([]byte("ok\n")) |
| 183 | +} |
| 184 | + |
| 185 | +func tokenMiddleware(next http.Handler) http.Handler { |
| 186 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 187 | + authHeader := strings.TrimSpace(r.Header.Get("Authorization")) |
| 188 | + if authHeader == "" { |
| 189 | + unauthorized(w, "missing Authorization header") |
| 190 | + return |
| 191 | + } |
| 192 | + |
| 193 | + parts := strings.SplitN(authHeader, " ", 2) |
| 194 | + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| 195 | + unauthorized(w, "invalid Authorization header") |
| 196 | + return |
| 197 | + } |
| 198 | + |
| 199 | + token := strings.TrimSpace(parts[1]) |
| 200 | + if token == "" { |
| 201 | + unauthorized(w, "missing bearer token") |
| 202 | + return |
| 203 | + } |
| 204 | + |
| 205 | + ctx := ContextWithToken(r.Context(), token) |
| 206 | + next.ServeHTTP(w, r.WithContext(ctx)) |
| 207 | + }) |
| 208 | +} |
| 209 | + |
| 210 | +func unauthorized(w http.ResponseWriter, message string) { |
| 211 | + w.Header().Set("WWW-Authenticate", "Bearer realm=\"github-mcp-server\"") |
| 212 | + http.Error(w, message, http.StatusUnauthorized) |
| 213 | +} |
0 commit comments