chore: import upstream snapshot with attribution
This commit is contained in:
@@ -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)
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
package ghmcp
|
||||
Reference in New Issue
Block a user