|
| 1 | +package ghmcp |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + "strconv" |
| 10 | + "syscall" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/github/github-mcp-server/pkg/translations" |
| 14 | + "github.com/mark3labs/mcp-go/server" |
| 15 | + "github.com/sirupsen/logrus" |
| 16 | +) |
| 17 | + |
| 18 | +type HttpServerConfig struct { |
| 19 | + // Version of the server |
| 20 | + Version string |
| 21 | + |
| 22 | + // GitHub Host to target for API requests (e.g. github.com or github.enterprise.com) |
| 23 | + Host string |
| 24 | + |
| 25 | + // GitHub Token to authenticate with the GitHub API |
| 26 | + Token string |
| 27 | + |
| 28 | + // EnabledToolsets is a list of toolsets to enable |
| 29 | + // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#tool-configuration |
| 30 | + EnabledToolsets []string |
| 31 | + |
| 32 | + // Whether to enable dynamic toolsets |
| 33 | + // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery |
| 34 | + DynamicToolsets bool |
| 35 | + |
| 36 | + // ReadOnly indicates if we should only register read-only tools |
| 37 | + ReadOnly bool |
| 38 | + |
| 39 | + // ExportTranslations indicates if we should export translations |
| 40 | + // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#i18n--overriding-descriptions |
| 41 | + ExportTranslations bool |
| 42 | + |
| 43 | + // EnableCommandLogging indicates if we should log commands |
| 44 | + EnableCommandLogging bool |
| 45 | + |
| 46 | + // Path to the log file if not stderr |
| 47 | + LogFilePath string |
| 48 | + |
| 49 | + // HTTP server configuration |
| 50 | + Address string |
| 51 | + |
| 52 | + // MCP endpoint path (defaults to "/mcp") |
| 53 | + MCPPath string |
| 54 | + |
| 55 | + // Enable CORS for cross-origin requests |
| 56 | + EnableCORS bool |
| 57 | + |
| 58 | + // GITHUB APP ID |
| 59 | + AppID string |
| 60 | + |
| 61 | + // GITHUB APP PRIVATE KEY |
| 62 | + AppPrivateKey string |
| 63 | + |
| 64 | + // Whether to enable GitHub App authentication via headers |
| 65 | + EnableGitHubAppAuth bool |
| 66 | + |
| 67 | + // Custom header name to read installation ID from (defaults to "X-GitHub-Installation-ID") |
| 68 | + InstallationIDHeader string |
| 69 | +} |
| 70 | + |
| 71 | +const installationContextKey = "installation_id" |
| 72 | + |
| 73 | +// RunHTTPServer is not concurrent safe. |
| 74 | +func RunHTTPServer(cfg HttpServerConfig) error { |
| 75 | + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 76 | + defer stop() |
| 77 | + |
| 78 | + t, dumpTranslations := translations.TranslationHelper() |
| 79 | + |
| 80 | + mcpCfg := MCPServerConfig{ |
| 81 | + Version: cfg.Version, |
| 82 | + Host: cfg.Host, |
| 83 | + Token: cfg.Token, |
| 84 | + EnabledToolsets: cfg.EnabledToolsets, |
| 85 | + DynamicToolsets: cfg.DynamicToolsets, |
| 86 | + ReadOnly: cfg.ReadOnly, |
| 87 | + Translator: t, |
| 88 | + AppID: cfg.AppID, |
| 89 | + AppPrivateKey: cfg.AppPrivateKey, |
| 90 | + EnableGitHubAppAuth: cfg.EnableGitHubAppAuth, |
| 91 | + InstallationIDHeader: cfg.InstallationIDHeader, |
| 92 | + } |
| 93 | + |
| 94 | + ghServer, err := NewMCPServer(mcpCfg) |
| 95 | + if err != nil { |
| 96 | + return fmt.Errorf("failed to create MCP server: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + httpServer := server.NewStreamableHTTPServer(ghServer) |
| 100 | + |
| 101 | + logrusLogger := logrus.New() |
| 102 | + if cfg.LogFilePath != "" { |
| 103 | + file, err := os.OpenFile(cfg.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) |
| 104 | + if err != nil { |
| 105 | + return fmt.Errorf("failed to open log file: %w", err) |
| 106 | + } |
| 107 | + logrusLogger.SetLevel(logrus.DebugLevel) |
| 108 | + logrusLogger.SetOutput(file) |
| 109 | + } else { |
| 110 | + logrusLogger.SetLevel(logrus.InfoLevel) |
| 111 | + } |
| 112 | + |
| 113 | + if cfg.Address == "" { |
| 114 | + cfg.Address = ":8080" |
| 115 | + } |
| 116 | + if cfg.MCPPath == "" { |
| 117 | + cfg.MCPPath = "/mcp" |
| 118 | + } |
| 119 | + if cfg.InstallationIDHeader == "" { |
| 120 | + cfg.InstallationIDHeader = "X-GitHub-Installation-ID" |
| 121 | + } |
| 122 | + |
| 123 | + mux := http.NewServeMux() |
| 124 | + var handler http.Handler = httpServer |
| 125 | + |
| 126 | + // Apply middlewares in the correct order: CORS first, then auth |
| 127 | + if cfg.EnableCORS { |
| 128 | + handler = corsMiddleware(handler) |
| 129 | + } |
| 130 | + if cfg.EnableGitHubAppAuth { |
| 131 | + handler = authMiddleware(handler, cfg.InstallationIDHeader, logrusLogger) |
| 132 | + } |
| 133 | + |
| 134 | + mux.Handle(cfg.MCPPath, handler) |
| 135 | + |
| 136 | + srv := &http.Server{ |
| 137 | + Addr: cfg.Address, |
| 138 | + Handler: mux, |
| 139 | + } |
| 140 | + |
| 141 | + if cfg.ExportTranslations { |
| 142 | + dumpTranslations() |
| 143 | + } |
| 144 | + |
| 145 | + errC := make(chan error, 1) |
| 146 | + go func() { |
| 147 | + logrusLogger.Infof("Starting HTTP server on %s", cfg.Address) |
| 148 | + logrusLogger.Infof("MCP endpoint available at http://localhost%s%s", cfg.Address, cfg.MCPPath) |
| 149 | + if cfg.EnableGitHubAppAuth { |
| 150 | + logrusLogger.Infof("GitHub App authentication enabled with header: %s", cfg.InstallationIDHeader) |
| 151 | + } |
| 152 | + errC <- srv.ListenAndServe() |
| 153 | + }() |
| 154 | + |
| 155 | + _, _ = fmt.Fprintf(os.Stderr, "GitHub MCP Server running on HTTP at %s\n", cfg.Address) |
| 156 | + _, _ = fmt.Fprintf(os.Stderr, "MCP endpoint: http://localhost%s%s\n", cfg.Address, cfg.MCPPath) |
| 157 | + if cfg.EnableGitHubAppAuth { |
| 158 | + _, _ = fmt.Fprintf(os.Stderr, "GitHub App authentication enabled with header: %s\n", cfg.InstallationIDHeader) |
| 159 | + } |
| 160 | + |
| 161 | + select { |
| 162 | + case <-ctx.Done(): |
| 163 | + logrusLogger.Infof("shutting down server...") |
| 164 | + shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 165 | + defer cancel() |
| 166 | + if err := srv.Shutdown(shutdownCtx); err != nil { |
| 167 | + logrusLogger.Errorf("error during server shutdown: %v", err) |
| 168 | + } |
| 169 | + case err := <-errC: |
| 170 | + if err != nil && err != http.ErrServerClosed { |
| 171 | + return fmt.Errorf("error running server: %w", err) |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + return nil |
| 176 | +} |
| 177 | + |
| 178 | +// corsMiddleware adds CORS headers to allow cross-origin requests |
| 179 | +func corsMiddleware(next http.Handler) http.Handler { |
| 180 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 181 | + // Set CORS headers |
| 182 | + w.Header().Set("Access-Control-Allow-Origin", "*") |
| 183 | + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") |
| 184 | + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, Accept-Encoding, Accept-Language, Cache-Control, Connection, Host, Origin, Referer, User-Agent") |
| 185 | + |
| 186 | + // Handle preflight requests |
| 187 | + if r.Method == "OPTIONS" { |
| 188 | + w.WriteHeader(http.StatusOK) |
| 189 | + return |
| 190 | + } |
| 191 | + |
| 192 | + next.ServeHTTP(w, r) |
| 193 | + }) |
| 194 | +} |
| 195 | + |
| 196 | +// authMiddleware extracts installation IDs from custom headers and adds them to the request context |
| 197 | +func authMiddleware(next http.Handler, headerName string, logger *logrus.Logger) http.Handler { |
| 198 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 199 | + installationIDStr := r.Header.Get(headerName) |
| 200 | + if installationIDStr == "" { |
| 201 | + next.ServeHTTP(w, r) |
| 202 | + return |
| 203 | + } |
| 204 | + |
| 205 | + installationID, err := strconv.ParseInt(installationIDStr, 10, 64) |
| 206 | + if err != nil { |
| 207 | + logger.Warnf("Invalid installation ID format in header %s", headerName) |
| 208 | + http.Error(w, "Invalid installation ID format", http.StatusBadRequest) |
| 209 | + return |
| 210 | + } |
| 211 | + |
| 212 | + if installationID <= 0 { |
| 213 | + logger.Warnf("Invalid installation ID value: %d", installationID) |
| 214 | + http.Error(w, "Invalid installation ID value", http.StatusBadRequest) |
| 215 | + return |
| 216 | + } |
| 217 | + |
| 218 | + ctx := context.WithValue(r.Context(), installationContextKey, installationID) |
| 219 | + r = r.WithContext(ctx) |
| 220 | + |
| 221 | + if logger.GetLevel() == logrus.DebugLevel { |
| 222 | + logger.Debugf("Authenticated request with installation ID %d", installationID) |
| 223 | + } else { |
| 224 | + logger.Debug("Request authenticated with GitHub App installation") |
| 225 | + } |
| 226 | + |
| 227 | + next.ServeHTTP(w, r) |
| 228 | + }) |
| 229 | +} |
0 commit comments