-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathmain.go
More file actions
235 lines (195 loc) · 6.83 KB
/
main.go
File metadata and controls
235 lines (195 loc) · 6.83 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
package main
import (
"context"
"fmt"
"io"
stdlog "log"
"os"
"os/signal"
"syscall"
"github.com/github/github-mcp-server/pkg/github"
iolog "github.com/github/github-mcp-server/pkg/log"
"github.com/github/github-mcp-server/pkg/translations"
gogithub "github.com/google/go-github/v69/github"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var version = "version"
var commit = "commit"
var date = "date"
var (
rootCmd = &cobra.Command{
Use: "server",
Short: "GitHub MCP Server",
Long: `A GitHub MCP server that handles various tools and resources.`,
Version: fmt.Sprintf("%s (%s) %s", version, commit, date),
}
stdioCmd = &cobra.Command{
Use: "stdio",
Short: "Start stdio server",
Long: `Start a server that communicates via standard input/output streams using JSON-RPC messages.`,
Run: func(_ *cobra.Command, _ []string) {
logFile := viper.GetString("log-file")
readOnly := viper.GetBool("read-only")
exportTranslations := viper.GetBool("export-translations")
logger, err := initLogger(logFile)
if err != nil {
stdlog.Fatal("Failed to initialize logger:", err)
}
enabledToolsets := viper.GetStringSlice("toolsets")
logCommands := viper.GetBool("enable-command-logging")
cfg := runConfig{
readOnly: readOnly,
logger: logger,
logCommands: logCommands,
exportTranslations: exportTranslations,
enabledToolsets: enabledToolsets,
}
if err := runStdioServer(cfg); err != nil {
stdlog.Fatal("failed to run stdio server:", err)
}
},
}
)
func init() {
cobra.OnInitialize(initConfig)
// Add global flags that will be shared by all commands
rootCmd.PersistentFlags().StringSlice("toolsets", github.DefaultTools, "An optional comma separated list of groups of tools to allow, defaults to enabling all")
rootCmd.PersistentFlags().Bool("dynamic-toolsets", false, "Enable dynamic toolsets")
rootCmd.PersistentFlags().Bool("read-only", false, "Restrict the server to read-only operations")
rootCmd.PersistentFlags().String("log-file", "", "Path to log file")
rootCmd.PersistentFlags().Bool("enable-command-logging", false, "When enabled, the server will log all command requests and responses to the log file")
rootCmd.PersistentFlags().Bool("export-translations", false, "Save translations to a JSON file")
rootCmd.PersistentFlags().String("gh-host", "", "Specify the GitHub hostname (for GitHub Enterprise etc.)")
// Bind flag to viper
_ = viper.BindPFlag("toolsets", rootCmd.PersistentFlags().Lookup("toolsets"))
_ = viper.BindPFlag("dynamic_toolsets", rootCmd.PersistentFlags().Lookup("dynamic-toolsets"))
_ = viper.BindPFlag("read-only", rootCmd.PersistentFlags().Lookup("read-only"))
_ = viper.BindPFlag("log-file", rootCmd.PersistentFlags().Lookup("log-file"))
_ = viper.BindPFlag("enable-command-logging", rootCmd.PersistentFlags().Lookup("enable-command-logging"))
_ = viper.BindPFlag("export-translations", rootCmd.PersistentFlags().Lookup("export-translations"))
_ = viper.BindPFlag("host", rootCmd.PersistentFlags().Lookup("gh-host"))
// Add subcommands
rootCmd.AddCommand(stdioCmd)
}
func initConfig() {
// Initialize Viper configuration
viper.SetEnvPrefix("github")
viper.AutomaticEnv()
}
func initLogger(outPath string) (*log.Logger, error) {
if outPath == "" {
return log.New(), nil
}
file, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err)
}
logger := log.New()
logger.SetLevel(log.DebugLevel)
logger.SetOutput(file)
return logger, nil
}
type runConfig struct {
readOnly bool
logger *log.Logger
logCommands bool
exportTranslations bool
enabledToolsets []string
}
func runStdioServer(cfg runConfig) error {
// Create app context
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Create GH client
token := viper.GetString("personal_access_token")
if token == "" {
cfg.logger.Fatal("GITHUB_PERSONAL_ACCESS_TOKEN not set")
}
ghClient := gogithub.NewClient(nil).WithAuthToken(token)
ghClient.UserAgent = fmt.Sprintf("github-mcp-server/%s", version)
host := viper.GetString("host")
if host != "" {
var err error
ghClient, err = ghClient.WithEnterpriseURLs(host, host)
if err != nil {
return fmt.Errorf("failed to create GitHub client with host: %w", err)
}
}
t, dumpTranslations := translations.TranslationHelper()
beforeInit := func(_ context.Context, _ any, message *mcp.InitializeRequest) {
ghClient.UserAgent = fmt.Sprintf("github-mcp-server/%s (%s/%s)", version, message.Params.ClientInfo.Name, message.Params.ClientInfo.Version)
}
getClient := func(_ context.Context) (*gogithub.Client, error) {
return ghClient, nil // closing over client
}
hooks := &server.Hooks{
OnBeforeInitialize: []server.OnBeforeInitializeFunc{beforeInit},
}
// Create server
ghServer := github.NewServer(version, server.WithHooks(hooks))
enabled := cfg.enabledToolsets
dynamic := viper.GetBool("dynamic_toolsets")
if dynamic {
// filter "all" from the enabled toolsets
enabled = make([]string, 0, len(cfg.enabledToolsets))
for _, toolset := range cfg.enabledToolsets {
if toolset != "all" {
enabled = append(enabled, toolset)
}
}
}
// Create default toolsets
toolsets, err := github.InitToolsets(enabled, cfg.readOnly, getClient, t)
context := github.InitContextToolset(getClient, t)
if err != nil {
stdlog.Fatal("Failed to initialize toolsets:", err)
}
// Register resources with the server
github.RegisterResources(ghServer, getClient, t)
// Register the tools with the server
toolsets.RegisterTools(ghServer)
context.RegisterTools(ghServer)
if dynamic {
dynamic := github.InitDynamicToolset(ghServer, toolsets, t)
dynamic.RegisterTools(ghServer)
}
stdioServer := server.NewStdioServer(ghServer)
stdLogger := stdlog.New(cfg.logger.Writer(), "stdioserver", 0)
stdioServer.SetErrorLogger(stdLogger)
if cfg.exportTranslations {
// Once server is initialized, all translations are loaded
dumpTranslations()
}
// Start listening for messages
errC := make(chan error, 1)
go func() {
in, out := io.Reader(os.Stdin), io.Writer(os.Stdout)
if cfg.logCommands {
loggedIO := iolog.NewIOLogger(in, out, cfg.logger)
in, out = loggedIO, loggedIO
}
errC <- stdioServer.Listen(ctx, in, 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():
cfg.logger.Infof("shutting down server...")
case err := <-errC:
if err != nil {
return fmt.Errorf("error running server: %w", err)
}
}
return nil
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}