From efd8fa7f374041b9705616bc2f56f03b580097c4 Mon Sep 17 00:00:00 2001 From: Navendu Pottekkat Date: Sun, 18 May 2025 17:48:50 +0530 Subject: [PATCH] chore: remove unused variables and type arguments --- server/server.go | 54 ++++++--- server/server_race_test.go | 7 +- server/server_test.go | 219 ++++++++++++++++++++++++++----------- 3 files changed, 202 insertions(+), 78 deletions(-) diff --git a/server/server.go b/server/server.go index f0fa78e7f..6005738b3 100644 --- a/server/server.go +++ b/server/server.go @@ -220,7 +220,11 @@ func WithRecovery() ServerOption { return func(ctx context.Context, request mcp.CallToolRequest) (result *mcp.CallToolResult, err error) { defer func() { if r := recover(); r != nil { - err = fmt.Errorf("panic recovered in %s tool handler: %v", request.Params.Name, r) + err = fmt.Errorf( + "panic recovered in %s tool handler: %v", + request.Params.Name, + r, + ) } }() return next(ctx, request) @@ -487,8 +491,8 @@ func (s *MCPServer) AddNotificationHandler( func (s *MCPServer) handleInitialize( ctx context.Context, - id any, - request mcp.InitializeRequest, + _ any, + _ mcp.InitializeRequest, ) (*mcp.InitializeResult, *requestError) { capabilities := mcp.ServerCapabilities{} @@ -542,9 +546,9 @@ func (s *MCPServer) handleInitialize( } func (s *MCPServer) handlePing( - ctx context.Context, - id any, - request mcp.PingRequest, + _ context.Context, + _ any, + _ mcp.PingRequest, ) (*mcp.EmptyResult, *requestError) { return &mcp.EmptyResult{}, nil } @@ -586,14 +590,14 @@ func (s *MCPServer) handleSetLevel( err: fmt.Errorf("invalid logging level '%s'", level), } } - + sessionLogging.SetLogLevel(level) return &mcp.EmptyResult{}, nil } func listByPagination[T mcp.Named]( - ctx context.Context, + _ context.Context, s *MCPServer, cursor mcp.Cursor, allElements []T, @@ -644,7 +648,12 @@ func (s *MCPServer) handleListResources( sort.Slice(resources, func(i, j int) bool { return resources[i].Name < resources[j].Name }) - resourcesToReturn, nextCursor, err := listByPagination[mcp.Resource](ctx, s, request.Params.Cursor, resources) + resourcesToReturn, nextCursor, err := listByPagination( + ctx, + s, + request.Params.Cursor, + resources, + ) if err != nil { return nil, &requestError{ id: id, @@ -675,7 +684,12 @@ func (s *MCPServer) handleListResourceTemplates( sort.Slice(templates, func(i, j int) bool { return templates[i].Name < templates[j].Name }) - templatesToReturn, nextCursor, err := listByPagination[mcp.ResourceTemplate](ctx, s, request.Params.Cursor, templates) + templatesToReturn, nextCursor, err := listByPagination( + ctx, + s, + request.Params.Cursor, + templates, + ) if err != nil { return nil, &requestError{ id: id, @@ -747,7 +761,11 @@ func (s *MCPServer) handleReadResource( return nil, &requestError{ id: id, code: mcp.RESOURCE_NOT_FOUND, - err: fmt.Errorf("handler not found for resource URI '%s': %w", request.Params.URI, ErrResourceNotFound), + err: fmt.Errorf( + "handler not found for resource URI '%s': %w", + request.Params.URI, + ErrResourceNotFound, + ), } } @@ -772,7 +790,12 @@ func (s *MCPServer) handleListPrompts( sort.Slice(prompts, func(i, j int) bool { return prompts[i].Name < prompts[j].Name }) - promptsToReturn, nextCursor, err := listByPagination[mcp.Prompt](ctx, s, request.Params.Cursor, prompts) + promptsToReturn, nextCursor, err := listByPagination( + ctx, + s, + request.Params.Cursor, + prompts, + ) if err != nil { return nil, &requestError{ id: id, @@ -885,7 +908,12 @@ func (s *MCPServer) handleListTools( s.toolFiltersMu.RUnlock() // Apply pagination - toolsToReturn, nextCursor, err := listByPagination[mcp.Tool](ctx, s, request.Params.Cursor, tools) + toolsToReturn, nextCursor, err := listByPagination( + ctx, + s, + request.Params.Cursor, + tools, + ) if err != nil { return nil, &requestError{ id: id, diff --git a/server/server_race_test.go b/server/server_race_test.go index c3a8d3e62..b5593c81c 100644 --- a/server/server_race_test.go +++ b/server/server_race_test.go @@ -126,7 +126,12 @@ func TestRaceConditions(t *testing.T) { } // Helper function to run an operation concurrently for a specified duration -func runConcurrentOperation(wg *sync.WaitGroup, duration time.Duration, name string, operation func()) { +func runConcurrentOperation( + wg *sync.WaitGroup, + duration time.Duration, + _ string, + operation func(), +) { wg.Add(1) go func() { defer wg.Done() diff --git a/server/server_test.go b/server/server_test.go index 5c2bff4e5..25daeb802 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -260,14 +260,18 @@ func TestMCPServer_Tools(t *testing.T) { initialized: true, }) require.NoError(t, err) - server.AddTool(mcp.NewTool("test-tool-1"), + server.AddTool( + mcp.NewTool("test-tool-1"), func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { return &mcp.CallToolResult{}, nil - }) - server.AddTool(mcp.NewTool("test-tool-2"), + }, + ) + server.AddTool( + mcp.NewTool("test-tool-2"), func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { return &mcp.CallToolResult{}, nil - }) + }, + ) }, expectedNotifications: 2, validate: func(t *testing.T, notifications []mcp.JSONRPCNotification, toolsList mcp.JSONRPCMessage) { @@ -503,9 +507,12 @@ func TestMCPServer_HandleNotifications(t *testing.T) { server := createTestServer() notificationReceived := false - server.AddNotificationHandler("notifications/initialized", func(ctx context.Context, notification mcp.JSONRPCNotification) { - notificationReceived = true - }) + server.AddNotificationHandler( + "notifications/initialized", + func(ctx context.Context, notification mcp.JSONRPCNotification) { + notificationReceived = true + }, + ) message := `{ "jsonrpc": "2.0", @@ -606,7 +613,7 @@ func TestMCPServer_SendNotificationToAllClients(t *testing.T) { contextPrepare := func(ctx context.Context, srv *MCPServer) context.Context { // Create 5 active sessions - for i := 0; i < 5; i++ { + for i := range 5 { err := srv.RegisterSession(ctx, &fakeSession{ sessionID: fmt.Sprintf("test%d", i), notificationChannel: make(chan mcp.JSONRPCNotification, 10), @@ -617,9 +624,9 @@ func TestMCPServer_SendNotificationToAllClients(t *testing.T) { return ctx } - validate := func(t *testing.T, ctx context.Context, srv *MCPServer) { + validate := func(t *testing.T, _ context.Context, srv *MCPServer) { // Send 10 notifications to all sessions - for i := 0; i < 10; i++ { + for i := range 10 { srv.SendNotificationToAllClients("method", map[string]any{ "count": i, }) @@ -640,10 +647,19 @@ func TestMCPServer_SendNotificationToAllClients(t *testing.T) { // Verify count parameter count, ok := notification.Params.AdditionalFields["count"] assert.True(t, ok, "count parameter not found") - assert.Equal(t, notificationCount, count.(int), "count should match notification count") + assert.Equal( + t, + notificationCount, + count.(int), + "count should match notification count", + ) notificationCount++ case <-time.After(100 * time.Millisecond): - t.Errorf("timeout waiting for notification %d for session %s", notificationCount, session.SessionID()) + t.Errorf( + "timeout waiting for notification %d for session %s", + notificationCount, + session.SessionID(), + ) return false } } @@ -796,9 +812,11 @@ func TestMCPServer_PromptHandling(t *testing.T) { func TestMCPServer_HandleInvalidMessages(t *testing.T) { var errs []error hooks := &Hooks{} - hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { - errs = append(errs, err) - }) + hooks.AddOnError( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { + errs = append(errs, err) + }, + ) server := NewMCPServer("test-server", "1.0.0", WithHooks(hooks)) @@ -827,7 +845,13 @@ func TestMCPServer_HandleInvalidMessages(t *testing.T) { ok := errors.As(err, &unparsableErr) assert.True(t, ok, "Error should be UnparsableMessageError") assert.Equal(t, mcp.MethodInitialize, unparsableErr.GetMethod()) - assert.Equal(t, json.RawMessage(`{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": "invalid"}`), unparsableErr.GetMessage()) + assert.Equal( + t, + json.RawMessage( + `{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": "invalid"}`, + ), + unparsableErr.GetMessage(), + ) }, }, { @@ -873,15 +897,19 @@ func TestMCPServer_HandleUndefinedHandlers(t *testing.T) { var beforeResults []beforeResult var afterResults []afterResult hooks := &Hooks{} - hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { - errs = append(errs, err) - }) + hooks.AddOnError( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { + errs = append(errs, err) + }, + ) hooks.AddBeforeAny(func(ctx context.Context, id any, method mcp.MCPMethod, message any) { beforeResults = append(beforeResults, beforeResult{method, message}) }) - hooks.AddOnSuccess(func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any) { - afterResults = append(afterResults, afterResult{method, message, result}) - }) + hooks.AddOnSuccess( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any) { + afterResults = append(afterResults, afterResult{method, message, result}) + }, + ) server := NewMCPServer("test-server", "1.0.0", WithResourceCapabilities(true, true), @@ -984,7 +1012,12 @@ func TestMCPServer_HandleUndefinedHandlers(t *testing.T) { if tt.validateCallbacks != nil { require.Len(t, errs, 1, "Expected exactly one error") require.Len(t, beforeResults, 1, "Expected exactly one before result") - require.Len(t, afterResults, 0, "Expected no after results because these calls generate errors") + require.Len( + t, + afterResults, + 0, + "Expected no after results because these calls generate errors", + ) tt.validateCallbacks(t, errs[0], beforeResults[0]) } }) @@ -994,9 +1027,11 @@ func TestMCPServer_HandleUndefinedHandlers(t *testing.T) { func TestMCPServer_HandleMethodsWithoutCapabilities(t *testing.T) { var errs []error hooks := &Hooks{} - hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { - errs = append(errs, err) - }) + hooks.AddOnError( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { + errs = append(errs, err) + }, + ) hooksOption := WithHooks(hooks) tests := []struct { @@ -1066,7 +1101,12 @@ func TestMCPServer_HandleMethodsWithoutCapabilities(t *testing.T) { assert.Equal(t, tt.expectedErr, errorResponse.Error.Code) require.Len(t, errs, 1, "Expected exactly one error") - assert.True(t, errors.Is(errs[0], ErrUnsupported), "Error should be ErrUnsupported but was %v", errs[0]) + assert.True( + t, + errors.Is(errs[0], ErrUnsupported), + "Error should be ErrUnsupported but was %v", + errs[0], + ) assert.Contains(t, errs[0].Error(), tt.errString) }) } @@ -1099,7 +1139,11 @@ func TestMCPServer_Instructions(t *testing.T) { initResult, ok := resp.Result.(mcp.InitializeResult) assert.True(t, ok) - assert.Equal(t, "These are test instructions for the client.", initResult.Instructions) + assert.Equal( + t, + "These are test instructions for the client.", + initResult.Instructions, + ) }, }, { @@ -1329,20 +1373,24 @@ func TestMCPServer_WithHooks(t *testing.T) { } }) - hooks.AddOnSuccess(func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any) { - onSuccessCount++ - // Only collect ping responses for our test - if method == mcp.MethodPing { - onSuccessData = append(onSuccessData, struct { - msg any - res any - }{message, result}) - } - }) + hooks.AddOnSuccess( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, result any) { + onSuccessCount++ + // Only collect ping responses for our test + if method == mcp.MethodPing { + onSuccessData = append(onSuccessData, struct { + msg any + res any + }{message, result}) + } + }, + ) - hooks.AddOnError(func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { - onErrorCount++ - }) + hooks.AddOnError( + func(ctx context.Context, id any, method mcp.MCPMethod, message any, err error) { + onErrorCount++ + }, + ) // Register method-specific hooks with type verification hooks.AddBeforePing(func(ctx context.Context, id any, message *mcp.PingRequest) { @@ -1350,21 +1398,25 @@ func TestMCPServer_WithHooks(t *testing.T) { beforePingMessages = append(beforePingMessages, message) }) - hooks.AddAfterPing(func(ctx context.Context, id any, message *mcp.PingRequest, result *mcp.EmptyResult) { - afterPingCount++ - afterPingData = append(afterPingData, struct { - msg *mcp.PingRequest - res *mcp.EmptyResult - }{message, result}) - }) + hooks.AddAfterPing( + func(ctx context.Context, id any, message *mcp.PingRequest, result *mcp.EmptyResult) { + afterPingCount++ + afterPingData = append(afterPingData, struct { + msg *mcp.PingRequest + res *mcp.EmptyResult + }{message, result}) + }, + ) hooks.AddBeforeListTools(func(ctx context.Context, id any, message *mcp.ListToolsRequest) { beforeToolsCount++ }) - hooks.AddAfterListTools(func(ctx context.Context, id any, message *mcp.ListToolsRequest, result *mcp.ListToolsResult) { - afterToolsCount++ - }) + hooks.AddAfterListTools( + func(ctx context.Context, id any, message *mcp.ListToolsRequest, result *mcp.ListToolsResult) { + afterToolsCount++ + }, + ) hooks.AddOnRequestInitialization(func(ctx context.Context, id any, message any) error { onRequestInitializationCount++ @@ -1438,9 +1490,19 @@ func TestMCPServer_WithHooks(t *testing.T) { // beforeAny is called for all 4 methods (initialize, ping, tools/list, tools/call) assert.Equal(t, 4, beforeAnyCount, "beforeAny should be called for each method") // onRequestInitialization is called for all 4 methods (initialize, ping, tools/list, tools/call) - assert.Equal(t, 4, onRequestInitializationCount, "onRequestInitializationCount should be called for each method") + assert.Equal( + t, + 4, + onRequestInitializationCount, + "onRequestInitializationCount should be called for each method", + ) // onSuccess is called for all 3 success methods (initialize, ping, tools/list) - assert.Equal(t, 3, onSuccessCount, "onSuccess should be called after all successful invocations") + assert.Equal( + t, + 3, + onSuccessCount, + "onSuccess should be called after all successful invocations", + ) // Error hook should be called once for the failed tools/call assert.Equal(t, 1, onErrorCount, "onError should be called once") @@ -1448,13 +1510,28 @@ func TestMCPServer_WithHooks(t *testing.T) { // Verify type matching between BeforeAny and BeforePing require.Len(t, beforePingMessages, 1, "Expected one BeforePing message") require.Len(t, beforeAnyMessages, 1, "Expected one BeforeAny Ping message") - assert.IsType(t, beforePingMessages[0], beforeAnyMessages[0], "BeforeAny message should be same type as BeforePing message") + assert.IsType( + t, + beforePingMessages[0], + beforeAnyMessages[0], + "BeforeAny message should be same type as BeforePing message", + ) // Verify type matching between OnSuccess and AfterPing require.Len(t, afterPingData, 1, "Expected one AfterPing message/result pair") require.Len(t, onSuccessData, 1, "Expected one OnSuccess Ping message/result pair") - assert.IsType(t, afterPingData[0].msg, onSuccessData[0].msg, "OnSuccess message should be same type as AfterPing message") - assert.IsType(t, afterPingData[0].res, onSuccessData[0].res, "OnSuccess result should be same type as AfterPing result") + assert.IsType( + t, + afterPingData[0].msg, + onSuccessData[0].msg, + "OnSuccess message should be same type as AfterPing message", + ) + assert.IsType( + t, + afterPingData[0].res, + onSuccessData[0].res, + "OnSuccess result should be same type as AfterPing result", + ) } func TestMCPServer_SessionHooks(t *testing.T) { @@ -1556,13 +1633,17 @@ func TestMCPServer_WithRecover(t *testing.T) { require.True(t, ok) assert.Equal(t, mcp.INTERNAL_ERROR, errorResponse.Error.Code) - assert.Equal(t, "panic recovered in panic-tool tool handler: test panic", errorResponse.Error.Message) + assert.Equal( + t, + "panic recovered in panic-tool tool handler: test panic", + errorResponse.Error.Message, + ) assert.Nil(t, errorResponse.Error.Data) } func getTools(length int) []mcp.Tool { list := make([]mcp.Tool, 0, 10000) - for i := 0; i < length; i++ { + for i := range length { list = append(list, mcp.Tool{ Name: fmt.Sprintf("tool%d", i), Description: fmt.Sprintf("tool%d", i), @@ -1572,7 +1653,7 @@ func getTools(length int) []mcp.Tool { } func listByPaginationForReflect[T any]( - ctx context.Context, + _ context.Context, s *MCPServer, cursor mcp.Cursor, allElements []T, @@ -1598,7 +1679,9 @@ func listByPaginationForReflect[T any]( // set the next cursor nextCursor := func() mcp.Cursor { if s.paginationLimit != nil && len(elementsToReturn) >= *s.paginationLimit { - nc := reflect.ValueOf(elementsToReturn[len(elementsToReturn)-1]).FieldByName("Name").String() + nc := reflect.ValueOf(elementsToReturn[len(elementsToReturn)-1]). + FieldByName("Name"). + String() toString := base64.StdEncoding.EncodeToString([]byte(nc)) return mcp.Cursor(toString) } @@ -1612,7 +1695,7 @@ func BenchmarkMCPServer_Pagination(b *testing.B) { ctx := context.Background() server := createTestServer() for i := 0; i < b.N; i++ { - _, _, _ = listByPagination[mcp.Tool](ctx, server, "dG9vbDY1NA==", list) + _, _, _ = listByPagination(ctx, server, "dG9vbDY1NA==", list) } } @@ -1621,7 +1704,7 @@ func BenchmarkMCPServer_PaginationForReflect(b *testing.B) { ctx := context.Background() server := createTestServer() for i := 0; i < b.N; i++ { - _, _, _ = listByPaginationForReflect[mcp.Tool](ctx, server, "dG9vbDY1NA==", list) + _, _, _ = listByPaginationForReflect(ctx, server, "dG9vbDY1NA==", list) } } @@ -1641,7 +1724,11 @@ func TestMCPServer_ToolCapabilitiesBehavior(t *testing.T) { defer s.capabilitiesMu.RUnlock() require.NotNil(t, s.capabilities.tools, "tools capability should be initialized") - assert.True(t, s.capabilities.tools.listChanged, "listChanged should be true when no capabilities were provided") + assert.True( + t, + s.capabilities.tools.listChanged, + "listChanged should be true when no capabilities were provided", + ) }, }, { @@ -1654,7 +1741,11 @@ func TestMCPServer_ToolCapabilitiesBehavior(t *testing.T) { defer s.capabilitiesMu.RUnlock() require.NotNil(t, s.capabilities.tools, "tools capability should be initialized") - assert.False(t, s.capabilities.tools.listChanged, "listChanged should remain false when explicitly set to false") + assert.False( + t, + s.capabilities.tools.listChanged, + "listChanged should remain false when explicitly set to false", + ) }, }, }