-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathserver.go
More file actions
916 lines (772 loc) · 30.5 KB
/
server.go
File metadata and controls
916 lines (772 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
package ghmcp
import (
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/github/github-mcp-server/pkg/errors"
"github.com/github/github-mcp-server/pkg/github"
"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/raw"
"github.com/github/github-mcp-server/pkg/translations"
gogithub "github.com/google/go-github/v79/github"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shurcooL/githubv4"
)
// MCPServerConfig contains all configuration needed to create an MCP server.
// This config struct is used by both NewMCPServer and NewUnauthenticatedMCPServer
// to ensure consistent configuration across authentication modes.
type MCPServerConfig 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
// Whether to enable dynamic toolsets
// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery
DynamicToolsets bool
// ReadOnly indicates if we should only offer read-only tools
ReadOnly bool
// Translator provides translated text for the server tooling
Translator translations.TranslationHelperFunc
// Content window size
ContentWindowSize int
// LockdownMode indicates if we should enable lockdown mode
LockdownMode bool
// Logger is used for logging within the server
Logger *slog.Logger
// RepoAccessTTL overrides the default TTL for repository access cache entries.
RepoAccessTTL *time.Duration
// OAuthClientID is the OAuth App client ID for device flow authentication.
// If empty, the default GitHub MCP Server OAuth App is used.
OAuthClientID string
// OAuthClientSecret is the OAuth App client secret (optional, for confidential clients).
OAuthClientSecret string
// OAuthScopes is a list of OAuth scopes to request during device flow authentication.
// If empty, the default scopes defined in DefaultOAuthScopes are used.
OAuthScopes []string
}
// githubClients holds all the GitHub API clients created for a server instance.
type githubClients struct {
rest *gogithub.Client
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 MCPServerConfig, apiHost apiHost) (*githubClients, error) {
// Construct REST client
restClient := gogithub.NewClient(nil).WithAuthToken(cfg.Token)
restClient.UserAgent = fmt.Sprintf("github-mcp-server/%s", cfg.Version)
restClient.BaseURL = apiHost.baseRESTURL
restClient.UploadURL = apiHost.uploadURL
// Construct GraphQL client
// We use NewEnterpriseClient unconditionally since we already parsed the API host
gqlHTTPClient := &http.Client{
Transport: &bearerAuthTransport{
transport: http.DefaultTransport,
token: cfg.Token,
},
}
gqlClient := githubv4.NewEnterpriseClient(apiHost.graphqlURL.String(), gqlHTTPClient)
// Create raw content client (shares REST client's HTTP transport)
rawClient := raw.NewClient(restClient, apiHost.rawURL)
// 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.GetInstance(gqlClient, opts...)
}
return &githubClients{
rest: restClient,
gql: gqlClient,
gqlHTTP: gqlHTTPClient,
raw: rawClient,
repoAccess: repoAccessCache,
}, nil
}
// resolveEnabledToolsets determines which toolsets should be enabled based on config.
// Returns nil for "use defaults", empty slice for "none", or explicit list.
func resolveEnabledToolsets(cfg MCPServerConfig) []string {
enabledToolsets := cfg.EnabledToolsets
// In dynamic mode, remove "all" and "default" since users enable toolsets on demand
if cfg.DynamicToolsets && enabledToolsets != nil {
enabledToolsets = github.RemoveToolset(enabledToolsets, string(github.ToolsetMetadataAll.ID))
enabledToolsets = github.RemoveToolset(enabledToolsets, string(github.ToolsetMetadataDefault.ID))
}
if enabledToolsets != nil {
return enabledToolsets
}
if cfg.DynamicToolsets {
// Dynamic mode with no toolsets specified: start empty so users enable on demand
return []string{}
}
if len(cfg.EnabledTools) > 0 {
// When specific tools are requested but no toolsets, don't use default toolsets
// This matches the original behavior: --tools=X alone registers only X
return []string{}
}
// nil means "use defaults" in WithToolsets
return nil
}
// NewMCPServer creates a fully initialized MCP server with GitHub API access.
// This constructor is used when a token is available at startup (PAT authentication).
// For OAuth device flow authentication without a pre-configured token, use NewUnauthenticatedMCPServer instead.
//
// The server creation involves several steps:
// 1. Parse API host configuration and create GitHub clients
// 2. Resolve which toolsets to enable
// 3. Create MCP server with appropriate capabilities
// 4. Add middleware for error handling, user agents, and dependency injection
// 5. Build and register the tool/resource/prompt inventory
// 6. Optionally register dynamic toolset management tools
func NewMCPServer(cfg MCPServerConfig) (*mcp.Server, error) {
apiHost, err := parseAPIHost(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)
}
enabledToolsets := resolveEnabledToolsets(cfg)
// For instruction generation, we need actual toolset names (not nil).
// nil means "use defaults" in inventory, so expand it for instructions.
instructionToolsets := enabledToolsets
if instructionToolsets == nil {
instructionToolsets = github.GetDefaultToolsetIDs()
}
// Create the MCP server
serverOpts := &mcp.ServerOptions{
Instructions: github.GenerateInstructions(instructionToolsets),
Logger: cfg.Logger,
CompletionHandler: github.CompletionsHandler(func(_ context.Context) (*gogithub.Client, error) {
return clients.rest, nil
}),
}
// In dynamic mode, explicitly advertise capabilities since tools/resources/prompts
// may be enabled at runtime even if none are registered initially.
if cfg.DynamicToolsets {
serverOpts.Capabilities = &mcp.ServerCapabilities{
Tools: &mcp.ToolCapabilities{},
Resources: &mcp.ResourceCapabilities{},
Prompts: &mcp.PromptCapabilities{},
}
}
ghServer := github.NewServer(cfg.Version, serverOpts)
// Add middlewares
ghServer.AddReceivingMiddleware(addGitHubAPIErrorToContext)
ghServer.AddReceivingMiddleware(addUserAgentsMiddleware(cfg, clients.rest, clients.gqlHTTP))
// Create dependencies for tool handlers
deps := github.NewBaseDeps(
clients.rest,
clients.gql,
clients.raw,
clients.repoAccess,
cfg.Translator,
github.FeatureFlags{LockdownMode: cfg.LockdownMode},
cfg.ContentWindowSize,
)
// Inject dependencies into context for all tool handlers
ghServer.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
return next(github.ContextWithDeps(ctx, deps), method, req)
}
})
// Build and register the tool/resource/prompt inventory
inventory := github.NewInventory(cfg.Translator).
WithDeprecatedAliases(github.DeprecatedToolAliases).
WithReadOnly(cfg.ReadOnly).
WithToolsets(enabledToolsets).
WithTools(github.CleanTools(cfg.EnabledTools)).
WithFeatureChecker(createFeatureChecker(cfg.EnabledFeatures)).
Build()
if unrecognized := inventory.UnrecognizedToolsets(); len(unrecognized) > 0 {
fmt.Fprintf(os.Stderr, "Warning: unrecognized toolsets ignored: %s\n", strings.Join(unrecognized, ", "))
}
// Register GitHub tools/resources/prompts from the inventory.
// In dynamic mode with no explicit toolsets, this is a no-op since enabledToolsets
// is empty - users enable toolsets at runtime via the dynamic tools below (but can
// enable toolsets or tools explicitly that do need registration).
inventory.RegisterAll(context.Background(), ghServer, deps)
// Register dynamic toolset management tools (enable/disable) - these are separate
// meta-tools that control the inventory, not part of the inventory itself
if cfg.DynamicToolsets {
registerDynamicTools(ghServer, inventory, deps, cfg.Translator)
}
return ghServer, nil
}
// registerDynamicTools adds the dynamic toolset enable/disable tools to the server.
func registerDynamicTools(server *mcp.Server, inventory *inventory.Inventory, deps *github.BaseDeps, t translations.TranslationHelperFunc) {
dynamicDeps := github.DynamicToolDependencies{
Server: server,
Inventory: inventory,
ToolDeps: deps,
T: t,
}
for _, tool := range github.DynamicTools(inventory) {
tool.RegisterFunc(server, dynamicDeps)
}
}
// createFeatureChecker returns a FeatureFlagChecker that checks if a flag name
// is present in the provided list of enabled features. For the local server,
// this is populated from the --features CLI flag.
func createFeatureChecker(enabledFeatures []string) inventory.FeatureFlagChecker {
// Build a set for O(1) lookup
featureSet := make(map[string]bool, len(enabledFeatures))
for _, f := range enabledFeatures {
featureSet[f] = true
}
return func(_ context.Context, flagName string) (bool, error) {
return featureSet[flagName], nil
}
}
// UnauthenticatedServerResult contains the server and components needed to complete
// authentication after the server is running.
type UnauthenticatedServerResult struct {
Server *mcp.Server
AuthManager *github.AuthManager
}
// NewUnauthenticatedMCPServer creates an MCP server with only authentication tools available.
// This constructor is used for OAuth device flow when no token is available at startup.
// After successful authentication via the auth tools, the OnAuthenticated callback
// initializes GitHub clients and registers all other tools dynamically.
//
// Architecture note: This shares significant setup logic with NewMCPServer. The duplication
// exists because the two modes have different initialization timing:
// - NewMCPServer: All setup happens at construction time (clients + tools)
// - NewUnauthenticatedMCPServer: Setup happens in two phases (auth tools first, then clients + tools after auth)
//
// Future improvement: Consider extracting common setup logic into shared helper functions
// to reduce duplication while maintaining the two-phase initialization pattern.
func NewUnauthenticatedMCPServer(cfg MCPServerConfig) (*UnauthenticatedServerResult, error) {
// Create OAuth host from the configured GitHub host
oauthHost := github.NewOAuthHostFromAPIHost(cfg.Host)
// Create auth manager
authManager := github.NewAuthManager(oauthHost, cfg.OAuthClientID, cfg.OAuthClientSecret, cfg.OAuthScopes)
// Build the tool inventory once before forking - this ensures tool filters are applied once
enabledToolsets := resolveEnabledToolsets(cfg)
inventory := github.NewInventory(cfg.Translator).
WithDeprecatedAliases(github.DeprecatedToolAliases).
WithReadOnly(cfg.ReadOnly).
WithToolsets(enabledToolsets).
WithTools(github.CleanTools(cfg.EnabledTools)).
WithFeatureChecker(createFeatureChecker(cfg.EnabledFeatures)).
Build()
if unrecognized := inventory.UnrecognizedToolsets(); len(unrecognized) > 0 {
fmt.Fprintf(os.Stderr, "Warning: unrecognized toolsets ignored: %s\n", strings.Join(unrecognized, ", "))
}
// Create the MCP server with capabilities advertised for dynamic tool registration
serverOpts := &mcp.ServerOptions{
Logger: cfg.Logger,
// Advertise capabilities since tools will be added after auth
Capabilities: &mcp.ServerCapabilities{
Tools: &mcp.ToolCapabilities{ListChanged: true},
Resources: &mcp.ResourceCapabilities{ListChanged: true},
Prompts: &mcp.PromptCapabilities{ListChanged: true},
},
}
ghServer := github.NewServer(cfg.Version, serverOpts)
// Add error context middleware
ghServer.AddReceivingMiddleware(addGitHubAPIErrorToContext)
// Create auth tool dependencies with a callback for when auth completes
authDeps := github.AuthToolDependencies{
AuthManager: authManager,
T: cfg.Translator,
Server: ghServer,
Logger: cfg.Logger,
OnAuthenticated: func(ctx context.Context, token string) error {
// Create API host for GitHub clients
apiHost, err := parseAPIHost(cfg.Host)
if err != nil {
return fmt.Errorf("failed to parse API host: %w", err)
}
// Create a new config with the token
authenticatedCfg := cfg
authenticatedCfg.Token = token
// Create GitHub clients
clients, err := createGitHubClients(authenticatedCfg, apiHost)
if err != nil {
return fmt.Errorf("failed to create GitHub clients: %w", err)
}
// Add user agent middleware
ghServer.AddReceivingMiddleware(addUserAgentsMiddleware(authenticatedCfg, clients.rest, clients.gqlHTTP))
// Create dependencies for tool handlers
deps := github.NewBaseDeps(
clients.rest,
clients.gql,
clients.raw,
clients.repoAccess,
cfg.Translator,
github.FeatureFlags{LockdownMode: cfg.LockdownMode},
cfg.ContentWindowSize,
)
// Inject dependencies into context for all tool handlers
ghServer.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
return next(github.ContextWithDeps(ctx, deps), method, req)
}
})
// Register all GitHub tools/resources/prompts using the pre-built inventory
inventory.RegisterAll(ctx, ghServer, deps)
// Register dynamic toolset management tools if enabled
if cfg.DynamicToolsets {
registerDynamicTools(ghServer, inventory, deps, cfg.Translator)
}
if cfg.Logger != nil {
availableTools := inventory.AvailableTools(ctx)
cfg.Logger.Info("authentication complete, tools registered", "toolCount", len(availableTools))
}
return nil
},
OnAuthComplete: func() {
// Remove auth tools after authentication completes.
// Note: This manual removal ensures auth tools don't remain available after login.
// The auth_login tool is removed by name here to keep the tool list clean.
// Future improvement: Consider using toolset-based filtering to automatically
// exclude auth toolset after authentication, removing the need for manual cleanup.
ghServer.RemoveTools("auth_login")
if cfg.Logger != nil {
cfg.Logger.Info("auth tools removed after successful authentication")
}
},
GetSessionInfo: func(ctx context.Context, token string) string {
// Create a temporary client to fetch user info
apiHost, err := parseAPIHost(cfg.Host)
if err != nil {
return ""
}
tempClient := gogithub.NewClient(nil).WithAuthToken(token)
tempClient.BaseURL = apiHost.baseRESTURL
// Build session information text
var sessionInfo strings.Builder
// Fetch and include user information
if user, _, err := tempClient.Users.Get(ctx, ""); err == nil && user != nil {
sessionInfo.WriteString("## Your GitHub Account\n\n")
sessionInfo.WriteString(fmt.Sprintf("**Username:** @%s\n", user.GetLogin()))
if name := user.GetName(); name != "" {
sessionInfo.WriteString(fmt.Sprintf("**Name:** %s\n", name))
}
if email := user.GetEmail(); email != "" {
sessionInfo.WriteString(fmt.Sprintf("**Email:** %s\n", email))
}
if company := user.GetCompany(); company != "" {
sessionInfo.WriteString(fmt.Sprintf("**Company:** %s\n", company))
}
if location := user.GetLocation(); location != "" {
sessionInfo.WriteString(fmt.Sprintf("**Location:** %s\n", location))
}
sessionInfo.WriteString(fmt.Sprintf("**Profile:** %s\n", user.GetHTMLURL()))
}
// Add server configuration
sessionInfo.WriteString("\n## Server Configuration\n\n")
// Determine effective toolsets
var effectiveToolsets []string
if enabledToolsets == nil {
// nil means defaults - expand them here
effectiveToolsets = github.GetDefaultToolsetIDs()
} else {
effectiveToolsets = enabledToolsets
}
if len(effectiveToolsets) > 0 {
sessionInfo.WriteString(fmt.Sprintf("**Enabled Toolsets:** %s\n", strings.Join(effectiveToolsets, ", ")))
}
if len(cfg.EnabledTools) > 0 {
sessionInfo.WriteString(fmt.Sprintf("**Enabled Tools:** %s\n", strings.Join(cfg.EnabledTools, ", ")))
}
// Configuration flags
var configFlags []string
if cfg.ReadOnly {
configFlags = append(configFlags, "Read-only mode (write operations disabled)")
}
if cfg.LockdownMode {
configFlags = append(configFlags, "Lockdown mode (repository access restricted)")
}
if cfg.DynamicToolsets {
configFlags = append(configFlags, "Dynamic toolsets (can be enabled at runtime)")
}
if len(configFlags) > 0 {
sessionInfo.WriteString("\n**Configuration:**\n")
for _, flag := range configFlags {
sessionInfo.WriteString(fmt.Sprintf("- %s\n", flag))
}
}
return sessionInfo.String()
},
}
// Register only auth tools
for _, tool := range github.AuthTools(cfg.Translator) {
tool.RegisterFunc(ghServer, authDeps)
}
return &UnauthenticatedServerResult{
Server: ghServer,
AuthManager: authManager,
}, 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
// Whether to enable dynamic toolsets
// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#dynamic-tool-discovery
DynamicToolsets bool
// ReadOnly indicates if we should only register read-only tools
ReadOnly bool
// ExportTranslations indicates if we should export translations
// See: https://github.com/github/github-mcp-server?tab=readme-ov-file#i18n--overriding-descriptions
ExportTranslations bool
// EnableCommandLogging indicates if we should log commands
EnableCommandLogging bool
// Path to the log file if not stderr
LogFilePath string
// Content window size
ContentWindowSize int
// LockdownMode indicates if we should enable lockdown mode
LockdownMode bool
// RepoAccessCacheTTL overrides the default TTL for repository access cache entries.
RepoAccessCacheTTL *time.Duration
// OAuthClientID is the OAuth App client ID for device flow authentication.
// If empty, the default GitHub MCP Server OAuth App is used.
OAuthClientID string
// OAuthClientSecret is the OAuth App client secret (optional, for confidential clients).
OAuthClientSecret string
// OAuthScopes is a list of OAuth scopes to request during device flow authentication.
// If empty, the default scopes defined in DefaultOAuthScopes are used.
OAuthScopes []string
}
// RunStdioServer is not concurrent safe.
func RunStdioServer(cfg StdioServerConfig) error {
// 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, "dynamicToolsets", cfg.DynamicToolsets, "readOnly", cfg.ReadOnly, "lockdownEnabled", cfg.LockdownMode)
var ghServer *mcp.Server
// If no token is provided, start in unauthenticated mode with only auth tools
if cfg.Token == "" {
logger.Info("no token provided, starting in unauthenticated mode with auth tools")
result, err := NewUnauthenticatedMCPServer(MCPServerConfig{
Version: cfg.Version,
Host: cfg.Host,
Translator: t,
Logger: logger,
OAuthClientID: cfg.OAuthClientID,
OAuthClientSecret: cfg.OAuthClientSecret,
OAuthScopes: cfg.OAuthScopes,
// Pass config for use after authentication
EnabledToolsets: cfg.EnabledToolsets,
EnabledTools: cfg.EnabledTools,
EnabledFeatures: cfg.EnabledFeatures,
DynamicToolsets: cfg.DynamicToolsets,
ReadOnly: cfg.ReadOnly,
ContentWindowSize: cfg.ContentWindowSize,
LockdownMode: cfg.LockdownMode,
RepoAccessTTL: cfg.RepoAccessCacheTTL,
})
if err != nil {
return fmt.Errorf("failed to create unauthenticated MCP server: %w", err)
}
ghServer = result.Server
} else {
var err error
ghServer, err = NewMCPServer(MCPServerConfig{
Version: cfg.Version,
Host: cfg.Host,
Token: cfg.Token,
EnabledToolsets: cfg.EnabledToolsets,
EnabledTools: cfg.EnabledTools,
EnabledFeatures: cfg.EnabledFeatures,
DynamicToolsets: cfg.DynamicToolsets,
ReadOnly: cfg.ReadOnly,
Translator: t,
ContentWindowSize: cfg.ContentWindowSize,
LockdownMode: cfg.LockdownMode,
Logger: logger,
RepoAccessTTL: cfg.RepoAccessCacheTTL,
})
if err != nil {
return fmt.Errorf("failed to create MCP server: %w", err)
}
}
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
}
type apiHost struct {
baseRESTURL *url.URL
graphqlURL *url.URL
uploadURL *url.URL
rawURL *url.URL
}
func newDotcomHost() (apiHost, error) {
baseRestURL, err := url.Parse("https://api.github.com/")
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse dotcom REST URL: %w", err)
}
gqlURL, err := url.Parse("https://api.github.com/graphql")
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse dotcom GraphQL URL: %w", err)
}
uploadURL, err := url.Parse("https://uploads.github.com")
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse dotcom Upload URL: %w", err)
}
rawURL, err := url.Parse("https://raw.githubusercontent.com/")
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse dotcom Raw URL: %w", err)
}
return apiHost{
baseRESTURL: baseRestURL,
graphqlURL: gqlURL,
uploadURL: uploadURL,
rawURL: rawURL,
}, nil
}
func newGHECHost(hostname string) (apiHost, error) {
u, err := url.Parse(hostname)
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHEC URL: %w", err)
}
// Unsecured GHEC would be an error
if u.Scheme == "http" {
return apiHost{}, fmt.Errorf("GHEC URL must be HTTPS")
}
restURL, err := url.Parse(fmt.Sprintf("https://api.%s/", u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHEC REST URL: %w", err)
}
gqlURL, err := url.Parse(fmt.Sprintf("https://api.%s/graphql", u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHEC GraphQL URL: %w", err)
}
uploadURL, err := url.Parse(fmt.Sprintf("https://uploads.%s", u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHEC Upload URL: %w", err)
}
rawURL, err := url.Parse(fmt.Sprintf("https://raw.%s/", u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHEC Raw URL: %w", err)
}
return apiHost{
baseRESTURL: restURL,
graphqlURL: gqlURL,
uploadURL: uploadURL,
rawURL: rawURL,
}, nil
}
func newGHESHost(hostname string) (apiHost, error) {
u, err := url.Parse(hostname)
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHES URL: %w", err)
}
restURL, err := url.Parse(fmt.Sprintf("%s://%s/api/v3/", u.Scheme, u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHES REST URL: %w", err)
}
gqlURL, err := url.Parse(fmt.Sprintf("%s://%s/api/graphql", u.Scheme, u.Hostname()))
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHES GraphQL URL: %w", err)
}
// Check if subdomain isolation is enabled
// See https://docs.github.com/en/enterprise-server@3.17/admin/configuring-settings/hardening-security-for-your-enterprise/enabling-subdomain-isolation#about-subdomain-isolation
hasSubdomainIsolation := checkSubdomainIsolation(u.Scheme, u.Hostname())
var uploadURL *url.URL
if hasSubdomainIsolation {
// With subdomain isolation: https://uploads.hostname/
uploadURL, err = url.Parse(fmt.Sprintf("%s://uploads.%s/", u.Scheme, u.Hostname()))
} else {
// Without subdomain isolation: https://hostname/api/uploads/
uploadURL, err = url.Parse(fmt.Sprintf("%s://%s/api/uploads/", u.Scheme, u.Hostname()))
}
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHES Upload URL: %w", err)
}
var rawURL *url.URL
if hasSubdomainIsolation {
// With subdomain isolation: https://raw.hostname/
rawURL, err = url.Parse(fmt.Sprintf("%s://raw.%s/", u.Scheme, u.Hostname()))
} else {
// Without subdomain isolation: https://hostname/raw/
rawURL, err = url.Parse(fmt.Sprintf("%s://%s/raw/", u.Scheme, u.Hostname()))
}
if err != nil {
return apiHost{}, fmt.Errorf("failed to parse GHES Raw URL: %w", err)
}
return apiHost{
baseRESTURL: restURL,
graphqlURL: gqlURL,
uploadURL: uploadURL,
rawURL: rawURL,
}, nil
}
// checkSubdomainIsolation detects if GitHub Enterprise Server has subdomain isolation enabled
// by attempting to ping the raw.<host>/_ping endpoint on the subdomain. The raw subdomain must always exist for subdomain isolation.
func checkSubdomainIsolation(scheme, hostname string) bool {
subdomainURL := fmt.Sprintf("%s://raw.%s/_ping", scheme, hostname)
client := &http.Client{
Timeout: 5 * time.Second,
// Don't follow redirects - we just want to check if the endpoint exists
//nolint:revive // parameters are required by http.Client.CheckRedirect signature
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(subdomainURL)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// Note that this does not handle ports yet, so development environments are out.
func parseAPIHost(s string) (apiHost, error) {
if s == "" {
return newDotcomHost()
}
u, err := url.Parse(s)
if err != nil {
return apiHost{}, fmt.Errorf("could not parse host as URL: %s", s)
}
if u.Scheme == "" {
return apiHost{}, fmt.Errorf("host must have a scheme (http or https): %s", s)
}
if strings.HasSuffix(u.Hostname(), "github.com") {
return newDotcomHost()
}
if strings.HasSuffix(u.Hostname(), "ghe.com") {
return newGHECHost(s)
}
return newGHESHost(s)
}
type userAgentTransport struct {
transport http.RoundTripper
agent string
}
func (t *userAgentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.Header.Set("User-Agent", t.agent)
return t.transport.RoundTrip(req)
}
type bearerAuthTransport struct {
transport http.RoundTripper
token string
}
func (t *bearerAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(req.Context())
req.Header.Set("Authorization", "Bearer "+t.token)
return t.transport.RoundTrip(req)
}
func addGitHubAPIErrorToContext(next mcp.MethodHandler) mcp.MethodHandler {
return func(ctx context.Context, method string, req mcp.Request) (result mcp.Result, err error) {
// Ensure the context is cleared of any previous errors
// as context isn't propagated through middleware
ctx = errors.ContextWithGitHubErrors(ctx)
return next(ctx, method, req)
}
}
func addUserAgentsMiddleware(cfg MCPServerConfig, restClient *gogithub.Client, 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,
)
restClient.UserAgent = userAgent
gqlHTTPClient.Transport = &userAgentTransport{
transport: gqlHTTPClient.Transport,
agent: userAgent,
}
return next(ctx, method, request)
}
}
}