Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 4.8k
Add HTTP server mode with OAuth token support#1216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Uh oh!
There was an error while loading. Please reload this page.
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -23,6 +23,7 @@ import ( | ||
| "github.com/mark3labs/mcp-go/mcp" | ||
| "github.com/mark3labs/mcp-go/server" | ||
| "github.com/shurcooL/githubv4" | ||
| "github.com/sirupsen/logrus" | ||
| ) | ||
| type MCPServerConfig struct { | ||
| @@ -120,11 +121,39 @@ func NewMCPServer(cfg MCPServerConfig) (*server.MCPServer, error) { | ||
| server.WithHooks(hooks), | ||
| ) | ||
| getClient := func(_ context.Context) (*gogithub.Client, error) { | ||
| getClient := func(ctx context.Context) (*gogithub.Client, error) { | ||
| if tokenVal := ctx.Value(githubTokenKey{}); tokenVal != nil { | ||
| if token, ok := tokenVal.(string); ok && token != "" { | ||
| client := gogithub.NewClient(nil).WithAuthToken(token) | ||
| client.UserAgent = restClient.UserAgent | ||
| client.BaseURL = apiHost.baseRESTURL | ||
| client.UploadURL = apiHost.uploadURL | ||
| return client, nil | ||
| } | ||
| } | ||
| return restClient, nil // closing over client | ||
| } | ||
| getGQLClient := func(_ context.Context) (*githubv4.Client, error) { | ||
| getGQLClient := func(ctx context.Context) (*githubv4.Client, error) { | ||
| if tokenVal := ctx.Value(githubTokenKey{}); tokenVal != nil { | ||
| if token, ok := tokenVal.(string); ok && token != "" { | ||
| httpClient := &http.Client{ | ||
| Transport: &bearerAuthTransport{ | ||
| transport: http.DefaultTransport, | ||
| token: token, | ||
| }, | ||
| } | ||
| if gqlHTTPClient.Transport != nil { | ||
| if uaTransport, ok := gqlHTTPClient.Transport.(*userAgentTransport); ok { | ||
| httpClient.Transport = &userAgentTransport{ | ||
| transport: httpClient.Transport, | ||
| agent: uaTransport.agent, | ||
| } | ||
| } | ||
| } | ||
| return githubv4.NewEnterpriseClient(apiHost.graphqlURL.String(), httpClient), nil | ||
| } | ||
| } | ||
| return gqlClient, nil // closing over client | ||
| } | ||
| @@ -155,6 +184,46 @@ func NewMCPServer(cfg MCPServerConfig) (*server.MCPServer, error) { | ||
| return ghServer, nil | ||
| } | ||
| type githubTokenKey struct{} | ||
| type HTTPServerConfig struct { | ||
| // Version of the server | ||
| Version string | ||
| // GitHub Host to target for API requests (e.g. github.com or github.enterprise.com) | ||
| Host string | ||
| // GitHub Token to authenticate with the GitHub API (optional for HTTP mode with OAuth) | ||
| Token string | ||
| // EnabledToolsets is a list of toolsets to enable | ||
| // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#tool-configuration | ||
| EnabledToolsets []string | ||
| // Whether to enable dynamic toolsets | ||
| // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery | ||
| DynamicToolsets bool | ||
| // ReadOnly indicates if we should only register read-only tools | ||
| ReadOnly bool | ||
| // ExportTranslations indicates if we should export translations | ||
| // See: https://github.com/github/github-mcp-server?tab=readme-ov-file#i18n--overriding-descriptions | ||
| ExportTranslations bool | ||
| // EnableCommandLogging indicates if we should log commands | ||
| EnableCommandLogging bool | ||
| // Path to the log file if not stderr | ||
| LogFilePath string | ||
| // Content window size | ||
| ContentWindowSize int | ||
| // Port to listen on for HTTP server | ||
| Port int | ||
| } | ||
| type StdioServerConfig struct { | ||
| // Version of the server | ||
| Version string | ||
| @@ -190,6 +259,77 @@ type StdioServerConfig struct { | ||
| ContentWindowSize int | ||
| } | ||
| func RunHTTPServer(cfg HTTPServerConfig) error { | ||
| ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | ||
| defer stop() | ||
| t, dumpTranslations := translations.TranslationHelper() | ||
| ghServer, err := NewMCPServer(MCPServerConfig{ | ||
| Version: cfg.Version, | ||
| Host: cfg.Host, | ||
| Token: cfg.Token, | ||
| EnabledToolsets: cfg.EnabledToolsets, | ||
| DynamicToolsets: cfg.DynamicToolsets, | ||
| ReadOnly: cfg.ReadOnly, | ||
| Translator: t, | ||
| ContentWindowSize: cfg.ContentWindowSize, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to create MCP server: %w", err) | ||
| } | ||
| logrusLogger := logrus.New() | ||
| if cfg.LogFilePath != "" { | ||
| file, err := os.OpenFile(cfg.LogFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to open log file: %w", err) | ||
| } | ||
| logrusLogger.SetLevel(logrus.DebugLevel) | ||
| logrusLogger.SetOutput(file) | ||
| } | ||
| httpOptions := []server.StreamableHTTPOption{ | ||
| server.WithLogger(logrusLogger), | ||
| server.WithHeartbeatInterval(30 * time.Second), | ||
| server.WithHTTPContextFunc(extractTokenFromAuthHeader), | ||
| } | ||
| httpServer := server.NewStreamableHTTPServer(ghServer, httpOptions...) | ||
| if cfg.ExportTranslations { | ||
| dumpTranslations() | ||
| } | ||
| addr := fmt.Sprintf(":%d", cfg.Port) | ||
| srv := &http.Server{ | ||
| Addr: addr, | ||
| Handler: httpServer, | ||
| } | ||
| _, _ = fmt.Fprintf(os.Stderr, "GitHub MCP Server running on HTTP at %s\n", addr) | ||
| errC := make(chan error, 1) | ||
| go func() { | ||
| errC <- srv.ListenAndServe() | ||
| }() | ||
| select { | ||
| case <-ctx.Done(): | ||
| logrusLogger.Infof("Shutting down server...") | ||
| shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| defer cancel() | ||
| return srv.Shutdown(shutdownCtx) | ||
| case err := <-errC: | ||
| if err != nil && err != http.ErrServerClosed { | ||
| return fmt.Errorf("error running server: %w", err) | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
| // RunStdioServer is not concurrent safe. | ||
| func RunStdioServer(cfg StdioServerConfig) error { | ||
| // Create app context | ||
| @@ -466,6 +606,14 @@ func (t *bearerAuthTransport) RoundTrip(req *http.Request) (*http.Response, erro | ||
| return t.transport.RoundTrip(req) | ||
| } | ||
| func extractTokenFromAuthHeader(ctx context.Context, r *http.Request) context.Context { | ||
| authHeader := r.Header.Get("Authorization") | ||
| if authHeader != "" && strings.HasPrefix(authHeader, "Bearer ") { | ||
| token := strings.TrimPrefix(authHeader, "Bearer ") | ||
| return context.WithValue(ctx, githubTokenKey{}, token) | ||
| } | ||
| return ctx | ||
talalryz marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| } | ||
| // cleanToolsets cleans and handles special toolset keywords: | ||
| // - Duplicates are removed from the result | ||
| // - Removes whitespaces | ||
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
CopilotAIOct 14, 2025
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The file permissions 0600 are appropriate for log files containing potentially sensitive information, but consider using 0640 if the log file needs to be readable by a logging service or monitoring system running under a different user in the same group.