chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:37:57 +08:00
commit e30f8ba47c
533 changed files with 115926 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
// Package buildinfo contains variables that are set at build time via ldflags.
// These allow official releases to ship default OAuth credentials so users can
// log in without configuring their own OAuth app. The values are public in
// practice (security relies on PKCE, not on the client secret), but are kept out
// of source and injected at build time.
//
// Example:
//
// go build -ldflags="-X github.com/github/github-mcp-server/internal/buildinfo.OAuthClientID=xxx"
package buildinfo
// OAuthClientID is the default OAuth client ID, set at build time. Empty in
// local/dev builds.
var OAuthClientID string
// OAuthClientSecret is the default OAuth client secret, set at build time. For
// public OAuth clients it is not truly secret per OAuth 2.1 — PKCE provides the
// security — but it is still injected at build time rather than committed.
var OAuthClientSecret string
+133
View File
@@ -0,0 +1,133 @@
package ghmcp
import (
"context"
"crypto/rand"
"fmt"
"log/slog"
"github.com/github/github-mcp-server/internal/oauth"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// sessionPrompter adapts an MCP server session to oauth.Prompter, presenting
// authorization prompts to the user via elicitation. Keeping the prompt on the
// MCP control channel (rather than a tool result) keeps the authorization URL
// and any session-bound state out of the model's context.
type sessionPrompter struct {
session *mcp.ServerSession
}
// elicitationCaps returns the client's declared elicitation capabilities, or nil
// if the client did not advertise any.
func (p *sessionPrompter) elicitationCaps() *mcp.ElicitationCapabilities {
params := p.session.InitializeParams()
if params == nil || params.Capabilities == nil {
return nil
}
return params.Capabilities.Elicitation
}
// CanPromptURL reports whether the client supports URL-mode elicitation.
func (p *sessionPrompter) CanPromptURL() bool {
caps := p.elicitationCaps()
return caps != nil && caps.URL != nil
}
// PromptURL presents the authorization URL via URL-mode elicitation and blocks
// until the user acknowledges, declines, or ctx is done.
func (p *sessionPrompter) PromptURL(ctx context.Context, prompt oauth.Prompt) error {
res, err := p.session.Elicit(ctx, &mcp.ElicitParams{
Mode: "url",
Message: prompt.Message,
URL: prompt.URL,
ElicitationID: rand.Text(),
})
if err != nil {
// The client advertised URL elicitation but the request itself failed:
// classify it as undeliverable (not a user decision) so the flow can fall
// back to a channel that needs no client capability.
return fmt.Errorf("%w: %w", oauth.ErrPromptUnavailable, err)
}
if res.Action != "accept" {
return oauth.ErrPromptDeclined
}
return nil
}
// CanPromptForm reports whether the client supports form-mode elicitation. The
// SDK treats a client that advertises neither form nor URL capabilities as
// supporting forms, for backward compatibility, so we mirror that here.
func (p *sessionPrompter) CanPromptForm() bool {
caps := p.elicitationCaps()
if caps == nil {
return false
}
return caps.Form != nil || caps.URL == nil
}
// PromptForm presents a textual acknowledgement (used to display a device code
// when URL elicitation is unavailable) and blocks until the user responds.
func (p *sessionPrompter) PromptForm(ctx context.Context, prompt oauth.Prompt) error {
res, err := p.session.Elicit(ctx, &mcp.ElicitParams{
Mode: "form",
Message: prompt.Message,
})
if err != nil {
// As with PromptURL, a delivery failure is undeliverable rather than a
// decline, so the flow can fall back instead of aborting.
return fmt.Errorf("%w: %w", oauth.ErrPromptUnavailable, err)
}
if res.Action != "accept" {
return oauth.ErrPromptDeclined
}
return nil
}
// oauthAuthenticator is the subset of *oauth.Manager that the middleware needs.
// Depending on the interface (rather than the concrete manager) lets the
// middleware be exercised with a deterministic fake, since driving the real
// manager to its branches would require standing up live GitHub flows.
type oauthAuthenticator interface {
HasToken() bool
Authenticate(ctx context.Context, prompter oauth.Prompter) (*oauth.Outcome, error)
}
// createOAuthMiddleware returns receiving middleware that authorizes the session
// lazily, on the first tool call. Authorization is deferred until here (rather
// than at startup) because the prompts depend on an initialized session whose
// elicitation capabilities are known.
//
// When a token is already available the call proceeds untouched. Otherwise the
// flow runs: secure channels (browser, URL elicitation) block until the token
// arrives and then the call proceeds; the last-resort channel returns the
// instruction to the user as a tool result and asks them to retry.
func createOAuthMiddleware(mgr oauthAuthenticator, logger *slog.Logger) func(next mcp.MethodHandler) mcp.MethodHandler {
return func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, request mcp.Request) (mcp.Result, error) {
if method != "tools/call" || mgr.HasToken() {
return next(ctx, method, request)
}
callReq, ok := request.(*mcp.CallToolRequest)
if !ok {
return next(ctx, method, request)
}
outcome, err := mgr.Authenticate(ctx, &sessionPrompter{session: callReq.Session})
if err != nil {
return nil, fmt.Errorf("github authorization failed: %w", err)
}
if outcome != nil && outcome.UserAction != nil {
logger.Info("surfacing github authorization instructions to user")
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: outcome.UserAction.Message}},
}, nil
}
return next(ctx, method, request)
}
}
}
// ensure sessionPrompter satisfies the Prompter contract.
var _ oauth.Prompter = (*sessionPrompter)(nil)
+391
View File
@@ -0,0 +1,391 @@
package ghmcp
import (
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/github/github-mcp-server/internal/oauth"
"github.com/github/github-mcp-server/pkg/github"
"github.com/github/github-mcp-server/pkg/http/headers"
"github.com/github/github-mcp-server/pkg/utils"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
// probeToolName is the name of the throwaway tool the harness registers; its
// handler runs a probe closure against a sessionPrompter so the adapter can be
// exercised against a real, fully-negotiated server session from the client side.
const probeToolName = "probe"
// runProbe stands up an in-memory MCP client/server pair, registers a tool whose
// handler runs probe against a sessionPrompter wrapping the live server session,
// and returns the text the probe produced. The client is configured with the
// given capabilities and elicitation handler so the adapter sees a real,
// fully-negotiated session rather than a hand-built fake.
func runProbe(
t *testing.T,
clientCaps *mcp.ClientCapabilities,
elicitationHandler func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error),
probe func(context.Context, *sessionPrompter) string,
) string {
t.Helper()
server := mcp.NewServer(&mcp.Implementation{Name: "test-server", Version: "v0.0.1"}, nil)
mcp.AddTool(server, &mcp.Tool{Name: probeToolName}, func(ctx context.Context, req *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, any, error) {
text := probe(ctx, &sessionPrompter{session: req.Session})
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: text}}}, nil, nil
})
st, ct := mcp.NewInMemoryTransports()
ss, err := server.Connect(context.Background(), st, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = ss.Close() })
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "v0.0.1"}, &mcp.ClientOptions{
Capabilities: clientCaps,
ElicitationHandler: elicitationHandler,
})
cs, err := client.Connect(context.Background(), ct, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = cs.Close() })
res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: probeToolName})
require.NoError(t, err)
require.Len(t, res.Content, 1)
text, ok := res.Content[0].(*mcp.TextContent)
require.True(t, ok, "probe result should be text content")
return text.Text
}
func TestSessionPrompterCapabilities(t *testing.T) {
t.Parallel()
tests := []struct {
name string
caps *mcp.ClientCapabilities
wantURL bool
wantForm bool
}{
{
name: "no elicitation advertised",
caps: &mcp.ClientCapabilities{},
wantURL: false,
wantForm: false,
},
{
name: "url only",
caps: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}}},
wantURL: true,
wantForm: false,
},
{
name: "form only",
caps: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{Form: &mcp.FormElicitationCapabilities{}}},
wantURL: false,
wantForm: true,
},
{
name: "url and form",
caps: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}, Form: &mcp.FormElicitationCapabilities{}}},
wantURL: true,
wantForm: true,
},
{
name: "empty elicitation capability implies form for backward compatibility",
caps: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{}},
wantURL: false,
wantForm: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got := runProbe(t, tc.caps, nil, func(_ context.Context, p *sessionPrompter) string {
if p.CanPromptURL() {
if p.CanPromptForm() {
return "url+form"
}
return "url"
}
if p.CanPromptForm() {
return "form"
}
return "none"
})
want := "none"
switch {
case tc.wantURL && tc.wantForm:
want = "url+form"
case tc.wantURL:
want = "url"
case tc.wantForm:
want = "form"
}
assert.Equal(t, want, got)
})
}
}
func TestSessionPrompterPromptActions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
action string
wantDecline bool
}{
{name: "accept", action: "accept", wantDecline: false},
{name: "decline", action: "decline", wantDecline: true},
{name: "cancel", action: "cancel", wantDecline: true},
}
caps := &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{
URL: &mcp.URLElicitationCapabilities{},
Form: &mcp.FormElicitationCapabilities{},
}}
for _, tc := range tests {
// URL and form modes share the accept/decline mapping; cover both.
for _, mode := range []string{"url", "form"} {
t.Run(tc.name+"/"+mode, func(t *testing.T) {
t.Parallel()
handler := func(_ context.Context, _ *mcp.ElicitRequest) (*mcp.ElicitResult, error) {
return &mcp.ElicitResult{Action: tc.action}, nil
}
got := runProbe(t, caps, handler, func(ctx context.Context, p *sessionPrompter) string {
var err error
if mode == "url" {
err = p.PromptURL(ctx, oauth.Prompt{Message: "msg", URL: "https://example.com/auth"})
} else {
err = p.PromptForm(ctx, oauth.Prompt{Message: "msg"})
}
if err == nil {
return "ok"
}
if err == oauth.ErrPromptDeclined {
return "declined"
}
return "error: " + err.Error()
})
if tc.wantDecline {
assert.Equal(t, "declined", got)
} else {
assert.Equal(t, "ok", got)
}
})
}
}
}
// TestSessionPrompterTransportError verifies that a prompt which fails to be
// delivered (the client errors instead of returning an action) is reported as
// ErrPromptUnavailable, not ErrPromptDeclined. The manager relies on this
// distinction to fall back to manual instructions instead of aborting.
func TestSessionPrompterTransportError(t *testing.T) {
t.Parallel()
caps := &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{
URL: &mcp.URLElicitationCapabilities{},
Form: &mcp.FormElicitationCapabilities{},
}}
for _, mode := range []string{"url", "form"} {
t.Run(mode, func(t *testing.T) {
t.Parallel()
handler := func(_ context.Context, _ *mcp.ElicitRequest) (*mcp.ElicitResult, error) {
return nil, errors.New("client cannot deliver elicitation")
}
got := runProbe(t, caps, handler, func(ctx context.Context, p *sessionPrompter) string {
var err error
if mode == "url" {
err = p.PromptURL(ctx, oauth.Prompt{Message: "msg", URL: "https://example.com/auth"})
} else {
err = p.PromptForm(ctx, oauth.Prompt{Message: "msg"})
}
switch {
case err == nil:
return "ok"
case errors.Is(err, oauth.ErrPromptDeclined):
return "declined"
case errors.Is(err, oauth.ErrPromptUnavailable):
return "unavailable"
default:
return "error: " + err.Error()
}
})
assert.Equal(t, "unavailable", got,
"a delivery failure must be classified as undeliverable, not a decline")
})
}
}
// fakeAuthenticator is a deterministic stand-in for *oauth.Manager that lets the
// middleware be tested at each branch without standing up live GitHub flows.
type fakeAuthenticator struct {
hasToken bool
outcome *oauth.Outcome
err error
authCalls int
lastPrompter oauth.Prompter
}
func (f *fakeAuthenticator) HasToken() bool { return f.hasToken }
func (f *fakeAuthenticator) Authenticate(_ context.Context, prompter oauth.Prompter) (*oauth.Outcome, error) {
f.authCalls++
f.lastPrompter = prompter
return f.outcome, f.err
}
func TestCreateOAuthMiddleware(t *testing.T) {
t.Parallel()
const nextText = "handler-ran"
newNext := func(called *bool) mcp.MethodHandler {
return func(_ context.Context, _ string, _ mcp.Request) (mcp.Result, error) {
*called = true
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: nextText}}}, nil
}
}
t.Run("non tool call passes through without authenticating", func(t *testing.T) {
t.Parallel()
fake := &fakeAuthenticator{hasToken: false}
var called bool
mw := createOAuthMiddleware(fake, discardLogger())
_, err := mw(newNext(&called))(context.Background(), "initialize", &mcp.InitializeRequest{})
require.NoError(t, err)
assert.True(t, called, "next should run")
assert.Zero(t, fake.authCalls, "authentication must not run for non tool calls")
})
t.Run("existing token short circuits authentication", func(t *testing.T) {
t.Parallel()
fake := &fakeAuthenticator{hasToken: true}
var called bool
mw := createOAuthMiddleware(fake, discardLogger())
_, err := mw(newNext(&called))(context.Background(), "tools/call", &mcp.CallToolRequest{})
require.NoError(t, err)
assert.True(t, called, "next should run")
assert.Zero(t, fake.authCalls, "authentication must be skipped when a token already exists")
})
t.Run("successful authentication proceeds to handler", func(t *testing.T) {
t.Parallel()
fake := &fakeAuthenticator{hasToken: false, outcome: nil, err: nil}
var called bool
mw := createOAuthMiddleware(fake, discardLogger())
res, err := mw(newNext(&called))(context.Background(), "tools/call", &mcp.CallToolRequest{})
require.NoError(t, err)
assert.Equal(t, 1, fake.authCalls)
assert.True(t, called, "next should run once authorized")
callRes, ok := res.(*mcp.CallToolResult)
require.True(t, ok)
require.Len(t, callRes.Content, 1)
assert.Equal(t, nextText, callRes.Content[0].(*mcp.TextContent).Text)
})
t.Run("pending user action is surfaced as a tool result", func(t *testing.T) {
t.Parallel()
const message = "Open https://example.com/auth to authorize, then retry."
fake := &fakeAuthenticator{hasToken: false, outcome: &oauth.Outcome{UserAction: &oauth.UserAction{Message: message}}}
var called bool
mw := createOAuthMiddleware(fake, discardLogger())
res, err := mw(newNext(&called))(context.Background(), "tools/call", &mcp.CallToolRequest{})
require.NoError(t, err)
assert.False(t, called, "next must not run while the user still needs to authorize")
callRes, ok := res.(*mcp.CallToolResult)
require.True(t, ok)
require.Len(t, callRes.Content, 1)
assert.Equal(t, message, callRes.Content[0].(*mcp.TextContent).Text)
})
t.Run("authentication error is returned", func(t *testing.T) {
t.Parallel()
fake := &fakeAuthenticator{hasToken: false, err: assert.AnError}
var called bool
mw := createOAuthMiddleware(fake, discardLogger())
_, err := mw(newNext(&called))(context.Background(), "tools/call", &mcp.CallToolRequest{})
require.Error(t, err)
assert.ErrorIs(t, err, assert.AnError)
assert.False(t, called, "next must not run when authentication fails")
})
}
// TestRunStdioServerRejectsTokenAndOAuth verifies the mutually-exclusive guard:
// supplying both a static token and an OAuth manager is rejected before the
// server starts, rather than silently preferring one for auth and the other for
// scope filtering.
func TestRunStdioServerRejectsTokenAndOAuth(t *testing.T) {
t.Parallel()
mgr := oauth.NewManager(oauth.NewGitHubConfig("client-id", "", nil, "", 0), discardLogger())
err := RunStdioServer(StdioServerConfig{
Token: "ghp_static",
OAuthManager: mgr,
})
require.Error(t, err)
assert.Contains(t, err.Error(), "mutually exclusive")
}
// TestCreateGitHubClientsTokenProvider proves the OAuth wiring: when a
// TokenProvider is configured the REST client authenticates with the provider's
// current token on every request (and never pins a stale one), which is what the
// lazy, refreshing OAuth token depends on.
func TestCreateGitHubClientsTokenProvider(t *testing.T) {
t.Parallel()
var gotAuth string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get(headers.AuthorizationHeader)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
current := ""
apiHost, err := utils.NewAPIHost(server.URL)
require.NoError(t, err)
clients, err := createGitHubClients(github.MCPServerConfig{
Version: "test",
TokenProvider: func() string { return current },
}, apiHost)
require.NoError(t, err)
do := func() {
resp, err := clients.rest.Client().Get(server.URL)
require.NoError(t, err)
defer resp.Body.Close()
}
do()
assert.Equal(t, "", gotAuth, "no auth header before authorization")
current = "oauth-token"
do()
assert.Equal(t, "Bearer oauth-token", gotAuth, "provider token used once available")
current = "refreshed-token"
do()
assert.Equal(t, "Bearer refreshed-token", gotAuth, "refreshed provider token used")
}
+446
View File
@@ -0,0 +1,446 @@
package ghmcp
import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/github/github-mcp-server/internal/oauth"
"github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/github"
"github.com/github/github-mcp-server/pkg/http/transport"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/lockdown"
mcplog "github.com/github/github-mcp-server/pkg/log"
"github.com/github/github-mcp-server/pkg/observability"
"github.com/github/github-mcp-server/pkg/observability/metrics"
"github.com/github/github-mcp-server/pkg/raw"
"github.com/github/github-mcp-server/pkg/scopes"
"github.com/github/github-mcp-server/pkg/translations"
"github.com/github/github-mcp-server/pkg/utils"
gogithub "github.com/google/go-github/v89/github"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shurcooL/githubv4"
)
// githubClients holds all the GitHub API clients created for a server instance.
type githubClients struct {
rest *gogithub.Client
restUATransp *transport.UserAgentTransport
gql *githubv4.Client
gqlHTTP *http.Client // retained for middleware to modify transport
raw *raw.Client
repoAccess *lockdown.RepoAccessCache
}
// createGitHubClients creates all the GitHub API clients needed by the server.
func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolver) (*githubClients, error) {
restURL, err := apiHost.BaseRESTURL(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get base REST URL: %w", err)
}
uploadURL, err := apiHost.UploadURL(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get upload URL: %w", err)
}
graphQLURL, err := apiHost.GraphqlURL(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get GraphQL URL: %w", err)
}
rawURL, err := apiHost.RawURL(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get Raw URL: %w", err)
}
// Construct REST client. When a TokenProvider is configured (OAuth), we
// authenticate via BearerAuthTransport and skip go-github's WithAuthToken:
// the latter installs its own round tripper that would pin the static token
// and shadow the dynamic one.
restUATransport := &transport.UserAgentTransport{
Transport: http.DefaultTransport,
Agent: fmt.Sprintf("github-mcp-server/%s", cfg.Version),
}
var restClient *gogithub.Client
if cfg.TokenProvider != nil {
restClient, err = gogithub.NewClient(
gogithub.WithHTTPClient(&http.Client{Transport: &transport.BearerAuthTransport{
Transport: restUATransport,
TokenProvider: cfg.TokenProvider,
}}),
gogithub.WithEnterpriseURLs(restURL.String(), uploadURL.String()),
)
} else {
restClient, err = gogithub.NewClient(
gogithub.WithHTTPClient(&http.Client{Transport: restUATransport}),
gogithub.WithAuthToken(cfg.Token),
gogithub.WithEnterpriseURLs(restURL.String(), uploadURL.String()),
)
}
if err != nil {
return nil, fmt.Errorf("failed to create REST client: %w", err)
}
// Construct GraphQL client
// We use NewEnterpriseClient unconditionally since we already parsed the API host
gqlHTTPClient := &http.Client{
Transport: &transport.BearerAuthTransport{
Transport: &transport.GraphQLFeaturesTransport{
Transport: http.DefaultTransport,
},
Token: cfg.Token,
TokenProvider: cfg.TokenProvider,
},
}
gqlClient := githubv4.NewEnterpriseClient(graphQLURL.String(), gqlHTTPClient)
// Create raw content client (shares REST client's HTTP transport)
rawClient, err := raw.NewClient(restClient, rawURL)
if err != nil {
return nil, fmt.Errorf("failed to create raw client: %w", err)
}
// Set up repo access cache for lockdown mode
var repoAccessCache *lockdown.RepoAccessCache
if cfg.LockdownMode {
opts := []lockdown.RepoAccessOption{
lockdown.WithLogger(cfg.Logger.With("component", "lockdown")),
}
if cfg.RepoAccessTTL != nil {
opts = append(opts, lockdown.WithTTL(*cfg.RepoAccessTTL))
}
repoAccessCache = lockdown.NewRepoAccessCache(gqlClient, restClient, opts...)
}
return &githubClients{
rest: restClient,
restUATransp: restUATransport,
gql: gqlClient,
gqlHTTP: gqlHTTPClient,
raw: rawClient,
repoAccess: repoAccessCache,
}, nil
}
func NewStdioMCPServer(ctx context.Context, cfg github.MCPServerConfig) (*mcp.Server, error) {
apiHost, err := utils.NewAPIHost(cfg.Host)
if err != nil {
return nil, fmt.Errorf("failed to parse API host: %w", err)
}
clients, err := createGitHubClients(cfg, apiHost)
if err != nil {
return nil, fmt.Errorf("failed to create GitHub clients: %w", err)
}
// Create feature checker — resolves explicit features + insiders expansion
featureChecker := createFeatureChecker(cfg.EnabledFeatures, cfg.InsidersMode)
// Create dependencies for tool handlers
obs, err := observability.NewExporters(cfg.Logger, metrics.NewNoopMetrics())
if err != nil {
return nil, fmt.Errorf("failed to create observability exporters: %w", err)
}
deps := github.NewBaseDeps(
clients.rest,
clients.gql,
clients.raw,
clients.repoAccess,
cfg.Translator,
github.FeatureFlags{
LockdownMode: cfg.LockdownMode,
},
cfg.ContentWindowSize,
featureChecker,
obs,
)
// Build and register the tool/resource/prompt inventory
inventoryBuilder := github.NewInventory(cfg.Translator).
WithDeprecatedAliases(github.DeprecatedToolAliases).
WithReadOnly(cfg.ReadOnly).
WithToolsets(github.ResolvedEnabledToolsets(cfg.EnabledToolsets, cfg.EnabledTools)).
WithTools(github.CleanTools(cfg.EnabledTools)).
WithExcludeTools(cfg.ExcludeTools).
WithServerInstructions().
WithFeatureChecker(featureChecker)
// Apply token scope filtering if scopes are known (for PAT filtering)
if cfg.TokenScopes != nil {
inventoryBuilder = inventoryBuilder.WithFilter(github.CreateToolScopeFilter(cfg.TokenScopes))
}
inventory, err := inventoryBuilder.Build()
if err != nil {
return nil, fmt.Errorf("failed to build inventory: %w", err)
}
ghServer, err := github.NewMCPServer(ctx, &cfg, deps, inventory)
if err != nil {
return nil, fmt.Errorf("failed to create GitHub MCP server: %w", err)
}
ghServer.AddReceivingMiddleware(addUserAgentsMiddleware(cfg, clients.restUATransp, clients.gqlHTTP))
return ghServer, nil
}
type StdioServerConfig 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
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
// EnabledTools is a list of specific tools to enable (additive to toolsets)
// When specified, these tools are registered in addition to any specified toolset tools
EnabledTools []string
// EnabledFeatures is a list of feature flags that are enabled
// Items with FeatureFlagEnable matching an entry in this list will be available
EnabledFeatures []string
// 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
// LockdownMode indicates if we should enable lockdown mode
LockdownMode bool
// InsidersMode expands to the curated set of feature flags enabled for insiders.
InsidersMode bool
// ExcludeTools is a list of tool names to disable regardless of other settings.
// These tools will be excluded even if their toolset is enabled or they are
// explicitly listed in EnabledTools.
ExcludeTools []string
// RepoAccessCacheTTL overrides the default TTL for repository access cache entries.
RepoAccessCacheTTL *time.Duration
// OAuthManager, when non-nil, enables OAuth 2.1 login for stdio mode. The
// server starts without a token and runs the authorization flow on the
// first tool call (see createOAuthMiddleware). It is mutually exclusive with
// a static Token.
OAuthManager *oauth.Manager
// OAuthScopes are the scopes requested during OAuth login. They double as
// the scope set for tool filtering: tools requiring a scope outside this set
// are hidden. The default set is the full supported list, which hides
// nothing; an explicit, narrower list filters accordingly.
OAuthScopes []string
}
// RunStdioServer is not concurrent safe.
func RunStdioServer(cfg StdioServerConfig) error {
// OAuth login and a static token are mutually exclusive: they would
// disagree on how the token is sourced (lazy provider vs. static) and on
// scope filtering, so reject the ambiguous combination up front.
if cfg.OAuthManager != nil && cfg.Token != "" {
return fmt.Errorf("OAuthManager and a static Token are mutually exclusive: provide one or the other")
}
// Create app context
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
t, dumpTranslations := translations.TranslationHelper()
var slogHandler slog.Handler
var logOutput io.Writer
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)
}
logOutput = file
slogHandler = slog.NewTextHandler(logOutput, &slog.HandlerOptions{Level: slog.LevelDebug})
} else {
logOutput = os.Stderr
slogHandler = slog.NewTextHandler(logOutput, &slog.HandlerOptions{Level: slog.LevelInfo})
}
logger := slog.New(slogHandler)
logger.Info("starting server", "version", cfg.Version, "host", cfg.Host, "readOnly", cfg.ReadOnly, "lockdownEnabled", cfg.LockdownMode)
// Determine the scope set used to filter tools. Classic PATs expose their
// granted scopes via the API; OAuth uses the requested scopes (the default
// set hides nothing, a narrower explicit set filters accordingly). Other
// token types don't advertise scopes, so filtering is skipped.
var tokenScopes []string
switch {
case strings.HasPrefix(cfg.Token, "ghp_"):
fetchedScopes, err := fetchTokenScopesForHost(ctx, cfg.Token, cfg.Host)
if err != nil {
logger.Warn("failed to fetch token scopes, continuing without scope filtering", "error", err)
} else {
tokenScopes = fetchedScopes
logger.Info("token scopes fetched for filtering", "scopes", tokenScopes)
}
case cfg.OAuthManager != nil:
tokenScopes = cfg.OAuthScopes
logger.Info("using requested OAuth scopes for tool filtering", "scopes", tokenScopes)
default:
logger.Debug("skipping scope filtering for non-PAT token")
}
// For OAuth, the token is resolved lazily: empty until the user authorizes
// on the first tool call, then refreshed for the rest of the session.
var tokenProvider func() string
if cfg.OAuthManager != nil {
tokenProvider = cfg.OAuthManager.AccessToken
}
ghServer, err := NewStdioMCPServer(ctx, github.MCPServerConfig{
Version: cfg.Version,
Host: cfg.Host,
Token: cfg.Token,
EnabledToolsets: cfg.EnabledToolsets,
EnabledTools: cfg.EnabledTools,
EnabledFeatures: cfg.EnabledFeatures,
ReadOnly: cfg.ReadOnly,
Translator: t,
ContentWindowSize: cfg.ContentWindowSize,
LockdownMode: cfg.LockdownMode,
InsidersMode: cfg.InsidersMode,
ExcludeTools: cfg.ExcludeTools,
Logger: logger,
RepoAccessTTL: cfg.RepoAccessCacheTTL,
TokenScopes: tokenScopes,
TokenProvider: tokenProvider,
})
if err != nil {
return fmt.Errorf("failed to create MCP server: %w", err)
}
// With OAuth, intercept tool calls to run the authorization flow on first
// use, before the handler tries to call GitHub with an empty token.
if cfg.OAuthManager != nil {
ghServer.AddReceivingMiddleware(createOAuthMiddleware(cfg.OAuthManager, logger))
}
if cfg.ExportTranslations {
// Once server is initialized, all translations are loaded
dumpTranslations()
}
// Start listening for messages
errC := make(chan error, 1)
go func() {
var in io.ReadCloser
var out io.WriteCloser
in = os.Stdin
out = os.Stdout
if cfg.EnableCommandLogging {
loggedIO := mcplog.NewIOLogger(in, out, logger)
in, out = loggedIO, loggedIO
}
// enable GitHub errors in the context
ctx := errors.ContextWithGitHubErrors(ctx)
errC <- ghServer.Run(ctx, &mcp.IOTransport{Reader: in, Writer: out})
}()
// Output github-mcp-server string
_, _ = fmt.Fprintf(os.Stderr, "GitHub MCP Server running on stdio\n")
// Wait for shutdown signal
select {
case <-ctx.Done():
logger.Info("shutting down server", "signal", "context done")
case err := <-errC:
if err != nil {
logger.Error("error running server", "error", err)
return fmt.Errorf("error running server: %w", err)
}
}
return nil
}
// createFeatureChecker returns a FeatureFlagChecker that resolves features
// using the centralized ResolveFeatureFlags function. For the local server,
// features are resolved once at startup from --features CLI flag and insiders mode.
func createFeatureChecker(enabledFeatures []string, insidersMode bool) inventory.FeatureFlagChecker {
featureSet := github.ResolveFeatureFlags(enabledFeatures, insidersMode)
return func(_ context.Context, flagName string) (bool, error) {
return featureSet[flagName], nil
}
}
func addUserAgentsMiddleware(cfg github.MCPServerConfig, restUATransp *transport.UserAgentTransport, gqlHTTPClient *http.Client) func(next mcp.MethodHandler) mcp.MethodHandler {
return func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, request mcp.Request) (result mcp.Result, err error) {
if method != "initialize" {
return next(ctx, method, request)
}
initializeRequest, ok := request.(*mcp.InitializeRequest)
if !ok {
return next(ctx, method, request)
}
message := initializeRequest
userAgent := fmt.Sprintf(
"github-mcp-server/%s (%s/%s)",
cfg.Version,
message.Params.ClientInfo.Name,
message.Params.ClientInfo.Version,
)
if cfg.InsidersMode {
userAgent += " (insiders)"
}
restUATransp.Agent = userAgent
gqlHTTPClient.Transport = &transport.UserAgentTransport{
Transport: gqlHTTPClient.Transport,
Agent: userAgent,
}
return next(ctx, method, request)
}
}
}
// fetchTokenScopesForHost fetches the OAuth scopes for a token from the GitHub API.
// It constructs the appropriate API host URL based on the configured host.
func fetchTokenScopesForHost(ctx context.Context, token, host string) ([]string, error) {
apiHost, err := utils.NewAPIHost(host)
if err != nil {
return nil, fmt.Errorf("failed to parse API host: %w", err)
}
fetcher := scopes.NewFetcher(apiHost, scopes.FetcherOptions{})
return fetcher.FetchTokenScopes(ctx, token)
}
+1
View File
@@ -0,0 +1 @@
package ghmcp
+218
View File
@@ -0,0 +1,218 @@
// githubv4mock package provides a mock GraphQL server used for testing queries produced via
// shurcooL/githubv4 or shurcooL/graphql modules.
package githubv4mock
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type Matcher struct {
Request string
Variables map[string]any
Response GQLResponse
}
// NewQueryMatcher constructs a new matcher for the provided query and variables.
// If the provided query is a string, it will be used-as-is, otherwise it will be
// converted to a string using the constructQuery function taken from shurcooL/graphql.
func NewQueryMatcher(query any, variables map[string]any, response GQLResponse) Matcher {
queryString, ok := query.(string)
if !ok {
queryString = constructQuery(query, variables)
}
return Matcher{
Request: queryString,
Variables: variables,
Response: response,
}
}
// NewMutationMatcher constructs a new matcher for the provided mutation and variables.
// If the provided mutation is a string, it will be used-as-is, otherwise it will be
// converted to a string using the constructMutation function taken from shurcooL/graphql.
//
// The input parameter is a special form of variable, matching the usage in shurcooL/githubv4. It will be added
// to the query as a variable called `input`. Furthermore, it will be converted to a map[string]any
// to be used for later equality comparison, as when the http handler is called, the request body will no longer
// contain the input struct type information.
func NewMutationMatcher(mutation any, input any, variables map[string]any, response GQLResponse) Matcher {
mutationString, ok := mutation.(string)
if !ok {
// Matching shurcooL/githubv4 mutation behaviour found in https://github.com/shurcooL/githubv4/blob/48295856cce734663ddbd790ff54800f784f3193/githubv4.go#L45-L56
if variables == nil {
variables = map[string]any{"input": input}
} else {
variables["input"] = input
}
mutationString = constructMutation(mutation, variables)
m, _ := githubv4InputStructToMap(input)
variables["input"] = m
}
return Matcher{
Request: mutationString,
Variables: variables,
Response: response,
}
}
type GQLResponse struct {
Data map[string]any `json:"data"`
Errors []struct {
Message string `json:"message"`
} `json:"errors,omitempty"`
}
// DataResponse is the happy path response constructor for a mocked GraphQL request.
func DataResponse(data map[string]any) GQLResponse {
return GQLResponse{
Data: data,
}
}
// ErrorResponse is the unhappy path response constructor for a mocked GraphQL request.\
// Note that for the moment it is only possible to return a single error message.
func ErrorResponse(errorMsg string) GQLResponse {
return GQLResponse{
Errors: []struct {
Message string `json:"message"`
}{
{
Message: errorMsg,
},
},
}
}
// githubv4InputStructToMap converts a struct to a map[string]any, it uses JSON marshalling rather than reflection
// to do so, because the json struct tags are used in the real implementation to produce the variable key names,
// and we need to ensure that when variable matching occurs in the http handler, the keys correctly match.
func githubv4InputStructToMap(s any) (map[string]any, error) {
jsonBytes, err := json.Marshal(s)
if err != nil {
return nil, err
}
var result map[string]any
err = json.Unmarshal(jsonBytes, &result)
return result, err
}
// NewMockedHTTPClient creates a new HTTP client that registers a handler for /graphql POST requests.
// For each request, an attempt will be be made to match the request body against the provided matchers.
// If a match is found, the corresponding response will be returned with StatusOK.
//
// Note that query and variable matching can be slightly fickle. The client expects an EXACT match on the query,
// which in most cases will have been constructed from a type with graphql tags. The query construction code in
// shurcooL/githubv4 uses the field types to derive the query string, thus a go string is not the same as a graphql.ID,
// even though `type ID string`. It is therefore expected that matching variables have the right type for example:
//
// githubv4mock.NewQueryMatcher(
// struct {
// Repository struct {
// PullRequest struct {
// ID githubv4.ID
// } `graphql:"pullRequest(number: $prNum)"`
// } `graphql:"repository(owner: $owner, name: $repo)"`
// }{},
// map[string]any{
// "owner": githubv4.String("owner"),
// "repo": githubv4.String("repo"),
// "prNum": githubv4.Int(42),
// },
// githubv4mock.DataResponse(
// map[string]any{
// "repository": map[string]any{
// "pullRequest": map[string]any{
// "id": "PR_kwDODKw3uc6WYN1T",
// },
// },
// },
// ),
// )
//
// To aid in variable equality checks, values are considered equal if they approximate to the same type. This is
// required because when the http handler is called, the request body no longer has the type information. This manifests
// particularly when using the githubv4.Input types which have type deffed fields in their structs. For example:
//
// type CloseIssueInput struct {
// IssueID ID `json:"issueId"`
// StateReason *IssueClosedStateReason `json:"stateReason,omitempty"`
// }
//
// This client does not currently provide a mechanism for out-of-band errors e.g. returning a 500,
// and errors are constrained to GQL errors returned in the response body with a 200 status code.
func NewMockedHTTPClient(ms ...Matcher) *http.Client {
matchers := make(map[string]Matcher, len(ms))
for _, m := range ms {
matchers[m.Request] = m
}
mux := http.NewServeMux()
mux.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
gqlRequest, err := parseBody(r.Body)
if err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
defer func() { _ = r.Body.Close() }()
matcher, ok := matchers[gqlRequest.Query]
if !ok {
http.Error(w, fmt.Sprintf("no matcher found for query %s", gqlRequest.Query), http.StatusNotFound)
return
}
if len(gqlRequest.Variables) > 0 {
if len(gqlRequest.Variables) != len(matcher.Variables) {
http.Error(w, "variables do not have the same length", http.StatusBadRequest)
return
}
for k, v := range matcher.Variables {
if !objectsAreEqualValues(v, gqlRequest.Variables[k]) {
http.Error(w, "variable does not match", http.StatusBadRequest)
return
}
}
}
responseBody, err := json.Marshal(matcher.Response)
if err != nil {
http.Error(w, "error marshalling response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(responseBody)
})
return &http.Client{Transport: &localRoundTripper{
handler: mux,
}}
}
type gqlRequest struct {
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
}
func parseBody(r io.Reader) (gqlRequest, error) {
var req gqlRequest
err := json.NewDecoder(r).Decode(&req)
return req, err
}
func Ptr[T any](v T) *T { return &v }
@@ -0,0 +1,44 @@
// Ths contents of this file are taken from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/graphql_test.go#L155-L165
// because they are not exported by the module, and we would like to use them in building the githubv4mock test utility.
//
// The original license, copied from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/LICENSE
//
// MIT License
// Copyright (c) 2017 Dmitri Shuralyov
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package githubv4mock
import (
"net/http"
"net/http/httptest"
)
// localRoundTripper is an http.RoundTripper that executes HTTP transactions
// by using handler directly, instead of going over an HTTP connection.
type localRoundTripper struct {
handler http.Handler
}
func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
l.handler.ServeHTTP(w, req)
return w.Result(), nil
}
@@ -0,0 +1,113 @@
// The contents of this file are taken from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/assert/assertions.go#L166
// because I do not want to take a dependency on the entire testify module just to use this equality check.
//
// There is a modification in objectsAreEqual to check that typed nils are equal, even if their types are different.
//
// The original license, copied from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/LICENSE
//
// MIT License
//
// Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package githubv4mock
import (
"bytes"
"reflect"
)
func objectsAreEqualValues(expected, actual any) bool {
if objectsAreEqual(expected, actual) {
return true
}
expectedValue := reflect.ValueOf(expected)
actualValue := reflect.ValueOf(actual)
if !expectedValue.IsValid() || !actualValue.IsValid() {
return false
}
expectedType := expectedValue.Type()
actualType := actualValue.Type()
if !expectedType.ConvertibleTo(actualType) {
return false
}
if !isNumericType(expectedType) || !isNumericType(actualType) {
// Attempt comparison after type conversion
return reflect.DeepEqual(
expectedValue.Convert(actualType).Interface(), actual,
)
}
// If BOTH values are numeric, there are chances of false positives due
// to overflow or underflow. So, we need to make sure to always convert
// the smaller type to a larger type before comparing.
if expectedType.Size() >= actualType.Size() {
return actualValue.Convert(expectedType).Interface() == expected
}
return expectedValue.Convert(actualType).Interface() == actual
}
// objectsAreEqual determines if two objects are considered equal.
//
// This function does no assertion of any kind.
func objectsAreEqual(expected, actual any) bool {
// There is a modification in objectsAreEqual to check that typed nils are equal, even if their types are different.
// This is required because when a nil is provided as a variable, the type is not known.
if isNil(expected) && isNil(actual) {
return true
}
exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
}
act, ok := actual.([]byte)
if !ok {
return false
}
if exp == nil || act == nil {
return exp == nil && act == nil
}
return bytes.Equal(exp, act)
}
// isNumericType returns true if the type is one of:
// int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,
// float32, float64, complex64, complex128
func isNumericType(t reflect.Type) bool {
return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128
}
func isNil(i any) bool {
if i == nil {
return true
}
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return v.IsNil()
default:
return false
}
}
@@ -0,0 +1,73 @@
// The contents of this file are taken from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/assert/assertions_test.go#L140-L174
//
// There is a modification to test objectsAreEqualValues to check that typed nils are equal, even if their types are different.
// The original license, copied from https://github.com/stretchr/testify/blob/016e2e9c269209287f33ec203f340a9a723fe22c/LICENSE
//
// MIT License
//
// Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package githubv4mock
import (
"fmt"
"math"
"testing"
"time"
)
func TestObjectsAreEqualValues(t *testing.T) {
now := time.Now()
cases := []struct {
expected interface{}
actual interface{}
result bool
}{
{uint32(10), int32(10), true},
{0, nil, false},
{nil, 0, false},
{now, now.In(time.Local), false}, // should not be time zone independent
{int(270), int8(14), false}, // should handle overflow/underflow
{int8(14), int(270), false},
{[]int{270, 270}, []int8{14, 14}, false},
{complex128(1e+100 + 1e+100i), complex64(complex(math.Inf(0), math.Inf(0))), false},
{complex64(complex(math.Inf(0), math.Inf(0))), complex128(1e+100 + 1e+100i), false},
{complex128(1e+100 + 1e+100i), 270, false},
{270, complex128(1e+100 + 1e+100i), false},
{complex128(1e+100 + 1e+100i), 3.14, false},
{3.14, complex128(1e+100 + 1e+100i), false},
{complex128(1e+10 + 1e+10i), complex64(1e+10 + 1e+10i), true},
{complex64(1e+10 + 1e+10i), complex128(1e+10 + 1e+10i), true},
{(*string)(nil), nil, true}, // typed nil vs untyped nil
{(*string)(nil), (*int)(nil), true}, // different typed nils
}
for _, c := range cases {
t.Run(fmt.Sprintf("ObjectsAreEqualValues(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
res := objectsAreEqualValues(c.expected, c.actual)
if res != c.result {
t.Errorf("ObjectsAreEqualValues(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
}
})
}
}
+157
View File
@@ -0,0 +1,157 @@
// Ths contents of this file are taken from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/query.go
// because they are not exported by the module, and we would like to use them in building the githubv4mock test utility.
//
// The original license, copied from https://github.com/shurcooL/graphql/blob/ed46e5a4646634fc16cb07c3b8db389542cc8847/LICENSE
//
// MIT License
// Copyright (c) 2017 Dmitri Shuralyov
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package githubv4mock
import (
"bytes"
"encoding/json"
"io"
"reflect"
"sort"
"github.com/shurcooL/graphql/ident"
)
func constructQuery(v any, variables map[string]any) string {
query := query(v)
if len(variables) > 0 {
return "query(" + queryArguments(variables) + ")" + query
}
return query
}
func constructMutation(v any, variables map[string]any) string {
query := query(v)
if len(variables) > 0 {
return "mutation(" + queryArguments(variables) + ")" + query
}
return "mutation" + query
}
// queryArguments constructs a minified arguments string for variables.
//
// E.g., map[string]any{"a": Int(123), "b": NewBoolean(true)} -> "$a:Int!$b:Boolean".
func queryArguments(variables map[string]any) string {
// Sort keys in order to produce deterministic output for testing purposes.
// TODO: If tests can be made to work with non-deterministic output, then no need to sort.
keys := make([]string, 0, len(variables))
for k := range variables {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, k := range keys {
_, _ = io.WriteString(&buf, "$")
_, _ = io.WriteString(&buf, k)
_, _ = io.WriteString(&buf, ":")
writeArgumentType(&buf, reflect.TypeOf(variables[k]), true)
// Don't insert a comma here.
// Commas in GraphQL are insignificant, and we want minified output.
// See https://spec.graphql.org/October2021/#sec-Insignificant-Commas.
}
return buf.String()
}
// writeArgumentType writes a minified GraphQL type for t to w.
// value indicates whether t is a value (required) type or pointer (optional) type.
// If value is true, then "!" is written at the end of t.
func writeArgumentType(w io.Writer, t reflect.Type, value bool) {
if t.Kind() == reflect.Ptr {
// Pointer is an optional type, so no "!" at the end of the pointer's underlying type.
writeArgumentType(w, t.Elem(), false)
return
}
switch t.Kind() {
case reflect.Slice, reflect.Array:
// List. E.g., "[Int]".
_, _ = io.WriteString(w, "[")
writeArgumentType(w, t.Elem(), true)
_, _ = io.WriteString(w, "]")
default:
// Named type. E.g., "Int".
name := t.Name()
if name == "string" { // HACK: Workaround for https://github.com/shurcooL/githubv4/issues/12.
name = "ID"
}
_, _ = io.WriteString(w, name)
}
if value {
// Value is a required type, so add "!" to the end.
_, _ = io.WriteString(w, "!")
}
}
// query uses writeQuery to recursively construct
// a minified query string from the provided struct v.
//
// E.g., struct{Foo Int, BarBaz *Boolean} -> "{foo,barBaz}".
func query(v any) string {
var buf bytes.Buffer
writeQuery(&buf, reflect.TypeOf(v), false)
return buf.String()
}
// writeQuery writes a minified query for t to w.
// If inline is true, the struct fields of t are inlined into parent struct.
func writeQuery(w io.Writer, t reflect.Type, inline bool) {
switch t.Kind() {
case reflect.Ptr, reflect.Slice:
writeQuery(w, t.Elem(), false)
case reflect.Struct:
// If the type implements json.Unmarshaler, it's a scalar. Don't expand it.
if reflect.PointerTo(t).Implements(jsonUnmarshaler) {
return
}
if !inline {
_, _ = io.WriteString(w, "{")
}
for i := 0; i < t.NumField(); i++ {
if i != 0 {
_, _ = io.WriteString(w, ",")
}
f := t.Field(i)
value, ok := f.Tag.Lookup("graphql")
inlineField := f.Anonymous && !ok
if !inlineField {
if ok {
_, _ = io.WriteString(w, value)
} else {
_, _ = io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase())
}
}
writeQuery(w, f.Type, inlineField)
}
if !inline {
_, _ = io.WriteString(w, "}")
}
}
}
var jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()
+157
View File
@@ -0,0 +1,157 @@
package oauth
import (
"context"
"embed"
"fmt"
"html/template"
"net"
"net/http"
"time"
)
//go:embed templates/*.html
var templateFS embed.FS
var (
errorTemplate = template.Must(template.ParseFS(templateFS, "templates/error.html"))
successTemplate = template.Must(template.ParseFS(templateFS, "templates/success.html"))
)
// callbackResult is delivered by the callback server once the browser redirect
// arrives. Exactly one of code or err is set.
type callbackResult struct {
code string
err error
}
// callbackServer is a short-lived local HTTP server that captures the
// authorization code from the OAuth redirect.
type callbackServer struct {
server *http.Server
listener net.Listener
redirect string
results chan callbackResult
}
// listenCallback binds the local callback listener.
//
// It binds to loopback (127.0.0.1) by default so the callback server is never
// exposed on other interfaces. bindAll is set only inside a container, where
// Docker's published-port DNAT delivers traffic to the container's eth0 rather
// than to loopback; host-side exposure is still constrained by the publish
// (e.g. -p 127.0.0.1:8085:8085). A native run — even with a fixed port — stays
// on loopback.
func listenCallback(port int, bindAll bool) (net.Listener, error) {
host := "127.0.0.1"
if bindAll {
host = "0.0.0.0"
}
addr := fmt.Sprintf("%s:%d", host, port)
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, fmt.Errorf("starting callback listener on %s: %w", addr, err)
}
return listener, nil
}
// newCallbackServer starts a callback server on listener that validates state
// and reports the result on a buffered channel. The redirect URI always uses
// localhost so it matches the value registered on the OAuth/GitHub App.
func newCallbackServer(listener net.Listener, expectedState string) *callbackServer {
cs := &callbackServer{
server: &http.Server{ReadHeaderTimeout: 10 * time.Second}, // ReadHeaderTimeout guards against Slowloris.
listener: listener,
redirect: fmt.Sprintf("http://localhost:%d/callback", listener.Addr().(*net.TCPAddr).Port),
results: make(chan callbackResult, 1),
}
cs.server.Handler = cs.handler(expectedState)
go func() {
if err := cs.server.Serve(listener); err != nil && err != http.ErrServerClosed {
cs.report(callbackResult{err: fmt.Errorf("callback server: %w", err)})
}
}()
return cs
}
// handler renders the callback endpoint. It reports the outcome exactly once and
// always shows the user a friendly page.
func (cs *callbackServer) handler(expectedState string) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if errCode := q.Get("error"); errCode != "" {
msg := errCode
if desc := q.Get("error_description"); desc != "" {
msg = fmt.Sprintf("%s: %s", errCode, desc)
}
cs.report(callbackResult{err: fmt.Errorf("authorization failed: %s", msg)})
renderError(w, msg)
return
}
if q.Get("state") != expectedState {
cs.report(callbackResult{err: fmt.Errorf("state mismatch (possible CSRF)")})
renderError(w, "state mismatch")
return
}
code := q.Get("code")
if code == "" {
cs.report(callbackResult{err: fmt.Errorf("no authorization code in callback")})
renderError(w, "no authorization code received")
return
}
cs.report(callbackResult{code: code})
renderSuccess(w)
})
return mux
}
// report delivers the first outcome and drops later ones (the channel is
// buffered for one; subsequent redirect retries must not block the handler).
func (cs *callbackServer) report(res callbackResult) {
select {
case cs.results <- res:
default:
}
}
// wait blocks for the callback outcome or ctx cancellation, then shuts the
// server down. It is safe to call once per server.
func (cs *callbackServer) wait(ctx context.Context) (string, error) {
defer cs.close()
select {
case res := <-cs.results:
return res.code, res.err
case <-ctx.Done():
return "", ctx.Err()
}
}
func (cs *callbackServer) close() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = cs.server.Shutdown(shutdownCtx)
_ = cs.listener.Close()
}
func renderSuccess(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := successTemplate.Execute(w, nil); err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
// renderError shows the failure page. html/template auto-escapes msg, so a
// hostile error_description cannot inject markup.
func renderError(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := errorTemplate.Execute(w, struct{ ErrorMessage string }{ErrorMessage: msg}); err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
+92
View File
@@ -0,0 +1,92 @@
package oauth
import (
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// serveCallback drives the callback handler with the given query string and
// returns the recorded response and the single reported result.
func serveCallback(t *testing.T, expectedState, query string) (*httptest.ResponseRecorder, callbackResult) {
t.Helper()
cs := &callbackServer{results: make(chan callbackResult, 1)}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/callback?"+query, nil)
cs.handler(expectedState).ServeHTTP(rec, req)
select {
case res := <-cs.results:
return rec, res
default:
t.Fatal("handler did not report a result")
return nil, callbackResult{}
}
}
func TestCallbackHandlerSuccess(t *testing.T) {
rec, res := serveCallback(t, "state123", "code=the-code&state=state123")
require.NoError(t, res.err)
assert.Equal(t, "the-code", res.code)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "Authorization Successful")
}
func TestCallbackHandlerStateMismatch(t *testing.T) {
rec, res := serveCallback(t, "expected", "code=the-code&state=attacker")
require.Error(t, res.err)
assert.Empty(t, res.code)
assert.Contains(t, res.err.Error(), "state mismatch")
assert.Contains(t, rec.Body.String(), "state mismatch")
}
func TestCallbackHandlerMissingCode(t *testing.T) {
_, res := serveCallback(t, "state123", "state=state123")
require.Error(t, res.err)
assert.Contains(t, res.err.Error(), "no authorization code")
}
func TestCallbackHandlerOAuthError(t *testing.T) {
_, res := serveCallback(t, "state123", "error=access_denied&error_description=user+said+no")
require.Error(t, res.err)
assert.Contains(t, res.err.Error(), "access_denied")
assert.Contains(t, res.err.Error(), "user said no")
}
func TestCallbackHandlerEscapesError(t *testing.T) {
rec, _ := serveCallback(t, "state123", "error=evil&error_description=%3Cscript%3Ealert(1)%3C%2Fscript%3E")
body := rec.Body.String()
assert.NotContains(t, body, "<script>", "error message must be HTML-escaped")
assert.Contains(t, body, "&lt;script&gt;")
}
func TestListenCallbackRandomPortIsLoopback(t *testing.T) {
listener, err := listenCallback(0, false)
require.NoError(t, err)
defer listener.Close()
addr, ok := listener.Addr().(*net.TCPAddr)
require.True(t, ok)
assert.True(t, addr.IP.IsLoopback(), "default bind must be loopback only, got %s", addr.IP)
assert.NotZero(t, addr.Port)
}
func TestListenCallbackBindAllForContainer(t *testing.T) {
listener, err := listenCallback(0, true)
require.NoError(t, err)
defer listener.Close()
addr, ok := listener.Addr().(*net.TCPAddr)
require.True(t, ok)
assert.True(t, addr.IP.IsUnspecified(), "bindAll must bind all interfaces, got %s", addr.IP)
}
+70
View File
@@ -0,0 +1,70 @@
package oauth
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
)
// errNoDisplay reports that the host has no display server, so no browser can be
// launched. It is a definitive headless signal (unlike a generic launch error),
// which lets the flow prefer device authorization — the only channel reachable
// from a browser on another machine (e.g. a remote SSH session).
var errNoDisplay = errors.New("no display server detected")
// openBrowser tries to open url in the user's default browser. It returns an
// error when no browser can plausibly be launched so the caller can fall back
// to elicitation. On Linux it treats a headless session (no display server) as
// unopenable, which is the common case for SSH and containers.
func openBrowser(url string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "linux":
if os.Getenv("DISPLAY") == "" && os.Getenv("WAYLAND_DISPLAY") == "" {
return errNoDisplay
}
cmd = exec.Command("xdg-open", url)
case "darwin":
cmd = exec.Command("open", url)
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
if err := cmd.Start(); err != nil {
return err
}
// The launcher (xdg-open/open/rundll32) exits as soon as it hands off to the
// browser. Reap it asynchronously so it does not linger as a zombie for the
// lifetime of this long-running server.
go func() { _ = cmd.Wait() }()
return nil
}
// isRunningInDocker reports whether the process is running inside a Docker (or
// containerd) container. Detection relies on Linux-specific paths and is always
// false elsewhere. It is used only to skip a PKCE flow that cannot work: a
// random callback port inside a container cannot be reached from the host
// browser, so we go straight to device flow in that case.
func isRunningInDocker() bool {
if runtime.GOOS != "linux" {
return false
}
if _, err := os.Stat("/.dockerenv"); err == nil {
return true
}
if data, err := os.ReadFile("/proc/1/cgroup"); err == nil {
s := string(data)
if strings.Contains(s, "docker") || strings.Contains(s, "containerd") {
return true
}
}
return false
}
+220
View File
@@ -0,0 +1,220 @@
package oauth
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/oauth2"
)
// deviceAuthTimeout bounds the synchronous device-code request made while
// preparing the device flow (before any waiting on the user).
const deviceAuthTimeout = 30 * time.Second
// errCallbackBind marks a failure to bind the local OAuth callback listener, so
// begin can treat a busy fixed port as fatal without mislabeling unrelated
// errors (e.g. a failure to generate the state parameter) as a port conflict.
var errCallbackBind = errors.New("OAuth callback listener could not bind")
// flowPlan is a prepared authorization flow ready to run in the background.
type flowPlan struct {
// run performs the blocking part of the flow (await callback + exchange, or
// poll the device endpoint) and returns the token.
run func(context.Context) (*oauth2.Token, error)
// display, if set, presents the prompt to the user via the Prompter and
// blocks until they act. ErrPromptDeclined (the user said no) or any other
// error aborts the flow, except ErrPromptUnavailable, which degrades to
// fallback when that is set.
display func(context.Context) error
// fallback, if set alongside display, is the manual user action to surface
// when the display prompt cannot be delivered (ErrPromptUnavailable). It lets
// a runtime elicitation failure degrade to the manual channel — keeping the
// background flow alive — instead of aborting.
fallback *UserAction
// userAction, if set, indicates the last-resort channel: the caller must
// surface it and the user retries after authorizing out of band.
userAction *UserAction
}
// begin selects and prepares the appropriate flow. PKCE is preferred for its
// stronger security; device flow is the fallback. A random callback port inside
// Docker cannot be reached from the host browser, so that combination goes
// straight to device flow.
func (m *Manager) begin(prompter Prompter) (*flowPlan, error) {
canPKCE := m.config.CallbackPort != 0 || !m.inDocker()
if canPKCE {
plan, err := m.beginPKCE(prompter)
if err == nil {
return plan, nil
}
// A fixed callback port that won't bind is fatal, not a cue to downgrade.
// The port was chosen deliberately (and registered with the OAuth app), so
// a bind failure means another process holds it — possibly one positioned
// to intercept the authorization redirect. Silently switching to device
// flow would mask that, so stop and make the user resolve it. Only genuine
// bind failures qualify; other errors fall through to device flow.
if m.config.CallbackPort != 0 && errors.Is(err, errCallbackBind) {
return nil, fmt.Errorf("OAuth callback port %d is not available; another process may be using it — free the port or set a different --oauth-callback-port: %w", m.config.CallbackPort, err)
}
m.logger.Info("PKCE flow unavailable, falling back to device flow", "reason", err)
} else {
m.logger.Info("no callback port inside container; using device flow")
}
return m.beginDevice(prompter)
}
// beginPKCE prepares the authorization-code + PKCE flow. It binds the callback
// server and selects the most secure available display channel: browser
// auto-open, then URL elicitation, then a tool-response message. On a headless
// host with a random callback port it diverts to device flow, whose redirect
// does not depend on reaching this machine's localhost.
func (m *Manager) beginPKCE(prompter Prompter) (*flowPlan, error) {
state, err := randomState()
if err != nil {
return nil, err
}
verifier := oauth2.GenerateVerifier()
// Bind to all interfaces only inside a container, where the published port
// is delivered via eth0 rather than loopback. Native runs stay on loopback.
listener, err := listenCallback(m.config.CallbackPort, m.inDocker())
if err != nil {
return nil, fmt.Errorf("%w: %w", errCallbackBind, err)
}
if m.inDocker() {
// Inside a container the callback binds all interfaces so the published
// port is reachable, which also exposes it to the container network.
// Publishing to loopback only (e.g. -p 127.0.0.1:%d:%d) keeps the
// authorization code off the network.
m.logger.Warn(fmt.Sprintf("OAuth callback is listening on all container interfaces; publish it to loopback only (e.g. -p 127.0.0.1:%d:%d) so the authorization code is not exposed on your network", m.config.CallbackPort, m.config.CallbackPort))
}
cs := newCallbackServer(listener, state)
oc := m.oauth2Config(cs.redirect)
authURL := oc.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier))
run := func(ctx context.Context) (*oauth2.Token, error) {
code, err := cs.wait(ctx)
if err != nil {
return nil, err
}
tok, err := oc.Exchange(ctx, code, oauth2.VerifierOption(verifier))
if err != nil {
return nil, fmt.Errorf("exchanging authorization code: %w", err)
}
return tok, nil
}
browserErr := m.openURL(authURL)
switch {
case browserErr == nil:
m.logger.Info("opened browser for GitHub authorization")
return &flowPlan{run: run}, nil
case errors.Is(browserErr, errNoDisplay) && m.config.CallbackPort == 0:
// Headless host with a random callback port: every PKCE channel ends in a
// redirect to this machine's localhost, which a browser on another machine
// (e.g. a remote SSH client) cannot reach — so even URL elicitation would
// dead-end. Device flow is the only channel reachable from elsewhere, so
// prefer it when the app supports it; otherwise fall through to the manual
// authorization URL below for a same-machine browser.
plan, deviceErr := m.beginDevice(prompter)
if deviceErr == nil {
cs.close()
m.logger.Info("no display server; using device flow")
return plan, nil
}
m.logger.Debug("device flow unavailable on headless host; offering manual authorization URL", "reason", deviceErr)
default:
m.logger.Debug("browser auto-open unavailable", "reason", browserErr)
}
// The manual instructions double as the fallback if a chosen display channel
// turns out to be undeliverable at runtime, so build them once here.
manual := &UserAction{
URL: authURL,
Message: fmt.Sprintf(
"To authorize the GitHub MCP Server, open this URL in your browser:\n\n%s\n\nAfter authorizing, retry your request.\n\n%s",
authURL, securityAdvisory,
),
}
if canPromptURL(prompter) {
display := func(ctx context.Context) error {
return prompter.PromptURL(ctx, Prompt{
Message: "Authorize the GitHub MCP Server in your browser to continue.",
URL: authURL,
})
}
return &flowPlan{run: run, display: display, fallback: manual}, nil
}
return &flowPlan{run: run, userAction: manual}, nil
}
// beginDevice prepares the device authorization flow. It requests a device code
// up front (so the code can be displayed) and selects a display channel:
// URL elicitation, then form elicitation, then a tool-response message.
func (m *Manager) beginDevice(prompter Prompter) (*flowPlan, error) {
oc := m.oauth2Config("")
ctx, cancel := context.WithTimeout(context.Background(), deviceAuthTimeout)
defer cancel()
da, err := oc.DeviceAuth(ctx)
if err != nil {
return nil, fmt.Errorf("requesting device code: %w", err)
}
run := func(ctx context.Context) (*oauth2.Token, error) {
tok, err := oc.DeviceAccessToken(ctx, da)
if err != nil {
return nil, fmt.Errorf("awaiting device authorization: %w", err)
}
return tok, nil
}
// As with PKCE, the manual instructions double as the runtime fallback, so
// build them once and reuse for both display plans and the last resort.
manual := &UserAction{
URL: da.VerificationURI,
UserCode: da.UserCode,
Message: fmt.Sprintf(
"%s\n\nAfter authorizing, retry your request.\n\n%s",
deviceInstruction(da), securityAdvisory,
),
}
if canPromptURL(prompter) {
display := func(ctx context.Context) error {
return prompter.PromptURL(ctx, Prompt{
Message: fmt.Sprintf("Enter code %s to authorize the GitHub MCP Server.", da.UserCode),
URL: da.VerificationURI,
UserCode: da.UserCode,
})
}
return &flowPlan{run: run, display: display, fallback: manual}, nil
}
if canPromptForm(prompter) {
display := func(ctx context.Context) error {
return prompter.PromptForm(ctx, Prompt{
Message: deviceInstruction(da),
URL: da.VerificationURI,
UserCode: da.UserCode,
})
}
return &flowPlan{run: run, display: display, fallback: manual}, nil
}
return &flowPlan{run: run, userAction: manual}, nil
}
// securityAdvisory nudges users on clients without URL elicitation to ask their
// vendor for it, since it keeps the authorization URL out of the model context.
const securityAdvisory = "Note: your MCP client does not appear to support secure URL elicitation. " +
"For improved security, consider asking your agent, CLI, or IDE to add it (for example, by opening an issue)."
func deviceInstruction(da *oauth2.DeviceAuthResponse) string {
return fmt.Sprintf("Visit %s and enter the code %s to authorize the GitHub MCP Server.", da.VerificationURI, da.UserCode)
}
+310
View File
@@ -0,0 +1,310 @@
package oauth
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"sync"
"time"
"golang.org/x/oauth2"
)
// DefaultAuthTimeout bounds how long a single authorization attempt waits for
// the user to complete the browser or device flow.
const DefaultAuthTimeout = 5 * time.Minute
// tokenRefreshTimeout bounds each background refresh of an expiring token so a
// stalled GitHub token endpoint cannot block a tool call indefinitely.
const tokenRefreshTimeout = 30 * time.Second
// flowStatus tracks the manager's single-flight authorization state.
type flowStatus int
const (
statusIdle flowStatus = iota // no flow running
statusStarting // a flow is being prepared (brief)
statusInProgress // a flow is running on a secure channel; callers may join
statusAwaitingUser // a flow is running but the user must act out-of-band
)
// Outcome reports the result of an authorization attempt that did not
// immediately yield a token.
type Outcome struct {
// UserAction, when non-nil, must be surfaced to the user. The authorization
// flow continues in the background; the user should retry once they have
// completed it.
UserAction *UserAction
}
// UserAction is an instruction for the user to complete authorization out of
// band (the last-resort channel, used when neither a browser nor URL
// elicitation is available).
type UserAction struct {
// Message is ready to display to the user.
Message string
// URL is the authorization URL or device verification URI.
URL string
// UserCode is the device-flow code to enter, if any.
UserCode string
}
// Manager owns the OAuth login flows and the resulting (refreshing) token for a
// single stdio session. It is safe for concurrent use; only one authorization
// flow runs at a time.
type Manager struct {
config Config
refreshConfig *oauth2.Config
logger *slog.Logger
// Test seams, set by NewManager to real implementations.
openURL func(string) error
inDocker func() bool
mu sync.Mutex
source oauth2.TokenSource // refreshing source, set once authorized
status flowStatus
pending *UserAction
done chan struct{}
lastErr error
refreshErrLogged bool // true once a refresh failure has been logged, reset on re-auth
}
// NewManager builds a Manager for the given configuration. A nil logger logs to
// stderr.
func NewManager(cfg Config, logger *slog.Logger) *Manager {
if logger == nil {
logger = slog.New(slog.NewTextHandler(os.Stderr, nil))
}
m := &Manager{
config: cfg,
logger: logger,
openURL: openBrowser,
inDocker: isRunningInDocker,
}
m.refreshConfig = m.oauth2Config("")
return m
}
// AccessToken returns a currently valid access token, refreshing it if needed,
// or "" if the session is not authorized (or a refresh has failed and
// re-authorization is required). It is cheap to call repeatedly: the underlying
// token source caches and only refreshes when the token has expired.
func (m *Manager) AccessToken() string {
m.mu.Lock()
src := m.source
m.mu.Unlock()
if src == nil {
return ""
}
// Refresh (if needed) happens here, off the lock, because ReuseTokenSource may
// make a blocking network call and holding m.mu would serialize every tool call.
tok, err := src.Token()
if err != nil {
// A refresh failure (expired GitHub App refresh token, revoked grant, or a
// network blip) leaves the session unauthorized and forces a re-login.
// Surface it once, otherwise it only manifests as a surprise re-authorization
// prompt. The oauth2 error carries the token endpoint's response, not the
// access or refresh token.
m.mu.Lock()
if !m.refreshErrLogged {
m.refreshErrLogged = true
m.logger.Warn("OAuth token refresh failed; re-authorization required", "error", err)
}
m.mu.Unlock()
return ""
}
if !tok.Valid() {
return ""
}
return tok.AccessToken
}
// HasToken reports whether a valid token is currently available.
func (m *Manager) HasToken() bool {
return m.AccessToken() != ""
}
// Authenticate ensures the session is authorized.
//
// It returns (nil, nil) once a token is available, so the caller may proceed.
// It returns (&Outcome{UserAction}, nil) when the user must complete the flow
// out of band; the flow continues in the background and the caller should show
// the action and have the user retry. It returns (nil, err) on failure.
//
// Only one flow runs at a time. Concurrent callers either join a running secure
// flow, receive the pending user action, or are told to retry shortly.
func (m *Manager) Authenticate(ctx context.Context, prompter Prompter) (*Outcome, error) {
if m.AccessToken() != "" {
return nil, nil
}
m.mu.Lock()
switch m.status {
case statusAwaitingUser:
ua := m.pending
m.mu.Unlock()
return &Outcome{UserAction: ua}, nil
case statusStarting:
m.mu.Unlock()
return &Outcome{UserAction: &UserAction{
Message: "GitHub authorization is already in progress. Please retry your request in a few seconds.",
}}, nil
case statusInProgress:
done := m.done
m.mu.Unlock()
return m.joinWait(ctx, done)
}
// Idle: this call owns the new flow.
m.status = statusStarting
m.lastErr = nil
m.done = make(chan struct{})
done := m.done
m.mu.Unlock()
plan, err := m.begin(prompter)
if err != nil {
m.complete(nil, err)
return nil, err
}
m.mu.Lock()
if plan.userAction != nil {
m.status = statusAwaitingUser
m.pending = plan.userAction
} else {
m.status = statusInProgress
}
m.mu.Unlock()
bgCtx, cancel := context.WithTimeout(context.Background(), DefaultAuthTimeout)
go m.runFlow(bgCtx, cancel, plan)
if plan.userAction != nil {
return &Outcome{UserAction: plan.userAction}, nil
}
return m.joinWait(ctx, done)
}
// runFlow executes a prepared flow in the background and records the result. The
// optional display prompt runs concurrently: a decline (or other failure) aborts
// the flow, while an undeliverable prompt degrades to the manual fallback without
// tearing the flow down, so the user can still authorize out of band.
func (m *Manager) runFlow(ctx context.Context, cancel context.CancelFunc, plan *flowPlan) {
defer cancel()
if plan.display != nil {
go func() {
err := plan.display(ctx)
switch {
case err == nil:
// Prompt shown; the flow completes when the token arrives.
case ctx.Err() != nil:
// The flow is already ending (timed out or cancelled elsewhere),
// so there is nothing to fall back to. Checking this before the
// fallback also prevents misreading a context-cancelled prompt as
// a transport failure.
case errors.Is(err, ErrPromptUnavailable) && plan.fallback != nil:
// The client advertised the capability but could not deliver the
// prompt. Surface the manual instructions instead of failing, and
// keep the background flow alive so the user can still authorize.
m.logger.Debug("authorization prompt undeliverable; falling back to manual instructions", "reason", err)
m.fallBackToUserAction(plan.fallback)
default:
// A user decline (ErrPromptDeclined) or any other prompt failure
// ends the flow.
m.logger.Debug("authorization prompt closed", "reason", err)
cancel()
}
}()
}
tok, err := plan.run(ctx)
m.complete(tok, err)
}
// fallBackToUserAction promotes a running secure flow to the manual user-action
// channel after its prompt could not be delivered. The background flow keeps
// running, so the user can complete authorization out of band and retry. It is a
// no-op if the flow has already resolved.
func (m *Manager) fallBackToUserAction(ua *UserAction) {
m.mu.Lock()
defer m.mu.Unlock()
if m.status != statusInProgress {
return
}
m.status = statusAwaitingUser
m.pending = ua
// Wake any callers joined on this flow so they receive the action, and clear
// done so complete() does not double-close it when run() later finishes.
if m.done != nil {
close(m.done)
m.done = nil
}
}
// complete records the flow result, installing a refreshing token source on
// success, and wakes any joined callers.
func (m *Manager) complete(tok *oauth2.Token, err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.status = statusIdle
m.pending = nil
if err != nil {
m.lastErr = err
m.logger.Debug("oauth flow failed", "error", err)
} else {
m.lastErr = nil
// Config.TokenSource returns a ReuseTokenSource that refreshes expired
// tokens using the refresh token — this is what makes GitHub App
// (expiring) tokens work transparently. The refresh uses a bounded HTTP
// client so a stalled token endpoint can't block a tool call forever.
refreshCtx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Timeout: tokenRefreshTimeout})
m.source = m.refreshConfig.TokenSource(refreshCtx, tok)
m.refreshErrLogged = false
m.logger.Info("github authorization complete")
}
if m.done != nil {
close(m.done)
m.done = nil
}
}
// joinWait blocks until the running flow finishes or ctx is cancelled. If the
// flow was promoted to the manual channel while waiting (its prompt could not be
// delivered), it returns that user action rather than an error.
func (m *Manager) joinWait(ctx context.Context, done chan struct{}) (*Outcome, error) {
select {
case <-done:
if m.AccessToken() != "" {
return nil, nil
}
m.mu.Lock()
pending := m.pending
err := m.lastErr
m.mu.Unlock()
if pending != nil {
return &Outcome{UserAction: pending}, nil
}
if err != nil {
return nil, err
}
return nil, errors.New("authorization did not complete")
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (m *Manager) oauth2Config(redirectURL string) *oauth2.Config {
return &oauth2.Config{
ClientID: m.config.ClientID,
ClientSecret: m.config.ClientSecret,
RedirectURL: redirectURL,
Scopes: m.config.Scopes,
Endpoint: m.config.Endpoint,
}
}
+321
View File
@@ -0,0 +1,321 @@
package oauth
import (
"context"
"errors"
"net"
"strconv"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newManager wires a Manager to the fake GitHub server. By default the browser
// auto-opens (driving the callback) and Docker detection is off.
func newManager(t *testing.T, f *fakeGitHub) *Manager {
t.Helper()
cfg := Config{
ClientID: "client-id",
ClientSecret: "client-secret",
Scopes: []string{"repo"},
Endpoint: f.endpoint(),
}
m := NewManager(cfg, testLogger())
m.openURL = browserGet
m.inDocker = func() bool { return false }
return m
}
func TestAuthenticatePKCEViaBrowser(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
assert.Nil(t, out, "browser flow completes without a user action")
assert.Equal(t, "gho_access", m.AccessToken())
// PKCE must have been exercised end to end.
f.mu.Lock()
defer f.mu.Unlock()
assert.Equal(t, "S256", f.codeChallengeMethod)
assert.NotEmpty(t, f.codeChallenge, "authorize must receive a code_challenge")
assert.NotEmpty(t, f.codeVerifier, "token exchange must send a code_verifier")
assert.Equal(t, []string{"authorization_code"}, f.grants)
}
func TestAuthenticateRefreshesExpiringGitHubAppToken(t *testing.T) {
f := newFakeGitHub(t)
// GitHub App: the initial token expires immediately and carries a refresh
// token, so the very next read must refresh transparently.
f.authToken = "ghu_initial"
f.authRefresh = "ghr_refresh"
f.authExpires = 1
f.refreshToken = "ghu_refreshed"
f.refreshExpires = 3600
m := newManager(t, f)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
assert.Equal(t, "ghu_refreshed", m.AccessToken(), "expired token must be refreshed")
assert.Equal(t, []string{"authorization_code", "refresh_token"}, f.recordedGrants())
}
func TestAuthenticateURLElicitation(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
m.openURL = func(string) error { return errors.New("no browser") }
prompter := &fakePrompter{
urlCapable: true,
onURL: func(_ context.Context, p Prompt) error {
return browserGet(p.URL) // user opens the URL and authorizes
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, prompter)
require.NoError(t, err)
assert.Nil(t, out)
assert.Equal(t, "gho_access", m.AccessToken())
prompter.mu.Lock()
defer prompter.mu.Unlock()
require.Len(t, prompter.urlCalls, 1)
assert.NotEmpty(t, prompter.urlCalls[0].URL)
}
func TestAuthenticateDeclinedPromptFails(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
m.openURL = func(string) error { return errors.New("no browser") }
prompter := &fakePrompter{
urlCapable: true,
onURL: func(_ context.Context, _ Prompt) error {
return ErrPromptDeclined
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := m.Authenticate(ctx, prompter)
require.Error(t, err, "declining the prompt must abort the flow")
assert.Empty(t, m.AccessToken())
}
func TestAuthenticateUndeliverablePromptFallsBack(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
m.openURL = func(string) error { return errors.New("no browser") }
// The client advertised URL elicitation but delivering the prompt fails (a
// transport/protocol error, not a user decision). This must degrade to the
// manual instructions rather than aborting like a decline does.
prompter := &fakePrompter{
urlCapable: true,
onURL: func(_ context.Context, _ Prompt) error {
return ErrPromptUnavailable
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, prompter)
require.NoError(t, err, "an undeliverable prompt must not abort the flow")
require.NotNil(t, out)
require.NotNil(t, out.UserAction, "an undeliverable prompt must fall back to a user action")
assert.NotEmpty(t, out.UserAction.URL)
assert.Contains(t, out.UserAction.Message, securityAdvisory)
// A concurrent retry while awaiting the user returns the same fallback action.
out2, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
require.NotNil(t, out2.UserAction)
assert.Equal(t, out.UserAction.URL, out2.UserAction.URL)
// The background flow stayed alive: opening the URL out of band completes it.
require.NoError(t, browserGet(out.UserAction.URL))
assert.Equal(t, "gho_access", waitForToken(t, m))
}
func TestAuthenticateLastDitchUserAction(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
m.openURL = func(string) error { return errors.New("no browser") }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// No browser and a nil prompter: the only channel left is a user action
// returned to the caller.
out, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
require.NotNil(t, out)
require.NotNil(t, out.UserAction)
assert.NotEmpty(t, out.UserAction.URL)
assert.Contains(t, out.UserAction.Message, "open this URL")
assert.Contains(t, out.UserAction.Message, securityAdvisory,
"missing URL elicitation should trigger the security advisory")
// A concurrent retry while awaiting the user returns the same action, not a
// second flow.
out2, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
require.NotNil(t, out2.UserAction)
assert.Equal(t, out.UserAction.URL, out2.UserAction.URL)
// The user opens the URL out of band; the background flow then completes.
require.NoError(t, browserGet(out.UserAction.URL))
assert.Equal(t, "gho_access", waitForToken(t, m))
}
func TestAuthenticateDeviceFlow(t *testing.T) {
f := newFakeGitHub(t)
f.deviceToken = "gho_device_token"
m := newManager(t, f)
// Inside Docker with a random port, PKCE is impossible, so the device flow
// is selected.
m.inDocker = func() bool { return true }
m.openURL = func(string) error { return errors.New("no browser") }
prompter := &fakePrompter{urlCapable: true} // shows the code, no action needed
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, prompter)
require.NoError(t, err)
assert.Nil(t, out)
assert.Equal(t, "gho_device_token", m.AccessToken())
assert.Contains(t, f.recordedGrants(), "urn:ietf:params:oauth:grant-type:device_code")
}
func TestAuthenticateDevicePollingPending(t *testing.T) {
f := newFakeGitHub(t)
f.deviceToken = "gho_device_token"
f.devicePending = 1 // one authorization_pending before success
m := newManager(t, f)
m.inDocker = func() bool { return true }
m.openURL = func(string) error { return errors.New("no browser") }
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
_, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
require.NoError(t, err)
assert.Equal(t, "gho_device_token", m.AccessToken())
}
func TestAuthenticateHeadlessPrefersDeviceFlow(t *testing.T) {
f := newFakeGitHub(t)
f.deviceToken = "gho_device_token"
m := newManager(t, f)
// A headless host (no display server) with a random callback port: a PKCE
// redirect to this machine's localhost is unreachable from a browser on
// another machine, so device flow must be chosen even though the client can
// elicit a URL (which would otherwise win over device flow).
m.openURL = func(string) error { return errNoDisplay }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
require.NoError(t, err)
assert.Nil(t, out)
assert.Equal(t, "gho_device_token", m.AccessToken())
grants := f.recordedGrants()
assert.Contains(t, grants, "urn:ietf:params:oauth:grant-type:device_code")
assert.NotContains(t, grants, "authorization_code",
"headless host must skip the unreachable PKCE authorization-code flow")
}
func TestAuthenticateFixedCallbackPortUnavailableIsFatal(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
// Occupy the fixed callback port so the OAuth listener cannot bind it. A held
// port could belong to another user's process that would receive the redirect,
// so the flow must fail loudly rather than quietly downgrade to device flow.
squatter, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer squatter.Close()
port := squatter.Addr().(*net.TCPAddr).Port
m.config.CallbackPort = port
// A browser that would have completed PKCE, proving the abort is caused by the
// unavailable port and not by a missing display channel.
m.openURL = browserGet
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
out, err := m.Authenticate(ctx, &fakePrompter{urlCapable: true})
require.Error(t, err)
assert.Nil(t, out)
assert.Contains(t, err.Error(), strconv.Itoa(port))
assert.Empty(t, m.AccessToken())
// The decisive check: no device-code grant was attempted, so the flow did not
// silently fall back when the deliberately chosen port was unavailable.
assert.Empty(t, f.recordedGrants(), "fixed-port bind failure must not fall back to device flow")
}
func TestAuthenticateNoTokenInitially(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
assert.False(t, m.HasToken())
assert.Empty(t, m.AccessToken())
}
func TestAuthenticateSingleFlight(t *testing.T) {
f := newFakeGitHub(t)
m := newManager(t, f)
// Hold the owner inside begin() (browser open blocks) so a concurrent caller
// observes the in-progress flow rather than starting its own.
entered := make(chan struct{})
release := make(chan struct{})
var once sync.Once
m.openURL = func(u string) error {
once.Do(func() { close(entered) })
<-release
return browserGet(u)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ownerDone := make(chan error, 1)
go func() {
_, err := m.Authenticate(ctx, nil)
ownerDone <- err
}()
<-entered // owner is now mid-flow with status "starting"
out, err := m.Authenticate(ctx, nil)
require.NoError(t, err)
require.NotNil(t, out.UserAction)
assert.Contains(t, out.UserAction.Message, "already in progress")
close(release)
require.NoError(t, <-ownerDone)
assert.Equal(t, "gho_access", waitForToken(t, m))
// Exactly one authorization happened despite the concurrent callers.
assert.Equal(t, []string{"authorization_code"}, f.recordedGrants())
}
+102
View File
@@ -0,0 +1,102 @@
// Package oauth implements the user-facing OAuth 2.1 login flows the stdio
// server uses to obtain a GitHub token without a pre-provisioned Personal
// Access Token.
//
// It supports both GitHub OAuth Apps and GitHub Apps (user-to-server). The
// only practical difference is that GitHub App user tokens expire and carry a
// refresh token; this package always returns a refreshing [golang.org/x/oauth2.TokenSource]
// so callers never have to special-case the app type.
//
// The package depends only on golang.org/x/oauth2 and the standard library. MCP
// concerns (sessions, elicitation) are abstracted behind the [Prompter]
// interface so the flows can be tested without a live client.
package oauth
import (
"crypto/rand"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/oauth2"
)
// Config describes an OAuth client and the GitHub endpoints it talks to.
type Config struct {
ClientID string
ClientSecret string
// Scopes requested during authorization. GitHub Apps ignore these (their
// access is governed by installed permissions); OAuth Apps honor them.
Scopes []string
// Endpoint holds the authorization, token, and device endpoints. Build one
// with [GitHubEndpoint].
Endpoint oauth2.Endpoint
// CallbackPort is the fixed local port for the PKCE callback server. Zero
// requests a random port, which is the secure default for native binaries
// but cannot be reached through Docker port mapping (see the Manager).
CallbackPort int
}
// NewGitHubConfig builds a Config for the given GitHub host. An empty host
// targets github.com; otherwise the host may be a GHES or ghe.com hostname,
// with or without a scheme.
func NewGitHubConfig(clientID, clientSecret string, scopes []string, host string, callbackPort int) Config {
return Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: scopes,
Endpoint: GitHubEndpoint(host),
CallbackPort: callbackPort,
}
}
// GitHubEndpoint returns the OAuth authorization, token, and device endpoints
// for a GitHub host. An empty host targets github.com.
func GitHubEndpoint(host string) oauth2.Endpoint {
base := NormalizeHost(host)
return oauth2.Endpoint{
AuthURL: base + "/login/oauth/authorize",
TokenURL: base + "/login/oauth/access_token",
DeviceAuthURL: base + "/login/device/code",
}
}
// NormalizeHost turns a user-supplied host into a scheme+host base URL with no
// trailing slash. The API subdomain is stripped because OAuth endpoints live on
// the web host, not the API host (api.github.com -> github.com). An empty host
// yields the github.com default, so callers can also use it to recognize the
// default host (NormalizeHost(host) == "https://github.com").
func NormalizeHost(host string) string {
host = strings.TrimSpace(host)
if host == "" {
return "https://github.com"
}
scheme := "https"
switch {
case strings.HasPrefix(host, "https://"):
host = strings.TrimPrefix(host, "https://")
case strings.HasPrefix(host, "http://"):
scheme = "http"
host = strings.TrimPrefix(host, "http://")
}
// Drop any path, query, or fragment; we only need scheme://host.
if i := strings.IndexAny(host, "/?#"); i >= 0 {
host = host[:i]
}
host = strings.TrimPrefix(host, "api.")
return fmt.Sprintf("%s://%s", scheme, host)
}
// randomState returns a cryptographically random URL-safe string used as the
// OAuth state parameter (CSRF protection) and elicitation IDs.
func randomState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating random state: %w", err)
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
+64
View File
@@ -0,0 +1,64 @@
package oauth
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNormalizeHost(t *testing.T) {
tests := []struct {
name string
host string
want string
}{
{"empty defaults to github.com", "", "https://github.com"},
{"bare host", "github.com", "https://github.com"},
{"https scheme preserved", "https://github.com", "https://github.com"},
{"http scheme preserved", "http://localhost:3000", "http://localhost:3000"},
{"api subdomain stripped", "api.github.com", "https://github.com"},
{"whitespace trimmed", " github.com ", "https://github.com"},
{"path and api stripped", "https://api.github.com/api/v3", "https://github.com"},
{"ghes host", "ghe.example.com", "https://ghe.example.com"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.want, NormalizeHost(tt.host))
})
}
}
func TestGitHubEndpoint(t *testing.T) {
ep := GitHubEndpoint("")
assert.Equal(t, "https://github.com/login/oauth/authorize", ep.AuthURL)
assert.Equal(t, "https://github.com/login/oauth/access_token", ep.TokenURL)
assert.Equal(t, "https://github.com/login/device/code", ep.DeviceAuthURL)
ghes := GitHubEndpoint("https://ghe.example.com")
assert.Equal(t, "https://ghe.example.com/login/oauth/authorize", ghes.AuthURL)
}
func TestNewGitHubConfig(t *testing.T) {
cfg := NewGitHubConfig("client", "secret", []string{"repo", "read:org"}, "", 8085)
assert.Equal(t, "client", cfg.ClientID)
assert.Equal(t, "secret", cfg.ClientSecret)
assert.Equal(t, []string{"repo", "read:org"}, cfg.Scopes)
assert.Equal(t, 8085, cfg.CallbackPort)
assert.Equal(t, GitHubEndpoint(""), cfg.Endpoint)
}
func TestRandomState(t *testing.T) {
s1, err := randomState()
require.NoError(t, err)
s2, err := randomState()
require.NoError(t, err)
assert.NotEqual(t, s1, s2, "state must be unique per call")
assert.NotContains(t, s1, "=", "state must be URL-safe without padding")
assert.NotContains(t, s1, "+")
assert.NotContains(t, s1, "/")
assert.GreaterOrEqual(t, len(s1), 22, "16 random bytes encode to 22 base64url chars")
assert.False(t, strings.ContainsAny(s1, " \t\n"))
}
+65
View File
@@ -0,0 +1,65 @@
package oauth
import (
"context"
"errors"
)
// ErrPromptDeclined is returned by a Prompter when the user actively cancels or
// declines the authorization prompt. It is a deliberate "no", so the flow stops
// rather than falling back to another channel.
var ErrPromptDeclined = errors.New("authorization declined by user")
// ErrPromptUnavailable is returned by a Prompter when the prompt could not be
// delivered at all — for example the client advertised an elicitation capability
// but the request failed at the transport or protocol level. Unlike
// ErrPromptDeclined it reflects no user decision, so the flow falls back to a
// channel that needs no client capability instead of giving up.
var ErrPromptUnavailable = errors.New("authorization prompt could not be delivered")
// Prompt is the content shown to the user when asking them to authorize.
type Prompt struct {
// Message is a human-readable instruction.
Message string
// URL is the authorization URL (PKCE) or device verification URI.
URL string
// UserCode is the device-flow code the user must enter, if any.
UserCode string
}
// Prompter presents authorization prompts to the user out of band from the LLM
// context — for example via MCP elicitation. Keeping prompts out of the model's
// context prevents the authorization URL (and any session-bound state) from
// leaking into tool arguments or transcripts.
//
// A nil Prompter is valid and reports no capabilities, which drives the flow to
// its last-resort channel. Implementations wrap a transport-specific client
// (e.g. an MCP session); see the ghmcp adapter.
type Prompter interface {
// CanPromptURL reports whether the client can display a URL securely via
// URL-mode elicitation.
CanPromptURL() bool
// PromptURL securely presents an authorization URL to the user and blocks
// until the user acknowledges, declines, or ctx is done. Returning nil means
// the prompt was shown (not that authorization completed); the caller waits
// for the OAuth flow itself to finish. It returns ErrPromptDeclined if the
// user declines or cancels, or ErrPromptUnavailable if the prompt could not
// be delivered.
PromptURL(ctx context.Context, p Prompt) error
// CanPromptForm reports whether the client supports form elicitation, used
// to display a device code when URL elicitation is unavailable.
CanPromptForm() bool
// PromptForm presents a textual acknowledgement prompt and blocks until the
// user responds. It returns ErrPromptDeclined if the user declines, or
// ErrPromptUnavailable if the prompt could not be delivered.
PromptForm(ctx context.Context, p Prompt) error
}
// canPromptURL reports URL support, tolerating a nil Prompter.
func canPromptURL(p Prompter) bool { return p != nil && p.CanPromptURL() }
// canPromptForm reports form support, tolerating a nil Prompter.
func canPromptForm(p Prompter) bool { return p != nil && p.CanPromptForm() }
+60
View File
@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authorization Failed</title>
<style>
html, body { height: 100%; margin: 0; }
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
background-color: #0d1117;
color: #e6edf3;
}
.card {
width: 500px;
background-color: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
padding: 32px;
text-align: center;
}
.octicon { margin-bottom: 16px; }
h1 {
font-size: 20px;
font-weight: 600;
margin: 0 0 12px 0;
color: #f85149;
}
p { font-size: 16px; color: #8b949e; margin: 16px 0 0 0; }
.flash-error {
margin-top: 16px;
padding: 12px 16px;
background-color: rgba(248, 81, 73, 0.1);
border: 1px solid rgba(248, 81, 73, 0.4);
border-radius: 6px;
}
code {
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
font-size: 14px;
color: #f85149;
}
</style>
</head>
<body>
<div class="card">
<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="80" height="80" fill="currentColor">
<path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path>
</svg>
<h1>Authorization Failed</h1>
<div class="flash-error">
<code>{{.ErrorMessage}}</code>
</div>
<p>You can close this window.</p>
</div>
</body>
</html>
+56
View File
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authorization Successful</title>
<style>
html, body { height: 100%; margin: 0; }
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
background-color: #0d1117;
color: #e6edf3;
}
.card {
width: 500px;
background-color: #161b22;
border: 1px solid #30363d;
border-radius: 6px;
padding: 32px;
text-align: center;
}
.octicon { margin-bottom: 16px; }
h1 {
font-size: 20px;
font-weight: 600;
margin: 0 0 12px 0;
color: #3fb950;
}
p { font-size: 16px; color: #8b949e; margin: 0; }
.flash {
margin-top: 16px;
padding: 12px 16px;
background-color: rgba(56, 139, 253, 0.15);
border: 1px solid rgba(56, 139, 253, 0.4);
border-radius: 6px;
}
.flash p { font-size: 14px; }
</style>
</head>
<body>
<div class="card">
<svg class="octicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="80" height="80" fill="currentColor">
<path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path>
</svg>
<h1>Authorization Successful</h1>
<p>You have successfully authorized the GitHub MCP Server.</p>
<div class="flash">
<p>You can close this window and retry your request.</p>
</div>
</div>
</body>
</html>
+216
View File
@@ -0,0 +1,216 @@
package oauth
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"golang.org/x/oauth2"
)
// fakeGitHub is an httptest-backed stand-in for GitHub's OAuth endpoints. It
// implements the authorize redirect, the token endpoint (authorization_code,
// refresh_token, and device_code grants), and the device-code endpoint, while
// recording what it received so tests can assert on real protocol behavior
// (PKCE challenge/verifier, grant sequence) rather than re-implementing it.
type fakeGitHub struct {
*httptest.Server
mu sync.Mutex
grants []string // grant_type of each token request, in order
codeChallenge string
codeChallengeMethod string
codeVerifier string
devicePending int // number of authorization_pending responses before success
// Token values returned per grant. A positive expires field is sent as
// expires_in (and makes the token expiring/refreshable).
authToken string
authRefresh string
authExpires int
refreshToken string
refreshExpires int
deviceToken string
}
func newFakeGitHub(t *testing.T) *fakeGitHub {
t.Helper()
f := &fakeGitHub{
authToken: "gho_access",
deviceToken: "gho_device",
}
mux := http.NewServeMux()
mux.HandleFunc("/login/oauth/authorize", f.handleAuthorize)
mux.HandleFunc("/login/oauth/access_token", f.handleToken)
mux.HandleFunc("/login/device/code", f.handleDeviceCode)
f.Server = httptest.NewServer(mux)
t.Cleanup(f.Server.Close)
return f
}
func (f *fakeGitHub) endpoint() oauth2.Endpoint {
return oauth2.Endpoint{
AuthURL: f.URL + "/login/oauth/authorize",
TokenURL: f.URL + "/login/oauth/access_token",
DeviceAuthURL: f.URL + "/login/device/code",
}
}
func (f *fakeGitHub) handleAuthorize(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
f.mu.Lock()
f.codeChallenge = q.Get("code_challenge")
f.codeChallengeMethod = q.Get("code_challenge_method")
f.mu.Unlock()
redirect := q.Get("redirect_uri") + "?code=authcode&state=" + url.QueryEscape(q.Get("state"))
http.Redirect(w, r, redirect, http.StatusFound)
}
func (f *fakeGitHub) handleToken(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
grant := r.Form.Get("grant_type")
f.mu.Lock()
f.grants = append(f.grants, grant)
switch grant {
case "authorization_code":
f.codeVerifier = r.Form.Get("code_verifier")
f.mu.Unlock()
writeToken(w, f.authToken, f.authRefresh, f.authExpires)
case "refresh_token":
f.mu.Unlock()
writeToken(w, f.refreshToken, "", f.refreshExpires)
case "urn:ietf:params:oauth:grant-type:device_code":
pending := f.devicePending
if pending > 0 {
f.devicePending--
}
f.mu.Unlock()
if pending > 0 {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "authorization_pending"})
return
}
writeToken(w, f.deviceToken, "", 0)
default:
f.mu.Unlock()
http.Error(w, "unsupported grant_type", http.StatusBadRequest)
}
}
func (f *fakeGitHub) handleDeviceCode(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"device_code": "devicecode",
"user_code": "ABCD-1234",
"verification_uri": f.URL + "/device",
"expires_in": 900,
"interval": 1,
})
}
func (f *fakeGitHub) recordedGrants() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.grants...)
}
func writeToken(w http.ResponseWriter, access, refresh string, expiresIn int) {
body := map[string]any{
"access_token": access,
"token_type": "bearer",
}
if refresh != "" {
body["refresh_token"] = refresh
}
if expiresIn != 0 {
body["expires_in"] = expiresIn
}
writeJSON(w, http.StatusOK, body)
}
func writeJSON(w http.ResponseWriter, status int, body map[string]any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
// fakePrompter is a configurable Prompter. The on* hooks simulate the user
// acting on the prompt; a nil hook means the prompt is shown and acknowledged.
type fakePrompter struct {
urlCapable bool
formCapable bool
onURL func(context.Context, Prompt) error
onForm func(context.Context, Prompt) error
mu sync.Mutex
urlCalls []Prompt
}
func (p *fakePrompter) CanPromptURL() bool { return p.urlCapable }
func (p *fakePrompter) PromptURL(ctx context.Context, prompt Prompt) error {
p.mu.Lock()
p.urlCalls = append(p.urlCalls, prompt)
p.mu.Unlock()
if p.onURL != nil {
return p.onURL(ctx, prompt)
}
return nil
}
func (p *fakePrompter) CanPromptForm() bool { return p.formCapable }
func (p *fakePrompter) PromptForm(ctx context.Context, prompt Prompt) error {
if p.onForm != nil {
return p.onForm(ctx, prompt)
}
return nil
}
// browserGet simulates a user completing the authorization-code flow by opening
// the URL: it follows the authorize redirect to the local callback, delivering
// the code to the manager's callback server. Used both as an openURL seam and
// inside prompter hooks.
func browserGet(rawurl string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawurl, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
_, _ = io.Copy(io.Discard, resp.Body)
return resp.Body.Close()
}
func testLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
// waitForToken polls until the manager has a token or the deadline passes. The
// authorization-code flow completes asynchronously after the callback fires, so
// tests wait for the resulting token rather than sleeping a fixed duration.
func waitForToken(t *testing.T, m *Manager) string {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
if tok := m.AccessToken(); tok != "" {
return tok
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("timed out waiting for access token")
return ""
}
+215
View File
@@ -0,0 +1,215 @@
package profiler
import (
"context"
"fmt"
"os"
"runtime"
"strconv"
"time"
"log/slog"
"math"
)
// Profile represents performance metrics for an operation
type Profile struct {
Operation string `json:"operation"`
Duration time.Duration `json:"duration_ns"`
MemoryBefore uint64 `json:"memory_before_bytes"`
MemoryAfter uint64 `json:"memory_after_bytes"`
MemoryDelta int64 `json:"memory_delta_bytes"`
LinesCount int `json:"lines_count,omitempty"`
BytesCount int64 `json:"bytes_count,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
// String returns a human-readable representation of the profile
func (p *Profile) String() string {
return fmt.Sprintf("[%s] %s: duration=%v, memory_delta=%+dB, lines=%d, bytes=%d",
p.Timestamp.Format("15:04:05.000"),
p.Operation,
p.Duration,
p.MemoryDelta,
p.LinesCount,
p.BytesCount,
)
}
func safeMemoryDelta(after, before uint64) int64 {
if after > math.MaxInt64 || before > math.MaxInt64 {
if after >= before {
diff := after - before
if diff > math.MaxInt64 {
return math.MaxInt64
}
return int64(diff)
}
diff := before - after
if diff > math.MaxInt64 {
return -math.MaxInt64
}
return -int64(diff)
}
return int64(after) - int64(before)
}
// Profiler provides minimal performance profiling capabilities
type Profiler struct {
logger *slog.Logger
enabled bool
}
// New creates a new Profiler instance
func New(logger *slog.Logger, enabled bool) *Profiler {
return &Profiler{
logger: logger,
enabled: enabled,
}
}
// ProfileFunc profiles a function execution
func (p *Profiler) ProfileFunc(ctx context.Context, operation string, fn func() error) (*Profile, error) {
if !p.enabled {
return nil, fn()
}
profile := &Profile{
Operation: operation,
Timestamp: time.Now(),
}
var memBefore runtime.MemStats
runtime.ReadMemStats(&memBefore)
profile.MemoryBefore = memBefore.Alloc
start := time.Now()
err := fn()
profile.Duration = time.Since(start)
var memAfter runtime.MemStats
runtime.ReadMemStats(&memAfter)
profile.MemoryAfter = memAfter.Alloc
profile.MemoryDelta = safeMemoryDelta(memAfter.Alloc, memBefore.Alloc)
if p.logger != nil {
p.logger.InfoContext(ctx, "Performance profile", "profile", profile.String())
}
return profile, err
}
// ProfileFuncWithMetrics profiles a function execution and captures additional metrics
func (p *Profiler) ProfileFuncWithMetrics(ctx context.Context, operation string, fn func() (int, int64, error)) (*Profile, error) {
if !p.enabled {
_, _, err := fn()
return nil, err
}
profile := &Profile{
Operation: operation,
Timestamp: time.Now(),
}
var memBefore runtime.MemStats
runtime.ReadMemStats(&memBefore)
profile.MemoryBefore = memBefore.Alloc
start := time.Now()
lines, bytes, err := fn()
profile.Duration = time.Since(start)
profile.LinesCount = lines
profile.BytesCount = bytes
var memAfter runtime.MemStats
runtime.ReadMemStats(&memAfter)
profile.MemoryAfter = memAfter.Alloc
profile.MemoryDelta = safeMemoryDelta(memAfter.Alloc, memBefore.Alloc)
if p.logger != nil {
p.logger.InfoContext(ctx, "Performance profile", "profile", profile.String())
}
return profile, err
}
// Start begins timing an operation and returns a function to complete the profiling
func (p *Profiler) Start(ctx context.Context, operation string) func(lines int, bytes int64) *Profile {
if !p.enabled {
return func(int, int64) *Profile { return nil }
}
profile := &Profile{
Operation: operation,
Timestamp: time.Now(),
}
var memBefore runtime.MemStats
runtime.ReadMemStats(&memBefore)
profile.MemoryBefore = memBefore.Alloc
start := time.Now()
return func(lines int, bytes int64) *Profile {
profile.Duration = time.Since(start)
profile.LinesCount = lines
profile.BytesCount = bytes
var memAfter runtime.MemStats
runtime.ReadMemStats(&memAfter)
profile.MemoryAfter = memAfter.Alloc
profile.MemoryDelta = safeMemoryDelta(memAfter.Alloc, memBefore.Alloc)
if p.logger != nil {
p.logger.InfoContext(ctx, "Performance profile", "profile", profile.String())
}
return profile
}
}
var globalProfiler *Profiler
// IsProfilingEnabled checks if profiling is enabled via environment variables
func IsProfilingEnabled() bool {
if enabled, err := strconv.ParseBool(os.Getenv("GITHUB_MCP_PROFILING_ENABLED")); err == nil {
return enabled
}
return false
}
// Init initializes the global profiler
func Init(logger *slog.Logger, enabled bool) {
globalProfiler = New(logger, enabled)
}
// InitFromEnv initializes the global profiler using environment variables
func InitFromEnv(logger *slog.Logger) {
globalProfiler = New(logger, IsProfilingEnabled())
}
// ProfileFunc profiles a function using the global profiler
func ProfileFunc(ctx context.Context, operation string, fn func() error) (*Profile, error) {
if globalProfiler == nil {
return nil, fn()
}
return globalProfiler.ProfileFunc(ctx, operation, fn)
}
// ProfileFuncWithMetrics profiles a function with metrics using the global profiler
func ProfileFuncWithMetrics(ctx context.Context, operation string, fn func() (int, int64, error)) (*Profile, error) {
if globalProfiler == nil {
_, _, err := fn()
return nil, err
}
return globalProfiler.ProfileFuncWithMetrics(ctx, operation, fn)
}
// Start begins timing using the global profiler
func Start(ctx context.Context, operation string) func(int, int64) *Profile {
if globalProfiler == nil {
return func(int, int64) *Profile { return nil }
}
return globalProfiler.Start(ctx, operation)
}
+101
View File
@@ -0,0 +1,101 @@
// Package toolsnaps provides test utilities for ensuring json schemas for tools
// have not changed unexpectedly.
package toolsnaps
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/josephburnett/jd/v2"
)
// Test checks that the JSON schema for a tool has not changed unexpectedly.
// It compares the marshaled JSON of the provided tool against a stored snapshot file.
// If the UPDATE_TOOLSNAPS environment variable is set to "true", it updates the snapshot file instead.
// If the snapshot does not exist and not running in CI, it creates the snapshot file.
// If the snapshot does not exist and running in CI (GITHUB_ACTIONS="true"), it returns an error.
// If the snapshot exists, it compares the tool's JSON to the snapshot and returns an error if they differ.
// Returns an error if marshaling, reading, or comparing fails.
func Test(toolName string, tool any) error {
toolJSON, err := json.MarshalIndent(tool, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal tool %s: %w", toolName, err)
}
snapPath := fmt.Sprintf("__toolsnaps__/%s.snap", toolName)
// If UPDATE_TOOLSNAPS is set, then we write the tool JSON to the snapshot file and exit
if os.Getenv("UPDATE_TOOLSNAPS") == "true" {
return writeSnap(snapPath, toolJSON)
}
snapJSON, err := os.ReadFile(snapPath) //nolint:gosec // filepaths are controlled by the test suite, so this is safe.
// If the snapshot file does not exist, this must be the first time this test is run.
// We write the tool JSON to the snapshot file and exit.
if os.IsNotExist(err) {
// If we're running in CI, we will error if there is not snapshot because it's important that snapshots
// are committed alongside the tests, rather than just being constructed and not committed during a CI run.
if os.Getenv("GITHUB_ACTIONS") == "true" {
return fmt.Errorf("tool snapshot does not exist for %s. Please run the tests with UPDATE_TOOLSNAPS=true to create it", toolName)
}
return writeSnap(snapPath, toolJSON)
}
// Otherwise we will compare the tool JSON to the snapshot JSON
toolNode, err := jd.ReadJsonString(string(toolJSON))
if err != nil {
return fmt.Errorf("failed to parse tool JSON for %s: %w", toolName, err)
}
snapNode, err := jd.ReadJsonString(string(snapJSON))
if err != nil {
return fmt.Errorf("failed to parse snapshot JSON for %s: %w", toolName, err)
}
// jd.Set allows arrays to be compared without order sensitivity,
// which is useful because we don't really care about this when exposing tool schemas.
diff := toolNode.Diff(snapNode, jd.SET).Render()
if diff != "" {
// If there is a difference, we return an error with the diff
return fmt.Errorf("tool schema for %s has changed unexpectedly:\n%s\nrun with `UPDATE_TOOLSNAPS=true` if this is expected", toolName, diff)
}
return nil
}
func writeSnap(snapPath string, contents []byte) error {
// Sort the JSON keys recursively to ensure consistent output.
// We do this by unmarshaling and remarshaling, which ensures Go's JSON encoder
// sorts all map keys alphabetically at every level.
sortedJSON, err := sortJSONKeys(contents)
if err != nil {
return fmt.Errorf("failed to sort JSON keys: %w", err)
}
// Ensure the directory exists
if err := os.MkdirAll(filepath.Dir(snapPath), 0700); err != nil {
return fmt.Errorf("failed to create snapshot directory: %w", err)
}
// Write the snapshot file
if err := os.WriteFile(snapPath, sortedJSON, 0600); err != nil {
return fmt.Errorf("failed to write snapshot file: %w", err)
}
return nil
}
// sortJSONKeys recursively sorts all object keys in a JSON byte array by
// unmarshaling to map[string]any and remarshaling. Go's JSON encoder
// automatically sorts map keys alphabetically.
func sortJSONKeys(jsonData []byte) ([]byte, error) {
var data any
if err := json.Unmarshal(jsonData, &data); err != nil {
return nil, err
}
return json.MarshalIndent(data, "", " ")
}
+314
View File
@@ -0,0 +1,314 @@
package toolsnaps
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type dummyTool struct {
Name string `json:"name"`
Value int `json:"value"`
}
// withIsolatedWorkingDir creates a temp dir, changes to it, and restores the original working dir after the test.
func withIsolatedWorkingDir(t *testing.T) {
dir := t.TempDir()
origDir, err := os.Getwd()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, os.Chdir(origDir)) })
require.NoError(t, os.Chdir(dir))
}
func TestSnapshotDoesNotExistNotInCI(t *testing.T) {
withIsolatedWorkingDir(t)
// Given we are not running in CI
t.Setenv("GITHUB_ACTIONS", "false") // This REALLY is required because the tests run in CI
tool := dummyTool{"foo", 42}
// When we test the snapshot
err := Test("dummy", tool)
// Then it should succeed and write the snapshot file
require.NoError(t, err)
path := filepath.Join("__toolsnaps__", "dummy.snap")
_, statErr := os.Stat(path)
assert.NoError(t, statErr, "expected snapshot file to be written")
}
func TestSnapshotDoesNotExistInCI(t *testing.T) {
withIsolatedWorkingDir(t)
// Ensure that UPDATE_TOOLSNAPS is not set for this test, which it might be if someone is running
// UPDATE_TOOLSNAPS=true go test ./...
t.Setenv("UPDATE_TOOLSNAPS", "false")
// Given we are running in CI
t.Setenv("GITHUB_ACTIONS", "true")
tool := dummyTool{"foo", 42}
// When we test the snapshot
err := Test("dummy", tool)
// Then it should error about missing snapshot in CI
require.Error(t, err)
assert.Contains(t, err.Error(), "tool snapshot does not exist", "expected error about missing snapshot in CI")
}
func TestSnapshotExistsMatch(t *testing.T) {
withIsolatedWorkingDir(t)
// Given a matching snapshot file exists
tool := dummyTool{"foo", 42}
b, _ := json.MarshalIndent(tool, "", " ")
require.NoError(t, os.MkdirAll("__toolsnaps__", 0700))
require.NoError(t, os.WriteFile(filepath.Join("__toolsnaps__", "dummy.snap"), b, 0600))
// When we test the snapshot
err := Test("dummy", tool)
// Then it should succeed (no error)
require.NoError(t, err)
}
func TestSnapshotExistsDiff(t *testing.T) {
withIsolatedWorkingDir(t)
// Ensure that UPDATE_TOOLSNAPS is not set for this test, which it might be if someone is running
// UPDATE_TOOLSNAPS=true go test ./...
t.Setenv("UPDATE_TOOLSNAPS", "false")
// Given a non-matching snapshot file exists
require.NoError(t, os.MkdirAll("__toolsnaps__", 0700))
require.NoError(t, os.WriteFile(filepath.Join("__toolsnaps__", "dummy.snap"), []byte(`{"name":"foo","value":1}`), 0600))
tool := dummyTool{"foo", 2}
// When we test the snapshot
err := Test("dummy", tool)
// Then it should error about the schema diff
require.Error(t, err)
assert.Contains(t, err.Error(), "tool schema for dummy has changed unexpectedly", "expected error about diff")
}
func TestUpdateToolsnaps(t *testing.T) {
withIsolatedWorkingDir(t)
// Given UPDATE_TOOLSNAPS is set, regardless of whether a matching snapshot file exists
t.Setenv("UPDATE_TOOLSNAPS", "true")
require.NoError(t, os.MkdirAll("__toolsnaps__", 0700))
require.NoError(t, os.WriteFile(filepath.Join("__toolsnaps__", "dummy.snap"), []byte(`{"name":"foo","value":1}`), 0600))
tool := dummyTool{"foo", 42}
// When we test the snapshot
err := Test("dummy", tool)
// Then it should succeed and write the snapshot file
require.NoError(t, err)
path := filepath.Join("__toolsnaps__", "dummy.snap")
_, statErr := os.Stat(path)
assert.NoError(t, statErr, "expected snapshot file to be written")
}
func TestMalformedSnapshotJSON(t *testing.T) {
withIsolatedWorkingDir(t)
// Ensure that UPDATE_TOOLSNAPS is not set for this test, which it might be if someone is running
// UPDATE_TOOLSNAPS=true go test ./...
t.Setenv("UPDATE_TOOLSNAPS", "false")
// Given a malformed snapshot file exists
require.NoError(t, os.MkdirAll("__toolsnaps__", 0700))
require.NoError(t, os.WriteFile(filepath.Join("__toolsnaps__", "dummy.snap"), []byte(`not-json`), 0600))
tool := dummyTool{"foo", 42}
// When we test the snapshot
err := Test("dummy", tool)
// Then it should error about malformed snapshot JSON
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to parse snapshot JSON for dummy", "expected error about malformed snapshot JSON")
}
func TestSortJSONKeys(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "simple object",
input: `{"z": 1, "a": 2, "m": 3}`,
expected: "{\n \"a\": 2,\n \"m\": 3,\n \"z\": 1\n}",
},
{
name: "nested object",
input: `{"z": {"y": 1, "x": 2}, "a": 3}`,
expected: "{\n \"a\": 3,\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}",
},
{
name: "array with objects",
input: `{"items": [{"z": 1, "a": 2}, {"y": 3, "b": 4}]}`,
expected: "{\n \"items\": [\n {\n \"a\": 2,\n \"z\": 1\n },\n {\n \"b\": 4,\n \"y\": 3\n }\n ]\n}",
},
{
name: "deeply nested",
input: `{"z": {"y": {"x": 1, "a": 2}, "b": 3}, "m": 4}`,
expected: "{\n \"m\": 4,\n \"z\": {\n \"b\": 3,\n \"y\": {\n \"a\": 2,\n \"x\": 1\n }\n }\n}",
},
{
name: "properties field like in toolsnaps",
input: `{"name": "test", "properties": {"repo": {"type": "string"}, "owner": {"type": "string"}, "page": {"type": "number"}}}`,
expected: "{\n \"name\": \"test\",\n \"properties\": {\n \"owner\": {\n \"type\": \"string\"\n },\n \"page\": {\n \"type\": \"number\"\n },\n \"repo\": {\n \"type\": \"string\"\n }\n }\n}",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := sortJSONKeys([]byte(tt.input))
require.NoError(t, err)
assert.Equal(t, tt.expected, string(result))
})
}
}
func TestSortJSONKeysIdempotent(t *testing.T) {
// Given a JSON string that's already sorted
input := `{"a": 1, "b": {"x": 2, "y": 3}, "c": [{"m": 4, "n": 5}]}`
// When we sort it once
sorted1, err := sortJSONKeys([]byte(input))
require.NoError(t, err)
// And sort it again
sorted2, err := sortJSONKeys(sorted1)
require.NoError(t, err)
// Then the results should be identical
assert.Equal(t, string(sorted1), string(sorted2))
}
func TestToolSnapKeysSorted(t *testing.T) {
withIsolatedWorkingDir(t)
// Given a tool with fields that could be in any order
type complexTool struct {
Name string `json:"name"`
Description string `json:"description"`
Properties map[string]any `json:"properties"`
Annotations map[string]any `json:"annotations"`
}
tool := complexTool{
Name: "test_tool",
Description: "A test tool",
Properties: map[string]any{
"zzz": "last",
"aaa": "first",
"mmm": "middle",
"owner": map[string]any{"type": "string", "description": "Owner"},
"repo": map[string]any{"type": "string", "description": "Repo"},
},
Annotations: map[string]any{
"readOnly": true,
"title": "Test",
},
}
// When we write the snapshot
t.Setenv("UPDATE_TOOLSNAPS", "true")
err := Test("complex", tool)
require.NoError(t, err)
// Then the snapshot file should have sorted keys
snapJSON, err := os.ReadFile("__toolsnaps__/complex.snap")
require.NoError(t, err)
// Verify that the JSON is properly sorted by checking key order
var parsed map[string]any
err = json.Unmarshal(snapJSON, &parsed)
require.NoError(t, err)
// Check that properties are sorted
propsJSON, _ := json.MarshalIndent(parsed["properties"], "", " ")
propsStr := string(propsJSON)
// The properties should have "aaa" before "mmm" before "zzz"
aaaIndex := -1
mmmIndex := -1
zzzIndex := -1
for i, line := range propsStr {
if line == 'a' && i+2 < len(propsStr) && propsStr[i:i+3] == "aaa" {
aaaIndex = i
}
if line == 'm' && i+2 < len(propsStr) && propsStr[i:i+3] == "mmm" {
mmmIndex = i
}
if line == 'z' && i+2 < len(propsStr) && propsStr[i:i+3] == "zzz" {
zzzIndex = i
}
}
assert.Greater(t, mmmIndex, aaaIndex, "mmm should come after aaa")
assert.Greater(t, zzzIndex, mmmIndex, "zzz should come after mmm")
}
func TestStructFieldOrderingSortedAlphabetically(t *testing.T) {
withIsolatedWorkingDir(t)
// Given a struct with fields defined in non-alphabetical order
// This test ensures that struct field order doesn't affect the JSON output
type toolWithNonAlphabeticalFields struct {
ZField string `json:"zField"` // Should appear last in JSON
AField string `json:"aField"` // Should appear first in JSON
MField string `json:"mField"` // Should appear in the middle
}
tool := toolWithNonAlphabeticalFields{
ZField: "z value",
AField: "a value",
MField: "m value",
}
// When we write the snapshot
t.Setenv("UPDATE_TOOLSNAPS", "true")
err := Test("struct_field_order", tool)
require.NoError(t, err)
// Then the snapshot file should have alphabetically sorted keys despite struct field order
snapJSON, err := os.ReadFile("__toolsnaps__/struct_field_order.snap")
require.NoError(t, err)
snapStr := string(snapJSON)
// Find the positions of each field in the JSON string
aFieldIndex := -1
mFieldIndex := -1
zFieldIndex := -1
for i := range len(snapStr) - 7 {
switch snapStr[i : i+6] {
case "aField":
aFieldIndex = i
case "mField":
mFieldIndex = i
case "zField":
zFieldIndex = i
}
}
// Verify alphabetical ordering in the JSON output
require.NotEqual(t, -1, aFieldIndex, "aField should be present")
require.NotEqual(t, -1, mFieldIndex, "mField should be present")
require.NotEqual(t, -1, zFieldIndex, "zField should be present")
assert.Less(t, aFieldIndex, mFieldIndex, "aField should appear before mField")
assert.Less(t, mFieldIndex, zFieldIndex, "mField should appear before zField")
// Also verify idempotency - running the test again should produce identical output
err = Test("struct_field_order", tool)
require.NoError(t, err)
snapJSON2, err := os.ReadFile("__toolsnaps__/struct_field_order.snap")
require.NoError(t, err)
assert.Equal(t, string(snapJSON), string(snapJSON2), "Multiple runs should produce identical output")
}