-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathserver_test.go
More file actions
444 lines (388 loc) · 14.2 KB
/
Copy pathserver_test.go
File metadata and controls
444 lines (388 loc) · 14.2 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
package github
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"github.com/github/github-mcp-server/pkg/inventory"
"github.com/github/github-mcp-server/pkg/lockdown"
"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/translations"
gogithub "github.com/google/go-github/v89/github"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/shurcooL/githubv4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// stubDeps is a test helper that implements ToolDependencies with configurable behavior.
// Use this when you need to test error paths or when you need closure-based client creation.
type stubDeps struct {
clientFn func(context.Context) (*gogithub.Client, error)
gqlClientFn func(context.Context) (*githubv4.Client, error)
rawClientFn func(context.Context) (*raw.Client, error)
repoAccessCache *lockdown.RepoAccessCache
t translations.TranslationHelperFunc
flags FeatureFlags
contentWindowSize int
obsv observability.Exporters
}
func (s stubDeps) GetClient(ctx context.Context) (*gogithub.Client, error) {
if s.clientFn != nil {
return s.clientFn(ctx)
}
return nil, nil
}
func (s stubDeps) GetGQLClient(ctx context.Context) (*githubv4.Client, error) {
if s.gqlClientFn != nil {
return s.gqlClientFn(ctx)
}
return nil, nil
}
func (s stubDeps) GetRawClient(ctx context.Context) (*raw.Client, error) {
if s.rawClientFn != nil {
return s.rawClientFn(ctx)
}
return nil, nil
}
func (s stubDeps) GetRepoAccessCache(_ context.Context) (*lockdown.RepoAccessCache, error) {
return s.repoAccessCache, nil
}
func (s stubDeps) GetT() translations.TranslationHelperFunc { return s.t }
func (s stubDeps) GetFlags(_ context.Context) FeatureFlags { return s.flags }
func (s stubDeps) GetContentWindowSize() int { return s.contentWindowSize }
func (s stubDeps) IsFeatureEnabled(_ context.Context, _ string) bool { return false }
func (s stubDeps) Logger(_ context.Context) *slog.Logger {
return s.obsv.Logger()
}
func (s stubDeps) Metrics(ctx context.Context) metrics.Metrics {
return s.obsv.Metrics(ctx)
}
// Helper functions to create stub client functions for error testing
// stubExporters returns a discard-logger + noop-metrics Exporters for tests.
func stubExporters() observability.Exporters {
obs, _ := observability.NewExporters(slog.New(slog.DiscardHandler), metrics.NewNoopMetrics())
return obs
}
func stubClientFnFromHTTP(t *testing.T, httpClient *http.Client) func(context.Context) (*gogithub.Client, error) {
t.Helper()
return func(_ context.Context) (*gogithub.Client, error) {
return mustNewGHClient(t, httpClient), nil
}
}
func stubClientFnErr(errMsg string) func(context.Context) (*gogithub.Client, error) {
return func(_ context.Context) (*gogithub.Client, error) {
return nil, errors.New(errMsg)
}
}
func stubGQLClientFnErr(errMsg string) func(context.Context) (*githubv4.Client, error) {
return func(_ context.Context) (*githubv4.Client, error) {
return nil, errors.New(errMsg)
}
}
func stubRepoAccessCache(restClient *gogithub.Client, ttl time.Duration) *lockdown.RepoAccessCache {
cacheName := fmt.Sprintf("repo-access-cache-test-%d", time.Now().UnixNano())
return lockdown.NewRepoAccessCache(
githubv4.NewClient(newRepoAccessHTTPClient()),
restClient,
lockdown.WithTTL(ttl),
lockdown.WithCacheName(cacheName),
)
}
func mockRESTPermissionServer(t *testing.T, defaultPerm string, overrides map[string]string) *gogithub.Client {
t.Helper()
return mustNewGHClient(t, MockHTTPClientWithHandler(func(w http.ResponseWriter, r *http.Request) {
perm := defaultPerm
for user, p := range overrides {
if strings.Contains(r.URL.Path, "/collaborators/"+user+"/") {
perm = p
break
}
}
resp := gogithub.RepositoryPermissionLevel{
Permission: gogithub.Ptr(perm),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}))
}
func stubFeatureFlags(enabledFlags map[string]bool) FeatureFlags {
return FeatureFlags{
LockdownMode: enabledFlags["lockdown-mode"],
}
}
func badRequestHandler(msg string) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
structuredErrorResponse := gogithub.ErrorResponse{
Message: msg,
}
b, err := json.Marshal(structuredErrorResponse)
if err != nil {
http.Error(w, "failed to marshal error response", http.StatusInternalServerError)
}
http.Error(w, string(b), http.StatusBadRequest)
}
}
// TestNewMCPServer_CreatesSuccessfully verifies that the server can be created
// with the deps injection middleware properly configured.
func TestNewMCPServer_CreatesSuccessfully(t *testing.T) {
t.Parallel()
// Create a minimal server configuration
cfg := MCPServerConfig{
Version: "test",
Host: "", // defaults to github.com
Token: "test-token",
EnabledToolsets: []string{"context"},
ReadOnly: false,
Translator: translations.NullTranslationHelper,
ContentWindowSize: 5000,
LockdownMode: false,
}
deps := stubDeps{obsv: stubExporters()}
// Build inventory
inv, err := NewInventory(cfg.Translator).
WithDeprecatedAliases(DeprecatedToolAliases).
WithToolsets(cfg.EnabledToolsets).
Build()
require.NoError(t, err, "expected inventory build to succeed")
// Create the server
server, err := NewMCPServer(context.Background(), &cfg, deps, inv)
require.NoError(t, err, "expected server creation to succeed")
require.NotNil(t, server, "expected server to be non-nil")
// The fact that the server was created successfully indicates that:
// 1. The deps injection middleware is properly added
// 2. Tools can be registered without panicking
//
// If the middleware wasn't properly added, tool calls would panic with
// "ToolDependencies not found in context" when executed.
//
// The actual middleware functionality and tool execution with ContextWithDeps
// is already tested in pkg/github/*_test.go.
}
// advertisedServerCapabilities connects an in-memory client to the given server
// and returns the capabilities the server advertised during initialization.
func advertisedServerCapabilities(t *testing.T, server *mcp.Server) *mcp.ServerCapabilities {
t.Helper()
ctx := context.Background()
clientTransport, serverTransport := mcp.NewInMemoryTransports()
serverSession, err := server.Connect(ctx, serverTransport, nil)
require.NoError(t, err, "expected server to connect")
t.Cleanup(func() { _ = serverSession.Close() })
client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "1.0.0"}, nil)
clientSession, err := client.Connect(ctx, clientTransport, nil)
require.NoError(t, err, "expected client to connect")
t.Cleanup(func() { _ = clientSession.Close() })
result := clientSession.InitializeResult()
require.NotNil(t, result, "expected an initialize result")
return result.Capabilities
}
// TestNewMCPServer_AdvertisedCapabilities locks in the capability contract set by
// NewMCPServer: tools, prompts, and resources are advertised without list-changed
// notifications (the server has a static item set and never emits list_changed),
// the deprecated logging capability is not advertised, and the inferred
// completions capability is preserved. This is asserted for both the stdio path
// (full inventory, items present) and the HTTP path (inventory emptied for the
// discovery/initialize request), which share the same NewMCPServer entry point.
func TestNewMCPServer_AdvertisedCapabilities(t *testing.T) {
t.Parallel()
cfg := MCPServerConfig{
Version: "test",
Token: "test-token",
EnabledToolsets: []string{"context"},
Translator: translations.NullTranslationHelper,
ContentWindowSize: 5000,
}
deps := stubDeps{obsv: stubExporters()}
fullInventory, err := NewInventory(cfg.Translator).
WithDeprecatedAliases(DeprecatedToolAliases).
WithToolsets(cfg.EnabledToolsets).
Build()
require.NoError(t, err, "expected inventory build to succeed")
tests := []struct {
name string
inv *inventory.Inventory
}{
{
name: "stdio path with registered items",
inv: fullInventory,
},
{
// The HTTP handler registers only the items relevant to a request;
// for initialize/discover that is nothing, so capabilities must come
// from the explicit declaration rather than being inferred from items.
name: "http path with no registered items for discovery",
inv: fullInventory.ForMCPRequest(inventory.MCPMethodDiscover, ""),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
server, err := NewMCPServer(context.Background(), &cfg, deps, tt.inv)
require.NoError(t, err, "expected server creation to succeed")
caps := advertisedServerCapabilities(t, server)
require.NotNil(t, caps.Tools, "tools capability should be advertised")
assert.False(t, caps.Tools.ListChanged, "tools list-changed must not be advertised")
require.NotNil(t, caps.Prompts, "prompts capability should be advertised")
assert.False(t, caps.Prompts.ListChanged, "prompts list-changed must not be advertised")
require.NotNil(t, caps.Resources, "resources capability should be advertised")
assert.False(t, caps.Resources.ListChanged, "resources list-changed must not be advertised")
assert.False(t, caps.Resources.Subscribe, "resources subscribe must not be advertised")
assert.NotNil(t, caps.Completions, "completions capability should be preserved")
// Intentionally asserting the deprecated logging capability is absent.
assert.Nil(t, caps.Logging, "deprecated logging capability should not be advertised") //nolint:staticcheck // SA1019: verifying the deprecated capability is not advertised
})
}
}
// TestNewServer_NameAndTitleViaTranslation verifies that server name and title
// can be overridden via the translation helper (GITHUB_MCP_SERVER_NAME /
// GITHUB_MCP_SERVER_TITLE env vars or github-mcp-server-config.json) and
// fall back to sensible defaults when not overridden.
func TestNewServer_NameAndTitleViaTranslation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
translator translations.TranslationHelperFunc
expectedName string
expectedTitle string
}{
{
name: "defaults when using NullTranslationHelper",
translator: translations.NullTranslationHelper,
expectedName: "github-mcp-server",
expectedTitle: "GitHub MCP Server",
},
{
name: "custom name and title via translator",
translator: func(key, defaultValue string) string {
switch key {
case "SERVER_NAME":
return "my-github-server"
case "SERVER_TITLE":
return "My GitHub MCP Server"
default:
return defaultValue
}
},
expectedName: "my-github-server",
expectedTitle: "My GitHub MCP Server",
},
{
name: "custom name only via translator",
translator: func(key, defaultValue string) string {
if key == "SERVER_NAME" {
return "ghes-server"
}
return defaultValue
},
expectedName: "ghes-server",
expectedTitle: "GitHub MCP Server",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
srv := NewServer("v1.0.0", tt.translator("SERVER_NAME", "github-mcp-server"), tt.translator("SERVER_TITLE", "GitHub MCP Server"), nil)
require.NotNil(t, srv)
// Connect a client to retrieve the initialize result and verify ServerInfo.
st, ct := mcp.NewInMemoryTransports()
client := mcp.NewClient(&mcp.Implementation{Name: "test-client"}, nil)
type clientResult struct {
result *mcp.InitializeResult
err error
}
clientResultCh := make(chan clientResult, 1)
go func() {
cs, err := client.Connect(context.Background(), ct, nil)
if err != nil {
clientResultCh <- clientResult{err: err}
return
}
t.Cleanup(func() { _ = cs.Close() })
clientResultCh <- clientResult{result: cs.InitializeResult()}
}()
ss, err := srv.Connect(context.Background(), st, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = ss.Close() })
got := <-clientResultCh
require.NoError(t, got.err)
require.NotNil(t, got.result)
require.NotNil(t, got.result.ServerInfo)
assert.Equal(t, tt.expectedName, got.result.ServerInfo.Name)
assert.Equal(t, tt.expectedTitle, got.result.ServerInfo.Title)
})
}
}
// TestResolveEnabledToolsets verifies the toolset resolution logic.
func TestResolveEnabledToolsets(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cfg MCPServerConfig
expectedResult []string
}{
{
name: "nil toolsets and no tools - use defaults",
cfg: MCPServerConfig{
EnabledToolsets: nil,
EnabledTools: nil,
},
expectedResult: nil, // nil means "use defaults"
},
{
name: "explicit toolsets",
cfg: MCPServerConfig{
EnabledToolsets: []string{"repos", "issues"},
},
expectedResult: []string{"repos", "issues"},
},
{
name: "empty toolsets - disable all",
cfg: MCPServerConfig{
EnabledToolsets: []string{},
},
expectedResult: []string{},
},
{
name: "specific tools without toolsets - no default toolsets",
cfg: MCPServerConfig{
EnabledToolsets: nil,
EnabledTools: []string{"get_me"},
},
expectedResult: []string{}, // empty slice when tools specified but no toolsets
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result := ResolvedEnabledToolsets(tc.cfg.EnabledToolsets, tc.cfg.EnabledTools)
assert.Equal(t, tc.expectedResult, result)
})
}
}
func TestCompletionsHandler_RejectsMissingRef(t *testing.T) {
getClient := func(_ context.Context) (*gogithub.Client, error) {
return &gogithub.Client{}, nil
}
handler := CompletionsHandler(getClient)
tests := []struct {
name string
req *mcp.CompleteRequest
}{
{name: "nil request", req: nil},
{name: "nil params", req: &mcp.CompleteRequest{}},
{name: "nil ref", req: &mcp.CompleteRequest{Params: &mcp.CompleteParams{}}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result, err := handler(context.Background(), tc.req)
require.Error(t, err)
assert.Nil(t, result)
assert.Contains(t, err.Error(), "missing required parameter: ref")
})
}
}