registry/internal/api/handlers/v0/servers_test.go
Radoslav Dimitrov 099a2d702e
Deduplicate server JSON structs between publisher and registry (#318)
<!-- Provide a brief summary of your changes -->

## Motivation and Context
<!-- Why is this change needed? What problem does it solve? -->

The following PR eliminates duplicate struct definitions by migrating
the publisher tool to use canonical types from pkg/model, creating a
single source of truth across the codebase. The publisher tool
previously had its own copies of structs that were duplicated, ie.
ServerJSON, Package, Repository, VersionDetail, EnvironmentVariable,
RuntimeArgument and a few others which was not optimal


**Changes in the PR:**
- Refactored the structs to single canonical types located at pkg/model
- Refactor the implementation to use/build canonical structures directly
  - Remove all duplicate definitions (5 structs eliminated)
- Publisher now uses model.ServerJSON, model.Package, model.Repository,
etc.
- Renamed some of the structs to better reflect their use case, i.e.
ServerJSON instead of ServerDetail
- Fixes an issue where the Remote property was missing from the previous
publisher copy of the Server

**Benefits:**
  - Single source of truth - Schema changes in one place
  - Type safety - Compiler catches mismatches
  - Enhanced validation - Field constraints and bson tags
  - Zero breaking changes - Same CLI interface and JSON output
  - Future-proof - New canonical fields automatically available

Supersedes: #217 and #240

## How Has This Been Tested?
<!-- Have you tested this in a real application? Which scenarios were
tested? -->

Locally

## Breaking Changes
<!-- Will users need to update their code or configurations? -->
No

## Types of changes
<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [ ] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [ ] My code follows the repository's style guidelines
- [ ] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed

## Additional context
<!-- Add any other context, implementation notes, or design decisions
-->

---------

Signed-off-by: Radoslav Dimitrov <radoslav@stacklok.com>
2025-08-28 14:58:15 +01:00

483 lines
14 KiB
Go

package v0_test
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/google/uuid"
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
apiv1 "github.com/modelcontextprotocol/registry/pkg/api/v1"
"github.com/modelcontextprotocol/registry/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestServersListEndpoint(t *testing.T) {
testCases := []struct {
name string
queryParams string
setupMocks func(*MockRegistryService)
expectedStatus int
expectedServers []apiv1.ServerRecord
expectedMeta *v0.Metadata
expectedError string
}{
{
name: "successful list with default parameters",
setupMocks: func(registry *MockRegistryService) {
servers := []apiv1.ServerRecord{
{
Server: model.ServerJSON{
Name: "test-server-1",
Description: "First test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-1",
Source: "github",
ID: "example/test-server-1",
},
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440001",
},
},
{
Server: model.ServerJSON{
Name: "test-server-2",
Description: "Second test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-2",
Source: "github",
ID: "example/test-server-2",
},
VersionDetail: model.VersionDetail{
Version: "2.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440002",
},
},
}
registry.Mock.On("List", "", 30).Return(servers, "", nil)
},
expectedStatus: http.StatusOK,
expectedServers: []apiv1.ServerRecord{
{
Server: model.ServerJSON{
Name: "test-server-1",
Description: "First test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-1",
Source: "github",
ID: "example/test-server-1",
},
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440001",
},
},
{
Server: model.ServerJSON{
Name: "test-server-2",
Description: "Second test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-2",
Source: "github",
ID: "example/test-server-2",
},
VersionDetail: model.VersionDetail{
Version: "2.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440002",
},
},
},
},
{
name: "successful list with cursor and limit",
queryParams: "?cursor=550e8400-e29b-41d4-a716-446655440000&limit=10",
setupMocks: func(registry *MockRegistryService) {
servers := []apiv1.ServerRecord{
{
Server: model.ServerJSON{
Name: "test-server-3",
Description: "Third test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-3",
Source: "github",
ID: "example/test-server-3",
},
VersionDetail: model.VersionDetail{
Version: "1.5.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440003",
},
},
}
nextCursor := uuid.New().String()
registry.Mock.On("List", mock.AnythingOfType("string"), 10).Return(servers, nextCursor, nil)
},
expectedStatus: http.StatusOK,
expectedServers: []apiv1.ServerRecord{
{
Server: model.ServerJSON{
Name: "test-server-3",
Description: "Third test server",
Repository: model.Repository{
URL: "https://github.com/example/test-server-3",
Source: "github",
ID: "example/test-server-3",
},
VersionDetail: model.VersionDetail{
Version: "1.5.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: "550e8400-e29b-41d4-a716-446655440003",
},
},
},
expectedMeta: &v0.Metadata{
NextCursor: "", // This will be dynamically set in the test
Count: 1,
},
},
{
name: "successful list with limit capping at 100",
queryParams: "?limit=150",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity, // Huma rejects values > maximum
expectedError: "validation failed",
},
{
name: "invalid cursor parameter",
queryParams: "?cursor=invalid-uuid",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity, // Huma returns 422 for validation errors
expectedError: "validation failed",
},
{
name: "invalid limit parameter - non-numeric",
queryParams: "?limit=abc",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity, // Huma returns 422 for validation errors
expectedError: "validation failed",
},
{
name: "invalid limit parameter - zero",
queryParams: "?limit=0",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity, // Huma returns 422 for validation errors
expectedError: "validation failed",
},
{
name: "invalid limit parameter - negative",
queryParams: "?limit=-5",
setupMocks: func(_ *MockRegistryService) {},
expectedStatus: http.StatusUnprocessableEntity, // Huma returns 422 for validation errors
expectedError: "validation failed",
},
{
name: "registry service error",
setupMocks: func(registry *MockRegistryService) {
registry.Mock.On("List", "", 30).Return([]apiv1.ServerRecord{}, "", errors.New("database connection error"))
},
expectedStatus: http.StatusInternalServerError,
expectedError: "Failed to get registry list",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create mock registry service
mockRegistry := new(MockRegistryService)
tc.setupMocks(mockRegistry)
// Create a new test API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the servers endpoints
v0.RegisterServersEndpoints(api, mockRegistry)
// Create request
url := "/v0/servers" + tc.queryParams
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
// Serve the request
mux.ServeHTTP(w, req)
// Check status code
assert.Equal(t, tc.expectedStatus, w.Code)
if tc.expectedStatus == http.StatusOK {
// Check content type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Parse response body
var resp struct {
Servers []apiv1.ServerRecord `json:"servers"`
Metadata *v0.Metadata `json:"metadata,omitempty"`
}
err := json.NewDecoder(w.Body).Decode(&resp)
assert.NoError(t, err)
// Check the response data
if tc.expectedServers != nil {
assert.Equal(t, tc.expectedServers, resp.Servers)
}
// Check metadata if expected
if tc.expectedMeta != nil {
assert.Equal(t, tc.expectedMeta.Count, resp.Metadata.Count)
if tc.expectedMeta.NextCursor != "" {
assert.NotEmpty(t, resp.Metadata.NextCursor)
}
}
} else if tc.expectedError != "" {
// Check error message for non-200 responses
assert.Contains(t, w.Body.String(), tc.expectedError)
}
// Verify mock expectations
mockRegistry.AssertExpectations(t)
})
}
}
func TestServersDetailEndpoint(t *testing.T) {
testCases := []struct {
name string
serverID string
setupMocks func(*MockRegistryService, string)
expectedStatus int
expectedServer *apiv1.ServerRecord
expectedError string
}{
{
name: "successful get server detail",
serverID: uuid.New().String(),
setupMocks: func(registry *MockRegistryService, serverID string) {
serverDetail := &apiv1.ServerRecord{
Server: model.ServerJSON{
Name: "test-server-detail",
Description: "Test server detail",
Repository: model.Repository{
URL: "https://github.com/example/test-server-detail",
Source: "github",
ID: "example/test-server-detail",
},
VersionDetail: model.VersionDetail{
Version: "2.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: serverID,
},
}
registry.Mock.On("GetByID", serverID).Return(serverDetail, nil)
},
expectedStatus: http.StatusOK,
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
setupMocks: func(_ *MockRegistryService, _ string) {},
expectedStatus: http.StatusUnprocessableEntity,
expectedError: "validation failed",
},
{
name: "server not found",
serverID: uuid.New().String(),
setupMocks: func(registry *MockRegistryService, serverID string) {
registry.Mock.On("GetByID", serverID).Return(nil, errors.New("record not found"))
},
expectedStatus: http.StatusNotFound,
expectedError: "Server not found",
},
{
name: "registry service error",
serverID: uuid.New().String(),
setupMocks: func(registry *MockRegistryService, serverID string) {
registry.Mock.On("GetByID", serverID).Return(nil, errors.New("database connection error"))
},
expectedStatus: http.StatusInternalServerError,
expectedError: "Failed to get server details",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create mock registry service
mockRegistry := new(MockRegistryService)
tc.setupMocks(mockRegistry, tc.serverID)
// Create a new test API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the servers endpoints
v0.RegisterServersEndpoints(api, mockRegistry)
// Create request
url := "/v0/servers/" + tc.serverID
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
// Serve the request
mux.ServeHTTP(w, req)
// Check status code
assert.Equal(t, tc.expectedStatus, w.Code)
if tc.expectedStatus == http.StatusOK {
// Check content type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Parse response body
var serverDetailResp apiv1.ServerRecord
err := json.NewDecoder(w.Body).Decode(&serverDetailResp)
assert.NoError(t, err)
// Check that we got a valid response
assert.NotEmpty(t, serverDetailResp.Server.Name)
} else if tc.expectedError != "" {
// Check error message for non-200 responses
assert.Contains(t, w.Body.String(), tc.expectedError)
}
// Verify mock expectations
mockRegistry.AssertExpectations(t)
})
}
}
// TestServersEndpointsIntegration tests the servers endpoints with actual HTTP requests
func TestServersEndpointsIntegration(t *testing.T) {
// Create mock registry service
mockRegistry := new(MockRegistryService)
// Test data
serverID := uuid.New().String()
servers := []apiv1.ServerRecord{
{
Server: model.ServerJSON{
Name: "integration-test-server",
Description: "Integration test server",
Repository: model.Repository{
URL: "https://github.com/example/integration-test",
Source: "github",
ID: "example/integration-test",
},
VersionDetail: model.VersionDetail{
Version: "1.0.0",
},
},
XIOModelContextProtocolRegistry: apiv1.RegistryExtensions{
ID: serverID,
},
},
}
serverDetail := &apiv1.ServerRecord{
Server: servers[0].Server,
XIOModelContextProtocolRegistry: servers[0].XIOModelContextProtocolRegistry,
}
// Setup mocks
mockRegistry.Mock.On("List", "", 30).Return(servers, "", nil)
mockRegistry.Mock.On("GetByID", serverID).Return(serverDetail, nil)
// Create a new test API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the servers endpoints
v0.RegisterServersEndpoints(api, mockRegistry)
// Create test server
server := httptest.NewServer(mux)
defer server.Close()
// Test list endpoint
t.Run("list servers integration", func(t *testing.T) {
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/v0/servers", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()
// Check status code
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Check content type
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
// Parse response body
var listResp struct {
Servers []apiv1.ServerRecord `json:"servers"`
}
err = json.NewDecoder(resp.Body).Decode(&listResp)
assert.NoError(t, err)
// Check the response data
assert.Equal(t, servers, listResp.Servers)
})
// Test get server detail endpoint
t.Run("get server detail integration", func(t *testing.T) {
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/v0/servers/"+serverID, nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()
// Check status code
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Check content type
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
// Parse response body
var serverDetailResp apiv1.ServerRecord
err = json.NewDecoder(resp.Body).Decode(&serverDetailResp)
assert.NoError(t, err)
// Check the response data
assert.Equal(t, *serverDetail, serverDetailResp)
})
// Verify mock expectations
mockRegistry.AssertExpectations(t)
}