From d124c6bf2b8d5167b210a5a0d6245f829bc48ec9 Mon Sep 17 00:00:00 2001 From: Max Farrell Date: Fri, 7 Aug 2026 20:28:35 -0500 Subject: [PATCH 1/3] Migrate to GitHub REST API version 2026-03-10 --- internal/ghmcp/oauth_test.go | 3 ++ internal/ghmcp/server.go | 2 +- internal/githubapp/githubapp.go | 7 ++-- internal/githubapp/githubapp_test.go | 2 ++ pkg/github/dependencies.go | 3 ++ pkg/github/dependencies_test.go | 45 ++++++++++++++++++++++++++ pkg/http/headers/headers.go | 2 ++ pkg/http/transport/api_version.go | 24 ++++++++++++++ pkg/http/transport/api_version_test.go | 33 +++++++++++++++++++ pkg/scopes/fetcher.go | 2 +- pkg/scopes/fetcher_test.go | 14 ++++++++ 11 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 pkg/http/transport/api_version.go create mode 100644 pkg/http/transport/api_version_test.go diff --git a/internal/ghmcp/oauth_test.go b/internal/ghmcp/oauth_test.go index b358876232..91d745f714 100644 --- a/internal/ghmcp/oauth_test.go +++ b/internal/ghmcp/oauth_test.go @@ -576,8 +576,10 @@ func TestCreateGitHubClientsTokenProvider(t *testing.T) { t.Parallel() var gotAuth string + var gotAPIVersion string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotAuth = r.Header.Get(headers.AuthorizationHeader) + gotAPIVersion = r.Header.Get(headers.GitHubAPIVersionHeader) w.WriteHeader(http.StatusOK) })) defer server.Close() @@ -600,6 +602,7 @@ func TestCreateGitHubClientsTokenProvider(t *testing.T) { do() assert.Equal(t, "", gotAuth, "no auth header before authorization") + assert.Equal(t, headers.GitHubAPIVersion, gotAPIVersion) current = "oauth-token" do() diff --git a/internal/ghmcp/server.go b/internal/ghmcp/server.go index 12306e6a23..dce3b5e54a 100644 --- a/internal/ghmcp/server.go +++ b/internal/ghmcp/server.go @@ -67,7 +67,7 @@ func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolv // the latter installs its own round tripper that would pin the static token // and shadow the dynamic one. restUATransport := &transport.UserAgentTransport{ - Transport: http.DefaultTransport, + Transport: &transport.APIVersionTransport{Transport: http.DefaultTransport}, Agent: fmt.Sprintf("github-mcp-server/%s", cfg.Version), } var restClient *gogithub.Client diff --git a/internal/githubapp/githubapp.go b/internal/githubapp/githubapp.go index bdd04af2cd..96c757cf9b 100644 --- a/internal/githubapp/githubapp.go +++ b/internal/githubapp/githubapp.go @@ -21,6 +21,7 @@ import ( "sync" "time" + "github.com/github/github-mcp-server/pkg/http/headers" "golang.org/x/oauth2" ) @@ -140,9 +141,9 @@ func (s *installationTokenSource) Token() (*oauth2.Token, error) { if err != nil { return nil, fmt.Errorf("creating installation token request: %w", err) } - req.Header.Set("Authorization", "Bearer "+jwt) - req.Header.Set("Accept", "application/vnd.github+json") - req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + req.Header.Set(headers.AuthorizationHeader, "Bearer "+jwt) + req.Header.Set(headers.AcceptHeader, "application/vnd.github+json") + req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) resp, err := s.httpClient.Do(req) if err != nil { diff --git a/internal/githubapp/githubapp_test.go b/internal/githubapp/githubapp_test.go index 6828dbc2dc..4c579e3d7c 100644 --- a/internal/githubapp/githubapp_test.go +++ b/internal/githubapp/githubapp_test.go @@ -20,6 +20,7 @@ import ( "testing" "time" + "github.com/github/github-mcp-server/pkg/http/headers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -155,6 +156,7 @@ func installationServer(t *testing.T, pub *rsa.PublicKey, token string, expiresA calls.Add(1) assert.Equal(t, http.MethodPost, r.Method) assert.Equal(t, "/app/installations/456/access_tokens", r.URL.Path) + assert.Equal(t, headers.GitHubAPIVersion, r.Header.Get(headers.GitHubAPIVersionHeader)) authz := r.Header.Get("Authorization") require.True(t, strings.HasPrefix(authz, "Bearer "), "must send the app JWT as a bearer token") diff --git a/pkg/github/dependencies.go b/pkg/github/dependencies.go index 49b6f6315a..cd0ee6edb1 100644 --- a/pkg/github/dependencies.go +++ b/pkg/github/dependencies.go @@ -324,6 +324,9 @@ func (d *RequestDeps) GetClient(ctx context.Context) (*gogithub.Client, error) { // Construct REST client restClient, err := gogithub.NewClient( + gogithub.WithHTTPClient(&http.Client{ + Transport: &transport.APIVersionTransport{Transport: http.DefaultTransport}, + }), gogithub.WithAuthToken(token), gogithub.WithUserAgent(fmt.Sprintf("github-mcp-server/%s", d.version)), gogithub.WithEnterpriseURLs(baseRestURL.String(), uploadURL.String()), diff --git a/pkg/github/dependencies_test.go b/pkg/github/dependencies_test.go index 1d747cae47..bd16bcb0b3 100644 --- a/pkg/github/dependencies_test.go +++ b/pkg/github/dependencies_test.go @@ -4,20 +4,65 @@ import ( "context" "errors" "log/slog" + "net/http" + "net/http/httptest" + "net/url" "testing" + ghcontext "github.com/github/github-mcp-server/pkg/context" "github.com/github/github-mcp-server/pkg/github" + "github.com/github/github-mcp-server/pkg/http/headers" "github.com/github/github-mcp-server/pkg/observability" "github.com/github/github-mcp-server/pkg/observability/metrics" "github.com/github/github-mcp-server/pkg/translations" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +type requestDepsAPIHost struct { + url *url.URL +} + +func (h requestDepsAPIHost) BaseRESTURL(context.Context) (*url.URL, error) { return h.url, nil } +func (h requestDepsAPIHost) GraphqlURL(context.Context) (*url.URL, error) { return h.url, nil } +func (h requestDepsAPIHost) UploadURL(context.Context) (*url.URL, error) { return h.url, nil } +func (h requestDepsAPIHost) RawURL(context.Context) (*url.URL, error) { return h.url, nil } +func (h requestDepsAPIHost) AuthorizationServerURL(context.Context) (*url.URL, error) { + return h.url, nil +} + func testExporters() observability.Exporters { obs, _ := observability.NewExporters(slog.New(slog.DiscardHandler), metrics.NewNoopMetrics()) return obs } +func TestRequestDepsGetClientSetsAPIVersion(t *testing.T) { + t.Parallel() + + var gotVersion string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotVersion = r.Header.Get(headers.GitHubAPIVersionHeader) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + serverURL, err := url.Parse(server.URL) + require.NoError(t, err) + apiHost := requestDepsAPIHost{url: serverURL} + deps := github.NewRequestDeps(apiHost, "test", false, nil, nil, 0, nil, testExporters()) + ctx := ghcontext.WithTokenInfo(context.Background(), &ghcontext.TokenInfo{Token: "test-token"}) + client, err := deps.GetClient(ctx) + require.NoError(t, err) + + req, err := client.NewRequest(ctx, http.MethodGet, "rate_limit", nil) + require.NoError(t, err) + resp, err := client.Do(req, nil) + require.NoError(t, err) + defer resp.Body.Close() + + assert.Equal(t, headers.GitHubAPIVersion, gotVersion) +} + func TestIsFeatureEnabled_WithEnabledFlag(t *testing.T) { t.Parallel() diff --git a/pkg/http/headers/headers.go b/pkg/http/headers/headers.go index e032a0ce93..0405101a10 100644 --- a/pkg/http/headers/headers.go +++ b/pkg/http/headers/headers.go @@ -53,4 +53,6 @@ const ( GraphQLFeaturesHeader = "GraphQL-Features" // GitHubAPIVersionHeader is the header used to specify the GitHub API version. GitHubAPIVersionHeader = "X-GitHub-Api-Version" + // GitHubAPIVersion is the GitHub REST API version used by this server. + GitHubAPIVersion = "2026-03-10" ) diff --git a/pkg/http/transport/api_version.go b/pkg/http/transport/api_version.go new file mode 100644 index 0000000000..eb76980032 --- /dev/null +++ b/pkg/http/transport/api_version.go @@ -0,0 +1,24 @@ +package transport + +import ( + "net/http" + + "github.com/github/github-mcp-server/pkg/http/headers" +) + +// APIVersionTransport sets the GitHub REST API version on every request. +type APIVersionTransport struct { + Transport http.RoundTripper +} + +// RoundTrip implements http.RoundTripper. +func (t *APIVersionTransport) RoundTrip(req *http.Request) (*http.Response, error) { + underlying := t.Transport + if underlying == nil { + underlying = http.DefaultTransport + } + + req = req.Clone(req.Context()) + req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) + return underlying.RoundTrip(req) +} diff --git a/pkg/http/transport/api_version_test.go b/pkg/http/transport/api_version_test.go new file mode 100644 index 0000000000..113755da0b --- /dev/null +++ b/pkg/http/transport/api_version_test.go @@ -0,0 +1,33 @@ +package transport + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/github/github-mcp-server/pkg/http/headers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAPIVersionTransport(t *testing.T) { + t.Parallel() + + var gotVersion string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotVersion = r.Header.Get(headers.GitHubAPIVersionHeader) + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + req, err := http.NewRequest(http.MethodGet, server.URL, nil) + require.NoError(t, err) + req.Header.Set(headers.GitHubAPIVersionHeader, "2022-11-28") + + resp, err := (&APIVersionTransport{}).RoundTrip(req) + require.NoError(t, err) + defer resp.Body.Close() + + assert.Equal(t, headers.GitHubAPIVersion, gotVersion) + assert.Equal(t, "2022-11-28", req.Header.Get(headers.GitHubAPIVersionHeader)) +} diff --git a/pkg/scopes/fetcher.go b/pkg/scopes/fetcher.go index b372455031..f3d0a619fd 100644 --- a/pkg/scopes/fetcher.go +++ b/pkg/scopes/fetcher.go @@ -81,7 +81,7 @@ func (f *Fetcher) FetchTokenScopes(ctx context.Context, token string) ([]string, req.Header.Set(headers.AuthorizationHeader, "Bearer "+token) req.Header.Set(headers.AcceptHeader, "application/vnd.github+json") - req.Header.Set(headers.GitHubAPIVersionHeader, "2022-11-28") + req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) resp, err := f.client.Do(req) if err != nil { diff --git a/pkg/scopes/fetcher_test.go b/pkg/scopes/fetcher_test.go index 7ef910a569..660a50322e 100644 --- a/pkg/scopes/fetcher_test.go +++ b/pkg/scopes/fetcher_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/github/github-mcp-server/pkg/http/headers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -148,6 +149,19 @@ func TestFetcher_FetchTokenScopes(t *testing.T) { expectedScopes: []string{"repo"}, expectError: false, }, + { + name: "verifies API version header is set", + handler: func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(headers.GitHubAPIVersionHeader) != headers.GitHubAPIVersion { + w.WriteHeader(http.StatusBadRequest) + return + } + w.Header().Set("X-OAuth-Scopes", "repo") + w.WriteHeader(http.StatusOK) + }, + expectedScopes: []string{"repo"}, + expectError: false, + }, { name: "verifies request method is HEAD", handler: func(w http.ResponseWriter, r *http.Request) { From e23db8691a2add65b56d8f3eeb779251ddf2747a Mon Sep 17 00:00:00 2001 From: Max Farrell Date: Fri, 7 Aug 2026 22:01:14 -0500 Subject: [PATCH 2/3] Preserve GHES API compatibility --- internal/ghmcp/oauth_test.go | 2 +- internal/githubapp/githubapp.go | 3 +- internal/githubapp/githubapp_test.go | 37 +++++++- pkg/github/__toolsnaps__/search_issues.snap | 1 - .../__toolsnaps__/search_pull_requests.snap | 1 - pkg/github/dependencies_test.go | 4 +- pkg/github/minimal_types.go | 4 +- pkg/http/headers/headers.go | 6 +- pkg/http/transport/api_version.go | 29 +++++- pkg/http/transport/api_version_test.go | 89 +++++++++++++++---- pkg/scopes/fetcher.go | 3 +- pkg/scopes/fetcher_test.go | 39 +++++++- pkg/utils/api.go | 5 +- pkg/utils/api_test.go | 24 +++++ 14 files changed, 215 insertions(+), 32 deletions(-) diff --git a/internal/ghmcp/oauth_test.go b/internal/ghmcp/oauth_test.go index 91d745f714..62cdf92166 100644 --- a/internal/ghmcp/oauth_test.go +++ b/internal/ghmcp/oauth_test.go @@ -602,7 +602,7 @@ func TestCreateGitHubClientsTokenProvider(t *testing.T) { do() assert.Equal(t, "", gotAuth, "no auth header before authorization") - assert.Equal(t, headers.GitHubAPIVersion, gotAPIVersion) + assert.Equal(t, headers.GitHubEnterpriseServerAPIVersion, gotAPIVersion) current = "oauth-token" do() diff --git a/internal/githubapp/githubapp.go b/internal/githubapp/githubapp.go index 96c757cf9b..ebf1edfcc6 100644 --- a/internal/githubapp/githubapp.go +++ b/internal/githubapp/githubapp.go @@ -22,6 +22,7 @@ import ( "time" "github.com/github/github-mcp-server/pkg/http/headers" + "github.com/github/github-mcp-server/pkg/http/transport" "golang.org/x/oauth2" ) @@ -143,7 +144,7 @@ func (s *installationTokenSource) Token() (*oauth2.Token, error) { } req.Header.Set(headers.AuthorizationHeader, "Bearer "+jwt) req.Header.Set(headers.AcceptHeader, "application/vnd.github+json") - req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) + transport.SetGitHubAPIVersionHeader(req) resp, err := s.httpClient.Do(req) if err != nil { diff --git a/internal/githubapp/githubapp_test.go b/internal/githubapp/githubapp_test.go index 4c579e3d7c..6d6d5dc4ce 100644 --- a/internal/githubapp/githubapp_test.go +++ b/internal/githubapp/githubapp_test.go @@ -12,6 +12,7 @@ import ( "encoding/json" "encoding/pem" "fmt" + "io" "log/slog" "net/http" "net/http/httptest" @@ -25,6 +26,12 @@ import ( "github.com/stretchr/testify/require" ) +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + func newTestKey(t *testing.T) *rsa.PrivateKey { t.Helper() key, err := rsa.GenerateKey(rand.Reader, 2048) @@ -156,7 +163,7 @@ func installationServer(t *testing.T, pub *rsa.PublicKey, token string, expiresA calls.Add(1) assert.Equal(t, http.MethodPost, r.Method) assert.Equal(t, "/app/installations/456/access_tokens", r.URL.Path) - assert.Equal(t, headers.GitHubAPIVersion, r.Header.Get(headers.GitHubAPIVersionHeader)) + assert.Equal(t, headers.GitHubEnterpriseServerAPIVersion, r.Header.Get(headers.GitHubAPIVersionHeader)) authz := r.Header.Get("Authorization") require.True(t, strings.HasPrefix(authz, "Bearer "), "must send the app JWT as a bearer token") @@ -187,6 +194,34 @@ func newTestTokenSource(t *testing.T, cfg Config, client *http.Client) *installa return newInstallationTokenSource(cfg, privateKey, client) } +func TestInstallationTokenSourceSetsAPIVersionForGitHubCloud(t *testing.T) { + key := newTestKey(t) + expiresAt := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + + for _, baseURL := range []string{"https://api.github.com", "https://api.example.ghe.com"} { + t.Run(baseURL, func(t *testing.T) { + var gotVersion string + client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + gotVersion = req.Header.Get(headers.GitHubAPIVersionHeader) + body := fmt.Sprintf(`{"token":"ghs_test","expires_at":%q}`, expiresAt) + return &http.Response{ + StatusCode: http.StatusCreated, + Status: "201 Created", + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + })} + source := newTestTokenSource(t, newTestConfig(key, baseURL), client) + + token, err := source.Token() + require.NoError(t, err) + assert.Equal(t, "ghs_test", token.AccessToken) + assert.Equal(t, headers.GitHubAPIVersion, gotVersion) + }) + } +} + func TestProviderFetchesToken(t *testing.T) { key := newTestKey(t) srv, calls := installationServer(t, &key.PublicKey, "ghs_fresh", time.Now().Add(time.Hour)) diff --git a/pkg/github/__toolsnaps__/search_issues.snap b/pkg/github/__toolsnaps__/search_issues.snap index bbba9b0b95..42ce5a87a4 100644 --- a/pkg/github/__toolsnaps__/search_issues.snap +++ b/pkg/github/__toolsnaps__/search_issues.snap @@ -22,7 +22,6 @@ "user", "author_association", "labels", - "assignee", "assignees", "milestone", "comments", diff --git a/pkg/github/__toolsnaps__/search_pull_requests.snap b/pkg/github/__toolsnaps__/search_pull_requests.snap index 847168b471..9738e938fb 100644 --- a/pkg/github/__toolsnaps__/search_pull_requests.snap +++ b/pkg/github/__toolsnaps__/search_pull_requests.snap @@ -22,7 +22,6 @@ "user", "author_association", "labels", - "assignee", "assignees", "milestone", "comments", diff --git a/pkg/github/dependencies_test.go b/pkg/github/dependencies_test.go index bd16bcb0b3..6c24254654 100644 --- a/pkg/github/dependencies_test.go +++ b/pkg/github/dependencies_test.go @@ -36,7 +36,7 @@ func testExporters() observability.Exporters { return obs } -func TestRequestDepsGetClientSetsAPIVersion(t *testing.T) { +func TestRequestDepsGetClientPreservesGHESAPIVersion(t *testing.T) { t.Parallel() var gotVersion string @@ -60,7 +60,7 @@ func TestRequestDepsGetClientSetsAPIVersion(t *testing.T) { require.NoError(t, err) defer resp.Body.Close() - assert.Equal(t, headers.GitHubAPIVersion, gotVersion) + assert.Equal(t, headers.GitHubEnterpriseServerAPIVersion, gotVersion) } func TestIsFeatureEnabled_WithEnabledFlag(t *testing.T) { diff --git a/pkg/github/minimal_types.go b/pkg/github/minimal_types.go index e2bf8b684b..5b14dc926b 100644 --- a/pkg/github/minimal_types.go +++ b/pkg/github/minimal_types.go @@ -75,7 +75,7 @@ var listReleasesItemFieldEnum = []any{ // the main lever for shrinking large result sets. var searchIssuesItemFieldEnum = []any{ "number", "title", "body", "state", "state_reason", "draft", "locked", - "html_url", "user", "author_association", "labels", "assignee", "assignees", + "html_url", "user", "author_association", "labels", "assignees", "milestone", "comments", "reactions", "created_at", "updated_at", "closed_at", "closed_by", "type", "repository_url", "pull_request", "field_values", } @@ -87,7 +87,7 @@ var searchIssuesItemFieldEnum = []any{ // the main lever for shrinking large result sets. var searchPullRequestsItemFieldEnum = []any{ "number", "title", "body", "state", "state_reason", "draft", "locked", - "html_url", "user", "author_association", "labels", "assignee", "assignees", + "html_url", "user", "author_association", "labels", "assignees", "milestone", "comments", "reactions", "created_at", "updated_at", "closed_at", "closed_by", "pull_request", "repository_url", } diff --git a/pkg/http/headers/headers.go b/pkg/http/headers/headers.go index 0405101a10..f914ae72c4 100644 --- a/pkg/http/headers/headers.go +++ b/pkg/http/headers/headers.go @@ -53,6 +53,10 @@ const ( GraphQLFeaturesHeader = "GraphQL-Features" // GitHubAPIVersionHeader is the header used to specify the GitHub API version. GitHubAPIVersionHeader = "X-GitHub-Api-Version" - // GitHubAPIVersion is the GitHub REST API version used by this server. + // GitHubAPIVersion is the GitHub REST API version used for GitHub.com and + // GitHub Enterprise Cloud requests. GitHubAPIVersion = "2026-03-10" + // GitHubEnterpriseServerAPIVersion is the compatibility version used for + // GitHub Enterprise Server requests. + GitHubEnterpriseServerAPIVersion = "2022-11-28" ) diff --git a/pkg/http/transport/api_version.go b/pkg/http/transport/api_version.go index eb76980032..292e69fa85 100644 --- a/pkg/http/transport/api_version.go +++ b/pkg/http/transport/api_version.go @@ -4,13 +4,38 @@ import ( "net/http" "github.com/github/github-mcp-server/pkg/http/headers" + "github.com/github/github-mcp-server/pkg/utils" ) -// APIVersionTransport sets the GitHub REST API version on every request. +// APIVersionTransport sets the GitHub REST API version on requests to +// GitHub.com and GitHub Enterprise Cloud. type APIVersionTransport struct { Transport http.RoundTripper } +// SetGitHubAPIVersionHeader selects the REST API version supported by the +// target deployment. GitHub Enterprise Server releases support API versions +// independently, so they retain the established compatibility version. +func SetGitHubAPIVersionHeader(req *http.Request) { + if req == nil || req.URL == nil { + return + } + + hostType, err := utils.ParseHostType(req.URL.String()) + if err != nil { + return + } + + if req.Header == nil { + req.Header = make(http.Header) + } + version := headers.GitHubAPIVersion + if hostType == utils.HostTypeGHES { + version = headers.GitHubEnterpriseServerAPIVersion + } + req.Header.Set(headers.GitHubAPIVersionHeader, version) +} + // RoundTrip implements http.RoundTripper. func (t *APIVersionTransport) RoundTrip(req *http.Request) (*http.Response, error) { underlying := t.Transport @@ -19,6 +44,6 @@ func (t *APIVersionTransport) RoundTrip(req *http.Request) (*http.Response, erro } req = req.Clone(req.Context()) - req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) + SetGitHubAPIVersionHeader(req) return underlying.RoundTrip(req) } diff --git a/pkg/http/transport/api_version_test.go b/pkg/http/transport/api_version_test.go index 113755da0b..97c6e3e5d4 100644 --- a/pkg/http/transport/api_version_test.go +++ b/pkg/http/transport/api_version_test.go @@ -2,7 +2,6 @@ package transport import ( "net/http" - "net/http/httptest" "testing" "github.com/github/github-mcp-server/pkg/http/headers" @@ -10,24 +9,84 @@ import ( "github.com/stretchr/testify/require" ) +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + func TestAPIVersionTransport(t *testing.T) { t.Parallel() - var gotVersion string - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotVersion = r.Header.Get(headers.GitHubAPIVersionHeader) - w.WriteHeader(http.StatusOK) - })) - defer server.Close() + tests := []struct { + name string + url string + existingVersion string + wantVersion string + }{ + { + name: "GitHub.com overrides the default version", + url: "https://api.github.com/repos/octo-org/octo-repo", + existingVersion: headers.GitHubEnterpriseServerAPIVersion, + wantVersion: headers.GitHubAPIVersion, + }, + { + name: "GitHub Enterprise Cloud sets the new version", + url: "https://api.example.ghe.com/repos/octo-org/octo-repo", + wantVersion: headers.GitHubAPIVersion, + }, + { + name: "GitHub Enterprise Server pins the compatibility version", + url: "https://github.example.com/api/v3/repos/octo-org/octo-repo", + existingVersion: headers.GitHubAPIVersion, + wantVersion: headers.GitHubEnterpriseServerAPIVersion, + }, + { + name: "GitHub Enterprise Server sets the compatibility version", + url: "https://github.example.com/api/v3/repos/octo-org/octo-repo", + wantVersion: headers.GitHubEnterpriseServerAPIVersion, + }, + { + name: "host classification is case insensitive", + url: "https://API.GITHUB.COM/repos/octo-org/octo-repo", + wantVersion: headers.GitHubAPIVersion, + }, + { + name: "lookalike domain is treated as GitHub Enterprise Server", + url: "https://api.github.com.example.org/api/v3/", + wantVersion: headers.GitHubEnterpriseServerAPIVersion, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var gotVersion string + underlying := roundTripFunc(func(req *http.Request) (*http.Response, error) { + gotVersion = req.Header.Get(headers.GitHubAPIVersionHeader) + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: http.NoBody, + Request: req, + }, nil + }) - req, err := http.NewRequest(http.MethodGet, server.URL, nil) - require.NoError(t, err) - req.Header.Set(headers.GitHubAPIVersionHeader, "2022-11-28") + req, err := http.NewRequest(http.MethodGet, tt.url, nil) + require.NoError(t, err) + if tt.existingVersion != "" { + req.Header.Set(headers.GitHubAPIVersionHeader, tt.existingVersion) + } else { + req.Header = nil + } - resp, err := (&APIVersionTransport{}).RoundTrip(req) - require.NoError(t, err) - defer resp.Body.Close() + resp, err := (&APIVersionTransport{Transport: underlying}).RoundTrip(req) + require.NoError(t, err) + defer resp.Body.Close() - assert.Equal(t, headers.GitHubAPIVersion, gotVersion) - assert.Equal(t, "2022-11-28", req.Header.Get(headers.GitHubAPIVersionHeader)) + assert.Equal(t, tt.wantVersion, gotVersion) + assert.Equal(t, tt.existingVersion, req.Header.Get(headers.GitHubAPIVersionHeader), "the original request must not be mutated") + }) + } } diff --git a/pkg/scopes/fetcher.go b/pkg/scopes/fetcher.go index f3d0a619fd..78ec3a315e 100644 --- a/pkg/scopes/fetcher.go +++ b/pkg/scopes/fetcher.go @@ -9,6 +9,7 @@ import ( "time" "github.com/github/github-mcp-server/pkg/http/headers" + "github.com/github/github-mcp-server/pkg/http/transport" "github.com/github/github-mcp-server/pkg/utils" ) @@ -81,7 +82,7 @@ func (f *Fetcher) FetchTokenScopes(ctx context.Context, token string) ([]string, req.Header.Set(headers.AuthorizationHeader, "Bearer "+token) req.Header.Set(headers.AcceptHeader, "application/vnd.github+json") - req.Header.Set(headers.GitHubAPIVersionHeader, headers.GitHubAPIVersion) + transport.SetGitHubAPIVersionHeader(req) resp, err := f.client.Do(req) if err != nil { diff --git a/pkg/scopes/fetcher_test.go b/pkg/scopes/fetcher_test.go index 660a50322e..b4c206a0d4 100644 --- a/pkg/scopes/fetcher_test.go +++ b/pkg/scopes/fetcher_test.go @@ -17,6 +17,12 @@ type testAPIHostResolver struct { baseURL string } +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + func (t testAPIHostResolver) BaseRESTURL(_ context.Context) (*url.URL, error) { return url.Parse(t.baseURL) } @@ -150,9 +156,9 @@ func TestFetcher_FetchTokenScopes(t *testing.T) { expectError: false, }, { - name: "verifies API version header is set", + name: "sets compatible API version header for GHES", handler: func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get(headers.GitHubAPIVersionHeader) != headers.GitHubAPIVersion { + if r.Header.Get(headers.GitHubAPIVersionHeader) != headers.GitHubEnterpriseServerAPIVersion { w.WriteHeader(http.StatusBadRequest) return } @@ -199,6 +205,35 @@ func TestFetcher_FetchTokenScopes(t *testing.T) { } } +func TestFetcher_FetchTokenScopesSetsAPIVersionForGitHubCloud(t *testing.T) { + t.Parallel() + + for _, baseURL := range []string{"https://api.github.com", "https://api.example.ghe.com"} { + t.Run(baseURL, func(t *testing.T) { + t.Parallel() + + var gotVersion string + client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + gotVersion = req.Header.Get(headers.GitHubAPIVersionHeader) + responseHeaders := make(http.Header) + responseHeaders.Set(OAuthScopesHeader, "repo") + return &http.Response{ + StatusCode: http.StatusOK, + Header: responseHeaders, + Body: http.NoBody, + Request: req, + }, nil + })} + fetcher := NewFetcher(testAPIHostResolver{baseURL: baseURL}, FetcherOptions{HTTPClient: client}) + + scopes, err := fetcher.FetchTokenScopes(context.Background(), "test-token") + require.NoError(t, err) + assert.Equal(t, []string{"repo"}, scopes) + assert.Equal(t, headers.GitHubAPIVersion, gotVersion) + }) + } +} + func TestFetcher_DefaultOptions(t *testing.T) { apiHost := testAPIHostResolver{baseURL: "https://api.github.com"} fetcher := NewFetcher(apiHost, FetcherOptions{}) diff --git a/pkg/utils/api.go b/pkg/utils/api.go index 95dfbd1d5b..4a9c81bad9 100644 --- a/pkg/utils/api.go +++ b/pkg/utils/api.go @@ -256,10 +256,11 @@ const ( ) func classifyHost(u *url.URL) HostType { + hostname := strings.ToLower(u.Hostname()) switch { - case u.Hostname() == "github.com" || strings.HasSuffix(u.Hostname(), ".github.com"): + case hostname == "github.com" || strings.HasSuffix(hostname, ".github.com"): return HostTypeDotcom - case u.Hostname() == "ghe.com" || strings.HasSuffix(u.Hostname(), ".ghe.com"): + case hostname == "ghe.com" || strings.HasSuffix(hostname, ".ghe.com"): return HostTypeGHEC default: return HostTypeGHES diff --git a/pkg/utils/api_test.go b/pkg/utils/api_test.go index 40fcb8f26a..4b73624dad 100644 --- a/pkg/utils/api_test.go +++ b/pkg/utils/api_test.go @@ -73,3 +73,27 @@ func TestParseAPIHost(t *testing.T) { }) } } + +func TestParseHostType(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + host string + want HostType + }{ + {name: "GitHub.com is case insensitive", host: "https://API.GITHUB.COM", want: HostTypeDotcom}, + {name: "GHEC is case insensitive", host: "https://API.EXAMPLE.GHE.COM", want: HostTypeGHEC}, + {name: "lookalike domain is GHES", host: "https://api.github.com.example.org", want: HostTypeGHES}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := ParseHostType(tt.host) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} From 11c5545c68f7768e26c86ea0e46b18cafd6a3dcd Mon Sep 17 00:00:00 2001 From: Sam Morrow Date: Fri, 13 Nov 2026 20:13:17 +0000 Subject: [PATCH 3/3] test: cover REST API version migration contracts Verify the pinned go-github SDK accepts the cloud API version and test cloud, GHES, lookalike hosts, resources.core-only rate limits, submodule directory entries, and workflow dispatch responses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pkg/github/actions_test.go | 17 +++++++ pkg/github/typed_repository_outputs_test.go | 10 +++- pkg/http/transport/api_version_test.go | 51 +++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/pkg/github/actions_test.go b/pkg/github/actions_test.go index cee001c804..380c049396 100644 --- a/pkg/github/actions_test.go +++ b/pkg/github/actions_test.go @@ -379,6 +379,23 @@ func Test_ActionsRunTrigger_RunWorkflow(t *testing.T) { expectError bool expectedErrMsg string }{ + { + name: "successful workflow run with 2026 API response", + mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ + PostReposActionsWorkflowsDispatchesByOwnerByRepoByWorkflowID: mockResponse(t, http.StatusOK, map[string]any{ + "workflow_run_id": 123, "run_url": "https://api.github.com/repos/owner/repo/actions/runs/123", + "html_url": "https://github.com/owner/repo/actions/runs/123", + }), + }), + requestArgs: map[string]any{ + "method": "run_workflow", + "owner": "owner", + "repo": "repo", + "workflow_id": "12345", + "ref": "main", + }, + expectError: false, + }, { name: "successful workflow run", mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{ diff --git a/pkg/github/typed_repository_outputs_test.go b/pkg/github/typed_repository_outputs_test.go index 672837c711..19f397a593 100644 --- a/pkg/github/typed_repository_outputs_test.go +++ b/pkg/github/typed_repository_outputs_test.go @@ -74,6 +74,11 @@ func typedRepositoryDeps(t *testing.T) BaseDeps { Name: new("lib"), Path: new("lib"), Type: new("file"), SHA: new("sha"), SubmoduleGitURL: new("https://github.com/owner/lib.git"), }})(w, r) + case strings.HasSuffix(r.URL.Path, "/cloud-submodule-directory"): + mockResponse(t, http.StatusOK, []*github.RepositoryContent{{ + Name: new("lib"), Path: new("lib"), Type: new("submodule"), SHA: new("sha"), + SubmoduleGitURL: new("https://github.com/owner/lib.git"), + }})(w, r) case strings.HasSuffix(r.URL.Path, "/empty-directory"): mockResponse(t, http.StatusOK, []*github.RepositoryContent{})(w, r) case strings.HasSuffix(r.URL.Path, "/submodule"): @@ -265,7 +270,7 @@ func TestTypedRepositoryOutputs(t *testing.T) { {"get_file_blame", coord(map[string]any{"path": "file", "start_line": "2", "end_line": "3", "perPage": "1"})}, {"get_file_blame", coord(map[string]any{"path": "file", "after": encodeBlameCursor(1)})}, } - for _, path := range []string{"text", "empty", "binary", "large", "submodule", "symlink", "directory", "submodule-directory", "empty-directory", "missing"} { + for _, path := range []string{"text", "empty", "binary", "large", "submodule", "symlink", "directory", "submodule-directory", "cloud-submodule-directory", "empty-directory", "missing"} { calls = append(calls, struct { name string args map[string]any @@ -385,6 +390,9 @@ func TestTypedRepositoryOutputs(t *testing.T) { if call.args["path"] == "submodule-directory" { assert.JSONEq(t, `[{"name":"lib","path":"lib","type":"file","sha":"sha","submodule_git_url":"https://github.com/owner/lib.git"}]`, mustMarshalJSON(t, result.StructuredContent)) } + if call.args["path"] == "cloud-submodule-directory" { + assert.JSONEq(t, `[{"name":"lib","path":"lib","type":"submodule","sha":"sha","submodule_git_url":"https://github.com/owner/lib.git"}]`, mustMarshalJSON(t, result.StructuredContent)) + } if call.args["path"] == "directory" && call.args["fields"] != nil && len(call.args["fields"].([]any)) == 3 { assert.JSONEq(t, `[{"size":0,"html_url":"https://github.com/owner/repo/blob/main/file","url":"api-content-url"}]`, mustMarshalJSON(t, result.StructuredContent)) } diff --git a/pkg/http/transport/api_version_test.go b/pkg/http/transport/api_version_test.go index d9a5a43104..deb7f70749 100644 --- a/pkg/http/transport/api_version_test.go +++ b/pkg/http/transport/api_version_test.go @@ -1,10 +1,14 @@ package transport import ( + "context" + "io" "net/http" + "strings" "testing" "github.com/github/github-mcp-server/v2/pkg/http/headers" + "github.com/google/go-github/v92/github" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -15,6 +19,53 @@ func (f apiVersionRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, e return f(req) } +func TestAPIVersionTransportWithGoGitHub(t *testing.T) { + t.Parallel() + + for _, tt := range []struct { + host string + version string + }{ + {"api.github.com", headers.GitHubAPIVersion}, + {"api.example.ghe.com", headers.GitHubAPIVersion}, + {"API.EXAMPLE.GHE.COM", headers.GitHubAPIVersion}, + {"github.example.com", headers.GitHubEnterpriseServerAPIVersion}, + {"api.github.com.example.org", headers.GitHubEnterpriseServerAPIVersion}, + {"api.example.ghe.com.example.org", headers.GitHubEnterpriseServerAPIVersion}, + } { + t.Run(tt.host, func(t *testing.T) { + t.Parallel() + + client, err := github.NewClient( + github.WithEnterpriseURLs("https://"+tt.host, "https://"+tt.host), + github.WithTransport(&APIVersionTransport{Transport: apiVersionRoundTripFunc(func(req *http.Request) (*http.Response, error) { + assert.Equal(t, tt.version, req.Header.Get(headers.GitHubAPIVersionHeader)) + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"resources":{"core":{"limit":5000,"remaining":4999}}}`)), + Request: req, + }, nil + })}), + ) + require.NoError(t, err) + + // Exercise the SDK's version guard as well as the transport override. + req, err := client.NewRequest(context.Background(), http.MethodGet, "rate_limit", nil, github.WithVersion(headers.GitHubAPIVersion)) + require.NoError(t, err) + resp, err := client.Do(req, nil) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + + limits, resp, err := client.RateLimit.Get(context.Background()) + require.NoError(t, err) + defer resp.Body.Close() + require.NotNil(t, limits.Core) + assert.Equal(t, 4999, limits.Core.Remaining) + }) + } +} + func TestAPIVersionTransport(t *testing.T) { t.Parallel()